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/rouge-3.3.0/lib/rouge/formatters/html_pygments.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/formatters/html_pygments.rb
# frozen_string_literal: true module Rouge module Formatters class HTMLPygments < Formatter def initialize(inner, css_class='codehilite') @inner = inner @css_class = css_class end def stream(tokens, &b) yield %(<div class="highlight"><pre class="#{@css_class}"><code>) @inner.stream(tokens, &b) yield "</code></pre></div>" 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/rouge-3.3.0/lib/rouge/formatters/html.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/formatters/html.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Formatters # Transforms a token stream into HTML output. class HTML < Formatter tag 'html' # @yield the html output. def stream(tokens, &b) tokens.each { |tok, val| yield span(tok, val) } end def span(tok, val) safe_span(tok, val.gsub(/[&<>]/, TABLE_FOR_ESCAPE_HTML)) end def safe_span(tok, safe_val) if tok == Token::Tokens::Text safe_val else shortname = tok.shortname \ or raise "unknown token: #{tok.inspect} for #{safe_val.inspect}" "<span class=\"#{shortname}\">#{safe_val}</span>" end end TABLE_FOR_ESCAPE_HTML = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', } 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/rouge-3.3.0/lib/rouge/guessers/source.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/guessers/source.rb
# frozen_string_literal: true module Rouge module Guessers class Source < Guesser include Util attr_reader :source def initialize(source) @source = source end def filter(lexers) # don't bother reading the input if # we've already filtered to 1 return lexers if lexers.size == 1 source_text = get_source(@source) Lexer.assert_utf8!(source_text) source_text = TextAnalyzer.new(source_text) collect_best(lexers) do |lexer| next unless lexer.methods(false).include? :detect? lexer.detect?(source_text) ? 1 : nil 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/rouge-3.3.0/lib/rouge/guessers/disambiguation.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/guessers/disambiguation.rb
# frozen_string_literal: true module Rouge module Guessers class Disambiguation < Guesser include Util include Lexers def initialize(filename, source) @filename = File.basename(filename) @source = source end def filter(lexers) return lexers if lexers.size == 1 return lexers if lexers.size == Lexer.all.size @analyzer = TextAnalyzer.new(get_source(@source)) self.class.disambiguators.each do |disambiguator| next unless disambiguator.match?(@filename) filtered = disambiguator.decide!(self) return filtered if filtered end return lexers end def contains?(text) return @analyzer.include?(text) end def matches?(re) return !!(@analyzer =~ re) end @disambiguators = [] def self.disambiguate(*patterns, &decider) @disambiguators << Disambiguator.new(patterns, &decider) end def self.disambiguators @disambiguators end class Disambiguator include Util def initialize(patterns, &decider) @patterns = patterns @decider = decider end def decide!(guesser) out = guesser.instance_eval(&@decider) case out when Array then out when nil then nil else [out] end end def match?(filename) @patterns.any? { |p| test_glob(p, filename) } end end disambiguate '*.pl' do next Perl if contains?('my $') next Prolog if contains?(':-') next Prolog if matches?(/\A\w+(\(\w+\,\s*\w+\))*\./) end disambiguate '*.h' do next ObjectiveC if matches?(/@(end|implementation|protocol|property)\b/) next ObjectiveC if contains?('@"') C end disambiguate '*.m' do next ObjectiveC if matches?(/@(end|implementation|protocol|property)\b/) next ObjectiveC if contains?('@"') next Mathematica if contains?('(*') next Mathematica if contains?(':=') next Matlab if matches?(/^\s*?%/) end disambiguate '*.php' do # PHP always takes precedence over Hack PHP end disambiguate '*.hh' do next Cpp if matches?(/^\s*#include/) next Hack if matches?(/^<\?hh/) next Hack if matches?(/(\(|, ?)\$\$/) Cpp 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/rouge-3.3.0/lib/rouge/guessers/mimetype.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/guessers/mimetype.rb
# frozen_string_literal: true module Rouge module Guessers class Mimetype < Guesser attr_reader :mimetype def initialize(mimetype) @mimetype = mimetype end def filter(lexers) lexers.select { |lexer| lexer.mimetypes.include? @mimetype } 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/rouge-3.3.0/lib/rouge/guessers/glob_mapping.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/guessers/glob_mapping.rb
# frozen_string_literal: true module Rouge module Guessers # This class allows for custom behavior # with glob -> lexer name mappings class GlobMapping < Guesser include Util def self.by_pairs(mapping, filename) glob_map = {} mapping.each do |(glob, lexer_name)| lexer = Lexer.find(lexer_name) # ignore unknown lexers next unless lexer glob_map[lexer.name] ||= [] glob_map[lexer.name] << glob end new(glob_map, filename) end attr_reader :glob_map, :filename def initialize(glob_map, filename) @glob_map = glob_map @filename = filename end def filter(lexers) basename = File.basename(filename) collect_best(lexers) do |lexer| score = (@glob_map[lexer.name] || []).map do |pattern| if test_glob(pattern, basename) # specificity is better the fewer wildcards there are -pattern.scan(/[*?\[]/).size end end.compact.min 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/rouge-3.3.0/lib/rouge/guessers/modeline.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/guessers/modeline.rb
# frozen_string_literal: true module Rouge module Guessers class Modeline < Guesser include Util # [jneen] regexen stolen from linguist EMACS_MODELINE = /-\*-\s*(?:(?!mode)[\w-]+\s*:\s*(?:[\w+-]+)\s*;?\s*)*(?:mode\s*:)?\s*([\w+-]+)\s*(?:;\s*(?!mode)[\w-]+\s*:\s*[\w+-]+\s*)*;?\s*-\*-/i # First form vim modeline # [text]{white}{vi:|vim:|ex:}[white]{options} # ex: 'vim: syntax=ruby' VIM_MODELINE_1 = /(?:vim|vi|ex):\s*(?:ft|filetype|syntax)=(\w+)\s?/i # Second form vim modeline (compatible with some versions of Vi) # [text]{white}{vi:|vim:|Vim:|ex:}[white]se[t] {options}:[text] # ex: 'vim set syntax=ruby:' VIM_MODELINE_2 = /(?:vim|vi|Vim|ex):\s*se(?:t)?.*\s(?:ft|filetype|syntax)=(\w+)\s?.*:/i MODELINES = [EMACS_MODELINE, VIM_MODELINE_1, VIM_MODELINE_2] def initialize(source, opts={}) @source = source @lines = opts[:lines] || 5 end def filter(lexers) # don't bother reading the stream if we've already decided return lexers if lexers.size == 1 source_text = get_source(@source) lines = source_text.split(/\n/) search_space = (lines.first(@lines) + lines.last(@lines)).join("\n") matches = MODELINES.map { |re| re.match(search_space) }.compact return lexers unless matches.any? match_set = Set.new(matches.map { |m| m[1] }) lexers.select { |l| match_set.include?(l.tag) || l.aliases.any? { |a| match_set.include?(a) } } 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/rouge-3.3.0/lib/rouge/guessers/filename.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/guessers/filename.rb
# frozen_string_literal: true module Rouge module Guessers class Filename < Guesser attr_reader :fname def initialize(filename) @filename = filename end # returns a list of lexers that match the given filename with # equal specificity (i.e. number of wildcards in the pattern). # This helps disambiguate between, e.g. the Nginx lexer, which # matches `nginx.conf`, and the Conf lexer, which matches `*.conf`. # In this case, nginx will win because the pattern has no wildcards, # while `*.conf` has one. def filter(lexers) mapping = {} lexers.each do |lexer| mapping[lexer.name] = lexer.filenames || [] end GlobMapping.new(mapping, @filename).filter(lexers) 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/rouge-3.3.0/lib/rouge/guessers/util.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/guessers/util.rb
# frozen_string_literal: true module Rouge module Guessers module Util module SourceNormalizer UTF8_BOM = "\xEF\xBB\xBF" UTF8_BOM_RE = /\A#{UTF8_BOM}/ # @param [String,nil] source # @return [String,nil] def self.normalize(source) source.sub(UTF8_BOM_RE, '').gsub(/\r\n/, "\n") end end def test_glob(pattern, path) File.fnmatch?(pattern, path, File::FNM_DOTMATCH | File::FNM_CASEFOLD) end # @param [String,IO] source # @return [String] def get_source(source) if source.respond_to?(:to_str) SourceNormalizer.normalize(source.to_str) elsif source.respond_to?(:read) SourceNormalizer.normalize(source.read) else raise ArgumentError, "Invalid source: #{source.inspect}" 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/ffi-1.9.25/samples/getlogin.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/samples/getlogin.rb
require 'rubygems' require 'ffi' module Foo extend FFI::Library ffi_lib FFI::Library::LIBC attach_function :getlogin, [ ], :string end puts "getlogin=#{Foo.getlogin}"
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/ffi-1.9.25/samples/hello.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/samples/hello.rb
require File.expand_path(File.join(File.dirname(__FILE__), "sample_helper")) module Foo extend FFI::Library ffi_lib FFI::Library::LIBC attach_function("cputs", "puts", [ :string ], :int) end Foo.cputs("Hello, World via libc puts using FFI on MRI ruby")
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/ffi-1.9.25/samples/qsort.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/samples/qsort.rb
require 'rubygems' require 'ffi' module LibC extend FFI::Library ffi_lib FFI::Library::LIBC callback :qsort_cmp, [ :pointer, :pointer ], :int attach_function :qsort, [ :pointer, :ulong, :ulong, :qsort_cmp ], :int end p = FFI::MemoryPointer.new(:int, 2) p.put_array_of_int32(0, [ 2, 1 ]) puts "ptr=#{p.inspect}" puts "Before qsort #{p.get_array_of_int32(0, 2).join(', ')}" LibC.qsort(p, 2, 4) do |p1, p2| i1 = p1.get_int32(0) i2 = p2.get_int32(0) puts "In block: comparing #{i1} and #{i2}" i1 < i2 ? -1 : i1 > i2 ? 1 : 0 end puts "After qsort #{p.get_array_of_int32(0, 2).join(', ')}"
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/ffi-1.9.25/samples/sample_helper.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/samples/sample_helper.rb
require 'rubygems' require 'spec' $:.unshift File.join(File.dirname(__FILE__), "..", "lib"), File.join(File.dirname(__FILE__), "..", "build", RUBY_VERSION) unless RUBY_PLATFORM =~ /java/ require "ffi"
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/ffi-1.9.25/samples/getpid.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/samples/getpid.rb
require 'rubygems' require 'ffi' module Foo extend FFI::Library ffi_lib FFI::Library::LIBC attach_function :getpid, [ ], :int end puts "My pid=#{Foo.getpid}"
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/ffi-1.9.25/samples/pty.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/samples/pty.rb
require 'ffi' module PTY private module LibC extend FFI::Library ffi_lib FFI::Library::LIBC attach_function :forkpty, [ :buffer_out, :buffer_out, :buffer_in, :buffer_in ], :int attach_function :openpty, [ :buffer_out, :buffer_out, :buffer_out, :buffer_in, :buffer_in ], :int attach_function :login_tty, [ :int ], :int attach_function :close, [ :int ], :int attach_function :strerror, [ :int ], :string attach_function :fork, [], :int attach_function :execv, [ :string, :buffer_in ], :int attach_function :execvp, [ :string, :buffer_in ], :int attach_function :dup2, [ :int, :int ], :int attach_function :dup, [ :int ], :int end Buffer = FFI::Buffer def self.build_args(args) cmd = args.shift cmd_args = args.map do |arg| MemoryPointer.from_string(arg) end exec_args = MemoryPointer.new(:pointer, 1 + cmd_args.length + 1) exec_cmd = MemoryPointer.from_string(cmd) exec_args[0].put_pointer(0, exec_cmd) cmd_args.each_with_index do |arg, i| exec_args[i + 1].put_pointer(0, arg) end [ cmd, exec_args ] end public def self.getpty(*args) mfdp = Buffer.new :int name = Buffer.new 1024 # # All the execv setup is done in the parent, since doing anything other than # execv in the child after fork is really flakey # exec_cmd, exec_args = build_args(args) pid = LibC.forkpty(mfdp, name, nil, nil) raise "forkpty failed: #{LibC.strerror(FFI.errno)}" if pid < 0 if pid == 0 LibC.execvp(exec_cmd, exec_args) exit 1 end masterfd = mfdp.get_int(0) rfp = FFI::IO.for_fd(masterfd, "r") wfp = FFI::IO.for_fd(LibC.dup(masterfd), "w") if block_given? yield rfp, wfp, pid rfp.close unless rfp.closed? wfp.close unless wfp.closed? else [ rfp, wfp, pid ] end end def self.spawn(*args, &block) self.getpty("/bin/sh", "-c", args[0], &block) end end module LibC extend FFI::Library attach_function :close, [ :int ], :int attach_function :write, [ :int, :buffer_in, :ulong ], :long attach_function :read, [ :int, :buffer_out, :ulong ], :long end PTY.getpty("/bin/ls", "-alR", "/") { |rfd, wfd, pid| #PTY.spawn("ls -laR /") { |rfd, wfd, pid| puts "child pid=#{pid}" while !rfd.eof? && (buf = rfd.gets) puts "child: '#{buf.strip}'" 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/ffi-1.9.25/samples/inotify.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/samples/inotify.rb
require 'rubygems' require 'ffi' module Inotify extend FFI::Library ffi_lib FFI::Library::LIBC class Event < FFI::Struct layout \ :wd, :int, :mask, :uint, :cookie, :uint, :len, :uint end attach_function :init, :inotify_init, [ ], :int attach_function :add_watch, :inotify_add_watch, [ :int, :string, :uint ], :int attach_function :rm_watch, :inotify_rm_watch, [ :int, :uint ], :int attach_function :read, [ :int, :buffer_out, :uint ], :int IN_ACCESS=0x00000001 IN_MODIFY=0x00000002 IN_ATTRIB=0x00000004 IN_CLOSE_WRITE=0x00000008 IN_CLOSE_NOWRITE=0x00000010 IN_CLOSE=(IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) IN_OPEN=0x00000020 IN_MOVED_FROM=0x00000040 IN_MOVED_TO=0x00000080 IN_MOVE= (IN_MOVED_FROM | IN_MOVED_TO) IN_CREATE=0x00000100 IN_DELETE=0x00000200 IN_DELETE_SELF=0x00000400 IN_MOVE_SELF=0x00000800 # Events sent by the kernel. IN_UNMOUNT=0x00002000 IN_Q_OVERFLOW=0x00004000 IN_IGNORED=0x00008000 IN_ONLYDIR=0x01000000 IN_DONT_FOLLOW=0x02000000 IN_MASK_ADD=0x20000000 IN_ISDIR=0x40000000 IN_ONESHOT=0x80000000 IN_ALL_EVENTS=(IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE \ | IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM \ | IN_MOVED_TO | IN_CREATE | IN_DELETE \ | IN_DELETE_SELF | IN_MOVE_SELF) end if $0 == __FILE__ fd = Inotify.init puts "fd=#{fd}" wd = Inotify.add_watch(fd, "/tmp/", Inotify::IN_ALL_EVENTS) fp = FFI::IO.for_fd(fd) puts "wfp=#{fp}" while true buf = FFI::Buffer.alloc_out(Inotify::Event.size + 4096, 1, false) ev = Inotify::Event.new buf ready = IO.select([ fp ], nil, nil, nil) n = Inotify.read(fd, buf, buf.total) puts "Read #{n} bytes from inotify fd" puts "event.wd=#{ev[:wd]} mask=#{ev[:mask]} len=#{ev[:len]} name=#{ev[:len] > 0 ? buf.get_string(16) : 'unknown'}" 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/ffi-1.9.25/samples/gettimeofday.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/samples/gettimeofday.rb
require 'rubygems' require 'ffi' class Timeval < FFI::Struct rb_maj, rb_min, rb_micro = RUBY_VERSION.split('.') if rb_maj.to_i >= 1 && rb_min.to_i >= 9 || RUBY_PLATFORM =~ /java/ layout :tv_sec => :ulong, :tv_usec => :ulong else layout :tv_sec, :ulong, 0, :tv_usec, :ulong, 4 end end module LibC extend FFI::Library ffi_lib FFI::Library::LIBC attach_function :gettimeofday, [ :pointer, :pointer ], :int end t = Timeval.new LibC.gettimeofday(t.pointer, nil) puts "t.tv_sec=#{t[:tv_sec]} t.tv_usec=#{t[:tv_usec]}"
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/ffi-1.9.25/ext/ffi_c/extconf.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/ext/ffi_c/extconf.rb
#!/usr/bin/env ruby if !defined?(RUBY_ENGINE) || RUBY_ENGINE == 'ruby' || RUBY_ENGINE == 'rbx' require 'mkmf' require 'rbconfig' dir_config("ffi_c") # recent versions of ruby add restrictive ansi and warning flags on a whim - kill them all $warnflags = '' $CFLAGS.gsub!(/[\s+]-ansi/, '') $CFLAGS.gsub!(/[\s+]-std=[^\s]+/, '') # solaris 10 needs -c99 for <stdbool.h> $CFLAGS << " -std=c99" if RbConfig::CONFIG['host_os'] =~ /solaris(!?2\.11)/ if ENV['RUBY_CC_VERSION'].nil? && (pkg_config("libffi") || have_header("ffi.h") || find_header("ffi.h", "/usr/local/include", "/usr/include/ffi")) # We need at least ffi_call and ffi_closure_alloc libffi_ok = have_library("ffi", "ffi_call", [ "ffi.h" ]) || have_library("libffi", "ffi_call", [ "ffi.h" ]) libffi_ok &&= have_func("ffi_closure_alloc") # Check if the raw api is available. $defs << "-DHAVE_RAW_API" if have_func("ffi_raw_call") && have_func("ffi_prep_raw_closure") end have_header('shlwapi.h') have_header('ruby/thread.h') # for compat with ruby < 2.0 have_func('rb_thread_blocking_region') have_func('rb_thread_call_with_gvl') have_func('rb_thread_call_without_gvl') if libffi_ok have_func('ffi_prep_cif_var') else $defs << "-DHAVE_FFI_PREP_CIF_VAR" end $defs << "-DHAVE_EXTCONF_H" if $defs.empty? # needed so create_header works $defs << "-DUSE_INTERNAL_LIBFFI" unless libffi_ok $defs << "-DRUBY_1_9" if RUBY_VERSION >= "1.9.0" $defs << "-DFFI_BUILDING" if RbConfig::CONFIG['host_os'] =~ /mswin/ # for compatibility with newer libffi create_header $LOCAL_LIBS << " ./libffi/.libs/libffi_convenience.lib" if !libffi_ok && RbConfig::CONFIG['host_os'] =~ /mswin/ create_makefile("ffi_c") unless libffi_ok File.open("Makefile", "a") do |mf| mf.puts "LIBFFI_HOST=--host=#{RbConfig::CONFIG['host_alias']}" if RbConfig::CONFIG.has_key?("host_alias") if RbConfig::CONFIG['host_os'].downcase =~ /darwin/ mf.puts "include ${srcdir}/libffi.darwin.mk" elsif RbConfig::CONFIG['host_os'].downcase =~ /bsd/ mf.puts '.include "${srcdir}/libffi.bsd.mk"' elsif RbConfig::CONFIG['host_os'].downcase =~ /mswin64/ mf.puts '!include $(srcdir)/libffi.vc64.mk' elsif RbConfig::CONFIG['host_os'].downcase =~ /mswin32/ mf.puts '!include $(srcdir)/libffi.vc.mk' else mf.puts "include ${srcdir}/libffi.mk" end end end else File.open("Makefile", "w") do |mf| mf.puts "# Dummy makefile for non-mri rubies" mf.puts "all install::\n" 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/ffi-1.9.25/lib/ffi.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi.rb
if !defined?(RUBY_ENGINE) || RUBY_ENGINE == 'ruby' || RUBY_ENGINE == 'rbx' Object.send(:remove_const, :FFI) if defined?(::FFI) begin require RUBY_VERSION.split('.')[0, 2].join('.') + '/ffi_c' rescue Exception require 'ffi_c' end require 'ffi/ffi' elsif defined?(RUBY_ENGINE) # Remove the ffi gem dir from the load path, then reload the internal ffi implementation $LOAD_PATH.delete(File.dirname(__FILE__)) $LOAD_PATH.delete(File.join(File.dirname(__FILE__), 'ffi')) unless $LOADED_FEATURES.nil? $LOADED_FEATURES.delete(__FILE__) $LOADED_FEATURES.delete('ffi.rb') end require 'ffi.rb' 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/ffi-1.9.25/lib/ffi/platform.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/platform.rb
# # Copyright (C) 2008, 2009 Wayne Meissner # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# require 'rbconfig' module FFI class PlatformError < LoadError; end # This module defines different constants and class methods to play with # various platforms. module Platform OS = case RbConfig::CONFIG['host_os'].downcase when /linux/ "linux" when /darwin/ "darwin" when /freebsd/ "freebsd" when /netbsd/ "netbsd" when /openbsd/ "openbsd" when /sunos|solaris/ "solaris" when /mingw|mswin/ "windows" else RbConfig::CONFIG['host_os'].downcase end ARCH = case CPU.downcase when /amd64|x86_64/ "x86_64" when /i?86|x86|i86pc/ "i386" when /ppc64|powerpc64/ "powerpc64" when /ppc|powerpc/ "powerpc" when /sparcv9|sparc64/ "sparcv9" else case RbConfig::CONFIG['host_cpu'] when /^arm/ "arm" else RbConfig::CONFIG['host_cpu'] end end private # @param [String) os # @return [Boolean] # Test if current OS is +os+. def self.is_os(os) OS == os end NAME = "#{ARCH}-#{OS}" IS_GNU = defined?(GNU_LIBC) IS_LINUX = is_os("linux") IS_MAC = is_os("darwin") IS_FREEBSD = is_os("freebsd") IS_NETBSD = is_os("netbsd") IS_OPENBSD = is_os("openbsd") IS_SOLARIS = is_os("solaris") IS_WINDOWS = is_os("windows") IS_BSD = IS_MAC || IS_FREEBSD || IS_NETBSD || IS_OPENBSD CONF_DIR = File.join(File.dirname(__FILE__), 'platform', NAME) public LIBPREFIX = case OS when /windows|msys/ '' when /cygwin/ 'cyg' else 'lib' end LIBSUFFIX = case OS when /darwin/ 'dylib' when /linux|bsd|solaris/ 'so' when /windows|cygwin|msys/ 'dll' else # Punt and just assume a sane unix (i.e. anything but AIX) 'so' end LIBC = if IS_WINDOWS RbConfig::CONFIG['RUBY_SO_NAME'].split('-')[-2] + '.dll' elsif IS_GNU GNU_LIBC elsif OS == 'cygwin' "cygwin1.dll" elsif OS == 'msys' # Not sure how msys 1.0 behaves, tested on MSYS2. "msys-2.0.dll" else "#{LIBPREFIX}c.#{LIBSUFFIX}" end # Test if current OS is a *BSD (include MAC) # @return [Boolean] def self.bsd? IS_BSD end # Test if current OS is Windows # @return [Boolean] def self.windows? IS_WINDOWS end # Test if current OS is Mac OS # @return [Boolean] def self.mac? IS_MAC end # Test if current OS is Solaris (Sun OS) # @return [Boolean] def self.solaris? IS_SOLARIS end # Test if current OS is a unix OS # @return [Boolean] def self.unix? !IS_WINDOWS 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/ffi-1.9.25/lib/ffi/io.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/io.rb
# # Copyright (C) 2008, 2009 Wayne Meissner # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# module FFI # This module implements a couple of class methods to play with IO. module IO # @param [Integer] fd file decriptor # @param [String] mode mode string # @return [::IO] # Synonym for IO::for_fd. def self.for_fd(fd, mode = "r") ::IO.for_fd(fd, mode) end # @param [#read] io io to read from # @param [AbstractMemory] buf destination for data read from +io+ # @param [nil, Numeric] len maximul number of bytes to read from +io+. If +nil+, # read until end of file. # @return [Numeric] length really read, in bytes # # A version of IO#read that reads data from an IO and put then into a native buffer. # # This will be optimized at some future time to eliminate the double copy. # def self.native_read(io, buf, len) tmp = io.read(len) return -1 unless tmp buf.put_bytes(0, tmp) tmp.length 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/ffi-1.9.25/lib/ffi/callback.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/callback.rb
# # All the code from this file is now implemented in C. This file remains # to satisfy any leftover require 'ffi/callback' in user code #
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/ffi-1.9.25/lib/ffi/errno.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/errno.rb
# # Copyright (C) 2008-2010 Wayne Meissner # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# module FFI # @return (see FFI::LastError.error) # @see FFI::LastError.error def self.errno FFI::LastError.error end # @param error (see FFI::LastError.error=) # @return (see FFI::LastError.error=) # @see FFI::LastError.error= def self.errno=(error) FFI::LastError.error = error 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/ffi-1.9.25/lib/ffi/library.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/library.rb
# # Copyright (C) 2008-2010 Wayne Meissner # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# module FFI CURRENT_PROCESS = USE_THIS_PROCESS_AS_LIBRARY = Object.new # @param [#to_s] lib library name # @return [String] library name formatted for current platform # Transform a generic library name to a platform library name # @example # # Linux # FFI.map_library_name 'c' # -> "libc.so.6" # FFI.map_library_name 'jpeg' # -> "libjpeg.so" # # Windows # FFI.map_library_name 'c' # -> "msvcrt.dll" # FFI.map_library_name 'jpeg' # -> "jpeg.dll" def self.map_library_name(lib) # Mangle the library name to reflect the native library naming conventions lib = Library::LIBC if lib == 'c' if lib && File.basename(lib) == lib lib = Platform::LIBPREFIX + lib unless lib =~ /^#{Platform::LIBPREFIX}/ r = Platform::IS_GNU ? "\\.so($|\\.[1234567890]+)" : "\\.#{Platform::LIBSUFFIX}$" lib += ".#{Platform::LIBSUFFIX}" unless lib =~ /#{r}/ end lib end # Exception raised when a function is not found in libraries class NotFoundError < LoadError def initialize(function, *libraries) super("Function '#{function}' not found in [#{libraries[0].nil? ? 'current process' : libraries.join(", ")}]") end end # This module is the base to use native functions. # # A basic usage may be: # require 'ffi' # # module Hello # extend FFI::Library # ffi_lib FFI::Library::LIBC # attach_function 'puts', [ :string ], :int # end # # Hello.puts("Hello, World") # # module Library CURRENT_PROCESS = FFI::CURRENT_PROCESS LIBC = FFI::Platform::LIBC # @param mod extended object # @return [nil] # @raise {RuntimeError} if +mod+ is not a Module # Test if extended object is a Module. If not, raise RuntimeError. def self.extended(mod) raise RuntimeError.new("must only be extended by module") unless mod.kind_of?(Module) end # @param [Array] names names of libraries to load # @return [Array<DynamicLibrary>] # @raise {LoadError} if a library cannot be opened # Load native libraries. def ffi_lib(*names) raise LoadError.new("library names list must not be empty") if names.empty? lib_flags = defined?(@ffi_lib_flags) ? @ffi_lib_flags : FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL ffi_libs = names.map do |name| if name == FFI::CURRENT_PROCESS FFI::DynamicLibrary.open(nil, FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL) else libnames = (name.is_a?(::Array) ? name : [ name ]).map(&:to_s).map { |n| [ n, FFI.map_library_name(n) ].uniq }.flatten.compact lib = nil errors = {} libnames.each do |libname| begin orig = libname lib = FFI::DynamicLibrary.open(libname, lib_flags) break if lib rescue Exception => ex ldscript = false if ex.message =~ /(([^ \t()])+\.so([^ \t:()])*):([ \t])*(invalid ELF header|file too short|invalid file format)/ if File.read($1) =~ /(?:GROUP|INPUT) *\( *([^ \)]+)/ libname = $1 ldscript = true end end if ldscript retry else # TODO better library lookup logic unless libname.start_with?("/") || FFI::Platform.windows? path = ['/usr/lib/','/usr/local/lib/'].find do |pth| File.exist?(pth + libname) end if path libname = path + libname retry end end libr = (orig == libname ? orig : "#{orig} #{libname}") errors[libr] = ex end end end if lib.nil? raise LoadError.new(errors.values.join(".\n")) end # return the found lib lib end end @ffi_libs = ffi_libs end # Set the calling convention for {#attach_function} and {#callback} # # @see http://en.wikipedia.org/wiki/Stdcall#stdcall # @note +:stdcall+ is typically used for attaching Windows API functions # # @param [Symbol] convention one of +:default+, +:stdcall+ # @return [Symbol] the new calling convention def ffi_convention(convention = nil) @ffi_convention ||= :default @ffi_convention = convention if convention @ffi_convention end # @see #ffi_lib # @return [Array<FFI::DynamicLibrary>] array of currently loaded FFI libraries # @raise [LoadError] if no libraries have been loaded (using {#ffi_lib}) # Get FFI libraries loaded using {#ffi_lib}. def ffi_libraries raise LoadError.new("no library specified") if !defined?(@ffi_libs) || @ffi_libs.empty? @ffi_libs end # Flags used in {#ffi_lib}. # # This map allows you to supply symbols to {#ffi_lib_flags} instead of # the actual constants. FlagsMap = { :global => DynamicLibrary::RTLD_GLOBAL, :local => DynamicLibrary::RTLD_LOCAL, :lazy => DynamicLibrary::RTLD_LAZY, :now => DynamicLibrary::RTLD_NOW } # Sets library flags for {#ffi_lib}. # # @example # ffi_lib_flags(:lazy, :local) # => 5 # # @param [Symbol, …] flags (see {FlagsMap}) # @return [Fixnum] the new value def ffi_lib_flags(*flags) @ffi_lib_flags = flags.inject(0) { |result, f| result | FlagsMap[f] } end ## # @overload attach_function(func, args, returns, options = {}) # @example attach function without an explicit name # module Foo # extend FFI::Library # ffi_lib FFI::Library::LIBC # attach_function :malloc, [:size_t], :pointer # end # # now callable via Foo.malloc # @overload attach_function(name, func, args, returns, options = {}) # @example attach function with an explicit name # module Bar # extend FFI::Library # ffi_lib FFI::Library::LIBC # attach_function :c_malloc, :malloc, [:size_t], :pointer # end # # now callable via Bar.c_malloc # # Attach C function +func+ to this module. # # # @param [#to_s] name name of ruby method to attach as # @param [#to_s] func name of C function to attach # @param [Array<Symbol>] args an array of types # @param [Symbol] returns type of return value # @option options [Boolean] :blocking (@blocking) set to true if the C function is a blocking call # @option options [Symbol] :convention (:default) calling convention (see {#ffi_convention}) # @option options [FFI::Enums] :enums # @option options [Hash] :type_map # # @return [FFI::VariadicInvoker] # # @raise [FFI::NotFoundError] if +func+ cannot be found in the attached libraries (see {#ffi_lib}) def attach_function(name, func, args, returns = nil, options = nil) mname, a2, a3, a4, a5 = name, func, args, returns, options cname, arg_types, ret_type, opts = (a4 && (a2.is_a?(String) || a2.is_a?(Symbol))) ? [ a2, a3, a4, a5 ] : [ mname.to_s, a2, a3, a4 ] # Convert :foo to the native type arg_types = arg_types.map { |e| find_type(e) } options = { :convention => ffi_convention, :type_map => defined?(@ffi_typedefs) ? @ffi_typedefs : nil, :blocking => defined?(@blocking) && @blocking, :enums => defined?(@ffi_enums) ? @ffi_enums : nil, } @blocking = false options.merge!(opts) if opts && opts.is_a?(Hash) # Try to locate the function in any of the libraries invokers = [] ffi_libraries.each do |lib| if invokers.empty? begin function = nil function_names(cname, arg_types).find do |fname| function = lib.find_function(fname) end raise LoadError unless function invokers << if arg_types.length > 0 && arg_types[arg_types.length - 1] == FFI::NativeType::VARARGS VariadicInvoker.new(function, arg_types, find_type(ret_type), options) else Function.new(find_type(ret_type), arg_types, function, options) end rescue LoadError end end end invoker = invokers.compact.shift raise FFI::NotFoundError.new(cname.to_s, ffi_libraries.map { |lib| lib.name }) unless invoker invoker.attach(self, mname.to_s) invoker end # @param [#to_s] name function name # @param [Array] arg_types function's argument types # @return [Array<String>] # This function returns a list of possible names to lookup. # @note Function names on windows may be decorated if they are using stdcall. See # * http://en.wikipedia.org/wiki/Name_mangling#C_name_decoration_in_Microsoft_Windows # * http://msdn.microsoft.com/en-us/library/zxk0tw93%28v=VS.100%29.aspx # * http://en.wikibooks.org/wiki/X86_Disassembly/Calling_Conventions#STDCALL # Note that decorated names can be overridden via def files. Also note that the # windows api, although using, doesn't have decorated names. def function_names(name, arg_types) result = [name.to_s] if ffi_convention == :stdcall # Get the size of each parameter size = arg_types.inject(0) do |mem, arg| size = arg.size # The size must be a multiple of 4 size += (4 - size) % 4 mem + size end result << "_#{name.to_s}@#{size}" # win32 result << "#{name.to_s}@#{size}" # win64 end result end # @overload attach_variable(mname, cname, type) # @param [#to_s] mname name of ruby method to attach as # @param [#to_s] cname name of C variable to attach # @param [DataConverter, Struct, Symbol, Type] type C variable's type # @example # module Bar # extend FFI::Library # ffi_lib 'my_lib' # attach_variable :c_myvar, :myvar, :long # end # # now callable via Bar.c_myvar # @overload attach_variable(cname, type) # @param [#to_s] mname name of ruby method to attach as # @param [DataConverter, Struct, Symbol, Type] type C variable's type # @example # module Bar # extend FFI::Library # ffi_lib 'my_lib' # attach_variable :myvar, :long # end # # now callable via Bar.myvar # @return [DynamicLibrary::Symbol] # @raise {FFI::NotFoundError} if +cname+ cannot be found in libraries # # Attach C variable +cname+ to this module. def attach_variable(mname, a1, a2 = nil) cname, type = a2 ? [ a1, a2 ] : [ mname.to_s, a1 ] address = nil ffi_libraries.each do |lib| begin address = lib.find_variable(cname.to_s) break unless address.nil? rescue LoadError end end raise FFI::NotFoundError.new(cname, ffi_libraries) if address.nil? || address.null? if type.is_a?(Class) && type < FFI::Struct # If it is a global struct, just attach directly to the pointer s = s = type.new(address) # Assigning twice to suppress unused variable warning self.module_eval <<-code, __FILE__, __LINE__ @@ffi_gvar_#{mname} = s def self.#{mname} @@ffi_gvar_#{mname} end code else sc = Class.new(FFI::Struct) sc.layout :gvar, find_type(type) s = sc.new(address) # # Attach to this module as mname/mname= # self.module_eval <<-code, __FILE__, __LINE__ @@ffi_gvar_#{mname} = s def self.#{mname} @@ffi_gvar_#{mname}[:gvar] end def self.#{mname}=(value) @@ffi_gvar_#{mname}[:gvar] = value end code end address end # @overload callback(name, params, ret) # @param name callback name to add to type map # @param [Array] params array of parameters' types # @param [DataConverter, Struct, Symbol, Type] ret callback return type # @overload callback(params, ret) # @param [Array] params array of parameters' types # @param [DataConverter, Struct, Symbol, Type] ret callback return type # @return [FFI::CallbackInfo] def callback(*args) raise ArgumentError, "wrong number of arguments" if args.length < 2 || args.length > 3 name, params, ret = if args.length == 3 args else [ nil, args[0], args[1] ] end native_params = params.map { |e| find_type(e) } raise ArgumentError, "callbacks cannot have variadic parameters" if native_params.include?(FFI::Type::VARARGS) options = Hash.new options[:convention] = ffi_convention options[:enums] = @ffi_enums if defined?(@ffi_enums) cb = FFI::CallbackInfo.new(find_type(ret), native_params, options) # Add to the symbol -> type map (unless there was no name) unless name.nil? typedef cb, name end cb end # Register or get an already registered type definition. # # To register a new type definition, +old+ should be a {FFI::Type}. +add+ # is in this case the type definition. # # If +old+ is a {DataConverter}, a {Type::Mapped} is returned. # # If +old+ is +:enum+ # * and +add+ is an +Array+, a call to {#enum} is made with +add+ as single parameter; # * in others cases, +info+ is used to create a named enum. # # If +old+ is a key for type map, #typedef get +old+ type definition. # # @param [DataConverter, Symbol, Type] old # @param [Symbol] add # @param [Symbol] info # @return [FFI::Enum, FFI::Type] def typedef(old, add, info=nil) @ffi_typedefs = Hash.new unless defined?(@ffi_typedefs) @ffi_typedefs[add] = if old.kind_of?(FFI::Type) old elsif @ffi_typedefs.has_key?(old) @ffi_typedefs[old] elsif old.is_a?(DataConverter) FFI::Type::Mapped.new(old) elsif old == :enum if add.kind_of?(Array) self.enum(add) else self.enum(info, add) end else FFI.find_type(old) end end private # Generic enum builder # @param [Class] klass can be one of FFI::Enum or FFI::Bitmask # @param args (see #enum or #bitmask) def generic_enum(klass, *args) native_type = args.first.kind_of?(FFI::Type) ? args.shift : nil name, values = if args[0].kind_of?(Symbol) && args[1].kind_of?(Array) [ args[0], args[1] ] elsif args[0].kind_of?(Array) [ nil, args[0] ] else [ nil, args ] end @ffi_enums = FFI::Enums.new unless defined?(@ffi_enums) @ffi_enums << (e = native_type ? klass.new(native_type, values, name) : klass.new(values, name)) # If called with a name, add a typedef alias typedef(e, name) if name e end public # @overload enum(name, values) # Create a named enum. # @example # enum :foo, [:zero, :one, :two] # named enum # @param [Symbol] name name for new enum # @param [Array] values values for enum # @overload enum(*args) # Create an unnamed enum. # @example # enum :zero, :one, :two # unnamed enum # @param args values for enum # @overload enum(values) # Create an unnamed enum. # @example # enum [:zero, :one, :two] # unnamed enum, equivalent to above example # @param [Array] values values for enum # @overload enum(native_type, name, values) # Create a named enum and specify the native type. # @example # enum FFI::Type::UINT64, :foo, [:zero, :one, :two] # named enum # @param [FFI::Type] native_type native type for new enum # @param [Symbol] name name for new enum # @param [Array] values values for enum # @overload enum(native_type, *args) # Create an unnamed enum and specify the native type. # @example # enum FFI::Type::UINT64, :zero, :one, :two # unnamed enum # @param [FFI::Type] native_type native type for new enum # @param args values for enum # @overload enum(native_type, values) # Create an unnamed enum and specify the native type. # @example # enum Type::UINT64, [:zero, :one, :two] # unnamed enum, equivalent to above example # @param [FFI::Type] native_type native type for new enum # @param [Array] values values for enum # @return [FFI::Enum] # Create a new {FFI::Enum}. def enum(*args) generic_enum(FFI::Enum, *args) end # @overload bitmask(name, values) # Create a named bitmask # @example # bitmask :foo, [:red, :green, :blue] # bits 0,1,2 are used # bitmask :foo, [:red, :green, 5, :blue] # bits 0,5,6 are used # @param [Symbol] name for new bitmask # @param [Array<Symbol, Integer>] values for new bitmask # @overload bitmask(*args) # Create an unamed bitmask # @example # bm = bitmask :red, :green, :blue # bits 0,1,2 are used # bm = bitmask :red, :green, 5, blue # bits 0,5,6 are used # @param [Symbol, Integer] args values for new bitmask # @overload bitmask(values) # Create an unamed bitmask # @example # bm = bitmask [:red, :green, :blue] # bits 0,1,2 are used # bm = bitmask [:red, :green, 5, blue] # bits 0,5,6 are used # @param [Array<Symbol, Integer>] values for new bitmask # @overload bitmask(native_type, name, values) # Create a named enum and specify the native type. # @example # bitmask FFI::Type::UINT64, :foo, [:red, :green, :blue] # @param [FFI::Type] native_type native type for new bitmask # @param [Symbol] name for new bitmask # @param [Array<Symbol, Integer>] values for new bitmask # @overload bitmask(native_type, *args) # @example # bitmask FFI::Type::UINT64, :red, :green, :blue # @param [FFI::Type] native_type native type for new bitmask # @param [Symbol, Integer] args values for new bitmask # @overload bitmask(native_type, values) # Create a named enum and specify the native type. # @example # bitmask FFI::Type::UINT64, [:red, :green, :blue] # @param [FFI::Type] native_type native type for new bitmask # @param [Array<Symbol, Integer>] values for new bitmask # @return [FFI::Bitmask] # Create a new FFI::Bitmask def bitmask(*args) generic_enum(FFI::Bitmask, *args) end # @param name # @return [FFI::Enum] # Find an enum by name. def enum_type(name) @ffi_enums.find(name) if defined?(@ffi_enums) end # @param symbol # @return [FFI::Enum] # Find an enum by a symbol it contains. def enum_value(symbol) @ffi_enums.__map_symbol(symbol) end # @param [DataConverter, Type, Struct, Symbol] t type to find # @return [Type] # Find a type definition. def find_type(t) if t.kind_of?(Type) t elsif defined?(@ffi_typedefs) && @ffi_typedefs.has_key?(t) @ffi_typedefs[t] elsif t.is_a?(Class) && t < Struct Type::POINTER elsif t.is_a?(DataConverter) # Add a typedef so next time the converter is used, it hits the cache typedef Type::Mapped.new(t), t end || FFI.find_type(t) 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/ffi-1.9.25/lib/ffi/version.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/version.rb
module FFI VERSION = '1.9.25' 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/ffi-1.9.25/lib/ffi/autopointer.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/autopointer.rb
# # Copyright (C) 2008-2010 Wayne Meissner # Copyright (C) 2008 Mike Dalessio # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module FFI class AutoPointer < Pointer extend DataConverter # @overload initialize(pointer, method) # @param pointer [Pointer] # @param method [Method] # @return [self] # The passed Method will be invoked at GC time. # @overload initialize(pointer, proc) # @param pointer [Pointer] # @return [self] # The passed Proc will be invoked at GC time (SEE WARNING BELOW!) # @note WARNING: passing a proc _may_ cause your pointer to never be # GC'd, unless you're careful to avoid trapping a reference to the # pointer in the proc. See the test specs for examples. # @overload initialize(pointer) { |p| ... } # @param pointer [Pointer] # @yieldparam [Pointer] p +pointer+ passed to the block # @return [self] # The passed block will be invoked at GC time. # @note # WARNING: passing a block will cause your pointer to never be GC'd. # This is bad. # @overload initialize(pointer) # @param pointer [Pointer] # @return [self] # The pointer's release() class method will be invoked at GC time. # # @note The safest, and therefore preferred, calling # idiom is to pass a Method as the second parameter. Example usage: # # class PointerHelper # def self.release(pointer) # ... # end # end # # p = AutoPointer.new(other_pointer, PointerHelper.method(:release)) # # The above code will cause PointerHelper#release to be invoked at GC time. # # @note # The last calling idiom (only one parameter) is generally only # going to be useful if you subclass {AutoPointer}, and override # #release, which by default does nothing. def initialize(ptr, proc=nil, &block) super(ptr.type_size, ptr) raise TypeError, "Invalid pointer" if ptr.nil? || !ptr.kind_of?(Pointer) \ || ptr.kind_of?(MemoryPointer) || ptr.kind_of?(AutoPointer) @releaser = if proc if not proc.respond_to?(:call) raise RuntimeError.new("proc must be callable") end CallableReleaser.new(ptr, proc) else if not self.class.respond_to?(:release) raise RuntimeError.new("no release method defined") end DefaultReleaser.new(ptr, self.class) end ObjectSpace.define_finalizer(self, @releaser) self end # @return [nil] # Free the pointer. def free @releaser.free end # @param [Boolean] autorelease # @return [Boolean] +autorelease+ # Set +autorelease+ property. See {Pointer Autorelease section at Pointer}. def autorelease=(autorelease) @releaser.autorelease=(autorelease) end # @return [Boolean] +autorelease+ # Get +autorelease+ property. See {Pointer Autorelease section at Pointer}. def autorelease? @releaser.autorelease end # @abstract Base class for {AutoPointer}'s releasers. # # All subclasses of Releaser should define a +#release(ptr)+ method. # A releaser is an object in charge of release an {AutoPointer}. class Releaser attr_accessor :autorelease # @param [Pointer] ptr # @param [#call] proc # @return [nil] # A new instance of Releaser. def initialize(ptr, proc) @ptr = ptr @proc = proc @autorelease = true end # @return [nil] # Free pointer. def free if @ptr release(@ptr) @autorelease = false @ptr = nil @proc = nil end end # @param args # Release pointer if +autorelease+ is set. def call(*args) release(@ptr) if @autorelease && @ptr end end # DefaultReleaser is a {Releaser} used when an {AutoPointer} is defined # without Proc or Method. In this case, the pointer to release must be of # a class derived from AutoPointer with a {release} class method. class DefaultReleaser < Releaser # @param [Pointer] ptr # @return [nil] # Release +ptr+ using the {release} class method of its class. def release(ptr) @proc.release(ptr) end end # CallableReleaser is a {Releaser} used when an {AutoPointer} is defined with a # Proc or a Method. class CallableReleaser < Releaser # Release +ptr+ by using Proc or Method defined at +ptr+ # {AutoPointer#initialize initialization}. # # @param [Pointer] ptr # @return [nil] def release(ptr) @proc.call(ptr) end end # Return native type of AutoPointer. # # Override {DataConverter#native_type}. # @return [Type::POINTER] # @raise {RuntimeError} if class does not implement a +#release+ method def self.native_type if not self.respond_to?(:release) raise RuntimeError.new("no release method defined for #{self.inspect}") end Type::POINTER end # Create a new AutoPointer. # # Override {DataConverter#from_native}. # @overload self.from_native(ptr, ctx) # @param [Pointer] ptr # @param ctx not used. Please set +nil+. # @return [AutoPointer] def self.from_native(val, ctx) self.new(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/ffi-1.9.25/lib/ffi/struct.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/struct.rb
# # Copyright (C) 2008-2010 Wayne Meissner # Copyright (C) 2008, 2009 Andrea Fazzi # Copyright (C) 2008, 2009 Luc Heinrich # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # require 'ffi/platform' require 'ffi/struct_layout_builder' module FFI class StructLayout # @return [Array<Array(Symbol, Numeric)> # Get an array of tuples (field name, offset of the field). def offsets members.map { |m| [ m, self[m].offset ] } end # @return [Numeric] # Get the offset of a field. def offset_of(field_name) self[field_name].offset end # An enum {Field} in a {StructLayout}. class Enum < Field # @param [AbstractMemory] ptr pointer on a {Struct} # @return [Object] # Get an object of type {#type} from memory pointed by +ptr+. def get(ptr) type.find(ptr.get_int(offset)) end # @param [AbstractMemory] ptr pointer on a {Struct} # @param value # @return [nil] # Set +value+ into memory pointed by +ptr+. def put(ptr, value) ptr.put_int(offset, type.find(value)) end end class InnerStruct < Field def get(ptr) type.struct_class.new(ptr.slice(self.offset, self.size)) end def put(ptr, value) raise TypeError, "wrong value type (expected #{type.struct_class})" unless value.is_a?(type.struct_class) ptr.slice(self.offset, self.size).__copy_from__(value.pointer, self.size) end end class Mapped < Field def initialize(name, offset, type, orig_field) super(name, offset, type) @orig_field = orig_field end def get(ptr) type.from_native(@orig_field.get(ptr), nil) end def put(ptr, value) @orig_field.put(ptr, type.to_native(value, nil)) end end end class Struct # Get struct size # @return [Numeric] def size self.class.size end # @return [Fixnum] Struct alignment def alignment self.class.alignment end alias_method :align, :alignment # (see FFI::StructLayout#offset_of) def offset_of(name) self.class.offset_of(name) end # (see FFI::StructLayout#members) def members self.class.members end # @return [Array] # Get array of values from Struct fields. def values members.map { |m| self[m] } end # (see FFI::StructLayout#offsets) def offsets self.class.offsets end # Clear the struct content. # @return [self] def clear pointer.clear self end # Get {Pointer} to struct content. # @return [AbstractMemory] def to_ptr pointer end # Get struct size # @return [Numeric] def self.size defined?(@layout) ? @layout.size : defined?(@size) ? @size : 0 end # set struct size # @param [Numeric] size # @return [size] def self.size=(size) raise ArgumentError, "Size already set" if defined?(@size) || defined?(@layout) @size = size end # @return (see Struct#alignment) def self.alignment @layout.alignment end # (see FFI::Type#members) def self.members @layout.members end # (see FFI::StructLayout#offsets) def self.offsets @layout.offsets end # (see FFI::StructLayout#offset_of) def self.offset_of(name) @layout.offset_of(name) end def self.in ptr(:in) end def self.out ptr(:out) end def self.ptr(flags = :inout) @ref_data_type ||= Type::Mapped.new(StructByReference.new(self)) end def self.val @val_data_type ||= StructByValue.new(self) end def self.by_value self.val end def self.by_ref(flags = :inout) self.ptr(flags) end class ManagedStructConverter < StructByReference # @param [Struct] struct_class def initialize(struct_class) super(struct_class) raise NoMethodError, "release() not implemented for class #{struct_class}" unless struct_class.respond_to? :release @method = struct_class.method(:release) end # @param [Pointer] ptr # @param [nil] ctx # @return [Struct] def from_native(ptr, ctx) struct_class.new(AutoPointer.new(ptr, @method)) end end def self.auto_ptr @managed_type ||= Type::Mapped.new(ManagedStructConverter.new(self)) end class << self public # @return [StructLayout] # @overload layout # @return [StructLayout] # Get struct layout. # @overload layout(*spec) # @param [Array<Symbol, Integer>,Array(Hash)] spec # @return [StructLayout] # Create struct layout from +spec+. # @example Creating a layout from an array +spec+ # class MyStruct < Struct # layout :field1, :int, # :field2, :pointer, # :field3, :string # end # @example Creating a layout from an array +spec+ with offset # class MyStructWithOffset < Struct # layout :field1, :int, # :field2, :pointer, 6, # set offset to 6 for this field # :field3, :string # end # @example Creating a layout from a hash +spec+ (Ruby 1.9 only) # class MyStructFromHash < Struct # layout :field1 => :int, # :field2 => :pointer, # :field3 => :string # end # @example Creating a layout with pointers to functions # class MyFunctionTable < Struct # layout :function1, callback([:int, :int], :int), # :function2, callback([:pointer], :void), # :field3, :string # end # @note Creating a layout from a hash +spec+ is supported only for Ruby 1.9. def layout(*spec) #raise RuntimeError, "struct layout already defined for #{self.inspect}" if defined?(@layout) return @layout if spec.size == 0 builder = StructLayoutBuilder.new builder.union = self < Union builder.packed = @packed if defined?(@packed) builder.alignment = @min_alignment if defined?(@min_alignment) if spec[0].kind_of?(Hash) hash_layout(builder, spec) else array_layout(builder, spec) end builder.size = @size if defined?(@size) && @size > builder.size cspec = builder.build @layout = cspec unless self == Struct @size = cspec.size return cspec end protected def callback(params, ret) mod = enclosing_module FFI::CallbackInfo.new(find_type(ret, mod), params.map { |e| find_type(e, mod) }) end def packed(packed = 1) @packed = packed end alias :pack :packed def aligned(alignment = 1) @min_alignment = alignment end alias :align :aligned def enclosing_module begin mod = self.name.split("::")[0..-2].inject(Object) { |obj, c| obj.const_get(c) } (mod < FFI::Library || mod < FFI::Struct || mod.respond_to?(:find_type)) ? mod : nil rescue Exception nil end end def find_field_type(type, mod = enclosing_module) if type.kind_of?(Class) && type < Struct FFI::Type::Struct.new(type) elsif type.kind_of?(Class) && type < FFI::StructLayout::Field type elsif type.kind_of?(::Array) FFI::Type::Array.new(find_field_type(type[0]), type[1]) else find_type(type, mod) end end def find_type(type, mod = enclosing_module) if mod mod.find_type(type) end || FFI.find_type(type) end private # @param [StructLayoutBuilder] builder # @param [Hash] spec # @return [builder] # Add hash +spec+ to +builder+. def hash_layout(builder, spec) spec[0].each do |name, type| builder.add name, find_field_type(type), nil end end # @param [StructLayoutBuilder] builder # @param [Array<Symbol, Integer>] spec # @return [builder] # Add array +spec+ to +builder+. def array_layout(builder, spec) i = 0 while i < spec.size name, type = spec[i, 2] i += 2 # If the next param is a Integer, it specifies the offset if spec[i].kind_of?(Integer) offset = spec[i] i += 1 else offset = nil end builder.add name, find_field_type(type), offset 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/ffi-1.9.25/lib/ffi/struct_layout_builder.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/struct_layout_builder.rb
# # Copyright (C) 2008-2010 Wayne Meissner # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # module FFI # Build a {StructLayout struct layout}. class StructLayoutBuilder attr_reader :size attr_reader :alignment def initialize @size = 0 @alignment = 1 @min_alignment = 1 @packed = false @union = false @fields = Array.new end # Set size attribute with +size+ only if +size+ is greater than attribute value. # @param [Numeric] size def size=(size) @size = size if size > @size end # Set alignment attribute with +align+ only if it is greater than attribute value. # @param [Numeric] align def alignment=(align) @alignment = align if align > @alignment @min_alignment = align end # Set union attribute. # Set to +true+ to build a {Union} instead of a {Struct}. # @param [Boolean] is_union # @return [is_union] def union=(is_union) @union = is_union end # Building a {Union} or a {Struct} ? # # @return [Boolean] # def union? @union end # Set packed attribute # @overload packed=(packed) Set alignment and packed attributes to # +packed+. # # @param [Fixnum] packed # # @return [packed] # @overload packed=(packed) Set packed attribute. # @param packed # # @return [0,1] # def packed=(packed) if packed.is_a?(0.class) @alignment = packed @packed = packed else @packed = packed ? 1 : 0 end end # List of number types NUMBER_TYPES = [ Type::INT8, Type::UINT8, Type::INT16, Type::UINT16, Type::INT32, Type::UINT32, Type::LONG, Type::ULONG, Type::INT64, Type::UINT64, Type::FLOAT32, Type::FLOAT64, Type::LONGDOUBLE, Type::BOOL, ] # @param [String, Symbol] name name of the field # @param [Array, DataConverter, Struct, StructLayout::Field, Symbol, Type] type type of the field # @param [Numeric, nil] offset # @return [self] # Add a field to the builder. # @note Setting +offset+ to +nil+ or +-1+ is equivalent to +0+. def add(name, type, offset = nil) if offset.nil? || offset == -1 offset = @union ? 0 : align(@size, @packed ? [ @packed, type.alignment ].min : [ @min_alignment, type.alignment ].max) end # # If a FFI::Type type was passed in as the field arg, try and convert to a StructLayout::Field instance # field = type.is_a?(StructLayout::Field) ? type : field_for_type(name, offset, type) @fields << field @alignment = [ @alignment, field.alignment ].max unless @packed @size = [ @size, field.size + (@union ? 0 : field.offset) ].max return self end # @param (see #add) # @return (see #add) # Same as {#add}. # @see #add def add_field(name, type, offset = nil) add(name, type, offset) end # @param (see #add) # @return (see #add) # Add a struct as a field to the builder. def add_struct(name, type, offset = nil) add(name, Type::Struct.new(type), offset) end # @param name (see #add) # @param type (see #add) # @param [Numeric] count array length # @param offset (see #add) # @return (see #add) # Add an array as a field to the builder. def add_array(name, type, count, offset = nil) add(name, Type::Array.new(type, count), offset) end # @return [StructLayout] # Build and return the struct layout. def build # Add tail padding if the struct is not packed size = @packed ? @size : align(@size, @alignment) layout = StructLayout.new(@fields, size, @alignment) layout.__union! if @union layout end private # @param [Numeric] offset # @param [Numeric] align # @return [Numeric] def align(offset, align) align + ((offset - 1) & ~(align - 1)); end # @param (see #add) # @return [StructLayout::Field] def field_for_type(name, offset, type) field_class = case when type.is_a?(Type::Function) StructLayout::Function when type.is_a?(Type::Struct) StructLayout::InnerStruct when type.is_a?(Type::Array) StructLayout::Array when type.is_a?(FFI::Enum) StructLayout::Enum when NUMBER_TYPES.include?(type) StructLayout::Number when type == Type::POINTER StructLayout::Pointer when type == Type::STRING StructLayout::String when type.is_a?(Class) && type < StructLayout::Field type when type.is_a?(DataConverter) return StructLayout::Mapped.new(name, offset, Type::Mapped.new(type), field_for_type(name, offset, type.native_type)) when type.is_a?(Type::Mapped) return StructLayout::Mapped.new(name, offset, type, field_for_type(name, offset, type.native_type)) else raise TypeError, "invalid struct field type #{type.inspect}" end field_class.new(name, offset, type) 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/ffi-1.9.25/lib/ffi/pointer.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/pointer.rb
# # Copyright (C) 2008, 2009 Wayne Meissner # Copyright (c) 2007, 2008 Evan Phoenix # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # require 'ffi/platform' module FFI class Pointer # Pointer size SIZE = Platform::ADDRESS_SIZE / 8 # Return the size of a pointer on the current platform, in bytes # @return [Numeric] def self.size SIZE end # @param [nil,Numeric] len length of string to return # @return [String] # Read pointer's contents as a string, or the first +len+ bytes of the # equivalent string if +len+ is not +nil+. def read_string(len=nil) if len return '' if len == 0 get_bytes(0, len) else get_string(0) end end # @param [Numeric] len length of string to return # @return [String] # Read the first +len+ bytes of pointer's contents as a string. # # Same as: # ptr.read_string(len) # with len not nil def read_string_length(len) get_bytes(0, len) end # @return [String] # Read pointer's contents as a string. # # Same as: # ptr.read_string # with no len def read_string_to_null get_string(0) end # @param [String] str string to write # @param [Numeric] len length of string to return # @return [self] # Write +len+ first bytes of +str+ in pointer's contents. # # Same as: # ptr.write_string(str, len) # with len not nil def write_string_length(str, len) put_bytes(0, str, 0, len) end # @param [String] str string to write # @param [Numeric] len length of string to return # @return [self] # Write +str+ in pointer's contents, or first +len+ bytes if # +len+ is not +nil+. def write_string(str, len=nil) len = str.bytesize unless len # Write the string data without NUL termination put_bytes(0, str, 0, len) end # @param [Type] type type of data to read from pointer's contents # @param [Symbol] reader method to send to +self+ to read +type+ # @param [Numeric] length # @return [Array] # Read an array of +type+ of length +length+. # @example # ptr.read_array_of_type(TYPE_UINT8, :get_uint8, 4) # -> [1, 2, 3, 4] def read_array_of_type(type, reader, length) ary = [] size = FFI.type_size(type) tmp = self length.times { |j| ary << tmp.send(reader) tmp += size unless j == length-1 # avoid OOB } ary end # @param [Type] type type of data to write to pointer's contents # @param [Symbol] writer method to send to +self+ to write +type+ # @param [Array] ary # @return [self] # Write +ary+ in pointer's contents as +type+. # @example # ptr.write_array_of_type(TYPE_UINT8, :put_uint8, [1, 2, 3 ,4]) def write_array_of_type(type, writer, ary) size = FFI.type_size(type) tmp = self ary.each_with_index {|i, j| tmp.send(writer, i) tmp += size unless j == ary.length-1 # avoid OOB } self end # @return [self] def to_ptr self end # @param [Symbol,Type] type of data to read # @return [Object] # Read pointer's contents as +type+ # # Same as: # ptr.get(type, 0) def read(type) get(type, 0) end # @param [Symbol,Type] type of data to read # @param [Object] value to write # @return [nil] # Write +value+ of type +type+ to pointer's content # # Same as: # ptr.put(type, 0) def write(type, value) put(type, 0, 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/ffi-1.9.25/lib/ffi/union.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/union.rb
# # Copyright (C) 2009 Andrea Fazzi <andrea.fazzi@alcacoop.it> # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # require 'ffi/struct' module FFI class Union < FFI::Struct def self.builder b = StructLayoutBuilder.new b.union = true b 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/ffi-1.9.25/lib/ffi/ffi.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/ffi.rb
# # Copyright (C) 2008-2010 JRuby project # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. require 'ffi/platform' require 'ffi/types' require 'ffi/library' require 'ffi/errno' require 'ffi/pointer' require 'ffi/memorypointer' require 'ffi/struct' require 'ffi/union' require 'ffi/managedstruct' require 'ffi/callback' require 'ffi/io' require 'ffi/autopointer' require 'ffi/variadic' require 'ffi/enum'
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/ffi-1.9.25/lib/ffi/types.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/types.rb
# # Copyright (C) 2008-2010 Wayne Meissner # Copyright (c) 2007, 2008 Evan Phoenix # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # see {file:README} module FFI # @param [Type, DataConverter, Symbol] old type definition used by {FFI.find_type} # @param [Symbol] add new type definition's name to add # @return [Type] # Add a definition type to type definitions. def self.typedef(old, add) TypeDefs[add] = self.find_type(old) end # (see FFI.typedef) def self.add_typedef(old, add) typedef old, add end # @param [Type, DataConverter, Symbol] name # @param [Hash] type_map if nil, {FFI::TypeDefs} is used # @return [Type] # Find a type in +type_map+ ({FFI::TypeDefs}, by default) from # a type objet, a type name (symbol). If +name+ is a {DataConverter}, # a new {Type::Mapped} is created. def self.find_type(name, type_map = nil) if name.is_a?(Type) name elsif type_map && type_map.has_key?(name) type_map[name] elsif TypeDefs.has_key?(name) TypeDefs[name] elsif name.is_a?(DataConverter) (type_map || TypeDefs)[name] = Type::Mapped.new(name) else raise TypeError, "unable to resolve type '#{name}'" end end # List of type definitions TypeDefs.merge!({ # The C void type; only useful for function return types :void => Type::VOID, # C boolean type :bool => Type::BOOL, # C nul-terminated string :string => Type::STRING, # C signed char :char => Type::CHAR, # C unsigned char :uchar => Type::UCHAR, # C signed short :short => Type::SHORT, # C unsigned short :ushort => Type::USHORT, # C signed int :int => Type::INT, # C unsigned int :uint => Type::UINT, # C signed long :long => Type::LONG, # C unsigned long :ulong => Type::ULONG, # C signed long long integer :long_long => Type::LONG_LONG, # C unsigned long long integer :ulong_long => Type::ULONG_LONG, # C single precision float :float => Type::FLOAT, # C double precision float :double => Type::DOUBLE, # C long double :long_double => Type::LONGDOUBLE, # Native memory address :pointer => Type::POINTER, # 8 bit signed integer :int8 => Type::INT8, # 8 bit unsigned integer :uint8 => Type::UINT8, # 16 bit signed integer :int16 => Type::INT16, # 16 bit unsigned integer :uint16 => Type::UINT16, # 32 bit signed integer :int32 => Type::INT32, # 32 bit unsigned integer :uint32 => Type::UINT32, # 64 bit signed integer :int64 => Type::INT64, # 64 bit unsigned integer :uint64 => Type::UINT64, :buffer_in => Type::BUFFER_IN, :buffer_out => Type::BUFFER_OUT, :buffer_inout => Type::BUFFER_INOUT, # Used in function prototypes to indicate the arguments are variadic :varargs => Type::VARARGS, }) # This will convert a pointer to a Ruby string (just like `:string`), but # also allow to work with the pointer itself. This is useful when you want # a Ruby string already containing a copy of the data, but also the pointer # to the data for you to do something with it, like freeing it, in case the # library handed the memory to off to the caller (Ruby-FFI). # # It's {typedef}'d as +:strptr+. class StrPtrConverter extend DataConverter native_type Type::POINTER # @param [Pointer] val # @param ctx not used # @return [Array(String, Pointer)] # Returns a [ String, Pointer ] tuple so the C memory for the string can be freed def self.from_native(val, ctx) [ val.null? ? nil : val.get_string(0), val ] end end typedef(StrPtrConverter, :strptr) # @param type +type+ is an instance of class accepted by {FFI.find_type} # @return [Numeric] # Get +type+ size, in bytes. def self.type_size(type) find_type(type).size end # Load all the platform dependent types begin File.open(File.join(Platform::CONF_DIR, 'types.conf'), "r") do |f| prefix = "rbx.platform.typedef." f.each_line { |line| if line.index(prefix) == 0 new_type, orig_type = line.chomp.slice(prefix.length..-1).split(/\s*=\s*/) typedef(orig_type.to_sym, new_type.to_sym) end } end typedef :pointer, :caddr_t rescue Errno::ENOENT 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/ffi-1.9.25/lib/ffi/enum.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/enum.rb
# # Copyright (C) 2009, 2010 Wayne Meissner # Copyright (C) 2009 Luc Heinrich # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # module FFI # An instance of this class permits to manage {Enum}s. In fact, Enums is a collection of {Enum}s. class Enums # @return [nil] def initialize @all_enums = Array.new @tagged_enums = Hash.new @symbol_map = Hash.new end # @param [Enum] enum # Add an {Enum} to the collection. def <<(enum) @all_enums << enum @tagged_enums[enum.tag] = enum unless enum.tag.nil? @symbol_map.merge!(enum.symbol_map) end # @param query enum tag or part of an enum name # @return [Enum] # Find a {Enum} in collection. def find(query) if @tagged_enums.has_key?(query) @tagged_enums[query] else @all_enums.detect { |enum| enum.symbols.include?(query) } end end # @param symbol a symbol to find in merge symbol maps of all enums. # @return a symbol def __map_symbol(symbol) @symbol_map[symbol] end end # Represents a C enum. # # For a C enum: # enum fruits { # apple, # banana, # orange, # pineapple # }; # are defined this vocabulary: # * a _symbol_ is a word from the enumeration (ie. _apple_, by example); # * a _value_ is the value of a symbol in the enumeration (by example, apple has value _0_ and banana _1_). class Enum include DataConverter attr_reader :tag attr_reader :native_type # @overload initialize(info, tag=nil) # @param [nil, Enumerable] info # @param [nil, Symbol] tag enum tag # @overload initialize(native_type, info, tag=nil) # @param [FFI::Type] native_type Native type for new Enum # @param [nil, Enumerable] info symbols and values for new Enum # @param [nil, Symbol] tag name of new Enum def initialize(*args) @native_type = args.first.kind_of?(FFI::Type) ? args.shift : Type::INT info, @tag = *args @kv_map = Hash.new unless info.nil? last_cst = nil value = 0 info.each do |i| case i when Symbol raise ArgumentError, "duplicate enum key" if @kv_map.has_key?(i) @kv_map[i] = value last_cst = i value += 1 when Integer @kv_map[last_cst] = i value = i+1 end end end @vk_map = @kv_map.invert end # @return [Array] enum symbol names def symbols @kv_map.keys end # Get a symbol or a value from the enum. # @overload [](query) # Get enum value from symbol. # @param [Symbol] query # @return [Integer] # @overload [](query) # Get enum symbol from value. # @param [Integer] query # @return [Symbol] def [](query) case query when Symbol @kv_map[query] when Integer @vk_map[query] end end alias find [] # Get the symbol map. # @return [Hash] def symbol_map @kv_map end alias to_h symbol_map alias to_hash symbol_map # @param [Symbol, Integer, #to_int] val # @param ctx unused # @return [Integer] value of a enum symbol def to_native(val, ctx) @kv_map[val] || if val.is_a?(Integer) val elsif val.respond_to?(:to_int) val.to_int else raise ArgumentError, "invalid enum value, #{val.inspect}" end end # @param val # @return symbol name if it exists for +val+. def from_native(val, ctx) @vk_map[val] || val end end # Represents a C enum whose values are power of 2 # # @example # enum { # red = (1<<0), # green = (1<<1), # blue = (1<<2) # } # # Contrary to classical enums, bitmask values are usually combined # when used. class Bitmask < Enum # @overload initialize(info, tag=nil) # @param [nil, Enumerable] info symbols and bit rank for new Bitmask # @param [nil, Symbol] tag name of new Bitmask # @overload initialize(native_type, info, tag=nil) # @param [FFI::Type] native_type Native type for new Bitmask # @param [nil, Enumerable] info symbols and bit rank for new Bitmask # @param [nil, Symbol] tag name of new Bitmask def initialize(*args) @native_type = args.first.kind_of?(FFI::Type) ? args.shift : Type::INT info, @tag = *args @kv_map = Hash.new unless info.nil? last_cst = nil value = 0 info.each do |i| case i when Symbol raise ArgumentError, "duplicate bitmask key" if @kv_map.has_key?(i) @kv_map[i] = 1 << value last_cst = i value += 1 when Integer raise ArgumentError, "bitmask index should be positive" if i<0 @kv_map[last_cst] = 1 << i value = i+1 end end end @vk_map = @kv_map.invert end # Get a symbol list or a value from the bitmask # @overload [](*query) # Get bitmask value from symbol list # @param [Symbol] query # @return [Integer] # @overload [](query) # Get bitmaks value from symbol array # @param [Array<Symbol>] query # @return [Integer] # @overload [](*query) # Get a list of bitmask symbols corresponding to # the or reduction of a list of integer # @param [Integer] query # @return [Array<Symbol>] # @overload [](query) # Get a list of bitmask symbols corresponding to # the or reduction of a list of integer # @param [Array<Integer>] query # @return [Array<Symbol>] def [](*query) flat_query = query.flatten raise ArgumentError, "query should be homogeneous, #{query.inspect}" unless flat_query.all? { |o| o.is_a?(Symbol) } || flat_query.all? { |o| o.is_a?(Integer) || o.respond_to?(:to_int) } case flat_query[0] when Symbol flat_query.inject(0) do |val, o| v = @kv_map[o] if v then val |= v else val end end when Integer, ->(o) { o.respond_to?(:to_int) } val = flat_query.inject(0) { |mask, o| mask |= o.to_int } @kv_map.select { |_, v| v & val != 0 }.keys end end # Get the native value of a bitmask # @overload to_native(query, ctx) # @param [Symbol, Integer, #to_int] query # @param ctx unused # @return [Integer] value of a bitmask # @overload to_native(query, ctx) # @param [Array<Symbol, Integer, #to_int>] query # @param ctx unused # @return [Integer] value of a bitmask def to_native(query, ctx) return 0 if query.nil? flat_query = [query].flatten flat_query.inject(0) do |val, o| case o when Symbol v = @kv_map[o] raise ArgumentError, "invalid bitmask value, #{o.inspect}" unless v val |= v when Integer val |= o when ->(obj) { obj.respond_to?(:to_int) } val |= o.to_int else raise ArgumentError, "invalid bitmask value, #{o.inspect}" end end end # @param [Integer] val # @param ctx unused # @return [Array<Symbol, Integer>] list of symbol names corresponding to val, plus an optional remainder if some bits don't match any constant def from_native(val, ctx) list = @kv_map.select { |_, v| v & val != 0 }.keys # If there are unmatch flags, # return them in an integer, # else information can be lost. # Similar to Enum behavior. remainder = val ^ list.inject(0) do |tmp, o| v = @kv_map[o] if v then tmp |= v else tmp end end list.push remainder unless remainder == 0 return list 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/ffi-1.9.25/lib/ffi/memorypointer.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/memorypointer.rb
# This class is now implemented in C
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/ffi-1.9.25/lib/ffi/variadic.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/variadic.rb
# # Copyright (C) 2008, 2009 Wayne Meissner # Copyright (C) 2009 Luc Heinrich # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # module FFI class VariadicInvoker def init(arg_types, type_map) @fixed = Array.new @type_map = type_map arg_types.each_with_index do |type, i| @fixed << type unless type == Type::VARARGS end end def call(*args, &block) param_types = Array.new(@fixed) param_values = Array.new @fixed.each_with_index do |t, i| param_values << args[i] end i = @fixed.length while i < args.length param_types << FFI.find_type(args[i], @type_map) param_values << args[i + 1] i += 2 end invoke(param_types, param_values, &block) end # # Attach the invoker to module +mod+ as +mname+ # def attach(mod, mname) invoker = self params = "*args" call = "call" mod.module_eval <<-code @@#{mname} = invoker def self.#{mname}(#{params}) @@#{mname}.#{call}(#{params}) end def #{mname}(#{params}) @@#{mname}.#{call}(#{params}) end code invoker 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/ffi-1.9.25/lib/ffi/buffer.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/buffer.rb
# # All the code from this file is now implemented in C. This file remains # to satisfy any leftover require 'ffi/buffer' in user code #
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/ffi-1.9.25/lib/ffi/managedstruct.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/managedstruct.rb
# Copyright (C) 2008 Mike Dalessio # # This file is part of ruby-ffi. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Ruby FFI project nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module FFI # # FFI::ManagedStruct allows custom garbage-collection of your FFI::Structs. # # The typical use case would be when interacting with a library # that has a nontrivial memory management design, such as a linked # list or a binary tree. # # When the {Struct} instance is garbage collected, FFI::ManagedStruct will # invoke the class's release() method during object finalization. # # @example Example usage: # module MyLibrary # ffi_lib "libmylibrary" # attach_function :new_dlist, [], :pointer # attach_function :destroy_dlist, [:pointer], :void # end # # class DoublyLinkedList < FFI::ManagedStruct # @@@ # struct do |s| # s.name 'struct dlist' # s.include 'dlist.h' # s.field :head, :pointer # s.field :tail, :pointer # end # @@@ # # def self.release ptr # MyLibrary.destroy_dlist(ptr) # end # end # # begin # ptr = DoublyLinkedList.new(MyLibrary.new_dlist) # # do something with the list # end # # struct is out of scope, and will be GC'd using DoublyLinkedList#release # # class ManagedStruct < FFI::Struct # @overload initialize(pointer) # @param [Pointer] pointer # Create a new ManagedStruct which will invoke the class method #release on # @overload initialize # A new instance of FFI::ManagedStruct. def initialize(pointer=nil) raise NoMethodError, "release() not implemented for class #{self}" unless self.class.respond_to? :release raise ArgumentError, "Must supply a pointer to memory for the Struct" unless pointer super AutoPointer.new(pointer, self.class.method(:release)) 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/ffi-1.9.25/lib/ffi/tools/struct_generator.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/tools/struct_generator.rb
require 'tempfile' module FFI ## # Generates an FFI Struct layout. # # Given the @@@ portion in: # # module Zlib::ZStream < FFI::Struct # @@@ # name "struct z_stream_s" # include "zlib.h" # # field :next_in, :pointer # field :avail_in, :uint # field :total_in, :ulong # # # ... # @@@ # end # # StructGenerator will create the layout: # # layout :next_in, :pointer, 0, # :avail_in, :uint, 4, # :total_in, :ulong, 8, # # ... # # StructGenerator does its best to pad the layout it produces to preserve # line numbers. Place the struct definition as close to the top of the file # for best results. class StructGenerator @options = {} attr_accessor :size attr_reader :fields def initialize(name, options = {}) @name = name @struct_name = nil @includes = [] @fields = [] @found = false @size = nil if block_given? then yield self calculate self.class.options.merge(options) end end def self.options=(options) @options = options end def self.options @options end def calculate(options = {}) binary = File.join Dir.tmpdir, "rb_struct_gen_bin_#{Process.pid}" raise "struct name not set" if @struct_name.nil? Tempfile.open("#{@name}.struct_generator") do |f| f.puts "#include <stdio.h>" @includes.each do |inc| f.puts "#include <#{inc}>" end f.puts "#include <stddef.h>\n\n" f.puts "int main(int argc, char **argv)\n{" f.puts " #{@struct_name} s;" f.puts %[ printf("sizeof(#{@struct_name}) %u\\n", (unsigned int) sizeof(#{@struct_name}));] @fields.each do |field| f.puts <<-EOF printf("#{field.name} %u %u\\n", (unsigned int) offsetof(#{@struct_name}, #{field.name}), (unsigned int) sizeof(s.#{field.name})); EOF end f.puts "\n return 0;\n}" f.flush output = `gcc #{options[:cppflags]} #{options[:cflags]} -D_DARWIN_USE_64_BIT_INODE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -x c -Wall -Werror #{f.path} -o #{binary} 2>&1` unless $?.success? then @found = false output = output.split("\n").map { |l| "\t#{l}" }.join "\n" raise "Compilation error generating struct #{@name} (#{@struct_name}):\n#{output}" end end output = `#{binary}`.split "\n" File.unlink(binary + (FFI::Platform.windows? ? ".exe" : "")) sizeof = output.shift unless @size m = /\s*sizeof\([^)]+\) (\d+)/.match sizeof @size = m[1] end line_no = 0 output.each do |line| md = line.match(/.+ (\d+) (\d+)/) @fields[line_no].offset = md[1].to_i @fields[line_no].size = md[2].to_i line_no += 1 end @found = true end def field(name, type=nil) field = Field.new(name, type) @fields << field return field end def found? @found end def dump_config(io) io.puts "rbx.platform.#{@name}.sizeof = #{@size}" @fields.each { |field| io.puts field.to_config(@name) } end def generate_layout buf = "" @fields.each_with_index do |field, i| if buf.empty? buf << "layout :#{field.name}, :#{field.type}, #{field.offset}" else buf << " :#{field.name}, :#{field.type}, #{field.offset}" end if i < @fields.length - 1 buf << ",\n" end end buf end def get_field(name) @fields.find { |f| name == f.name } end def include(i) @includes << i end def name(n) @struct_name = n end end ## # A field in a Struct. class StructGenerator::Field attr_reader :name attr_reader :type attr_reader :offset attr_accessor :size def initialize(name, type) @name = name @type = type @offset = nil @size = nil end def offset=(o) @offset = o end def to_config(name) buf = [] buf << "rbx.platform.#{name}.#{@name}.offset = #{@offset}" buf << "rbx.platform.#{name}.#{@name}.size = #{@size}" buf << "rbx.platform.#{name}.#{@name}.type = #{@type}" if @type buf 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/ffi-1.9.25/lib/ffi/tools/types_generator.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/tools/types_generator.rb
require 'tempfile' module FFI # @private class TypesGenerator ## # Maps different C types to the C type representations we use TYPE_MAP = { "char" => :char, "signed char" => :char, "__signed char" => :char, "unsigned char" => :uchar, "short" => :short, "signed short" => :short, "signed short int" => :short, "unsigned short" => :ushort, "unsigned short int" => :ushort, "int" => :int, "signed int" => :int, "unsigned int" => :uint, "long" => :long, "long int" => :long, "signed long" => :long, "signed long int" => :long, "unsigned long" => :ulong, "unsigned long int" => :ulong, "long unsigned int" => :ulong, "long long" => :long_long, "long long int" => :long_long, "signed long long" => :long_long, "signed long long int" => :long_long, "unsigned long long" => :ulong_long, "unsigned long long int" => :ulong_long, "char *" => :string, "void *" => :pointer, } def self.generate(options = {}) typedefs = nil Tempfile.open 'ffi_types_generator' do |io| io.puts <<-C #include <sys/types.h> #if !(defined(WIN32)) #include <sys/socket.h> #include <sys/resource.h> #endif C io.close cc = ENV['CC'] || 'gcc' cmd = "#{cc} -E -x c #{options[:cppflags]} -D_DARWIN_USE_64_BIT_INODE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -c" if options[:input] typedefs = File.read(options[:input]) elsif options[:remote] typedefs = `ssh #{options[:remote]} #{cmd} - < #{io.path}` else typedefs = `#{cmd} #{io.path}` end end code = "" typedefs.each_line do |type| # We only care about single line typedef next unless type =~ /typedef/ # Ignore unions or structs next if type =~ /union|struct/ # strip off the starting typedef and ending ; type.gsub!(/^(.*typedef\s*)/, "") type.gsub!(/\s*;\s*$/, "") parts = type.split(/\s+/) def_type = parts.join(" ") # GCC does mapping with __attribute__ stuf, also see # http://hal.cs.berkeley.edu/cil/cil016.html section 16.2.7. Problem # with this is that the __attribute__ stuff can either occur before or # after the new type that is defined... if type =~ /__attribute__/ if parts.last =~ /__QI__|__HI__|__SI__|__DI__|__word__/ # In this case, the new type is BEFORE __attribute__ we need to # find the final_type as the type before the part that starts with # __attribute__ final_type = "" parts.each do |p| break if p =~ /__attribute__/ final_type = p end else final_type = parts.pop end def_type = case type when /__QI__/ then "char" when /__HI__/ then "short" when /__SI__/ then "int" when /__DI__/ then "long long" when /__word__/ then "long" else "int" end def_type = "unsigned #{def_type}" if type =~ /unsigned/ else final_type = parts.pop def_type = parts.join(" ") end if type = TYPE_MAP[def_type] code << "rbx.platform.typedef.#{final_type} = #{type}\n" TYPE_MAP[final_type] = TYPE_MAP[def_type] else # Fallback to an ordinary pointer if we don't know the type if def_type =~ /\*/ code << "rbx.platform.typedef.#{final_type} = pointer\n" TYPE_MAP[final_type] = :pointer end end end code 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/ffi-1.9.25/lib/ffi/tools/const_generator.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/tools/const_generator.rb
require 'tempfile' require 'open3' module FFI # ConstGenerator turns C constants into ruby values. # # @example a simple example for stdio # cg = FFI::ConstGenerator.new('stdio') do |gen| # gen.const(:SEEK_SET) # gen.const('SEEK_CUR') # gen.const('seek_end') # this constant does not exist # end # #calculate called automatically at the end of the block # # cg['SEEK_SET'] # => 0 # cg['SEEK_CUR'] # => 1 # cg['seek_end'] # => nil # cg.to_ruby # => "SEEK_SET = 0\nSEEK_CUR = 1\n# seek_end not available" class ConstGenerator @options = {} attr_reader :constants # Creates a new constant generator that uses +prefix+ as a name, and an # options hash. # # The only option is +:required+, which if set to +true+ raises an error if a # constant you have requested was not found. # # @param [#to_s] prefix # @param [Hash] options # @return # @option options [Boolean] :required # @overload initialize(prefix, options) # @overload initialize(prefix, options) { |gen| ... } # @yieldparam [ConstGenerator] gen new generator is passed to the block # When passed a block, {#calculate} is automatically called at the end of # the block, otherwise you must call it yourself. def initialize(prefix = nil, options = {}) @includes = ['stdio.h', 'stddef.h'] @constants = {} @prefix = prefix @required = options[:required] @options = options if block_given? then yield self calculate self.class.options.merge(options) end end # Set class options # These options are merged with {#initialize} options when it is called with a block. # @param [Hash] options # @return [Hash] class options def self.options=(options) @options = options end # Get class options. # @return [Hash] class options def self.options @options end # @param [String] name # @return constant value (converted if a +converter+ was defined). # Access a constant by name. def [](name) @constants[name].converted_value end # Request the value for C constant +name+. # # @param [#to_s] name C constant name # @param [String] format a printf format string to print the value out # @param [String] cast a C cast for the value # @param ruby_name alternate ruby name for {#to_ruby} # # @overload const(name, format=nil, cast='', ruby_name=nil, converter=nil) # +converter+ is a Method or a Proc. # @param [#call] converter convert the value from a string to the appropriate # type for {#to_ruby}. # @overload const(name, format=nil, cast='', ruby_name=nil) { |value| ... } # Use a converter block. This block convert the value from a string to the # appropriate type for {#to_ruby}. # @yieldparam value constant value def const(name, format = nil, cast = '', ruby_name = nil, converter = nil, &converter_proc) format ||= '%d' cast ||= '' if converter_proc and converter then raise ArgumentError, "Supply only converter or converter block" end converter = converter_proc if converter.nil? const = Constant.new name, format, cast, ruby_name, converter @constants[name.to_s] = const return const end # Calculate constants values. # @param [Hash] options # @option options [String] :cppflags flags for C compiler # @return [nil] # @raise if a constant is missing and +:required+ was set to +true+ (see {#initialize}) def calculate(options = {}) binary = File.join Dir.tmpdir, "rb_const_gen_bin_#{Process.pid}" Tempfile.open("#{@prefix}.const_generator") do |f| @includes.each do |inc| f.puts "#include <#{inc}>" end f.puts "\nint main(int argc, char **argv)\n{" @constants.each_value do |const| f.puts <<-EOF #ifdef #{const.name} printf("#{const.name} #{const.format}\\n", #{const.cast}#{const.name}); #endif EOF end f.puts "\n\treturn 0;\n}" f.flush output = `gcc #{options[:cppflags]} -D_DARWIN_USE_64_BIT_INODE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -x c -Wall -Werror #{f.path} -o #{binary} 2>&1` unless $?.success? then output = output.split("\n").map { |l| "\t#{l}" }.join "\n" raise "Compilation error generating constants #{@prefix}:\n#{output}" end end output = `#{binary}` File.unlink(binary + (FFI::Platform.windows? ? ".exe" : "")) output.each_line do |line| line =~ /^(\S+)\s(.*)$/ const = @constants[$1] const.value = $2 end missing_constants = @constants.select do |name, constant| constant.value.nil? end.map { |name,| name } if @required and not missing_constants.empty? then raise "Missing required constants for #{@prefix}: #{missing_constants.join ', '}" end end # Dump constants to +io+. # @param [#puts] io # @return [nil] def dump_constants(io) @constants.each do |name, constant| name = [@prefix, name].join '.' if @prefix io.puts "#{name} = #{constant.converted_value}" end end # Outputs values for discovered constants. If the constant's value was # not discovered it is not omitted. # @return [String] def to_ruby @constants.sort_by { |name,| name }.map do |name, constant| if constant.value.nil? then "# #{name} not available" else constant.to_ruby end end.join "\n" end # Add additional C include file(s) to calculate constants from. # @note +stdio.h+ and +stddef.h+ automatically included # @param [List<String>, Array<String>] i include file(s) # @return [Array<String>] array of include files def include(*i) @includes |= i.flatten end end # This class hold constants for {ConstGenerator} class ConstGenerator::Constant attr_reader :name, :format, :cast attr_accessor :value # @param [#to_s] name # @param [String] format a printf format string to print the value out # @param [String] cast a C cast for the value # @param ruby_name alternate ruby name for {#to_ruby} # @param [#call] converter convert the value from a string to the appropriate # type for {#to_ruby}. def initialize(name, format, cast, ruby_name = nil, converter=nil) @name = name @format = format @cast = cast @ruby_name = ruby_name @converter = converter @value = nil end # Return constant value (converted if a +converter+ was defined). # @return constant value. def converted_value if @converter @converter.call(@value) else @value end end # get constant ruby name # @return [String] def ruby_name @ruby_name || @name end # Get an evaluable string from constant. # @return [String] def to_ruby "#{ruby_name} = #{converted_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/ffi-1.9.25/lib/ffi/tools/generator.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/tools/generator.rb
module FFI # @private class Generator def initialize(ffi_name, rb_name, options = {}) @ffi_name = ffi_name @rb_name = rb_name @options = options @name = File.basename rb_name, '.rb' file = File.read @ffi_name new_file = file.gsub(/^( *)@@@(.*?)@@@/m) do @constants = [] @structs = [] indent = $1 original_lines = $2.count "\n" instance_eval $2, @ffi_name, $`.count("\n") new_lines = [] @constants.each { |c| new_lines << c.to_ruby } @structs.each { |s| new_lines << s.generate_layout } new_lines = new_lines.join("\n").split "\n" # expand multiline blocks new_lines = new_lines.map { |line| indent + line } padding = original_lines - new_lines.length new_lines += [nil] * padding if padding >= 0 new_lines.join "\n" end open @rb_name, 'w' do |f| f.puts "# This file is generated by rake. Do not edit." f.puts f.puts new_file end end def constants(options = {}, &block) @constants << FFI::ConstGenerator.new(@name, @options.merge(options), &block) end def struct(options = {}, &block) @structs << FFI::StructGenerator.new(@name, @options.merge(options), &block) end ## # Utility converter for constants def to_s proc { |obj| obj.to_s.inspect } 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/ffi-1.9.25/lib/ffi/tools/generator_task.rb
_vendor/ruby/2.6.0/gems/ffi-1.9.25/lib/ffi/tools/generator_task.rb
begin require 'ffi/struct_generator' require 'ffi/const_generator' require 'ffi/generator' rescue LoadError # from Rakefile require 'lib/ffi/struct_generator' require 'lib/ffi/const_generator' require 'lib/ffi/generator' end require 'rake' require 'rake/tasklib' require 'tempfile' ## # Rake task that calculates C structs for FFI::Struct. # @private class FFI::Generator::Task < Rake::TaskLib def initialize(rb_names) task :clean do rm_f rb_names end rb_names.each do |rb_name| ffi_name = "#{rb_name}.ffi" file rb_name => ffi_name do |t| puts "Generating #{rb_name}..." if Rake.application.options.trace FFI::Generator.new ffi_name, rb_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/rb-fsevent-0.10.3/ext/rakefile.rb
_vendor/ruby/2.6.0/gems/rb-fsevent-0.10.3/ext/rakefile.rb
# -*- encoding: utf-8 -*- require 'rubygems' unless defined?(Gem) require 'pathname' require 'date' require 'time' require 'rake/clean' raise "unable to find xcodebuild" unless system('which', 'xcodebuild') FSEVENT_WATCH_EXE_VERSION = '0.1.5' $this_dir = Pathname.new(__FILE__).dirname.expand_path $final_exe = $this_dir.parent.join('bin/fsevent_watch') $src_dir = $this_dir.join('fsevent_watch') $obj_dir = $this_dir.join('build') SRC = Pathname.glob("#{$src_dir}/*.c") OBJ = SRC.map {|s| $obj_dir.join("#{s.basename('.c')}.o")} $now = DateTime.now.xmlschema rescue Time.now.xmlschema $CC = ENV['CC'] || `which clang || which gcc`.strip $CFLAGS = ENV['CFLAGS'] || '-fconstant-cfstrings -fasm-blocks -fstrict-aliasing -Wall' $ARCHFLAGS = ENV['ARCHFLAGS'] || '-arch x86_64' $DEFINES = "-DNS_BUILD_32_LIKE_64 -DNS_BLOCK_ASSERTIONS -DPROJECT_VERSION=#{FSEVENT_WATCH_EXE_VERSION}" $GCC_C_LANGUAGE_STANDARD = ENV['GCC_C_LANGUAGE_STANDARD'] || 'gnu11' # generic developer id name so it'll match correctly for anyone who has only # one developer id in their keychain (not that I expect anyone else to bother) $CODE_SIGN_IDENTITY = 'Developer ID Application' $arch = `uname -m`.strip $os_release = `uname -r`.strip $BUILD_TRIPLE = "#{$arch}-apple-darwin#{$os_release}" $CCVersion = `#{$CC} --version | head -n 1`.strip CLEAN.include OBJ.map(&:to_s) CLEAN.include $obj_dir.join('Info.plist').to_s CLEAN.include $obj_dir.join('fsevent_watch').to_s CLOBBER.include $final_exe.to_s task :sw_vers do $mac_product_version = `sw_vers -productVersion`.strip $mac_build_version = `sw_vers -buildVersion`.strip $MACOSX_DEPLOYMENT_TARGET = ENV['MACOSX_DEPLOYMENT_TARGET'] || $mac_product_version.sub(/\.\d*$/, '') $CFLAGS = "#{$CFLAGS} -mmacosx-version-min=#{$MACOSX_DEPLOYMENT_TARGET}" end task :get_sdk_info => :sw_vers do $SDK_INFO = {} version_info = `xcodebuild -version -sdk macosx#{$MACOSX_DEPLOYMENT_TARGET}` raise "invalid SDK" unless !!$?.exitstatus version_info.strip.each_line do |line| next if line.strip.empty? next unless line.include?(':') match = line.match(/([^:]*): (.*)/) next unless match $SDK_INFO[match[1]] = match[2] end end task :debug => :sw_vers do $DEFINES = "-DDEBUG #{$DEFINES}" $CFLAGS = "#{$CFLAGS} -O0 -fno-omit-frame-pointer -g" end task :release => :sw_vers do $DEFINES = "-DNDEBUG #{$DEFINES}" $CFLAGS = "#{$CFLAGS} -Ofast" end desc 'configure build type depending on whether ENV var FWDEBUG is set' task :set_build_type => :sw_vers do if ENV['FWDEBUG'] Rake::Task[:debug].invoke else Rake::Task[:release].invoke end end desc 'set build arch to ppc' task :ppc do $ARCHFLAGS = '-arch ppc' end desc 'set build arch to x86_64' task :x86_64 do $ARCHFLAGS = '-arch x86_64' end desc 'set build arch to i386' task :x86 do $ARCHFLAGS = '-arch i386' end task :setup_env => [:set_build_type, :sw_vers, :get_sdk_info] directory $obj_dir.to_s file $obj_dir.to_s => :setup_env SRC.zip(OBJ).each do |source, object| file object.to_s => [source.to_s, $obj_dir.to_s] do cmd = [ $CC, $ARCHFLAGS, "-std=#{$GCC_C_LANGUAGE_STANDARD}", $CFLAGS, $DEFINES, "-I#{$src_dir}", '-isysroot', $SDK_INFO['Path'], '-c', source, '-o', object ] sh(cmd.map {|s| s.to_s}.join(' ')) end end file $obj_dir.join('Info.plist').to_s => [$obj_dir.to_s, :setup_env] do File.open($obj_dir.join('Info.plist').to_s, 'w+') do |file| indentation = '' indent = lambda {|num| indentation = ' ' * num } add = lambda {|str| file << "#{indentation}#{str}\n" } key = lambda {|str| add["<key>#{str}</key>"] } string = lambda {|str| add["<string>#{str}</string>"] } add['<?xml version="1.0" encoding="UTF-8"?>'] add['<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'] add['<plist version="1.0">'] indent[2] add['<dict>'] indent[4] key['CFBundleExecutable'] string['fsevent_watch'] key['CFBundleIdentifier'] string['com.teaspoonofinsanity.fsevent_watch'] key['CFBundleName'] string['fsevent_watch'] key['CFBundleDisplayName'] string['FSEvent Watch CLI'] key['NSHumanReadableCopyright'] string['Copyright (C) 2011-2017 Travis Tilley'] key['CFBundleVersion'] string["#{FSEVENT_WATCH_EXE_VERSION}"] key['LSMinimumSystemVersion'] string["#{$MACOSX_DEPLOYMENT_TARGET}"] key['DTSDKBuild'] string["#{$SDK_INFO['ProductBuildVersion']}"] key['DTSDKName'] string["macosx#{$SDK_INFO['SDKVersion']}"] key['DTSDKPath'] string["#{$SDK_INFO['Path']}"] key['BuildMachineOSBuild'] string["#{$mac_build_version}"] key['BuildMachineOSVersion'] string["#{$mac_product_version}"] key['FSEWCompiledAt'] string["#{$now}"] key['FSEWVersionInfoBuilder'] string["#{`whoami`.strip}"] key['FSEWBuildTriple'] string["#{$BUILD_TRIPLE}"] key['FSEWCC'] string["#{$CC}"] key['FSEWCCVersion'] string["#{$CCVersion}"] key['FSEWCFLAGS'] string["#{$CFLAGS}"] indent[2] add['</dict>'] indent[0] add['</plist>'] end end desc 'generate an Info.plist used for code signing as well as embedding build settings into the resulting binary' task :plist => $obj_dir.join('Info.plist').to_s file $obj_dir.join('fsevent_watch').to_s => [$obj_dir.to_s, $obj_dir.join('Info.plist').to_s] + OBJ.map(&:to_s) do cmd = [ $CC, $ARCHFLAGS, "-std=#{$GCC_C_LANGUAGE_STANDARD}", $CFLAGS, $DEFINES, "-I#{$src_dir}", '-isysroot', $SDK_INFO['Path'], '-framework CoreFoundation -framework CoreServices', '-sectcreate __TEXT __info_plist', $obj_dir.join('Info.plist') ] + OBJ + [ '-o', $obj_dir.join('fsevent_watch') ] sh(cmd.map {|s| s.to_s}.join(' ')) end desc 'compile and link build/fsevent_watch' task :build => $obj_dir.join('fsevent_watch').to_s desc 'codesign build/fsevent_watch binary' task :codesign => :build do sh "codesign -s '#{$CODE_SIGN_IDENTITY}' #{$obj_dir.join('fsevent_watch')}" end directory $this_dir.parent.join('bin') desc 'replace bundled fsevent_watch binary with build/fsevent_watch' task :replace_exe => [$this_dir.parent.join('bin'), :build] do sh "mv #{$obj_dir.join('fsevent_watch')} #{$final_exe}" end task :default => [:replace_exe, :clean]
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/rb-fsevent-0.10.3/lib/otnetstring.rb
_vendor/ruby/2.6.0/gems/rb-fsevent-0.10.3/lib/otnetstring.rb
# Copyright (c) 2011 Konstantin Haase # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'stringio' module OTNetstring class Error < StandardError; end class << self def parse(io, encoding = 'internal', fallback_encoding = nil) fallback_encoding = io.encoding if io.respond_to? :encoding io = StringIO.new(io) if io.respond_to? :to_str length, byte = "", nil while byte.nil? || byte =~ /\d/ length << byte if byte byte = io.read(1) end if length.size > 9 raise Error, "#{length} is longer than 9 digits" elsif length !~ /\d+/ raise Error, "Expected '#{byte}' to be a digit" end length = Integer(length) case byte when '#' then Integer io.read(length) when ',' then with_encoding io.read(length), encoding, fallback_encoding when '~' then raise Error, "nil has length of 0, #{length} given" unless length == 0 when '!' then io.read(length) == 'true' when '[', '{' array = [] start = io.pos array << parse(io, encoding, fallback_encoding) while io.pos - start < length raise Error, 'Nested element longer than container' if io.pos - start != length byte == "{" ? Hash[*array] : array else raise Error, "Unknown type '#{byte}'" end end def encode(obj, string_sep = ',') case obj when String then with_encoding "#{obj.bytesize}#{string_sep}#{obj}", "binary" when Integer then encode(obj.inspect, '#') when NilClass then "0~" when Array then encode(obj.map { |e| encode(e) }.join, '[') when Hash then encode(obj.map { |a,b| encode(a)+encode(b) }.join, '{') when FalseClass, TrueClass then encode(obj.inspect, '!') else raise Error, 'cannot encode %p' % obj end end private def with_encoding(str, encoding, fallback = nil) return str unless str.respond_to? :encode encoding = Encoding.find encoding if encoding.respond_to? :to_str encoding ||= fallback encoding ? str.encode(encoding) : str rescue EncodingError str.force_encoding(encoding) 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/rb-fsevent-0.10.3/lib/rb-fsevent.rb
_vendor/ruby/2.6.0/gems/rb-fsevent-0.10.3/lib/rb-fsevent.rb
# -*- encoding: utf-8 -*- require 'rb-fsevent/fsevent' require 'rb-fsevent/version'
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/rb-fsevent-0.10.3/lib/rb-fsevent/version.rb
_vendor/ruby/2.6.0/gems/rb-fsevent-0.10.3/lib/rb-fsevent/version.rb
# -*- encoding: utf-8 -*- class FSEvent VERSION = '0.10.3' 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/rb-fsevent-0.10.3/lib/rb-fsevent/fsevent.rb
_vendor/ruby/2.6.0/gems/rb-fsevent-0.10.3/lib/rb-fsevent/fsevent.rb
# -*- encoding: utf-8 -*- require 'otnetstring' class FSEvent class << self class_eval <<-END def root_path "#{File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))}" end END class_eval <<-END def watcher_path "#{File.join(FSEvent.root_path, 'bin', 'fsevent_watch')}" end END end attr_reader :paths, :callback def initialize args = nil, &block watch(args, &block) unless args.nil? end def watch(watch_paths, options=nil, &block) @paths = watch_paths.kind_of?(Array) ? watch_paths : [watch_paths] @callback = block if options.kind_of?(Hash) @options = parse_options(options) elsif options.kind_of?(Array) @options = options else @options = [] end end def run @pipe = open_pipe @running = true # please note the use of IO::select() here, as it is used specifically to # preserve correct signal handling behavior in ruby 1.8. while @running && IO::select([@pipe], nil, nil, nil) # managing the IO ourselves allows us to be careful and never pass an # incomplete message to OTNetstring.parse() message = "" length = "" byte = nil reading_length = true found_length = false while reading_length byte = @pipe.read_nonblock(1) if "#{byte}" =~ /\d/ length << byte found_length = true elsif found_length == false next else reading_length = false end end length = Integer(length, 10) type = byte message << "#{length}#{type}" message << @pipe.read(length) decoded = OTNetstring.parse(message) modified_paths = decoded["events"].map {|event| event["path"]} # passing the full info as a second block param feels icky, but such is # the trap of backward compatibility. case callback.arity when 1 callback.call(modified_paths) when 2 callback.call(modified_paths, decoded) end end rescue Interrupt, IOError, Errno::EBADF ensure stop end def stop unless @pipe.nil? Process.kill('KILL', @pipe.pid) if process_running?(@pipe.pid) @pipe.close end rescue IOError ensure @running = false end def process_running?(pid) begin Process.kill(0, pid) true rescue Errno::ESRCH false end end if RUBY_VERSION < '1.9' def open_pipe IO.popen("'#{self.class.watcher_path}' #{options_string} #{shellescaped_paths}") end private def options_string @options.join(' ') end def shellescaped_paths @paths.map {|path| shellescape(path)}.join(' ') end # for Ruby 1.8.6 support def shellescape(str) # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Process as a single byte sequence because not all shell # implementations are multibyte aware. str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1") # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. str.gsub!(/\n/, "'\n'") return str end else def open_pipe IO.popen([self.class.watcher_path] + @options + @paths) end end private def parse_options(options={}) opts = ['--format=otnetstring'] opts.concat(['--since-when', options[:since_when]]) if options[:since_when] opts.concat(['--latency', options[:latency]]) if options[:latency] opts.push('--no-defer') if options[:no_defer] opts.push('--watch-root') if options[:watch_root] opts.push('--file-events') if options[:file_events] # ruby 1.9's IO.popen(array-of-stuff) syntax requires all items to be strings opts.map {|opt| "#{opt}"} 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/init.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/init.rb
begin require File.join(File.dirname(__FILE__), 'lib', 'sass') # From here rescue LoadError begin require 'sass' # From gem rescue LoadError => e # gems:install may be run to install Haml with the skeleton plugin # but not the gem itself installed. # Don't die if this is the case. raise e unless defined?(Rake) && (Rake.application.top_level_tasks.include?('gems') || Rake.application.top_level_tasks.include?('gems:install')) end end # Load Sass. # Sass may be undefined if we're running gems:install. require 'sass/plugin' if defined?(Sass)
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/rails/init.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/rails/init.rb
Kernel.load File.join(File.dirname(__FILE__), '..', 'init.rb')
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/test/test_helper.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/test_helper.rb
lib_dir = File.dirname(__FILE__) + '/../lib' require 'minitest/autorun' require 'fileutils' $:.unshift lib_dir unless $:.include?(lib_dir) require 'sass' require 'mathn' if ENV['MATHN'] == 'true' Sass::RAILS_LOADED = true unless defined?(Sass::RAILS_LOADED) Sass.tests_running = true if defined?(Encoding) $-w, w = false, $-w Encoding.default_external = 'UTF-8' $-w = w end module Sass::Script::Functions def option(name) Sass::Script::Value::String.new(@options[name.value.to_sym].to_s) end end class MiniTest::Test def munge_filename(opts = {}) opts[:filename] ||= filename_for_test(opts[:syntax] || :sass) opts[:sourcemap_filename] ||= sourcemap_filename_for_test opts end def test_name caller. map {|c| Sass::Util.caller_info(c)[2]}. compact. map {|c| c.sub(/^(block|rescue) in /, '')}. find {|c| c =~ /^test_/} end def filename_for_test(syntax = :sass) "#{test_name}_inline.#{syntax}" end def sourcemap_filename_for_test(syntax = :sass) "#{test_name}_inline.css.map" end def clean_up_sassc path = File.dirname(__FILE__) + "/../.sass-cache" Sass::Util.retry_on_windows {FileUtils.rm_r(path) if File.exist?(path)} end def assert_warning(message) the_real_stderr, $stderr = $stderr, StringIO.new result = yield if message.is_a?(Regexp) assert_match message, $stderr.string.strip else assert_equal message.strip, $stderr.string.strip end result ensure $stderr = the_real_stderr end def assert_no_warning the_real_stderr, $stderr = $stderr, StringIO.new result = yield assert_equal '', $stderr.string result ensure $stderr = the_real_stderr end def silence_warnings(&block) Sass::Util.silence_sass_warnings(&block) end def assert_raise_message(klass, message) yield rescue Exception => e assert_instance_of(klass, e) assert_equal(message, e.message) else flunk "Expected exception #{klass}, none raised" end def assert_raise_line(line) yield rescue Sass::SyntaxError => e assert_equal(line, e.sass_line) else flunk "Expected exception on line #{line}, none raised" end def assert_sass_to_sass(sass, options: {}) assert_equal(sass.rstrip, to_sass(sass, options).rstrip, "Expected Sass to transform to itself") end def assert_scss_to_sass(sass, scss, options: {}) assert_equal(sass.rstrip, to_sass(scss, options.merge(:syntax => :scss)).rstrip, "Expected SCSS to transform to Sass") end def assert_scss_to_scss(scss, source: scss, options: {}) assert_equal(scss.rstrip, to_scss(source, options.merge(:syntax => :scss)).rstrip, "Expected SCSS to transform to #{scss == source ? 'itself' : 'SCSS'}") end def assert_sass_to_scss(scss, sass, options: {}) assert_equal(scss.rstrip, to_scss(sass, options).rstrip, "Expected Sass to transform to SCSS") end def assert_converts(sass, scss, options: {}) assert_sass_to_sass(sass, options: options) assert_scss_to_sass(sass, scss, options: options) assert_scss_to_scss(scss, options: options) assert_sass_to_scss(scss, sass, options: options) end def to_sass(scss, options = {}) Sass::Util.silence_sass_warnings do Sass::Engine.new(scss, options).to_tree.to_sass(options) end end def to_scss(sass, options = {}) Sass::Util.silence_sass_warnings do Sass::Engine.new(sass, options).to_tree.to_scss(options) end end end module PublicApiLinter def lint_api(api_class, duck_type_class) define_method :test_lint_instance do assert lint_instance.is_a?(duck_type_class) end api_class.instance_methods.each do |meth| define_method :"test_has_#{meth}" do assert lint_instance.respond_to?(meth), "#{duck_type_class.name} does not implement #{meth}" 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/test/sass/logger_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/logger_test.rb
require File.dirname(__FILE__) + '/../test_helper' require 'pathname' class LoggerTest < MiniTest::Test class InterceptedLogger < Sass::Logger::Base attr_accessor :messages def initialize(*args) super self.messages = [] end def reset! self.messages = [] end def _log(*args) messages << [args] end end def test_global_sass_logger_instance_exists assert Sass.logger.respond_to?(:warn) end def test_log_level_orders logged_levels = { :trace => [ [], [:trace, :debug, :info, :warn, :error]], :debug => [ [:trace], [:debug, :info, :warn, :error]], :info => [ [:trace, :debug], [:info, :warn, :error]], :warn => [ [:trace, :debug, :info], [:warn, :error]], :error => [ [:trace, :debug, :info, :warn], [:error]] } logged_levels.each do |level, (should_not_be_logged, should_be_logged)| logger = Sass::Logger::Base.new(level) should_not_be_logged.each do |should_level| assert !logger.logging_level?(should_level) end should_be_logged.each do |should_level| assert logger.logging_level?(should_level) end end end def test_logging_can_be_disabled logger = InterceptedLogger.new logger.error("message #1") assert_equal 1, logger.messages.size logger.reset! logger.disabled = true logger.error("message #2") assert_equal 0, logger.messages.size 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/test/sass/compiler_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/compiler_test.rb
require 'minitest/autorun' require File.dirname(__FILE__) + '/../test_helper' require 'sass/plugin' require 'sass/plugin/compiler' class CompilerTest < MiniTest::Test class FakeListener attr_accessor :options attr_accessor :directories attr_reader :start_called attr_reader :thread def initialize(*args, &on_filesystem_event) self.options = args.last.is_a?(Hash) ? args.pop : {} self.directories = args @on_filesystem_event = on_filesystem_event @start_called = false reset_events! end def fire_events!(*args) @on_filesystem_event.call(@modified, @added, @removed) reset_events! end def changed(filename) @modified << File.expand_path(filename) end def added(filename) @added << File.expand_path(filename) end def removed(filename) @removed << File.expand_path(filename) end def on_start!(&run_during_start) @run_during_start = run_during_start end def start! @run_during_start.call(self) if @run_during_start end def start parent = Thread.current @thread = Thread.new do @run_during_start.call(self) if @run_during_start parent.raise Interrupt end end def stop end def reset_events! @modified = [] @added = [] @removed = [] end end module MockWatcher attr_accessor :run_during_start attr_accessor :update_stylesheets_times attr_accessor :update_stylesheets_called_with attr_accessor :deleted_css_files def fake_listener @fake_listener end def update_stylesheets(individual_files) @update_stylesheets_times ||= 0 @update_stylesheets_times += 1 (@update_stylesheets_called_with ||= []) << individual_files end def try_delete_css(css_filename) (@deleted_css_files ||= []) << css_filename end private def create_listener(*args, &on_filesystem_event) args.pop if args.last.is_a?(Hash) @fake_listener = FakeListener.new(*args, &on_filesystem_event) @fake_listener.on_start!(&run_during_start) @fake_listener end end def test_initialize watcher end def test_watch_starts_the_listener start_called = false c = watcher do |listener| start_called = true end c.watch assert start_called, "start! was not called" end def test_sass_callbacks_fire_from_listener_events c = watcher do |listener| listener.changed "changed.scss" listener.added "added.scss" listener.removed "removed.scss" listener.fire_events! end modified_fired = false c.on_template_modified do |sass_file| modified_fired = true assert_equal "changed.scss", sass_file end added_fired = false c.on_template_created do |sass_file| added_fired = true assert_equal "added.scss", sass_file end removed_fired = false c.on_template_deleted do |sass_file| removed_fired = true assert_equal "removed.scss", sass_file end c.watch assert_equal 2, c.update_stylesheets_times assert modified_fired assert added_fired assert removed_fired end def test_removing_a_sass_file_removes_corresponding_css_file c = watcher do |listener| listener.removed "remove_me.scss" listener.fire_events! end c.watch assert_equal "./remove_me.css", c.deleted_css_files.first end def test_an_importer_can_watch_an_image image_importer = Sass::Importers::Filesystem.new(".") class << image_importer def watched_file?(filename) filename =~ /\.png$/ end end c = watcher(:load_paths => [image_importer]) do |listener| listener.changed "image.png" listener.fire_events! end modified_fired = false c.on_template_modified do |f| modified_fired = true assert_equal "image.png", f end c.watch assert_equal 2, c.update_stylesheets_times assert modified_fired end def test_watching_specific_files_and_one_is_deleted directories = nil c = watcher do |listener| directories = listener.directories listener.removed File.expand_path("./foo.scss") listener.fire_events! end c.watch([[File.expand_path("./foo.scss"), File.expand_path("./foo.css"), nil]]) assert directories.include?(File.expand_path(".")), directories.inspect assert_equal File.expand_path("./foo.css"), c.deleted_css_files.first, "the corresponding css file was not deleted" assert_equal [], c.update_stylesheets_called_with[1], "the sass file should not have been compiled" end def test_watched_directories_are_dedupped directories = nil c = watcher(:load_paths => [".", "./foo", "."]) do |listener| directories = listener.directories end c.watch assert_equal [File.expand_path(".")], directories end def test_a_changed_css_in_a_watched_directory_does_not_force_a_compile c = watcher do |listener| listener.changed "foo.css" listener.fire_events! end c.on_template_modified do |f| assert false, "Should not have been called" end c.watch assert_equal 1, c.update_stylesheets_times end private def default_options {:template_location => [[".","."]]} end def watcher(options = {}, &run_during_start) options = default_options.merge(options) watcher = Sass::Plugin::Compiler.new(options) watcher.extend(MockWatcher) watcher.run_during_start = run_during_start watcher 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/test/sass/functions_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/functions_test.rb
require 'minitest/autorun' require File.dirname(__FILE__) + '/../test_helper' require File.dirname(__FILE__) + '/test_helper' require 'sass/script' require 'mock_importer' module Sass::Script::Functions def no_kw_args Sass::Script::Value::String.new("no-kw-args") end def only_var_args(*args) Sass::Script::Value::String.new("only-var-args("+args.map{|a| a.plus(Sass::Script::Value::Number.new(1)).to_s }.join(", ")+")") end declare :only_var_args, [], :var_args => true def only_kw_args(kwargs) Sass::Script::Value::String.new("only-kw-args(" + kwargs.keys.map {|a| a.to_s}.sort.join(", ") + ")") end declare :only_kw_args, [], :var_kwargs => true def deprecated_arg_fn(arg1, arg2, arg3 = nil) Sass::Script::Value::List.new( [arg1, arg2, arg3 || Sass::Script::Value::Null.new], separator: :space) end declare :deprecated_arg_fn, [:arg1, :arg2, :arg3], :deprecated => [:arg_1, :arg_2, :arg3] declare :deprecated_arg_fn, [:arg1, :arg2], :deprecated => [:arg_1, :arg_2] end module Sass::Script::Functions::UserFunctions def call_options_on_new_value str = Sass::Script::Value::String.new("foo") str.options[:foo] str end def user_defined Sass::Script::Value::String.new("I'm a user-defined string!") end def _preceding_underscore Sass::Script::Value::String.new("I'm another user-defined string!") end def fetch_the_variable environment.var('variable') end end module Sass::Script::Functions include Sass::Script::Functions::UserFunctions end class SassFunctionTest < MiniTest::Test # Tests taken from: # http://www.w3.org/Style/CSS/Test/CSS3/Color/20070927/html4/t040204-hsl-h-rotating-b.htm # http://www.w3.org/Style/CSS/Test/CSS3/Color/20070927/html4/t040204-hsl-values-b.htm File.read(File.dirname(__FILE__) + "/data/hsl-rgb.txt").split("\n\n").each do |chunk| hsls, rgbs = chunk.strip.split("====") hsls.strip.split("\n").zip(rgbs.strip.split("\n")) do |hsl, rgb| hsl_method = "test_hsl: #{hsl} = #{rgb}" unless method_defined?(hsl_method) define_method(hsl_method) do assert_equal(evaluate(rgb), evaluate(hsl)) end end rgb_to_hsl_method = "test_rgb_to_hsl: #{rgb} = #{hsl}" unless method_defined?(rgb_to_hsl_method) define_method(rgb_to_hsl_method) do rgb_color = perform(rgb) hsl_color = perform(hsl) white = hsl_color.lightness == 100 black = hsl_color.lightness == 0 grayscale = white || black || hsl_color.saturation == 0 assert_in_delta(hsl_color.hue, rgb_color.hue, 0.0001, "Hues should be equal") unless grayscale assert_in_delta(hsl_color.saturation, rgb_color.saturation, 0.0001, "Saturations should be equal") unless white || black assert_in_delta(hsl_color.lightness, rgb_color.lightness, 0.0001, "Lightnesses should be equal") end end end end def test_hsl_kwargs assert_equal "#33cccc", evaluate("hsl($hue: 180, $saturation: 60%, $lightness: 50%)") end def test_hsl_clamps_bounds assert_equal("#1f1f1f", evaluate("hsl(10, -114, 12)")) assert_equal("white", evaluate("hsl(10, 10, 256%)")) end def test_hsl_checks_types assert_error_message("$hue: \"foo\" is not a number for `hsl'", "hsl(\"foo\", 10, 12)"); assert_error_message("$saturation: \"foo\" is not a number for `hsl'", "hsl(10, \"foo\", 12)"); assert_error_message("$lightness: \"foo\" is not a number for `hsl'", "hsl(10, 10, \"foo\")"); end def test_hsla assert_equal "rgba(51, 204, 204, 0.4)", evaluate("hsla(180, 60%, 50%, 0.4)") assert_equal "#33cccc", evaluate("hsla(180, 60%, 50%, 1)") assert_equal "rgba(51, 204, 204, 0)", evaluate("hsla(180, 60%, 50%, 0)") assert_equal "rgba(51, 204, 204, 0.4)", evaluate("hsla($hue: 180, $saturation: 60%, $lightness: 50%, $alpha: 0.4)") end def test_hsla_clamps_bounds assert_equal("#1f1f1f", evaluate("hsla(10, -114, 12, 1)")) assert_equal("rgba(255, 255, 255, 0)", evaluate("hsla(10, 10, 256%, 0)")) assert_equal("rgba(28, 24, 23, 0)", evaluate("hsla(10, 10, 10, -0.1)")) assert_equal("#1c1817", evaluate("hsla(10, 10, 10, 1.1)")) end def test_hsla_checks_types assert_error_message("$hue: \"foo\" is not a number for `hsla'", "hsla(\"foo\", 10, 12, 0.3)"); assert_error_message("$saturation: \"foo\" is not a number for `hsla'", "hsla(10, \"foo\", 12, 0)"); assert_error_message("$lightness: \"foo\" is not a number for `hsla'", "hsla(10, 10, \"foo\", 1)"); assert_error_message("$alpha: \"foo\" is not a number for `hsla'", "hsla(10, 10, 10, \"foo\")"); end def test_hsla_percent_warning assert_warning(<<WARNING) {evaluate("hsla(180, 60%, 50%, 40%)")} DEPRECATION WARNING: Passing a percentage as the alpha value to hsla() will be interpreted differently in future versions of Sass. For now, use 40 instead. WARNING end def test_hsla_unit_warning assert_warning(<<WARNING) {evaluate("hsla(180, 60%, 50%, 40em)")} DEPRECATION WARNING: Passing a number with units as the alpha value to hsla() is deprecated and will be an error in future versions of Sass. Use 40 instead. WARNING end def test_percentage assert_equal("50%", evaluate("percentage(.5)")) assert_equal("100%", evaluate("percentage(1)")) assert_equal("25%", evaluate("percentage(25px / 100px)")) assert_equal("50%", evaluate("percentage($number: 0.5)")) end def test_percentage_checks_types assert_error_message("$number: 25px is not a unitless number for `percentage'", "percentage(25px)") assert_error_message("$number: #cccccc is not a unitless number for `percentage'", "percentage(#ccc)") assert_error_message("$number: \"string\" is not a unitless number for `percentage'", %Q{percentage("string")}) end def test_round assert_equal("5", evaluate("round(4.8)")) assert_equal("5px", evaluate("round(4.8px)")) assert_equal("5px", evaluate("round(5.49px)")) assert_equal("5px", evaluate("round($number: 5.49px)")) assert_equal("-6", evaluate("round(-5.5)")) end def test_round_checks_types assert_error_message("$value: #cccccc is not a number for `round'", "round(#ccc)") end def test_floor assert_equal("4", evaluate("floor(4.8)")) assert_equal("4px", evaluate("floor(4.8px)")) assert_equal("4px", evaluate("floor($number: 4.8px)")) end def test_floor_checks_types assert_error_message("$value: \"foo\" is not a number for `floor'", "floor(\"foo\")") end def test_ceil assert_equal("5", evaluate("ceil(4.1)")) assert_equal("5px", evaluate("ceil(4.8px)")) assert_equal("5px", evaluate("ceil($number: 4.8px)")) end def test_ceil_checks_types assert_error_message("$value: \"a\" is not a number for `ceil'", "ceil(\"a\")") end def test_abs assert_equal("5", evaluate("abs(-5)")) assert_equal("5px", evaluate("abs(-5px)")) assert_equal("5", evaluate("abs(5)")) assert_equal("5px", evaluate("abs(5px)")) assert_equal("5px", evaluate("abs($number: 5px)")) end def test_abs_checks_types assert_error_message("$value: #aaaaaa is not a number for `abs'", "abs(#aaa)") end def test_min assert_equal("1", evaluate("min(1, 2, 3)")) assert_equal("1", evaluate("min(3px, 2px, 1)")) assert_equal("4em", evaluate("min(4em)")) assert_equal("10cm", evaluate("min(10cm, 6in)")) assert_equal("1q", evaluate("min(1cm, 1q)")) assert_error_message("#aaaaaa is not a number for `min'", "min(#aaa)") assert_error_message("Incompatible units: 'px' and 'em'.", "min(3em, 4em, 1px)") end def test_max assert_equal("3", evaluate("max(1, 2, 3)")) assert_equal("3", evaluate("max(3, 2px, 1px)")) assert_equal("4em", evaluate("max(4em)")) assert_equal("6in", evaluate("max(10cm, 6in)")) assert_equal("11mm", evaluate("max(11mm, 10q)")) assert_error_message("#aaaaaa is not a number for `max'", "max(#aaa)") assert_error_message("Incompatible units: 'px' and 'em'.", "max(3em, 4em, 1px)") end def test_rgb assert_equal("#123456", evaluate("rgb(18, 52, 86)")) assert_equal("#beaded", evaluate("rgb(190, 173, 237)")) assert_equal("springgreen", evaluate("rgb(0, 255, 127)")) assert_equal("springgreen", evaluate("rgb($red: 0, $green: 255, $blue: 127)")) end def test_rgb_percent assert_equal("#123457", evaluate("rgb(7.1%, 20.4%, 34%)")) assert_equal("#beaded", evaluate("rgb(74.7%, 173, 93%)")) assert_equal("#beaded", evaluate("rgb(190, 68%, 237)")) assert_equal("#00ff80", evaluate("rgb(0%, 100%, 50%)")) end def test_rgb_clamps_bounds assert_equal("#ff0101", evaluate("rgb(256, 1, 1)")) assert_equal("#01ff01", evaluate("rgb(1, 256, 1)")) assert_equal("#0101ff", evaluate("rgb(1, 1, 256)")) assert_equal("#01ffff", evaluate("rgb(1, 256, 257)")) assert_equal("#000101", evaluate("rgb(-1, 1, 1)")) end def test_rgb_clamps_percent_bounds assert_equal("red", evaluate("rgb(100.1%, 0, 0)")) assert_equal("black", evaluate("rgb(0, -0.1%, 0)")) assert_equal("blue", evaluate("rgb(0, 0, 101%)")) end def test_rgb_tests_types assert_error_message("$red: \"foo\" is not a number for `rgb'", "rgb(\"foo\", 10, 12)"); assert_error_message("$green: \"foo\" is not a number for `rgb'", "rgb(10, \"foo\", 12)"); assert_error_message("$blue: \"foo\" is not a number for `rgb'", "rgb(10, 10, \"foo\")"); end def test_rgba assert_equal("rgba(18, 52, 86, 0.5)", evaluate("rgba(18, 52, 86, 0.5)")) assert_equal("#beaded", evaluate("rgba(190, 173, 237, 1)")) assert_equal("rgba(0, 255, 127, 0)", evaluate("rgba(0, 255, 127, 0)")) assert_equal("rgba(0, 255, 127, 0)", evaluate("rgba($red: 0, $green: 255, $blue: 127, $alpha: 0)")) end def test_rgba_clamps_bounds assert_equal("rgba(255, 1, 1, 0.3)", evaluate("rgba(256, 1, 1, 0.3)")) assert_equal("rgba(1, 255, 1, 0.3)", evaluate("rgba(1, 256, 1, 0.3)")) assert_equal("rgba(1, 1, 255, 0.3)", evaluate("rgba(1, 1, 256, 0.3)")) assert_equal("rgba(1, 255, 255, 0.3)", evaluate("rgba(1, 256, 257, 0.3)")) assert_equal("rgba(0, 1, 1, 0.3)", evaluate("rgba(-1, 1, 1, 0.3)")) assert_equal("rgba(1, 1, 1, 0)", evaluate("rgba(1, 1, 1, -0.2)")) assert_equal("#010101", evaluate("rgba(1, 1, 1, 1.2)")) end def test_rgba_tests_types assert_error_message("$red: \"foo\" is not a number for `rgba'", "rgba(\"foo\", 10, 12, 0.2)"); assert_error_message("$green: \"foo\" is not a number for `rgba'", "rgba(10, \"foo\", 12, 0.1)"); assert_error_message("$blue: \"foo\" is not a number for `rgba'", "rgba(10, 10, \"foo\", 0)"); assert_error_message("$alpha: \"foo\" is not a number for `rgba'", "rgba(10, 10, 10, \"foo\")"); end def test_rgba_with_color assert_equal "rgba(16, 32, 48, 0.5)", evaluate("rgba(#102030, 0.5)") assert_equal "rgba(0, 0, 255, 0.5)", evaluate("rgba(blue, 0.5)") assert_equal "rgba(0, 0, 255, 0.5)", evaluate("rgba($color: blue, $alpha: 0.5)") end def test_rgba_with_color_tests_types assert_error_message("$color: \"foo\" is not a color for `rgba'", "rgba(\"foo\", 0.2)"); assert_error_message("$alpha: \"foo\" is not a number for `rgba'", "rgba(blue, \"foo\")"); end def test_rgba_tests_num_args assert_error_message("wrong number of arguments (0 for 4) for `rgba'", "rgba()"); assert_error_message("wrong number of arguments (1 for 4) for `rgba'", "rgba(blue)"); assert_error_message("wrong number of arguments (3 for 4) for `rgba'", "rgba(1, 2, 3)"); assert_error_message("wrong number of arguments (5 for 4) for `rgba'", "rgba(1, 2, 3, 0.4, 5)"); end def test_rgba_percent_warning assert_warning(<<WARNING) {evaluate("rgba(1, 2, 3, 40%)")} DEPRECATION WARNING: Passing a percentage as the alpha value to rgba() will be interpreted differently in future versions of Sass. For now, use 40 instead. WARNING end def test_rgba_unit_warning assert_warning(<<WARNING) {evaluate("rgba(1, 2, 3, 40em)")} DEPRECATION WARNING: Passing a number with units as the alpha value to rgba() is deprecated and will be an error in future versions of Sass. Use 40 instead. WARNING end def test_red assert_equal("18", evaluate("red(#123456)")) assert_equal("18", evaluate("red($color: #123456)")) end def test_red_exception assert_error_message("$color: 12 is not a color for `red'", "red(12)") end def test_green assert_equal("52", evaluate("green(#123456)")) assert_equal("52", evaluate("green($color: #123456)")) end def test_green_exception assert_error_message("$color: 12 is not a color for `green'", "green(12)") end def test_blue assert_equal("86", evaluate("blue(#123456)")) assert_equal("86", evaluate("blue($color: #123456)")) end def test_blue_exception assert_error_message("$color: 12 is not a color for `blue'", "blue(12)") end def test_hue assert_equal("18deg", evaluate("hue(hsl(18, 50%, 20%))")) assert_equal("18deg", evaluate("hue($color: hsl(18, 50%, 20%))")) end def test_hue_exception assert_error_message("$color: 12 is not a color for `hue'", "hue(12)") end def test_saturation assert_equal("52%", evaluate("saturation(hsl(20, 52%, 20%))")) assert_equal("52%", evaluate("saturation(hsl(20, 52, 20%))")) assert_equal("52%", evaluate("saturation($color: hsl(20, 52, 20%))")) end def test_saturation_exception assert_error_message("$color: 12 is not a color for `saturation'", "saturation(12)") end def test_lightness assert_equal("86%", evaluate("lightness(hsl(120, 50%, 86%))")) assert_equal("86%", evaluate("lightness(hsl(120, 50%, 86))")) assert_equal("86%", evaluate("lightness($color: hsl(120, 50%, 86))")) end def test_lightness_exception assert_error_message("$color: 12 is not a color for `lightness'", "lightness(12)") end def test_alpha assert_equal("1", evaluate("alpha(#123456)")) assert_equal("0.34", evaluate("alpha(rgba(0, 1, 2, 0.34))")) assert_equal("0", evaluate("alpha(hsla(0, 1, 2, 0))")) assert_equal("0", evaluate("alpha($color: hsla(0, 1, 2, 0))")) end def test_alpha_exception assert_error_message("$color: 12 is not a color for `alpha'", "alpha(12)") end def test_opacity assert_equal("1", evaluate("opacity(#123456)")) assert_equal("0.34", evaluate("opacity(rgba(0, 1, 2, 0.34))")) assert_equal("0", evaluate("opacity(hsla(0, 1, 2, 0))")) assert_equal("0", evaluate("opacity($color: hsla(0, 1, 2, 0))")) assert_equal("opacity(20%)", evaluate("opacity(20%)")) end def test_opacity_exception assert_error_message("$color: \"foo\" is not a color for `opacity'", "opacity(foo)") end def test_opacify assert_equal("rgba(0, 0, 0, 0.75)", evaluate("opacify(rgba(0, 0, 0, 0.5), 0.25)")) assert_equal("rgba(0, 0, 0, 0.3)", evaluate("opacify(rgba(0, 0, 0, 0.2), 0.1)")) assert_equal("rgba(0, 0, 0, 0.7)", evaluate("fade-in(rgba(0, 0, 0, 0.2), 0.5px)")) assert_equal("black", evaluate("fade_in(rgba(0, 0, 0, 0.2), 0.8)")) assert_equal("black", evaluate("opacify(rgba(0, 0, 0, 0.2), 1)")) assert_equal("rgba(0, 0, 0, 0.2)", evaluate("opacify(rgba(0, 0, 0, 0.2), 0%)")) assert_equal("rgba(0, 0, 0, 0.2)", evaluate("opacify($color: rgba(0, 0, 0, 0.2), $amount: 0%)")) assert_equal("rgba(0, 0, 0, 0.2)", evaluate("fade-in($color: rgba(0, 0, 0, 0.2), $amount: 0%)")) end def test_opacify_tests_bounds assert_error_message("Amount -0.001 must be between 0 and 1 for `opacify'", "opacify(rgba(0, 0, 0, 0.2), -0.001)") assert_error_message("Amount 1.001 must be between 0 and 1 for `opacify'", "opacify(rgba(0, 0, 0, 0.2), 1.001)") end def test_opacify_tests_types assert_error_message("$color: \"foo\" is not a color for `opacify'", "opacify(\"foo\", 10%)") assert_error_message("$amount: \"foo\" is not a number for `opacify'", "opacify(#fff, \"foo\")") end def test_transparentize assert_equal("rgba(0, 0, 0, 0.3)", evaluate("transparentize(rgba(0, 0, 0, 0.5), 0.2)")) assert_equal("rgba(0, 0, 0, 0.1)", evaluate("transparentize(rgba(0, 0, 0, 0.2), 0.1)")) assert_equal("rgba(0, 0, 0, 0.2)", evaluate("fade-out(rgba(0, 0, 0, 0.5), 0.3px)")) assert_equal("rgba(0, 0, 0, 0)", evaluate("fade_out(rgba(0, 0, 0, 0.2), 0.2)")) assert_equal("rgba(0, 0, 0, 0)", evaluate("transparentize(rgba(0, 0, 0, 0.2), 1)")) assert_equal("rgba(0, 0, 0, 0.2)", evaluate("transparentize(rgba(0, 0, 0, 0.2), 0)")) assert_equal("rgba(0, 0, 0, 0.2)", evaluate("transparentize($color: rgba(0, 0, 0, 0.2), $amount: 0)")) assert_equal("rgba(0, 0, 0, 0.2)", evaluate("fade-out($color: rgba(0, 0, 0, 0.2), $amount: 0)")) end def test_transparentize_tests_bounds assert_error_message("Amount -0.001 must be between 0 and 1 for `transparentize'", "transparentize(rgba(0, 0, 0, 0.2), -0.001)") assert_error_message("Amount 1.001 must be between 0 and 1 for `transparentize'", "transparentize(rgba(0, 0, 0, 0.2), 1.001)") end def test_transparentize_tests_types assert_error_message("$color: \"foo\" is not a color for `transparentize'", "transparentize(\"foo\", 10%)") assert_error_message("$amount: \"foo\" is not a number for `transparentize'", "transparentize(#fff, \"foo\")") end def test_lighten assert_equal("#4d4d4d", evaluate("lighten(hsl(0, 0, 0), 30%)")) assert_equal("#ee0000", evaluate("lighten(#800, 20%)")) assert_equal("white", evaluate("lighten(#fff, 20%)")) assert_equal("white", evaluate("lighten(#800, 100%)")) assert_equal("#880000", evaluate("lighten(#800, 0%)")) assert_equal("rgba(238, 0, 0, 0.5)", evaluate("lighten(rgba(136, 0, 0, 0.5), 20%)")) assert_equal("rgba(238, 0, 0, 0.5)", evaluate("lighten($color: rgba(136, 0, 0, 0.5), $amount: 20%)")) end def test_lighten_tests_bounds assert_error_message("Amount -0.001 must be between 0% and 100% for `lighten'", "lighten(#123, -0.001)") assert_error_message("Amount 100.001 must be between 0% and 100% for `lighten'", "lighten(#123, 100.001)") end def test_lighten_tests_types assert_error_message("$color: \"foo\" is not a color for `lighten'", "lighten(\"foo\", 10%)") assert_error_message("$amount: \"foo\" is not a number for `lighten'", "lighten(#fff, \"foo\")") end def test_darken assert_equal("#ff6a00", evaluate("darken(hsl(25, 100, 80), 30%)")) assert_equal("#220000", evaluate("darken(#800, 20%)")) assert_equal("black", evaluate("darken(#000, 20%)")) assert_equal("black", evaluate("darken(#800, 100%)")) assert_equal("#880000", evaluate("darken(#800, 0%)")) assert_equal("rgba(34, 0, 0, 0.5)", evaluate("darken(rgba(136, 0, 0, 0.5), 20%)")) assert_equal("rgba(34, 0, 0, 0.5)", evaluate("darken($color: rgba(136, 0, 0, 0.5), $amount: 20%)")) end def test_darken_tests_bounds assert_error_message("Amount -0.001 must be between 0% and 100% for `darken'", "darken(#123, -0.001)") assert_error_message("Amount 100.001 must be between 0% and 100% for `darken'", "darken(#123, 100.001)") end def test_darken_tests_types assert_error_message("$color: \"foo\" is not a color for `darken'", "darken(\"foo\", 10%)") assert_error_message("$amount: \"foo\" is not a number for `darken'", "darken(#fff, \"foo\")") end def test_saturate assert_equal("#d9f2d9", evaluate("saturate(hsl(120, 30, 90), 20%)")) assert_equal("#9e3f3f", evaluate("saturate(#855, 20%)")) assert_equal("black", evaluate("saturate(#000, 20%)")) assert_equal("white", evaluate("saturate(#fff, 20%)")) assert_equal("#33ff33", evaluate("saturate(#8a8, 100%)")) assert_equal("#88aa88", evaluate("saturate(#8a8, 0%)")) assert_equal("rgba(158, 63, 63, 0.5)", evaluate("saturate(rgba(136, 85, 85, 0.5), 20%)")) assert_equal("rgba(158, 63, 63, 0.5)", evaluate("saturate($color: rgba(136, 85, 85, 0.5), $amount: 20%)")) assert_equal("saturate(50%)", evaluate("saturate(50%)")) end def test_saturate_tests_bounds assert_error_message("Amount -0.001 must be between 0% and 100% for `saturate'", "saturate(#123, -0.001)") assert_error_message("Amount 100.001 must be between 0% and 100% for `saturate'", "saturate(#123, 100.001)") end def test_saturate_tests_types assert_error_message("$color: \"foo\" is not a color for `saturate'", "saturate(\"foo\", 10%)") assert_error_message("$amount: \"foo\" is not a number for `saturate'", "saturate(#fff, \"foo\")") end def test_desaturate assert_equal("#e3e8e3", evaluate("desaturate(hsl(120, 30, 90), 20%)")) assert_equal("#726b6b", evaluate("desaturate(#855, 20%)")) assert_equal("black", evaluate("desaturate(#000, 20%)")) assert_equal("white", evaluate("desaturate(#fff, 20%)")) assert_equal("#999999", evaluate("desaturate(#8a8, 100%)")) assert_equal("#88aa88", evaluate("desaturate(#8a8, 0%)")) assert_equal("rgba(114, 107, 107, 0.5)", evaluate("desaturate(rgba(136, 85, 85, 0.5), 20%)")) assert_equal("rgba(114, 107, 107, 0.5)", evaluate("desaturate($color: rgba(136, 85, 85, 0.5), $amount: 20%)")) end def test_desaturate_tests_bounds assert_error_message("Amount -0.001 must be between 0% and 100% for `desaturate'", "desaturate(#123, -0.001)") assert_error_message("Amount 100.001 must be between 0% and 100% for `desaturate'", "desaturate(#123, 100.001)") end def test_desaturate_tests_types assert_error_message("$color: \"foo\" is not a color for `desaturate'", "desaturate(\"foo\", 10%)") assert_error_message("$amount: \"foo\" is not a number for `desaturate'", "desaturate(#fff, \"foo\")") end def test_adjust_hue assert_equal("#deeded", evaluate("adjust-hue(hsl(120, 30, 90), 60deg)")) assert_equal("#ededde", evaluate("adjust-hue(hsl(120, 30, 90), -60deg)")) assert_equal("#886a11", evaluate("adjust-hue(#811, 45deg)")) assert_equal("black", evaluate("adjust-hue(#000, 45deg)")) assert_equal("white", evaluate("adjust-hue(#fff, 45deg)")) assert_equal("#88aa88", evaluate("adjust-hue(#8a8, 360deg)")) assert_equal("#88aa88", evaluate("adjust-hue(#8a8, 0deg)")) assert_equal("rgba(136, 106, 17, 0.5)", evaluate("adjust-hue(rgba(136, 17, 17, 0.5), 45deg)")) assert_equal("rgba(136, 106, 17, 0.5)", evaluate("adjust-hue($color: rgba(136, 17, 17, 0.5), $degrees: 45deg)")) end def test_adjust_hue_tests_types assert_error_message("$color: \"foo\" is not a color for `adjust-hue'", "adjust-hue(\"foo\", 10%)") assert_error_message("$degrees: \"foo\" is not a number for `adjust-hue'", "adjust-hue(#fff, \"foo\")") end def test_adjust_color # HSL assert_equal(evaluate("hsl(180, 30, 90)"), evaluate("adjust-color(hsl(120, 30, 90), $hue: 60deg)")) assert_equal(evaluate("hsl(120, 50, 90)"), evaluate("adjust-color(hsl(120, 30, 90), $saturation: 20%)")) assert_equal(evaluate("hsl(120, 30, 60)"), evaluate("adjust-color(hsl(120, 30, 90), $lightness: -30%)")) # RGB assert_equal(evaluate("rgb(15, 20, 30)"), evaluate("adjust-color(rgb(10, 20, 30), $red: 5)")) assert_equal(evaluate("rgb(10, 15, 30)"), evaluate("adjust-color(rgb(10, 20, 30), $green: -5)")) assert_equal(evaluate("rgb(10, 20, 40)"), evaluate("adjust-color(rgb(10, 20, 30), $blue: 10)")) # Alpha assert_equal(evaluate("hsla(120, 30, 90, 0.65)"), evaluate("adjust-color(hsl(120, 30, 90), $alpha: -0.35)")) assert_equal(evaluate("rgba(10, 20, 30, 0.9)"), evaluate("adjust-color(rgba(10, 20, 30, 0.4), $alpha: 0.5)")) # HSL composability assert_equal(evaluate("hsl(180, 20, 90)"), evaluate("adjust-color(hsl(120, 30, 90), $hue: 60deg, $saturation: -10%)")) assert_equal(evaluate("hsl(180, 20, 95)"), evaluate("adjust-color(hsl(120, 30, 90), $hue: 60deg, $saturation: -10%, $lightness: 5%)")) assert_equal(evaluate("hsla(120, 20, 95, 0.3)"), evaluate("adjust-color(hsl(120, 30, 90), $saturation: -10%, $lightness: 5%, $alpha: -0.7)")) # RGB composability assert_equal(evaluate("rgb(15, 20, 29)"), evaluate("adjust-color(rgb(10, 20, 30), $red: 5, $blue: -1)")) assert_equal(evaluate("rgb(15, 45, 29)"), evaluate("adjust-color(rgb(10, 20, 30), $red: 5, $green: 25, $blue: -1)")) assert_equal(evaluate("rgba(10, 25, 29, 0.7)"), evaluate("adjust-color(rgb(10, 20, 30), $green: 5, $blue: -1, $alpha: -0.3)")) # HSL range restriction assert_equal(evaluate("hsl(120, 30, 90)"), evaluate("adjust-color(hsl(120, 30, 90), $hue: 720deg)")) assert_equal(evaluate("hsl(120, 0, 90)"), evaluate("adjust-color(hsl(120, 30, 90), $saturation: -90%)")) assert_equal(evaluate("hsl(120, 30, 100)"), evaluate("adjust-color(hsl(120, 30, 90), $lightness: 30%)")) # RGB range restriction assert_equal(evaluate("rgb(255, 20, 30)"), evaluate("adjust-color(rgb(10, 20, 30), $red: 250)")) assert_equal(evaluate("rgb(10, 0, 30)"), evaluate("adjust-color(rgb(10, 20, 30), $green: -30)")) assert_equal(evaluate("rgb(10, 20, 0)"), evaluate("adjust-color(rgb(10, 20, 30), $blue: -40)")) end def test_adjust_color_tests_types assert_error_message("$color: \"foo\" is not a color for `adjust-color'", "adjust-color(foo, $hue: 10)") # HSL assert_error_message("$hue: \"foo\" is not a number for `adjust-color'", "adjust-color(blue, $hue: foo)") assert_error_message("$saturation: \"foo\" is not a number for `adjust-color'", "adjust-color(blue, $saturation: foo)") assert_error_message("$lightness: \"foo\" is not a number for `adjust-color'", "adjust-color(blue, $lightness: foo)") # RGB assert_error_message("$red: \"foo\" is not a number for `adjust-color'", "adjust-color(blue, $red: foo)") assert_error_message("$green: \"foo\" is not a number for `adjust-color'", "adjust-color(blue, $green: foo)") assert_error_message("$blue: \"foo\" is not a number for `adjust-color'", "adjust-color(blue, $blue: foo)") # Alpha assert_error_message("$alpha: \"foo\" is not a number for `adjust-color'", "adjust-color(blue, $alpha: foo)") end def test_adjust_color_tests_arg_range # HSL assert_error_message("$saturation: Amount 101% must be between -100% and 100% for `adjust-color'", "adjust-color(blue, $saturation: 101%)") assert_error_message("$saturation: Amount -101% must be between -100% and 100% for `adjust-color'", "adjust-color(blue, $saturation: -101%)") assert_error_message("$lightness: Amount 101% must be between -100% and 100% for `adjust-color'", "adjust-color(blue, $lightness: 101%)") assert_error_message("$lightness: Amount -101% must be between -100% and 100% for `adjust-color'", "adjust-color(blue, $lightness: -101%)") # RGB assert_error_message("$red: Amount 256 must be between -255 and 255 for `adjust-color'", "adjust-color(blue, $red: 256)") assert_error_message("$red: Amount -256 must be between -255 and 255 for `adjust-color'", "adjust-color(blue, $red: -256)") assert_error_message("$green: Amount 256 must be between -255 and 255 for `adjust-color'", "adjust-color(blue, $green: 256)") assert_error_message("$green: Amount -256 must be between -255 and 255 for `adjust-color'", "adjust-color(blue, $green: -256)") assert_error_message("$blue: Amount 256 must be between -255 and 255 for `adjust-color'", "adjust-color(blue, $blue: 256)") assert_error_message("$blue: Amount -256 must be between -255 and 255 for `adjust-color'", "adjust-color(blue, $blue: -256)") # Alpha assert_error_message("$alpha: Amount 1.1 must be between -1 and 1 for `adjust-color'", "adjust-color(blue, $alpha: 1.1)") assert_error_message("$alpha: Amount -1.1 must be between -1 and 1 for `adjust-color'", "adjust-color(blue, $alpha: -1.1)") end def test_adjust_color_argument_errors assert_error_message("Unknown argument $hoo (260deg) for `adjust-color'", "adjust-color(blue, $hoo: 260deg)") assert_error_message("Cannot specify HSL and RGB values for a color at the same time for `adjust-color'", "adjust-color(blue, $hue: 120deg, $red: 10)"); assert_error_message("10px is not a keyword argument for `adjust_color'", "adjust-color(blue, 10px)") assert_error_message("10px is not a keyword argument for `adjust_color'", "adjust-color(blue, 10px, 20px)") assert_error_message("10px is not a keyword argument for `adjust_color'", "adjust-color(blue, 10px, $hue: 180deg)") end def test_scale_color # HSL assert_equal(evaluate("hsl(120, 51, 90)"), evaluate("scale-color(hsl(120, 30, 90), $saturation: 30%)")) assert_equal(evaluate("hsl(120, 30, 76.5)"), evaluate("scale-color(hsl(120, 30, 90), $lightness: -15%)")) # RGB assert_equal(evaluate("rgb(157, 20, 30)"), evaluate("scale-color(rgb(10, 20, 30), $red: 60%)")) assert_equal(evaluate("rgb(10, 38.8, 30)"), evaluate("scale-color(rgb(10, 20, 30), $green: 8%)")) assert_equal(evaluate("rgb(10, 20, 20)"), evaluate("scale-color(rgb(10, 20, 30), $blue: -(1/3)*100%)")) # Alpha assert_equal(evaluate("hsla(120, 30, 90, 0.86)"), evaluate("scale-color(hsl(120, 30, 90), $alpha: -14%)")) assert_equal(evaluate("rgba(10, 20, 30, 0.82)"), evaluate("scale-color(rgba(10, 20, 30, 0.8), $alpha: 10%)")) # HSL composability assert_equal(evaluate("hsl(120, 51, 76.5)"), evaluate("scale-color(hsl(120, 30, 90), $saturation: 30%, $lightness: -15%)")) assert_equal(evaluate("hsla(120, 51, 90, 0.2)"), evaluate("scale-color(hsl(120, 30, 90), $saturation: 30%, $alpha: -80%)")) # RGB composability assert_equal(evaluate("rgb(157, 38.8, 30)"), evaluate("scale-color(rgb(10, 20, 30), $red: 60%, $green: 8%)")) assert_equal(evaluate("rgb(157, 38.8, 20)"), evaluate("scale-color(rgb(10, 20, 30), $red: 60%, $green: 8%, $blue: -(1/3)*100%)")) assert_equal(evaluate("rgba(10, 38.8, 20, 0.55)"), evaluate("scale-color(rgba(10, 20, 30, 0.5), $green: 8%, $blue: -(1/3)*100%, $alpha: 10%)")) # Extremes assert_equal(evaluate("hsl(120, 100, 90)"), evaluate("scale-color(hsl(120, 30, 90), $saturation: 100%)")) assert_equal(evaluate("hsl(120, 30, 90)"), evaluate("scale-color(hsl(120, 30, 90), $saturation: 0%)")) assert_equal(evaluate("hsl(120, 0, 90)"), evaluate("scale-color(hsl(120, 30, 90), $saturation: -100%)")) end def test_scale_color_tests_types assert_error_message("$color: \"foo\" is not a color for `scale-color'", "scale-color(foo, $red: 10%)") # HSL assert_error_message("$saturation: \"foo\" is not a number for `scale-color'", "scale-color(blue, $saturation: foo)") assert_error_message("$lightness: \"foo\" is not a number for `scale-color'", "scale-color(blue, $lightness: foo)") # RGB assert_error_message("$red: \"foo\" is not a number for `scale-color'", "scale-color(blue, $red: foo)") assert_error_message("$green: \"foo\" is not a number for `scale-color'", "scale-color(blue, $green: foo)") assert_error_message("$blue: \"foo\" is not a number for `scale-color'", "scale-color(blue, $blue: foo)") # Alpha assert_error_message("$alpha: \"foo\" is not a number for `scale-color'", "scale-color(blue, $alpha: foo)") end def test_scale_color_argument_errors # Range assert_error_message("$saturation: Amount 101% must be between -100% and 100% for `scale-color'", "scale-color(blue, $saturation: 101%)") assert_error_message("$red: Amount -101% must be between -100% and 100% for `scale-color'", "scale-color(blue, $red: -101%)") assert_error_message("$alpha: Amount -101% must be between -100% and 100% for `scale-color'", "scale-color(blue, $alpha: -101%)") # Unit assert_error_message("Expected $saturation to have a unit of % but got 80 for `scale-color'", "scale-color(blue, $saturation: 80)") assert_error_message("Expected $alpha to have a unit of % but got 0.5 for `scale-color'", "scale-color(blue, $alpha: 0.5)") # Unknown argument assert_error_message("Unknown argument $hue (80%) for `scale-color'", "scale-color(blue, $hue: 80%)") # Non-keyword arg assert_error_message("10px is not a keyword argument for `scale_color'", "scale-color(blue, 10px)") # HSL/RGB
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/test/sass/encoding_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/encoding_test.rb
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/../test_helper' require File.dirname(__FILE__) + '/test_helper' require 'sass/util/test' class EncodingTest < MiniTest::Test include Sass::Util::Test def test_encoding_error render("foo\nbar\nb\xFEaz".force_encoding("utf-8")) assert(false, "Expected exception") rescue Sass::SyntaxError => e assert_equal(3, e.sass_line) assert_equal('Invalid UTF-8 character "\xFE"', e.message) end def test_ascii_incompatible_encoding_error template = "foo\nbar\nb_z".encode("utf-16le") template[9] = "\xFE".force_encoding("utf-16le") render(template) assert(false, "Expected exception") rescue Sass::SyntaxError => e assert_equal(3, e.sass_line) assert_equal('Invalid UTF-16LE character "\xFE"', e.message) end def test_prefers_charset_to_ruby_encoding assert_renders_encoded(<<CSS, <<SASS.encode("IBM866").force_encoding("UTF-8")) @charset "UTF-8"; fЖЖ { a: b; } CSS @charset "ibm866" fЖЖ a: b SASS end def test_uses_ruby_encoding_without_charset assert_renders_encoded(<<CSS, <<SASS.encode("IBM866")) @charset "UTF-8"; тАЬ { a: b; } CSS тАЬ a: b SASS end def test_multibyte_charset_without_bom_declared_as_binary engine = Sass::Engine.new(<<SASS.encode("UTF-16LE").force_encoding("BINARY")) @charset "utf-16le" fóó a: b SASS # Since multibyte encodings' @charset declarations aren't # ASCII-compatible, we have to interpret the files as UTF-8 which will # inevitably fail. assert_raise_message(Sass::SyntaxError, "Invalid UTF-8 character \"\\xF3\"") {engine.render} end def test_multibyte_charset_without_bom_declared_as_utf_8 engine = Sass::Engine.new(<<SASS.encode("UTF-16LE").force_encoding("UTF-8")) @charset "utf-16le" fóó a: b SASS # Since multibyte encodings' @charset declarations aren't # ASCII-compatible, we have to interpret the files as UTF-8 which will # inevitably fail. assert_raise_message(Sass::SyntaxError, "Invalid UTF-8 character \"\\xF3\"") {engine.render} end def test_utf_16le_with_bom assert_renders_encoded(<<CSS, <<SASS.encode("UTF-16LE").force_encoding("BINARY")) @charset "UTF-8"; fóó { a: b; } CSS \uFEFFfóó a: b SASS end def test_utf_16be_with_bom assert_renders_encoded(<<CSS, <<SASS.encode("UTF-16BE").force_encoding("BINARY")) @charset "UTF-8"; fóó { a: b; } CSS \uFEFFfóó a: b SASS end def test_utf_8_with_bom assert_renders_encoded(<<CSS, <<SASS.force_encoding("BINARY")) @charset "UTF-8"; fóó { a: b; } CSS \uFEFFfóó a: b SASS end def test_charset_with_multibyte_encoding engine = Sass::Engine.new(<<SASS) @charset "utf-32be" fóó a: b SASS # The charset declaration is just false here, so we should get an # encoding error. assert_raise_message(Sass::SyntaxError, "Invalid UTF-32BE character \"\\xC3\"") {engine.render} end def test_charset_with_special_case_encoding # For some reason, a file with an ASCII-compatible UTF-16 charset # declaration is specced to be parsed as UTF-8. assert_renders_encoded(<<CSS, <<SASS.force_encoding("BINARY")) @charset "UTF-8"; fóó { a: b; } CSS @charset "utf-16" fóó a: b SASS end def test_compressed_output_uses_bom assert_equal("\uFEFFfóó{a:b}\n", render(<<SASS, :style => :compressed)) fóó a: b SASS end def test_newline_normalization assert_equal("/* foo\nbar\nbaz\nbang\nqux */\n", render("/* foo\nbar\r\nbaz\fbang\rqux */", :syntax => :scss)) end def test_null_normalization assert_equal(<<CSS, render("/* foo\x00bar\x00baz */", :syntax => :scss)) @charset "UTF-8"; /* foo�bar�baz */ CSS end # Regression def test_multibyte_prop_name assert_equal(<<CSS, render(<<SASS)) @charset "UTF-8"; #bar { cölor: blue; } CSS #bar cölor: blue SASS end def test_multibyte_and_interpolation assert_equal(<<CSS, render(<<SCSS, :syntax => :scss)) #bar { background: a 0%; } CSS #bar { //  background: \#{a} 0%; } SCSS end private def assert_renders_encoded(css, sass) result = render(sass) assert_equal css.encoding, result.encoding assert_equal css, result end def render(sass, options = {}) munge_filename options Sass::Engine.new(sass, options).render 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/test/sass/mock_importer.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/mock_importer.rb
class MockImporter < Sass::Importers::Base def initialize(name = "mock") @name = name @imports = Hash.new({}) end def find_relative(uri, base, options) nil end def find(uri, options) contents = @imports[uri][:contents] return unless contents options[:syntax] = @imports[uri][:syntax] options[:filename] = uri options[:importer] = self @imports[uri][:engine] = Sass::Engine.new(contents, options) end def mtime(uri, options) @imports[uri][:mtime] end def key(uri, options) ["mock", uri] end def to_s @name end # Methods for testing def add_import(uri, contents, syntax = :scss, mtime = Time.now - 10) @imports[uri] = { :contents => contents, :mtime => mtime, :syntax => syntax } end def touch(uri) @imports[uri][:mtime] = Time.now end def engine(uri) @imports[uri][:engine] 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/test/sass/importer_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/importer_test.rb
require File.dirname(__FILE__) + '/../test_helper' require File.dirname(__FILE__) + '/test_helper' require 'mock_importer' require 'sass/plugin' class ImporterTest < MiniTest::Test class FruitImporter < Sass::Importers::Base def find(name, context = nil) fruit = parse(name) return unless fruit color = case fruit when "apple" "red" when "orange" "orange" else "blue" end contents = %Q{ $#{fruit}-color: #{color} !default; @mixin #{fruit} { color: $#{fruit}-color; } } Sass::Engine.new(contents, :filename => name, :syntax => :scss, :importer => self) end def key(name, context) [self.class.name, name] end def public_url(name, sourcemap_directory = nil) "http://#{parse(name)}.example.com/style.scss" end private def parse(name) name[%r{fruits/(\w+)(\.s[ac]ss)?}, 1] end end class NoPublicUrlImporter < FruitImporter def public_url(name, sourcemap_directory = nil) nil end private def parse(name) name[%r{ephemeral/(\w+)(\.s[ac]ss)?}, 1] end end # This class proves that you can override the extension scheme for importers class ReversedExtImporter < Sass::Importers::Filesystem def extensions {"sscs" => :scss, "ssas" => :sass} end end # This importer maps one import to another import # based on the mappings passed to importer's constructor. class IndirectImporter < Sass::Importers::Base def initialize(mappings, mtimes) @mappings = mappings @mtimes = mtimes end def find_relative(uri, base, options) nil end def find(name, options) if @mappings.has_key?(name) Sass::Engine.new( %Q[@import "#{@mappings[name]}";], options.merge( :filename => name, :syntax => :scss, :importer => self ) ) end end def mtime(uri, options) @mtimes.fetch(uri, @mtimes.has_key?(uri) ? Time.now : nil) end def key(uri, options) [self.class.name, uri] end def to_s "IndirectImporter(#{@mappings.keys.join(", ")})" end end # This importer maps the import to single class # based on the mappings passed to importer's constructor. class ClassImporter < Sass::Importers::Base def initialize(mappings, mtimes) @mappings = mappings @mtimes = mtimes end def find_relative(uri, base, options) nil end def find(name, options) if @mappings.has_key?(name) Sass::Engine.new( %Q[.#{name}{#{@mappings[name]}}], options.merge( :filename => name, :syntax => :scss, :importer => self ) ) end end def mtime(uri, options) @mtimes.fetch(uri, @mtimes.has_key?(uri) ? Time.now : nil) end def key(uri, options) [self.class.name, uri] end def to_s "ClassImporter(#{@mappings.keys.join(", ")})" end end def test_can_resolve_generated_imports scss_file = %Q{ $pear-color: green; @import "fruits/apple"; @import "fruits/orange"; @import "fruits/pear"; .apple { @include apple; } .orange { @include orange; } .pear { @include pear; } } css_file = <<CSS .apple { color: red; } .orange { color: orange; } .pear { color: green; } CSS options = {:style => :compact, :load_paths => [FruitImporter.new], :syntax => :scss} assert_equal css_file, Sass::Engine.new(scss_file, options).render end def test_extension_overrides FileUtils.mkdir_p(absolutize("tmp")) open(absolutize("tmp/foo.ssas"), "w") {|f| f.write(".foo\n reversed: true\n")} open(absolutize("tmp/bar.sscs"), "w") {|f| f.write(".bar {reversed: true}\n")} scss_file = %Q{ @import "foo", "bar"; @import "foo.ssas", "bar.sscs"; } css_file = <<CSS .foo { reversed: true; } .bar { reversed: true; } .foo { reversed: true; } .bar { reversed: true; } CSS options = {:style => :compact, :load_paths => [ReversedExtImporter.new(absolutize("tmp"))], :syntax => :scss} assert_equal css_file, Sass::Engine.new(scss_file, options).render ensure FileUtils.rm_rf(absolutize("tmp")) end def test_staleness_check_across_importers file_system_importer = Sass::Importers::Filesystem.new(fixture_dir) # Make sure the first import is older indirect_importer = IndirectImporter.new({"apple" => "pear"}, {"apple" => Time.now - 1}) # Make css file is newer so the dependencies are the only way for the css file to be out of date. FileUtils.touch(fixture_file("test_staleness_check_across_importers.css")) # Make sure the first import is older class_importer = ClassImporter.new({"pear" => %Q{color: green;}}, {"pear" => Time.now + 1}) options = { :style => :compact, :filename => fixture_file("test_staleness_check_across_importers.scss"), :importer => file_system_importer, :load_paths => [file_system_importer, indirect_importer, class_importer], :syntax => :scss } assert_equal File.read(fixture_file("test_staleness_check_across_importers.css")), Sass::Engine.new(File.read(fixture_file("test_staleness_check_across_importers.scss")), options).render checker = Sass::Plugin::StalenessChecker.new(options) assert checker.stylesheet_needs_update?( fixture_file("test_staleness_check_across_importers.css"), fixture_file("test_staleness_check_across_importers.scss"), file_system_importer ) end def test_source_map_with_only_css_uri_supports_public_url_imports fruit_importer = FruitImporter.new options = { :filename => 'fruits/orange', :importer => fruit_importer, :syntax => :scss } engine = Sass::Engine.new(<<SCSS, options) .orchard { color: blue; } SCSS _, sourcemap = engine.render_with_sourcemap('sourcemap_uri') assert_equal <<JSON.strip, sourcemap.to_json(:css_uri => 'css_uri') { "version": 3, "mappings": "AAAA,QAAS;EACP,KAAK,EAAE,IAAI", "sources": ["http://orange.example.com/style.scss"], "names": [], "file": "css_uri" } JSON end def test_source_map_with_only_css_uri_can_have_no_public_url ephemeral_importer = NoPublicUrlImporter.new mock_importer = MockImporter.new def mock_importer.public_url(name, sourcemap_directory = nil) "source_uri" end options = { :filename => filename_for_test, :sourcemap_filename => sourcemap_filename_for_test, :importer => mock_importer, :syntax => :scss, :load_paths => [ephemeral_importer], :cache => false } engine = Sass::Engine.new(<<SCSS, options) @import "ephemeral/orange"; .orange { @include orange; } SCSS css_output, sourcemap = engine.render_with_sourcemap('sourcemap_uri') assert_equal <<CSS.strip, css_output.strip .orange { color: orange; } /*# sourceMappingURL=sourcemap_uri */ CSS map = sourcemap.to_json(:css_uri => 'css_uri') assert_equal <<JSON.strip, map { "version": 3, "mappings": "AACA,OAAQ", "sources": ["source_uri"], "names": [], "file": "css_uri" } JSON end def test_source_map_with_only_css_uri_falls_back_to_file_uris file_system_importer = Sass::Importers::Filesystem.new('.') options = { :filename => filename_for_test(:scss), :sourcemap_filename => sourcemap_filename_for_test, :importer => file_system_importer, :syntax => :scss } engine = Sass::Engine.new(<<SCSS, options) .foo {a: b} SCSS _, sourcemap = engine.render_with_sourcemap('http://1.example.com/style.map') uri = Sass::Util.file_uri_from_path(File.absolute_path(filename_for_test(:scss))) assert_equal <<JSON.strip, sourcemap.to_json(:css_uri => 'css_uri') { "version": 3, "mappings": "AAAA,IAAK;EAAC,CAAC,EAAE,CAAC", "sources": ["#{uri}"], "names": [], "file": "css_uri" } JSON end def test_source_map_with_css_uri_and_css_path_falls_back_to_file_uris file_system_importer = Sass::Importers::Filesystem.new('.') options = { :filename => filename_for_test(:scss), :sourcemap_filename => sourcemap_filename_for_test, :importer => file_system_importer, :syntax => :scss } engine = Sass::Engine.new(<<SCSS, options) .foo {a: b} SCSS _, sourcemap = engine.render_with_sourcemap('http://1.example.com/style.map') uri = Sass::Util.file_uri_from_path(File.absolute_path(filename_for_test(:scss))) assert_equal <<JSON.strip, sourcemap.to_json(:css_uri => 'css_uri', :css_path => 'css_path') { "version": 3, "mappings": "AAAA,IAAK;EAAC,CAAC,EAAE,CAAC", "sources": ["#{uri}"], "names": [], "file": "css_uri" } JSON end def test_source_map_with_css_uri_and_sourcemap_path_supports_filesystem_importer file_system_importer = Sass::Importers::Filesystem.new('.') css_uri = 'css_uri' sourcemap_path = 'map/style.map' options = { :filename => 'sass/style.scss', :sourcemap_filename => sourcemap_path, :importer => file_system_importer, :syntax => :scss } engine = Sass::Engine.new(<<SCSS, options) .foo {a: b} SCSS rendered, sourcemap = engine.render_with_sourcemap('http://1.example.com/style.map') rendered, sourcemap = engine.render_with_sourcemap('http://map.example.com/map/style.map') assert_equal <<JSON.strip, sourcemap.to_json(:css_uri => css_uri, :sourcemap_path => sourcemap_path) { "version": 3, "mappings": "AAAA,IAAK;EAAC,CAAC,EAAE,CAAC", "sources": ["../sass/style.scss"], "names": [], "file": "css_uri" } JSON end def test_source_map_with_css_path_and_sourcemap_path_supports_file_system_importer file_system_importer = Sass::Importers::Filesystem.new('.') sass_path = 'sass/style.scss' css_path = 'static/style.css' sourcemap_path = 'map/style.map' options = { :filename => sass_path, :sourcemap_filename => sourcemap_path, :importer => file_system_importer, :syntax => :scss } engine = Sass::Engine.new(<<SCSS, options) .foo {a: b} SCSS _, sourcemap = engine.render_with_sourcemap('http://map.example.com/map/style.map') assert_equal <<JSON.strip, sourcemap.to_json(:css_path => css_path, :sourcemap_path => sourcemap_path) { "version": 3, "mappings": "AAAA,IAAK;EAAC,CAAC,EAAE,CAAC", "sources": ["../sass/style.scss"], "names": [], "file": "../static/style.css" } JSON end def test_render_with_sourcemap_requires_filename file_system_importer = Sass::Importers::Filesystem.new('.') engine = Sass::Engine.new(".foo {a: b}", :syntax => :scss, :importer => file_system_importer) assert_raise_message(Sass::SyntaxError, <<MESSAGE) {engine.render_with_sourcemap('sourcemap_url')} Error generating source map: couldn't determine public URL for the source stylesheet. No filename is available so there's nothing for the source map to link to. MESSAGE end def test_render_with_sourcemap_requires_importer_with_public_url class_importer = ClassImporter.new({"pear" => "color: green;"}, {"pear" => Time.now}) assert_raise_message(Sass::SyntaxError, <<MESSAGE) {class_importer.find("pear", {}).render_with_sourcemap('sourcemap_url')} Error generating source map: couldn't determine public URL for "pear". Without a public URL, there's nothing for the source map to link to. Custom importers should define the #public_url method. MESSAGE end def fixture_dir File.join(File.dirname(__FILE__), "fixtures") end def fixture_file(path) File.join(fixture_dir, path) end def test_filesystem_importer_eql importer = Sass::Importers::Filesystem.new('.') assert importer.eql?(Sass::Importers::Filesystem.new('.')) assert importer.eql?(ReversedExtImporter.new('.')) assert !importer.eql?(Sass::Importers::Filesystem.new('foo')) assert !importer.eql?(nil) assert !importer.eql?('foo') end def test_absolute_files_across_template_locations importer = Sass::Importers::Filesystem.new(absolutize 'templates') refute_nil importer.mtime(absolutize('more_templates/more1.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/test/sass/source_map_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/source_map_test.rb
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/../test_helper' require File.dirname(__FILE__) + '/test_helper' class SourcemapTest < MiniTest::Test def test_to_json_requires_args _, sourcemap = render_with_sourcemap('') assert_raises(ArgumentError) {sourcemap.to_json({})} assert_raises(ArgumentError) {sourcemap.to_json({:css_path => 'foo'})} assert_raises(ArgumentError) {sourcemap.to_json({:sourcemap_path => 'foo'})} end def test_simple_mapping_scss assert_parses_with_sourcemap <<SCSS, <<CSS, <<JSON a { foo: bar; /* SOME COMMENT */ font-size: 12px; } SCSS a { foo: bar; /* SOME COMMENT */ font-size: 12px; } /*# sourceMappingURL=test.css.map */ CSS { "version": 3, "mappings": "AAAA,CAAE;EACA,GAAG,EAAE,GAAG;EACV,kBAAkB;EAChB,SAAS,EAAE,IAAI", "sources": ["test_simple_mapping_scss_inline.scss"], "names": [], "file": "test.css" } JSON end def test_simple_mapping_sass silence_warnings {assert_parses_with_sourcemap <<SASS, <<CSS, <<JSON, :syntax => :sass} a foo: bar /* SOME COMMENT */ :font-size 12px SASS a { foo: bar; /* SOME COMMENT */ font-size: 12px; } /*# sourceMappingURL=test.css.map */ CSS { "version": 3, "mappings": "AAAA,CAAC;EACC,GAAG,EAAE,GAAG;;EAEP,SAAS,EAAC,IAAI", "sources": ["test_simple_mapping_sass_inline.sass"], "names": [], "file": "test.css" } JSON end def test_simple_mapping_with_file_uris uri = Sass::Util.file_uri_from_path(File.absolute_path(filename_for_test(:scss))) assert_parses_with_sourcemap <<SCSS, <<CSS, <<JSON, :sourcemap => :file a { foo: bar; /* SOME COMMENT */ font-size: 12px; } SCSS a { foo: bar; /* SOME COMMENT */ font-size: 12px; } /*# sourceMappingURL=test.css.map */ CSS { "version": 3, "mappings": "AAAA,CAAE;EACA,GAAG,EAAE,GAAG;EACV,kBAAkB;EAChB,SAAS,EAAE,IAAI", "sources": ["#{uri}"], "names": [], "file": "test.css" } JSON end def test_mapping_with_directory_scss options = {:filename => "scss/style.scss", :output => "css/style.css"} assert_parses_with_sourcemap <<SCSS, <<CSS, <<JSON, options a { foo: bar; /* SOME COMMENT */ font-size: 12px; } SCSS a { foo: bar; /* SOME COMMENT */ font-size: 12px; } /*# sourceMappingURL=style.css.map */ CSS { "version": 3, "mappings": "AAAA,CAAE;EACA,GAAG,EAAE,GAAG;EACV,kBAAkB;EAChB,SAAS,EAAE,IAAI", "sources": ["../scss/style.scss"], "names": [], "file": "style.css" } JSON end def test_mapping_with_directory_sass options = {:filename => "sass/style.sass", :output => "css/style.css", :syntax => :sass} silence_warnings {assert_parses_with_sourcemap <<SASS, <<CSS, <<JSON, options} a foo: bar /* SOME COMMENT */ :font-size 12px SASS a { foo: bar; /* SOME COMMENT */ font-size: 12px; } /*# sourceMappingURL=style.css.map */ CSS { "version": 3, "mappings": "AAAA,CAAC;EACC,GAAG,EAAE,GAAG;;EAEP,SAAS,EAAC,IAAI", "sources": ["../sass/style.sass"], "names": [], "file": "style.css" } JSON end def test_simple_charset_mapping_scss assert_parses_with_sourcemap <<SCSS, <<CSS, <<JSON a { fóó: bár; } SCSS @charset "UTF-8"; a { fóó: bár; } /*# sourceMappingURL=test.css.map */ CSS { "version": 3, "mappings": ";AAAA,CAAE;EACA,GAAG,EAAE,GAAG", "sources": ["test_simple_charset_mapping_scss_inline.scss"], "names": [], "file": "test.css" } JSON end def test_simple_charset_mapping_sass assert_parses_with_sourcemap <<SASS, <<CSS, <<JSON, :syntax => :sass a fóó: bár SASS @charset "UTF-8"; a { fóó: bár; } /*# sourceMappingURL=test.css.map */ CSS { "version": 3, "mappings": ";AAAA,CAAC;EACC,GAAG,EAAE,GAAG", "sources": ["test_simple_charset_mapping_sass_inline.sass"], "names": [], "file": "test.css" } JSON end def test_different_charset_than_encoding_scss assert_parses_with_sourcemap(<<SCSS.force_encoding("IBM866"), <<CSS, <<JSON) @charset "IBM866"; f\x86\x86 { \x86: b; } SCSS @charset "UTF-8"; fЖЖ { Ж: b; } /*# sourceMappingURL=test.css.map */ CSS { "version": 3, "mappings": ";AACA,GAAI;EACF,CAAC,EAAE,CAAC", "sources": ["test_different_charset_than_encoding_scss_inline.scss"], "names": [], "file": "test.css" } JSON end def test_different_charset_than_encoding_sass assert_parses_with_sourcemap(<<SASS.force_encoding("IBM866"), <<CSS, <<JSON, :syntax => :sass) @charset "IBM866" f\x86\x86 \x86: b SASS @charset "UTF-8"; fЖЖ { Ж: b; } /*# sourceMappingURL=test.css.map */ CSS { "version": 3, "mappings": ";AACA,GAAG;EACD,CAAC,EAAE,CAAC", "sources": ["test_different_charset_than_encoding_sass_inline.sass"], "names": [], "file": "test.css" } JSON end def test_import_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' @import {{1}}url(foo){{/1}},{{2}}url(moo) {{/2}}, {{3}}url(bar) {{/3}}; @import {{4}}url(baz) screen print{{/4}}; SCSS {{1}}@import url(foo){{/1}}; {{2}}@import url(moo){{/2}}; {{3}}@import url(bar){{/3}}; {{4}}@import url(baz) screen print{{/4}}; /*# sourceMappingURL=test.css.map */ CSS end def test_import_sourcemap_sass assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass @import {{1}}foo.css{{/1}},{{2}}moo.css{{/2}}, {{3}}bar.css{{/3}} @import {{4}}url(baz.css){{/4}} @import {{5}}url(qux.css) screen print{{/5}} SASS {{1}}@import url(foo.css){{/1}}; {{2}}@import url(moo.css){{/2}}; {{3}}@import url(bar.css){{/3}}; {{4}}@import url(baz.css){{/4}}; {{5}}@import url(qux.css) screen print{{/5}}; /*# sourceMappingURL=test.css.map */ CSS end def test_media_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' {{1}}@media screen, tv {{/1}}{ {{2}}body {{/2}}{ {{3}}max-width{{/3}}: {{4}}1070px{{/4}}; } } SCSS {{1}}@media screen, tv{{/1}} { {{2}}body{{/2}} { {{3}}max-width{{/3}}: {{4}}1070px{{/4}}; } } /*# sourceMappingURL=test.css.map */ CSS end def test_media_sourcemap_sass assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass {{1}}@media screen, tv{{/1}} {{2}}body{{/2}} {{3}}max-width{{/3}}: {{4}}1070px{{/4}} SASS {{1}}@media screen, tv{{/1}} { {{2}}body{{/2}} { {{3}}max-width{{/3}}: {{4}}1070px{{/4}}; } } /*# sourceMappingURL=test.css.map */ CSS end def test_interpolation_and_vars_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' $te: "te"; $teal: {{5}}teal{{/5}}; {{1}}p {{/1}}{ {{2}}con#{$te}nt{{/2}}: {{3}}"I a#{$te} #{5 + 10} pies!"{{/3}}; {{4}}color{{/4}}: $teal; } $name: foo; $attr: border; {{6}}p.#{$name} {{/6}}{ {{7}}#{$attr}-color{{/7}}: {{8}}blue{{/8}}; $font-size: 12px; $line-height: 30px; {{9}}font{{/9}}: {{10}}#{$font-size}/#{$line-height}{{/10}}; } SCSS {{1}}p{{/1}} { {{2}}content{{/2}}: {{3}}"I ate 15 pies!"{{/3}}; {{4}}color{{/4}}: {{5}}teal{{/5}}; } {{6}}p.foo{{/6}} { {{7}}border-color{{/7}}: {{8}}blue{{/8}}; {{9}}font{{/9}}: {{10}}12px/30px{{/10}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_interpolation_and_vars_sourcemap_sass assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass $te: "te" $teal: {{5}}teal{{/5}} {{1}}p{{/1}} {{2}}con#{$te}nt{{/2}}: {{3}}"I a#{$te} #{5 + 10} pies!"{{/3}} {{4}}color{{/4}}: $teal $name: foo $attr: border {{6}}p.#{$name}{{/6}} {{7}}#{$attr}-color{{/7}}: {{8}}blue{{/8}} $font-size: 12px $line-height: 30px {{9}}font{{/9}}: {{10}}#{$font-size}/#{$line-height}{{/10}} SASS {{1}}p{{/1}} { {{2}}content{{/2}}: {{3}}"I ate 15 pies!"{{/3}}; {{4}}color{{/4}}: {{5}}teal{{/5}}; } {{6}}p.foo{{/6}} { {{7}}border-color{{/7}}: {{8}}blue{{/8}}; {{9}}font{{/9}}: {{10}}12px/30px{{/10}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_selectors_properties_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' $width: 2px; $translucent-red: rgba(255, 0, 0, 0.5); {{1}}a {{/1}}{ {{9}}.special {{/9}}{ {{10}}color{{/10}}: {{11}}red{{/11}}; {{12}}&:hover {{/12}}{ {{13}}foo{{/13}}: {{14}}bar{{/14}}; {{15}}cursor{{/15}}: {{16}}e + -resize{{/16}}; {{17}}color{{/17}}: {{18}}opacify($translucent-red, 0.3){{/18}}; } {{19}}&:after {{/19}}{ {{20}}content{{/20}}: {{21}}"I ate #{5 + 10} pies #{$width} thick!"{{/21}}; } } {{22}}&:active {{/22}}{ {{23}}border{{/23}}: {{24}}$width solid black{{/24}}; } {{2}}/* SOME COMMENT */{{/2}} {{3}}font{{/3}}: {{4}}2px/3px {{/4}}{ {{5}}family{{/5}}: {{6}}fantasy{{/6}}; {{7}}size{{/7}}: {{8}}1em + (2em * 3){{/8}}; } } SCSS {{1}}a{{/1}} { {{2}}/* SOME COMMENT */{{/2}} {{3}}font{{/3}}: {{4}}2px/3px{{/4}}; {{5}}font-family{{/5}}: {{6}}fantasy{{/6}}; {{7}}font-size{{/7}}: {{8}}7em{{/8}}; } {{9}}a .special{{/9}} { {{10}}color{{/10}}: {{11}}red{{/11}}; } {{12}}a .special:hover{{/12}} { {{13}}foo{{/13}}: {{14}}bar{{/14}}; {{15}}cursor{{/15}}: {{16}}e-resize{{/16}}; {{17}}color{{/17}}: {{18}}rgba(255, 0, 0, 0.8){{/18}}; } {{19}}a .special:after{{/19}} { {{20}}content{{/20}}: {{21}}"I ate 15 pies 2px thick!"{{/21}}; } {{22}}a:active{{/22}} { {{23}}border{{/23}}: {{24}}2px solid black{{/24}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_selectors_properties_sourcemap_sass assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass $width: 2px $translucent-red: rgba(255, 0, 0, 0.5) {{1}}a{{/1}} {{9}}.special{{/9}} {{10}}color{{/10}}: {{11}}red{{/11}} {{12}}&:hover{{/12}} {{13}}foo{{/13}}: {{14}}bar{{/14}} {{15}}cursor{{/15}}: {{16}}e + -resize{{/16}} {{17}}color{{/17}}: {{18}}opacify($translucent-red, 0.3){{/18}} {{19}}&:after{{/19}} {{20}}content{{/20}}: {{21}}"I ate #{5 + 10} pies #{$width} thick!"{{/21}} {{22}}&:active{{/22}} {{23}}border{{/23}}: {{24}}$width solid black{{/24}} {{2}}/* SOME COMMENT */{{/2}} {{3}}font{{/3}}: {{4}}2px/3px{{/4}} {{5}}family{{/5}}: {{6}}fantasy{{/6}} {{7}}size{{/7}}: {{8}}1em + (2em * 3){{/8}} SASS {{1}}a{{/1}} { {{2}}/* SOME COMMENT */{{/2}} {{3}}font{{/3}}: {{4}}2px/3px{{/4}}; {{5}}font-family{{/5}}: {{6}}fantasy{{/6}}; {{7}}font-size{{/7}}: {{8}}7em{{/8}}; } {{9}}a .special{{/9}} { {{10}}color{{/10}}: {{11}}red{{/11}}; } {{12}}a .special:hover{{/12}} { {{13}}foo{{/13}}: {{14}}bar{{/14}}; {{15}}cursor{{/15}}: {{16}}e-resize{{/16}}; {{17}}color{{/17}}: {{18}}rgba(255, 0, 0, 0.8){{/18}}; } {{19}}a .special:after{{/19}} { {{20}}content{{/20}}: {{21}}"I ate 15 pies 2px thick!"{{/21}}; } {{22}}a:active{{/22}} { {{23}}border{{/23}}: {{24}}2px solid black{{/24}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_extend_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' {{1}}.error {{/1}}{ {{2}}border{{/2}}: {{3}}1px #ff00aa{{/3}}; {{4}}background-color{{/4}}: {{5}}#fdd{{/5}}; } {{6}}.seriousError {{/6}}{ @extend .error; {{7}}border-width{{/7}}: {{8}}3px{{/8}}; } SCSS {{1}}.error, .seriousError{{/1}} { {{2}}border{{/2}}: {{3}}1px #ff00aa{{/3}}; {{4}}background-color{{/4}}: {{5}}#fdd{{/5}}; } {{6}}.seriousError{{/6}} { {{7}}border-width{{/7}}: {{8}}3px{{/8}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_extend_sourcemap_sass assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass {{1}}.error{{/1}} {{2}}border{{/2}}: {{3}}1px #f00{{/3}} {{4}}background-color{{/4}}: {{5}}#fdd{{/5}} {{6}}.seriousError{{/6}} @extend .error {{7}}border-width{{/7}}: {{8}}3px{{/8}} SASS {{1}}.error, .seriousError{{/1}} { {{2}}border{{/2}}: {{3}}1px #f00{{/3}}; {{4}}background-color{{/4}}: {{5}}#fdd{{/5}}; } {{6}}.seriousError{{/6}} { {{7}}border-width{{/7}}: {{8}}3px{{/8}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_for_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' @for $i from 1 through 3 { {{1}}{{4}}{{7}}.item-#{$i} {{/1}}{{/4}}{{/7}}{ {{2}}{{5}}{{8}}width{{/2}}{{/5}}{{/8}}: {{3}}{{6}}{{9}}2em * $i{{/3}}{{/6}}{{/9}}; } } SCSS {{1}}.item-1{{/1}} { {{2}}width{{/2}}: {{3}}2em{{/3}}; } {{4}}.item-2{{/4}} { {{5}}width{{/5}}: {{6}}4em{{/6}}; } {{7}}.item-3{{/7}} { {{8}}width{{/8}}: {{9}}6em{{/9}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_for_sourcemap_sass assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass @for $i from 1 through 3 {{1}}{{4}}{{7}}.item-#{$i}{{/1}}{{/4}}{{/7}} {{2}}{{5}}{{8}}width{{/2}}{{/5}}{{/8}}: {{3}}{{6}}{{9}}2em * $i{{/3}}{{/6}}{{/9}} SASS {{1}}.item-1{{/1}} { {{2}}width{{/2}}: {{3}}2em{{/3}}; } {{4}}.item-2{{/4}} { {{5}}width{{/5}}: {{6}}4em{{/6}}; } {{7}}.item-3{{/7}} { {{8}}width{{/8}}: {{9}}6em{{/9}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_while_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' $i: 6; @while $i > 0 { {{1}}{{4}}{{7}}.item-#{$i} {{/1}}{{/4}}{{/7}}{ {{2}}{{5}}{{8}}width{{/2}}{{/5}}{{/8}}: {{3}}{{6}}{{9}}2em * $i{{/3}}{{/6}}{{/9}}; } $i: $i - 2 !global; } SCSS {{1}}.item-6{{/1}} { {{2}}width{{/2}}: {{3}}12em{{/3}}; } {{4}}.item-4{{/4}} { {{5}}width{{/5}}: {{6}}8em{{/6}}; } {{7}}.item-2{{/7}} { {{8}}width{{/8}}: {{9}}4em{{/9}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_while_sourcemap_sass assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass $i: 6 @while $i > 0 {{1}}{{4}}{{7}}.item-#{$i}{{/1}}{{/4}}{{/7}} {{2}}{{5}}{{8}}width{{/2}}{{/5}}{{/8}}: {{3}}{{6}}{{9}}2em * $i{{/3}}{{/6}}{{/9}} $i: $i - 2 !global SASS {{1}}.item-6{{/1}} { {{2}}width{{/2}}: {{3}}12em{{/3}}; } {{4}}.item-4{{/4}} { {{5}}width{{/5}}: {{6}}8em{{/6}}; } {{7}}.item-2{{/7}} { {{8}}width{{/8}}: {{9}}4em{{/9}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_each_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' @each $animal in puma, sea-slug, egret, salamander { {{1}}{{4}}{{7}}{{10}}.#{$animal}-icon {{/1}}{{/4}}{{/7}}{{/10}}{ {{2}}{{5}}{{8}}{{11}}background-image{{/2}}{{/5}}{{/8}}{{/11}}: {{3}}{{6}}{{9}}{{12}}url('/images/#{$animal}.png'){{/3}}{{/6}}{{/9}}{{/12}}; } } SCSS {{1}}.puma-icon{{/1}} { {{2}}background-image{{/2}}: {{3}}url("/images/puma.png"){{/3}}; } {{4}}.sea-slug-icon{{/4}} { {{5}}background-image{{/5}}: {{6}}url("/images/sea-slug.png"){{/6}}; } {{7}}.egret-icon{{/7}} { {{8}}background-image{{/8}}: {{9}}url("/images/egret.png"){{/9}}; } {{10}}.salamander-icon{{/10}} { {{11}}background-image{{/11}}: {{12}}url("/images/salamander.png"){{/12}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_each_sourcemap_sass assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass @each $animal in puma, sea-slug, egret, salamander {{1}}{{4}}{{7}}{{10}}.#{$animal}-icon{{/1}}{{/4}}{{/7}}{{/10}} {{2}}{{5}}{{8}}{{11}}background-image{{/2}}{{/5}}{{/8}}{{/11}}: {{3}}{{6}}{{9}}{{12}}url('/images/#{$animal}.png'){{/3}}{{/6}}{{/9}}{{/12}} SASS {{1}}.puma-icon{{/1}} { {{2}}background-image{{/2}}: {{3}}url("/images/puma.png"){{/3}}; } {{4}}.sea-slug-icon{{/4}} { {{5}}background-image{{/5}}: {{6}}url("/images/sea-slug.png"){{/6}}; } {{7}}.egret-icon{{/7}} { {{8}}background-image{{/8}}: {{9}}url("/images/egret.png"){{/9}}; } {{10}}.salamander-icon{{/10}} { {{11}}background-image{{/11}}: {{12}}url("/images/salamander.png"){{/12}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_mixin_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' @mixin large-text { font: { {{2}}size{{/2}}: {{3}}20px{{/3}}; {{4}}weight{{/4}}: {{5}}bold{{/5}}; } {{6}}color{{/6}}: {{7}}#ff0000{{/7}}; } {{1}}.page-title {{/1}}{ @include large-text; {{8}}padding{{/8}}: {{9}}4px{{/9}}; } @mixin dashed-border($color, $width: {{14}}1in{{/14}}) { border: { {{11}}{{18}}color{{/11}}{{/18}}: $color; {{13}}{{20}}width{{/13}}{{/20}}: $width; {{15}}{{22}}style{{/15}}{{/22}}: {{16}}{{23}}dashed{{/16}}{{/23}}; } } {{10}}p {{/10}}{ @include dashed-border({{12}}blue{{/12}}); } {{17}}h1 {{/17}}{ @include dashed-border({{19}}blue{{/19}}, {{21}}2in{{/21}}); } @mixin box-shadow($shadows...) { {{25}}-moz-box-shadow{{/25}}: {{26}}$shadows{{/26}}; {{27}}-webkit-box-shadow{{/27}}: {{28}}$shadows{{/28}}; {{29}}box-shadow{{/29}}: {{30}}$shadows{{/30}}; } {{24}}.shadows {{/24}}{ @include box-shadow(0px 4px 5px #666, 2px 6px 10px #999); } SCSS {{1}}.page-title{{/1}} { {{2}}font-size{{/2}}: {{3}}20px{{/3}}; {{4}}font-weight{{/4}}: {{5}}bold{{/5}}; {{6}}color{{/6}}: {{7}}#ff0000{{/7}}; {{8}}padding{{/8}}: {{9}}4px{{/9}}; } {{10}}p{{/10}} { {{11}}border-color{{/11}}: {{12}}blue{{/12}}; {{13}}border-width{{/13}}: {{14}}1in{{/14}}; {{15}}border-style{{/15}}: {{16}}dashed{{/16}}; } {{17}}h1{{/17}} { {{18}}border-color{{/18}}: {{19}}blue{{/19}}; {{20}}border-width{{/20}}: {{21}}2in{{/21}}; {{22}}border-style{{/22}}: {{23}}dashed{{/23}}; } {{24}}.shadows{{/24}} { {{25}}-moz-box-shadow{{/25}}: {{26}}0px 4px 5px #666, 2px 6px 10px #999{{/26}}; {{27}}-webkit-box-shadow{{/27}}: {{28}}0px 4px 5px #666, 2px 6px 10px #999{{/28}}; {{29}}box-shadow{{/29}}: {{30}}0px 4px 5px #666, 2px 6px 10px #999{{/30}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_mixin_sourcemap_sass silence_warnings {assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass} =large-text :font {{2}}size{{/2}}: {{3}}20px{{/3}} {{4}}weight{{/4}}: {{5}}bold{{/5}} {{6}}color{{/6}}: {{7}}#ff0000{{/7}} {{1}}.page-title{{/1}} +large-text {{8}}padding{{/8}}: {{9}}4px{{/9}} =dashed-border($color, $width: {{14}}1in{{/14}}) border: {{11}}{{18}}color{{/11}}{{/18}}: $color {{13}}{{20}}width{{/13}}{{/20}}: $width {{15}}{{22}}style{{/15}}{{/22}}: {{16}}{{23}}dashed{{/16}}{{/23}} {{10}}p{{/10}} +dashed-border({{12}}blue{{/12}}) {{17}}h1{{/17}} +dashed-border({{19}}blue{{/19}}, {{21}}2in{{/21}}) =box-shadow($shadows...) {{25}}-moz-box-shadow{{/25}}: {{26}}$shadows{{/26}} {{27}}-webkit-box-shadow{{/27}}: {{28}}$shadows{{/28}} {{29}}box-shadow{{/29}}: {{30}}$shadows{{/30}} {{24}}.shadows{{/24}} +box-shadow(0px 4px 5px #666, 2px 6px 10px #999) SASS {{1}}.page-title{{/1}} { {{2}}font-size{{/2}}: {{3}}20px{{/3}}; {{4}}font-weight{{/4}}: {{5}}bold{{/5}}; {{6}}color{{/6}}: {{7}}#ff0000{{/7}}; {{8}}padding{{/8}}: {{9}}4px{{/9}}; } {{10}}p{{/10}} { {{11}}border-color{{/11}}: {{12}}blue{{/12}}; {{13}}border-width{{/13}}: {{14}}1in{{/14}}; {{15}}border-style{{/15}}: {{16}}dashed{{/16}}; } {{17}}h1{{/17}} { {{18}}border-color{{/18}}: {{19}}blue{{/19}}; {{20}}border-width{{/20}}: {{21}}2in{{/21}}; {{22}}border-style{{/22}}: {{23}}dashed{{/23}}; } {{24}}.shadows{{/24}} { {{25}}-moz-box-shadow{{/25}}: {{26}}0px 4px 5px #666, 2px 6px 10px #999{{/26}}; {{27}}-webkit-box-shadow{{/27}}: {{28}}0px 4px 5px #666, 2px 6px 10px #999{{/28}}; {{29}}box-shadow{{/29}}: {{30}}0px 4px 5px #666, 2px 6px 10px #999{{/30}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_function_sourcemap_scss assert_parses_with_mapping <<'SCSS', <<'CSS' $grid-width: 20px; $gutter-width: 5px; @function grid-width($n) { @return $n * $grid-width + ($n - 1) * $gutter-width; } {{1}}sidebar {{/1}}{ {{2}}width{{/2}}: {{3}}grid-width(5){{/3}}; } SCSS {{1}}sidebar{{/1}} { {{2}}width{{/2}}: {{3}}120px{{/3}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_function_sourcemap_sass assert_parses_with_mapping <<'SASS', <<'CSS', :syntax => :sass $grid-width: 20px $gutter-width: 5px @function grid-width($n) @return $n * $grid-width + ($n - 1) * $gutter-width {{1}}sidebar{{/1}} {{2}}width{{/2}}: {{3}}grid-width(5){{/3}} SASS {{1}}sidebar{{/1}} { {{2}}width{{/2}}: {{3}}120px{{/3}}; } /*# sourceMappingURL=test.css.map */ CSS end # Regression tests def test_properties_sass silence_warnings {assert_parses_with_mapping <<SASS, <<CSS, :syntax => :sass} {{1}}.foo{{/1}} :{{2}}name{{/2}} {{3}}value{{/3}} {{4}}name{{/4}}: {{5}}value{{/5}} :{{6}}name{{/6}} {{7}}value{{/7}} {{8}}name{{/8}}: {{9}}value{{/9}} SASS {{1}}.foo{{/1}} { {{2}}name{{/2}}: {{3}}value{{/3}}; {{4}}name{{/4}}: {{5}}value{{/5}}; {{6}}name{{/6}}: {{7}}value{{/7}}; {{8}}name{{/8}}: {{9}}value{{/9}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_multiline_script_scss assert_parses_with_mapping <<SCSS, <<CSS, :syntax => :scss $var: {{3}}foo + bar{{/3}}; {{1}}x {{/1}}{ {{2}}y{{/2}}: $var } SCSS {{1}}x{{/1}} { {{2}}y{{/2}}: {{3}}foobar{{/3}}; } /*# sourceMappingURL=test.css.map */ CSS end def test_multiline_interpolation_source_range engine = Sass::Engine.new(<<-SCSS, :cache => false, :syntax => :scss) p { filter: progid:DXImageTransform( '\#{123}'); } SCSS interpolated = engine.to_tree.children. first.children. first.value.first.children[1] assert_equal "123", interpolated.to_sass range = interpolated.source_range assert_equal 3, range.start_pos.line assert_equal 14, range.start_pos.offset assert_equal 3, range.end_pos.line assert_equal 17, range.end_pos.offset end def test_list_source_range engine = Sass::Engine.new(<<-SCSS, :cache => false, :syntax => :scss) @each $a, $b in (1, 2), (2, 4), (3, 6) { } SCSS list = engine.to_tree.children.first.list assert_equal 1, list.source_range.start_pos.line assert_equal 1, list.source_range.end_pos.line assert_equal 16, list.source_range.start_pos.offset assert_equal 38, list.source_range.end_pos.offset end def test_map_source_range engine = Sass::Engine.new(<<-SCSS, :cache => false, :syntax => :scss) $margins: (sm: 4px, md: 8px, lg: 16px); SCSS expr = engine.to_tree.children.first.expr assert_equal 1, expr.source_range.start_pos.line assert_equal 1, expr.source_range.end_pos.line assert_equal 12, expr.source_range.start_pos.offset assert_equal 38, expr.source_range.end_pos.offset end def test_sources_array_is_uri_escaped map = Sass::Source::Map.new importer = Sass::Importers::Filesystem.new('.') map.add( Sass::Source::Range.new( Sass::Source::Position.new(0, 0), Sass::Source::Position.new(0, 10), 'source file.scss', importer), Sass::Source::Range.new( Sass::Source::Position.new(0, 0), Sass::Source::Position.new(0, 10), nil, nil)) json = map.to_json(:css_path => 'output file.css', :sourcemap_path => 'output file.css.map') assert_equal json, <<JSON.rstrip { "version": 3, "mappings": "DADD,UAAU", "sources": ["source%20file.scss"], "names": [], "file": "output%20file.css" } JSON end def test_scss_comment_source_range assert_parses_with_mapping <<SCSS, <<CSS, :syntax => :scss $var: val; {{1}}/* text */{{/1}} {{2}}/* multiline comment */{{/2}} SCSS {{1}}/* text */{{/1}} {{2}}/* multiline comment */{{/2}} /*# sourceMappingURL=test.css.map */ CSS end def test_sass_comment_source_range assert_parses_with_mapping <<SASS, <<CSS, :syntax => :sass {{1}}body{{/1}} {{2}}/* text */{{/2}} {{3}}/* multiline comment */{{/3}} SASS {{1}}body{{/1}} { {{2}}/* text */{{/2}} } {{3}}/* multiline * comment */{{/3}} /*# sourceMappingURL=test.css.map */ CSS end def test_scss_comment_interpolation_source_range assert_parses_with_mapping <<SCSS, <<CSS, :syntax => :scss $var: 2; {{1}}/* two \#{$var} and four \#{2 * $var} */{{/1}} {{2}}/* multiline comment \#{ 2 + 2 } and \#{ 2 + 2 } */{{/2}} SCSS {{1}}/* two 2 and four 4 */{{/1}} {{2}}/* multiline comment 4 and 4 */{{/2}} /*# sourceMappingURL=test.css.map */ CSS end def test_sass_comment_interpolation_source_range assert_parses_with_mapping <<SASS, <<CSS, :syntax => :sass $var: 2 {{1}}/* two \#{$var} and four \#{2 * $var} */{{/1}} {{2}}/* multiline comment \#{ 2 + 2 } and \#{ 2 + 2 } */{{/2}} SASS {{1}}/* two 2 and four 4 */{{/1}} {{2}}/* multiline * comment 4 and 4 */{{/2}} /*# sourceMappingURL=test.css.map */ CSS end private ANNOTATION_REGEX = /\{\{(\/?)([^}]+)\}\}/ def build_ranges(text, file_name = nil) ranges = Hash.new {|h, k| h[k] = []} start_positions = {} text.split("\n").each_with_index do |line_text, line| line += 1 # lines shoud be 1-based while (match = line_text.match(ANNOTATION_REGEX)) closing = !match[1].empty? name = match[2] match_offsets = match.offset(0) offset = match_offsets[0] + 1 # Offsets are 1-based in source maps. assert(!closing || start_positions[name], "Closing annotation #{name} found before opening one.") position = Sass::Source::Position.new(line, offset) if closing ranges[name] << Sass::Source::Range.new( start_positions[name], position, file_name, Sass::Importers::Filesystem.new('.')) start_positions.delete name else assert(!start_positions[name], "Overlapping range annotation #{name} encountered on line #{line}") start_positions[name] = position end line_text.slice!(match_offsets[0], match_offsets[1] - match_offsets[0]) end end ranges end def build_mapping_from_annotations(source, css, source_file_name) source_ranges = build_ranges(source, source_file_name) target_ranges = build_ranges(css) map = Sass::Source::Map.new source_ranges.map do |(name, sources)| assert(sources.length == 1, "#{sources.length} source ranges encountered for annotation #{name}") assert(target_ranges[name], "No target ranges for annotation #{name}") target_ranges[name].map {|target_range| [sources.first, target_range]} end. flatten(1). sort_by {|(_, target)| [target.start_pos.line, target.start_pos.offset]}. each {|(s2, target)| map.add(s2, target)} map end def assert_parses_with_mapping(source, css, options={}) options[:syntax] ||= :scss input_filename = filename_for_test(options[:syntax]) mapping = build_mapping_from_annotations(source, css, input_filename) source.gsub!(ANNOTATION_REGEX, "") css.gsub!(ANNOTATION_REGEX, "") rendered, sourcemap = render_with_sourcemap(source, options) assert_equal css.rstrip, rendered.rstrip assert_sourcemaps_equal source, css, mapping, sourcemap end def assert_positions_equal(expected, actual, lines, message = nil) prefix = message ? message + ": " : "" expected_location = lines[expected.line - 1] + "\n" + ("-" * (expected.offset - 1)) + "^" actual_location = lines[actual.line - 1] + "\n" + ("-" * (actual.offset - 1)) + "^" assert_equal(expected.line, actual.line, prefix + "Expected #{expected.inspect}\n" + expected_location + "\n\n" + "But was #{actual.inspect}\n" + actual_location) assert_equal(expected.offset, actual.offset, prefix + "Expected #{expected.inspect}\n" + expected_location + "\n\n" + "But was #{actual.inspect}\n" + actual_location) end def assert_ranges_equal(expected, actual, lines, prefix) assert_positions_equal(expected.start_pos, actual.start_pos, lines, prefix + " start position") assert_positions_equal(expected.end_pos, actual.end_pos, lines, prefix + " end position") if expected.file.nil? assert_nil(actual.file) else assert_equal(expected.file, actual.file) end end def assert_sourcemaps_equal(source, css, expected, actual) assert_equal(expected.data.length, actual.data.length, <<MESSAGE) Wrong number of mappings. Expected: #{dump_sourcemap_as_expectation(source, css, expected).gsub(/^/, '| ')} Actual: #{dump_sourcemap_as_expectation(source, css, actual).gsub(/^/, '| ')} MESSAGE source_lines = source.split("\n") css_lines = css.split("\n") expected.data.zip(actual.data) do |expected_mapping, actual_mapping| assert_ranges_equal(expected_mapping.input, actual_mapping.input, source_lines, "Input") assert_ranges_equal(expected_mapping.output, actual_mapping.output, css_lines, "Output") end end def assert_parses_with_sourcemap(source, css, sourcemap_json, options={}) rendered, sourcemap = render_with_sourcemap(source, options) css_path = options[:output] || "test.css" sourcemap_path = Sass::Util.sourcemap_name(css_path) rendered_json = sourcemap.to_json(:css_path => css_path, :sourcemap_path => sourcemap_path, :type => options[:sourcemap]) assert_equal css.rstrip, rendered.rstrip assert_equal sourcemap_json.rstrip, rendered_json end def render_with_sourcemap(source, options={}) options[:syntax] ||= :scss munge_filename options engine = Sass::Engine.new(source, options) engine.options[:cache] = false sourcemap_path = Sass::Util.sourcemap_name(options[:output] || "test.css") engine.render_with_sourcemap File.basename(sourcemap_path) end def dump_sourcemap_as_expectation(source, css, sourcemap) mappings_to_annotations(source, sourcemap.data.map {|d| d.input}) + "\n\n" + "=" * 20 + " maps to:\n\n" + mappings_to_annotations(css, sourcemap.data.map {|d| d.output}) end def mappings_to_annotations(source, ranges) additional_offsets = Hash.new(0) lines = source.split("\n") add_annotation = lambda do |pos, str| line_num = pos.line - 1 line = lines[line_num] offset = pos.offset + additional_offsets[line_num] - 1 line << " " * (offset - line.length) if offset > line.length line.insert(offset, str) additional_offsets[line_num] += str.length end ranges.each_with_index do |range, i| add_annotation[range.start_pos, "{{#{i + 1}}}"] add_annotation[range.end_pos, "{{/#{i + 1}}}"] end return lines.join("\n") 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/test/sass/extend_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/extend_test.rb
require File.dirname(__FILE__) + '/../test_helper' class ExtendTest < MiniTest::Test def test_basic assert_equal <<CSS, render(<<SCSS) .foo, .bar { a: b; } CSS .foo {a: b} .bar {@extend .foo} SCSS assert_equal <<CSS, render(<<SCSS) .foo, .bar { a: b; } CSS .bar {@extend .foo} .foo {a: b} SCSS assert_equal <<CSS, render(<<SCSS) .foo, .bar { a: b; } .bar { c: d; } CSS .foo {a: b} .bar {c: d; @extend .foo} SCSS assert_equal <<CSS, render(<<SCSS) .foo, .bar { a: b; } .bar { c: d; } CSS .foo {a: b} .bar {@extend .foo; c: d} SCSS end def test_indented_syntax assert_equal <<CSS, render(<<SASS, :syntax => :sass) .foo, .bar { a: b; } CSS .foo a: b .bar @extend .foo SASS assert_equal <<CSS, render(<<SASS, :syntax => :sass) .foo, .bar { a: b; } CSS .foo a: b .bar @extend \#{".foo"} SASS end def test_multiple_targets assert_equal <<CSS, render(<<SCSS) .foo, .bar { a: b; } .blip .foo, .blip .bar { c: d; } CSS .foo {a: b} .bar {@extend .foo} .blip .foo {c: d} SCSS end def test_multiple_extendees assert_equal <<CSS, render(<<SCSS) .foo, .baz { a: b; } .bar, .baz { c: d; } CSS .foo {a: b} .bar {c: d} .baz {@extend .foo; @extend .bar} SCSS end def test_multiple_extends_with_single_extender_and_single_target assert_extends('.foo .bar', '.baz {@extend .foo; @extend .bar}', '.foo .bar, .baz .bar, .foo .baz, .baz .baz') assert_extends '.foo.bar', '.baz {@extend .foo; @extend .bar}', '.foo.bar, .baz' end def test_multiple_extends_with_multiple_extenders_and_single_target assert_equal <<CSS, render(<<SCSS) .foo .bar, .baz .bar, .foo .bang, .baz .bang { a: b; } CSS .foo .bar {a: b} .baz {@extend .foo} .bang {@extend .bar} SCSS assert_equal <<CSS, render(<<SCSS) .foo.bar, .bar.baz, .baz.bang, .foo.bang { a: b; } CSS .foo.bar {a: b} .baz {@extend .foo} .bang {@extend .bar} SCSS end def test_chained_extends assert_equal <<CSS, render(<<SCSS) .foo, .bar, .baz, .bip { a: b; } CSS .foo {a: b} .bar {@extend .foo} .baz {@extend .bar} .bip {@extend .bar} SCSS end def test_dynamic_extendee assert_extends '.foo', '.bar {@extend #{".foo"}}', '.foo, .bar' assert_extends('[baz^="blip12px"]', '.bar {@extend [baz^="blip#{12px}"]}', '[baz^="blip12px"], .bar') end def test_nested_target assert_extends '.foo .bar', '.baz {@extend .bar}', '.foo .bar, .foo .baz' end def test_target_with_child assert_extends '.foo .bar', '.baz {@extend .foo}', '.foo .bar, .baz .bar' end def test_class_unification assert_unification '.foo.bar', '.baz {@extend .foo}', '.foo.bar, .bar.baz' assert_unification '.foo.baz', '.baz {@extend .foo}', '.baz' end def test_id_unification assert_unification '.foo.bar', '#baz {@extend .foo}', '.foo.bar, .bar#baz' assert_unification '.foo#baz', '#baz {@extend .foo}', '#baz' assert_unification '.foo#baz', '#bar {@extend .foo}', '.foo#baz' end def test_universal_unification_with_simple_target assert_unification '.foo', '* {@extend .foo}', '.foo, *' assert_unification '.foo', '*|* {@extend .foo}', '.foo, *|*' assert_unification '.foo.bar', '* {@extend .foo}', '.bar' assert_unification '.foo.bar', '*|* {@extend .foo}', '.bar' assert_unification '.foo.bar', 'ns|* {@extend .foo}', '.foo.bar, ns|*.bar' end def test_universal_unification_with_namespaceless_universal_target assert_unification '*.foo', 'ns|* {@extend .foo}', '*.foo' assert_unification '*.foo', '* {@extend .foo}', '*' assert_unification '*.foo', '*|* {@extend .foo}', '*' assert_unification '*|*.foo', '* {@extend .foo}', '*|*.foo, *' assert_unification '*|*.foo', '*|* {@extend .foo}', '*|*' assert_unification '*|*.foo', 'ns|* {@extend .foo}', '*|*.foo, ns|*' end def test_universal_unification_with_namespaced_universal_target assert_unification 'ns|*.foo', '* {@extend .foo}', 'ns|*.foo' assert_unification 'ns1|*.foo', 'ns2|* {@extend .foo}', 'ns1|*.foo' assert_unification 'ns|*.foo', '*|* {@extend .foo}', 'ns|*' assert_unification 'ns|*.foo', 'ns|* {@extend .foo}', 'ns|*' end def test_universal_unification_with_namespaceless_element_target assert_unification 'a.foo', 'ns|* {@extend .foo}', 'a.foo' assert_unification 'a.foo', '* {@extend .foo}', 'a' assert_unification 'a.foo', '*|* {@extend .foo}', 'a' assert_unification '*|a.foo', '* {@extend .foo}', '*|a.foo, a' assert_unification '*|a.foo', '*|* {@extend .foo}', '*|a' assert_unification '*|a.foo', 'ns|* {@extend .foo}', '*|a.foo, ns|a' end def test_universal_unification_with_namespaced_element_target assert_unification 'ns|a.foo', '* {@extend .foo}', 'ns|a.foo' assert_unification 'ns1|a.foo', 'ns2|* {@extend .foo}', 'ns1|a.foo' assert_unification 'ns|a.foo', '*|* {@extend .foo}', 'ns|a' assert_unification 'ns|a.foo', 'ns|* {@extend .foo}', 'ns|a' end def test_element_unification_with_simple_target assert_unification '.foo', 'a {@extend .foo}', '.foo, a' assert_unification '.foo.bar', 'a {@extend .foo}', '.foo.bar, a.bar' assert_unification '.foo.bar', '*|a {@extend .foo}', '.foo.bar, *|a.bar' assert_unification '.foo.bar', 'ns|a {@extend .foo}', '.foo.bar, ns|a.bar' end def test_element_unification_with_namespaceless_universal_target assert_unification '*.foo', 'ns|a {@extend .foo}', '*.foo' assert_unification '*.foo', 'a {@extend .foo}', '*.foo, a' assert_unification '*.foo', '*|a {@extend .foo}', '*.foo, a' assert_unification '*|*.foo', 'a {@extend .foo}', '*|*.foo, a' assert_unification '*|*.foo', '*|a {@extend .foo}', '*|*.foo, *|a' assert_unification '*|*.foo', 'ns|a {@extend .foo}', '*|*.foo, ns|a' end def test_element_unification_with_namespaced_universal_target assert_unification 'ns|*.foo', 'a {@extend .foo}', 'ns|*.foo' assert_unification 'ns1|*.foo', 'ns2|a {@extend .foo}', 'ns1|*.foo' assert_unification 'ns|*.foo', '*|a {@extend .foo}', 'ns|*.foo, ns|a' assert_unification 'ns|*.foo', 'ns|a {@extend .foo}', 'ns|*.foo, ns|a' end def test_element_unification_with_namespaceless_element_target assert_unification 'a.foo', 'ns|a {@extend .foo}', 'a.foo' assert_unification 'a.foo', 'h1 {@extend .foo}', 'a.foo' assert_unification 'a.foo', 'a {@extend .foo}', 'a' assert_unification 'a.foo', '*|a {@extend .foo}', 'a' assert_unification '*|a.foo', 'a {@extend .foo}', '*|a.foo, a' assert_unification '*|a.foo', '*|a {@extend .foo}', '*|a' assert_unification '*|a.foo', 'ns|a {@extend .foo}', '*|a.foo, ns|a' end def test_element_unification_with_namespaced_element_target assert_unification 'ns|a.foo', 'a {@extend .foo}', 'ns|a.foo' assert_unification 'ns1|a.foo', 'ns2|a {@extend .foo}', 'ns1|a.foo' assert_unification 'ns|a.foo', '*|a {@extend .foo}', 'ns|a' assert_unification 'ns|a.foo', 'ns|a {@extend .foo}', 'ns|a' end def test_attribute_unification assert_unification '[foo=bar].baz', '[foo=baz] {@extend .baz}', '[foo=bar].baz, [foo=bar][foo=baz]' assert_unification '[foo=bar].baz', '[foo^=bar] {@extend .baz}', '[foo=bar].baz, [foo=bar][foo^=bar]' assert_unification '[foo=bar].baz', '[foot=bar] {@extend .baz}', '[foo=bar].baz, [foo=bar][foot=bar]' assert_unification '[foo=bar].baz', '[ns|foo=bar] {@extend .baz}', '[foo=bar].baz, [foo=bar][ns|foo=bar]' assert_unification '%-a [foo=bar].bar', '[foo=bar] {@extend .bar}', '-a [foo=bar]' end def test_pseudo_unification assert_unification ':foo.baz', ':foo(2n+1) {@extend .baz}', ':foo.baz, :foo:foo(2n+1)' assert_unification ':foo.baz', '::foo {@extend .baz}', ':foo.baz, :foo::foo' assert_unification '::foo.baz', '::bar {@extend .baz}', '::foo.baz' assert_unification '::foo.baz', '::foo(2n+1) {@extend .baz}', '::foo.baz' assert_unification '::foo.baz', '::foo {@extend .baz}', '::foo' assert_unification '::foo(2n+1).baz', '::foo(2n+1) {@extend .baz}', '::foo(2n+1)' assert_unification ':foo.baz', ':bar {@extend .baz}', ':foo.baz, :foo:bar' assert_unification '.baz:foo', ':after {@extend .baz}', '.baz:foo, :foo:after' assert_unification '.baz:after', ':foo {@extend .baz}', '.baz:after, :foo:after' assert_unification ':foo.baz', ':foo {@extend .baz}', ':foo' end def test_pseudoelement_remains_at_end_of_selector assert_extends '.foo::bar', '.baz {@extend .foo}', '.foo::bar, .baz::bar' assert_extends 'a.foo::bar', '.baz {@extend .foo}', 'a.foo::bar, a.baz::bar' end def test_pseudoclass_remains_at_end_of_selector assert_extends '.foo:bar', '.baz {@extend .foo}', '.foo:bar, .baz:bar' assert_extends 'a.foo:bar', '.baz {@extend .foo}', 'a.foo:bar, a.baz:bar' end def test_id_unification_again assert_unification('#id.foo .bar', '#id.baz .qux {@extend .bar}', '#id.foo .bar, #id.baz.foo .qux') end def test_root_unification assert_extends( ".foo:root .bar", ".baz:root .qux {@extend .bar}", ".foo:root .bar, .baz.foo:root .qux") end def test_not_remains_at_end_of_selector assert_extends '.foo:not(.bar)', '.baz {@extend .foo}', '.foo:not(.bar), .baz:not(.bar)' end def test_pseudoelement_goes_lefter_than_pseudoclass assert_extends '.foo::bar', '.baz:bang {@extend .foo}', '.foo::bar, .baz:bang::bar' assert_extends '.foo:bar', '.baz::bang {@extend .foo}', '.foo:bar, .baz:bar::bang' end def test_pseudoelement_goes_lefter_than_not assert_extends '.foo::bar', '.baz:not(.bang) {@extend .foo}', '.foo::bar, .baz:not(.bang)::bar' assert_extends '.foo:not(.bang)', '.baz::bar {@extend .foo}', '.foo:not(.bang), .baz:not(.bang)::bar' end def test_negation_unification assert_extends ':not(.foo).baz', ':not(.bar) {@extend .baz}', ':not(.foo).baz, :not(.foo):not(.bar)' # Unifying to :not(.foo) here would reduce the specificity of the original selector. assert_extends ':not(.foo).baz', ':not(.foo) {@extend .baz}', ':not(.foo).baz, :not(.foo)' end def test_prefixed_pseudoclass_unification assert_unification( ':nth-child(2n+1 of .foo).baz', ':nth-child(2n of .foo) {@extend .baz}', ':nth-child(2n+1 of .foo).baz, :nth-child(2n+1 of .foo):nth-child(2n of .foo)') assert_unification( ':nth-child(2n+1 of .foo).baz', ':nth-child(2n+1 of .bar) {@extend .baz}', ':nth-child(2n+1 of .foo).baz, :nth-child(2n+1 of .foo):nth-child(2n+1 of .bar)') assert_unification( ':nth-child(2n+1 of .foo).baz', ':nth-child(2n+1 of .foo) {@extend .baz}', ':nth-child(2n+1 of .foo)') end def test_extend_into_not assert_extends(':not(.foo)', '.x {@extend .foo}', ':not(.foo):not(.x)') assert_extends(':not(.foo.bar)', '.x {@extend .bar}', ':not(.foo.bar):not(.foo.x)') assert_extends( ':not(.foo.bar, .baz.bar)', '.x {@extend .bar}', ':not(.foo.bar, .foo.x, .baz.bar, .baz.x)') end def test_extend_into_mergeable_pseudoclasses assert_extends(':matches(.foo)', '.x {@extend .foo}', ':matches(.foo, .x)') assert_extends(':matches(.foo.bar)', '.x {@extend .bar}', ':matches(.foo.bar, .foo.x)') assert_extends( ':matches(.foo.bar, .baz.bar)', '.x {@extend .bar}', ':matches(.foo.bar, .foo.x, .baz.bar, .baz.x)') assert_extends(':-moz-any(.foo)', '.x {@extend .foo}', ':-moz-any(.foo, .x)') assert_extends(':current(.foo)', '.x {@extend .foo}', ':current(.foo, .x)') assert_extends(':has(.foo)', '.x {@extend .foo}', ':has(.foo, .x)') assert_extends(':host(.foo)', '.x {@extend .foo}', ':host(.foo, .x)') assert_extends(':host-context(.foo)', '.x {@extend .foo}', ':host-context(.foo, .x)') assert_extends(':nth-child(n of .foo)', '.x {@extend .foo}', ':nth-child(n of .foo, .x)') assert_extends( ':nth-last-child(n of .foo)', '.x {@extend .foo}', ':nth-last-child(n of .foo, .x)') end def test_complex_extend_into_pseudoclass # Unlike other selectors, we don't allow complex selectors to be # added to `:not` if they weren't there before. At time of # writing, most browsers don't support that and will throw away # the entire selector if it exists. #assert_extends(':not(.bar)', '.x .y {@extend .bar}', ':not(.bar)') # If the `:not()` already has a complex selector, we won't break # anything by adding a new one. assert_extends(':not(.baz .bar)', '.x .y {@extend .bar}', ':not(.baz .bar):not(.baz .x .y):not(.x .baz .y)') # If the `:not()` would only contain complex selectors, there's no # harm in letting it continue to exist. assert_extends(':not(%bar)', '.x .y {@extend %bar}', ':not(.x .y)') assert_extends(':matches(.bar)', '.x .y {@extend .bar}', ':matches(.bar, .x .y)') assert_extends(':current(.bar)', '.x .y {@extend .bar}', ':current(.bar, .x .y)') assert_extends(':has(.bar)', '.x .y {@extend .bar}', ':has(.bar, .x .y)') assert_extends(':host(.bar)', '.x .y {@extend .bar}', ':host(.bar, .x .y)') assert_extends(':host-context(.bar)', '.x .y {@extend .bar}', ':host-context(.bar, .x .y)') assert_extends( ':-moz-any(.bar)', '.x .y {@extend .bar}', ':-moz-any(.bar, .x .y)') assert_extends( ':nth-child(n of .bar)', '.x .y {@extend .bar}', ':nth-child(n of .bar, .x .y)') assert_extends( ':nth-last-child(n of .bar)', '.x .y {@extend .bar}', ':nth-last-child(n of .bar, .x .y)') end def test_extend_over_selector_pseudoclass assert_extends(':not(.foo)', '.x {@extend :not(.foo)}', ':not(.foo), .x') assert_extends( ':matches(.foo, .bar)', '.x {@extend :matches(.foo, .bar)}', ':matches(.foo, .bar), .x') end def test_matches_within_not assert_extends( ':not(.foo, .bar)', ':matches(.x, .y) {@extend .foo}', ':not(.foo, .x, .y, .bar)') end def test_pseudoclasses_merge assert_extends(':matches(.foo)', ':matches(.bar) {@extend .foo}', ':matches(.foo, .bar)') assert_extends(':-moz-any(.foo)', ':-moz-any(.bar) {@extend .foo}', ':-moz-any(.foo, .bar)') assert_extends(':current(.foo)', ':current(.bar) {@extend .foo}', ':current(.foo, .bar)') assert_extends( ':nth-child(n of .foo)', ':nth-child(n of .bar) {@extend .foo}', ':nth-child(n of .foo, .bar)') assert_extends( ':nth-last-child(n of .foo)', ':nth-last-child(n of .bar) {@extend .foo}', ':nth-last-child(n of .foo, .bar)') end def test_nesting_pseudoclasses_merge assert_extends(':has(.foo)', ':has(.bar) {@extend .foo}', ':has(.foo, :has(.bar))') assert_extends(':host(.foo)', ':host(.bar) {@extend .foo}', ':host(.foo, :host(.bar))') assert_extends( ':host-context(.foo)', ':host-context(.bar) {@extend .foo}', ':host-context(.foo, :host-context(.bar))') end def test_not_unifies_with_unique_values assert_unification('foo', ':not(bar) {@extend foo}', ':not(bar)') assert_unification('#foo', ':not(#bar) {@extend #foo}', ':not(#bar)') end def test_not_adds_no_specificity assert_specificity_equals(':not(.foo)', '.foo') end def test_matches_has_a_specificity_range # `:matches(.foo, #bar)` has minimum specificity equal to that of `.foo`, # which means `:matches(.foo, #bar) .a` can have less specificity than # `#b.a`. Thus the selector generated by `#b.a` should be preserved. assert_equal <<CSS, render(<<SCSS) :matches(.foo, #bar) .a, :matches(.foo, #bar) #b.a { a: b; } CSS :matches(.foo, #bar) %x {a: b} .a {@extend %x} #b.a {@extend %x} SCSS # `:matches(.foo, #bar)` has maximum specificity equal to that of `#bar`, # which means `:matches(.foo, #bar).b` can have greater specificity than `.a # .b`. Thus the selector generated by `:matches(.foo, #bar).b` should be # preserved. assert_equal <<CSS, render(<<SCSS) .a .b, .a .b:matches(.foo, #bar) { a: b; } CSS .a %x {a: b} .b {@extend %x} .b:matches(.foo, #bar) {@extend %x} SCSS end def test_extend_into_not_and_normal_extend assert_equal <<CSS, render(<<SCSS) .x:not(.y):not(.bar), .foo:not(.y):not(.bar) { a: b; } CSS .x:not(.y) {a: b} .foo {@extend .x} .bar {@extend .y} SCSS end def test_extend_into_matches_and_normal_extend assert_equal <<CSS, render(<<SCSS) .x:matches(.y, .bar), .foo:matches(.y, .bar) { a: b; } CSS .x:matches(.y) {a: b} .foo {@extend .x} .bar {@extend .y} SCSS end def test_multilayer_pseudoclass_extend assert_equal <<CSS, render(<<SCSS) :matches(.x, .foo, .bar) { a: b; } CSS :matches(.x) {a: b} .foo {@extend .x} .bar {@extend .foo} SCSS end def test_root_only_allowed_at_root assert_extends(':root .foo', '.bar .baz {@extend .foo}', ':root .foo, :root .bar .baz') assert_extends('.foo:root .bar', '.baz:root .bang {@extend .bar}', '.foo:root .bar, .baz.foo:root .bang') assert_extends('html:root .bar', 'xml:root .bang {@extend .bar}', 'html:root .bar') assert_extends('.foo:root > .bar .x', '.baz:root .bang .y {@extend .x}', '.foo:root > .bar .x, .baz.foo:root > .bar .bang .y') end def test_comma_extendee assert_equal <<CSS, render(<<SCSS) .foo, .baz { a: b; } .bar, .baz { c: d; } CSS .foo {a: b} .bar {c: d} .baz {@extend .foo, .bar} SCSS end def test_redundant_selector_elimination assert_equal <<CSS, render(<<SCSS) .foo.bar, .x, .y { a: b; } CSS .foo.bar {a: b} .x {@extend .foo, .bar} .y {@extend .foo, .bar} SCSS end def test_nested_pseudo_selectors assert_equal <<CSS, render(<<SCSS) .foo .bar:not(.baz), .bang .bar:not(.baz) { a: b; } CSS .foo { .bar:not(.baz) {a: b} } .bang {@extend .foo} SCSS end ## Long Extendees def test_long_extendee assert_warning(<<WARNING) {assert_extends '.foo.bar', '.baz {@extend .foo.bar}', '.foo.bar, .baz'} DEPRECATION WARNING on line 2 of test_long_extendee_inline.scss: Extending a compound selector, .foo.bar, is deprecated and will not be supported in a future release. Consider "@extend .foo, .bar" instead. See http://bit.ly/ExtendCompound for details. WARNING end def test_long_extendee_requires_all_selectors silence_warnings do assert_extend_doesnt_match('.baz', '.foo.bar', :not_found, 2) do render_extends '.foo', '.baz {@extend .foo.bar}' end end end def test_long_extendee_matches_supersets silence_warnings {assert_extends '.foo.bar.bap', '.baz {@extend .foo.bar}', '.foo.bar.bap, .bap.baz'} end def test_long_extendee_runs_unification silence_warnings {assert_extends 'ns|*.foo.bar', '*|a.baz {@extend .foo.bar}', 'ns|*.foo.bar, ns|a.baz'} end ## Long Extenders def test_long_extender assert_extends '.foo.bar', '.baz.bang {@extend .foo}', '.foo.bar, .bar.baz.bang' end def test_long_extender_runs_unification assert_extends 'ns|*.foo.bar', '*|a.baz {@extend .foo}', 'ns|*.foo.bar, ns|a.bar.baz' end def test_long_extender_doesnt_unify assert_extends 'a.foo#bar', 'h1.baz {@extend .foo}', 'a.foo#bar' assert_extends 'a.foo#bar', '.bang#baz {@extend .foo}', 'a.foo#bar' end ## Nested Extenders def test_nested_extender assert_extends '.foo', 'foo bar {@extend .foo}', '.foo, foo bar' end def test_nested_extender_runs_unification assert_extends '.foo.bar', 'foo bar {@extend .foo}', '.foo.bar, foo bar.bar' end def test_nested_extender_doesnt_unify assert_extends 'baz.foo', 'foo bar {@extend .foo}', 'baz.foo' end def test_nested_extender_alternates_parents assert_extends('.baz .bip .foo', 'foo .grank bar {@extend .foo}', '.baz .bip .foo, .baz .bip foo .grank bar, foo .grank .baz .bip bar') end def test_nested_extender_unifies_identical_parents assert_extends('.baz .bip .foo', '.baz .bip bar {@extend .foo}', '.baz .bip .foo, .baz .bip bar') end def test_nested_extender_unifies_common_substring assert_extends('.baz .bip .bap .bink .foo', '.brat .bip .bap bar {@extend .foo}', '.baz .bip .bap .bink .foo, .baz .brat .bip .bap .bink bar, .brat .baz .bip .bap .bink bar') end def test_nested_extender_unifies_common_subseq assert_extends('.a .x .b .y .foo', '.a .n .b .m bar {@extend .foo}', '.a .x .b .y .foo, .a .x .n .b .y .m bar, .a .n .x .b .y .m bar, .a .x .n .b .m .y bar, .a .n .x .b .m .y bar') end def test_nested_extender_chooses_first_subseq assert_extends('.a .b .c .d .foo', '.c .d .a .b .bar {@extend .foo}', '.a .b .c .d .foo, .a .b .c .d .a .b .bar') end def test_nested_extender_counts_extended_subselectors assert_extends('.a .bip.bop .foo', '.b .bip .bar {@extend .foo}', '.a .bip.bop .foo, .a .b .bip.bop .bar, .b .a .bip.bop .bar') end def test_nested_extender_counts_extended_superselectors assert_extends('.a .bip .foo', '.b .bip.bop .bar {@extend .foo}', '.a .bip .foo, .a .b .bip.bop .bar, .b .a .bip.bop .bar') end def test_nested_extender_with_child_selector assert_extends '.baz .foo', 'foo > bar {@extend .foo}', '.baz .foo, .baz foo > bar' end def test_nested_extender_finds_common_selectors_around_child_selector assert_extends 'a > b c .c1', 'a c .c2 {@extend .c1}', 'a > b c .c1, a > b c .c2' assert_extends 'a > b c .c1', 'b c .c2 {@extend .c1}', 'a > b c .c1, a > b c .c2' end def test_nested_extender_doesnt_find_common_selectors_around_adjacent_sibling_selector assert_extends 'a + b c .c1', 'a c .c2 {@extend .c1}', 'a + b c .c1, a + b a c .c2, a a + b c .c2' assert_extends 'a + b c .c1', 'a b .c2 {@extend .c1}', 'a + b c .c1, a a + b c .c2' assert_extends 'a + b c .c1', 'b c .c2 {@extend .c1}', 'a + b c .c1, a + b c .c2' end def test_nested_extender_doesnt_find_common_selectors_around_sibling_selector assert_extends 'a ~ b c .c1', 'a c .c2 {@extend .c1}', 'a ~ b c .c1, a ~ b a c .c2, a a ~ b c .c2' assert_extends 'a ~ b c .c1', 'a b .c2 {@extend .c1}', 'a ~ b c .c1, a a ~ b c .c2' assert_extends 'a ~ b c .c1', 'b c .c2 {@extend .c1}', 'a ~ b c .c1, a ~ b c .c2' end def test_nested_extender_doesnt_find_common_selectors_around_reference_selector silence_warnings {assert_extends 'a /for/ b c .c1', 'a c .c2 {@extend .c1}', 'a /for/ b c .c1, a /for/ b a c .c2, a a /for/ b c .c2'} silence_warnings {assert_extends 'a /for/ b c .c1', 'a b .c2 {@extend .c1}', 'a /for/ b c .c1, a a /for/ b c .c2'} silence_warnings {assert_extends 'a /for/ b c .c1', 'b c .c2 {@extend .c1}', 'a /for/ b c .c1, a /for/ b c .c2'} end def test_nested_extender_with_early_child_selectors_doesnt_subseq_them assert_extends('.bip > .bap .foo', '.grip > .bap .bar {@extend .foo}', '.bip > .bap .foo, .bip > .bap .grip > .bap .bar, .grip > .bap .bip > .bap .bar') assert_extends('.bap > .bip .foo', '.bap > .grip .bar {@extend .foo}', '.bap > .bip .foo, .bap > .bip .bap > .grip .bar, .bap > .grip .bap > .bip .bar') end def test_nested_extender_with_child_selector_unifies assert_extends '.baz.foo', 'foo > bar {@extend .foo}', '.baz.foo, foo > bar.baz' assert_equal <<CSS, render(<<SCSS) .baz > .foo, .baz > .bar { a: b; } CSS .baz > { .foo {a: b} .bar {@extend .foo} } SCSS assert_equal <<CSS, render(<<SCSS) .foo .bar, .foo > .baz { a: b; } CSS .foo { .bar {a: b} > .baz {@extend .bar} } SCSS end def test_nested_extender_with_early_child_selector assert_equal <<CSS, render(<<SCSS) .foo .bar, .foo .bip > .baz { a: b; } CSS .foo { .bar {a: b} .bip > .baz {@extend .bar} } SCSS assert_equal <<CSS, render(<<SCSS) .foo .bip .bar, .foo .bip .foo > .baz { a: b; } CSS .foo { .bip .bar {a: b} > .baz {@extend .bar} } SCSS assert_extends '.foo > .bar', '.bip + .baz {@extend .bar}', '.foo > .bar, .foo > .bip + .baz' assert_extends '.foo + .bar', '.bip > .baz {@extend .bar}', '.foo + .bar, .bip > .foo + .baz' assert_extends '.foo > .bar', '.bip > .baz {@extend .bar}', '.foo > .bar, .bip.foo > .baz' end def test_nested_extender_with_trailing_child_selector assert_raises(Sass::SyntaxError, "bar > can't extend: invalid selector") do render("bar > {@extend .baz}") end end def test_nested_extender_with_sibling_selector assert_extends '.baz .foo', 'foo + bar {@extend .foo}', '.baz .foo, .baz foo + bar' end def test_nested_extender_with_hacky_selector assert_extends('.baz .foo', 'foo + > > + bar {@extend .foo}', '.baz .foo, .baz foo + > > + bar, foo .baz + > > + bar') assert_extends '.baz .foo', '> > bar {@extend .foo}', '.baz .foo, > > .baz bar' end def test_nested_extender_merges_with_same_selector assert_equal <<CSS, render(<<SCSS) .foo .bar, .foo .baz { a: b; } CSS .foo { .bar {a: b} .baz {@extend .bar} } SCSS end def test_nested_extender_with_child_selector_merges_with_same_selector assert_extends('.foo > .bar .baz', '.foo > .bar .bang {@extend .baz}', '.foo > .bar .baz, .foo > .bar .bang') end # Combinator Unification def test_combinator_unification_for_hacky_combinators assert_extends '.a > + x', '.b y {@extend x}', '.a > + x, .a .b > + y, .b .a > + y' assert_extends '.a x', '.b > + y {@extend x}', '.a x, .a .b > + y, .b .a > + y' assert_extends '.a > + x', '.b > + y {@extend x}', '.a > + x, .a .b > + y, .b .a > + y' assert_extends '.a ~ > + x', '.b > + y {@extend x}', '.a ~ > + x, .a .b ~ > + y, .b .a ~ > + y' assert_extends '.a + > x', '.b > + y {@extend x}', '.a + > x' assert_extends '.a + > x', '.b > + y {@extend x}', '.a + > x' assert_extends '.a ~ > + .b > x', '.c > + .d > y {@extend x}', '.a ~ > + .b > x, .a .c ~ > + .d.b > y, .c .a ~ > + .d.b > y' end def test_combinator_unification_double_tilde assert_extends '.a.b ~ x', '.a ~ y {@extend x}', '.a.b ~ x, .a.b ~ y' assert_extends '.a ~ x', '.a.b ~ y {@extend x}', '.a ~ x, .a.b ~ y' assert_extends '.a ~ x', '.b ~ y {@extend x}', '.a ~ x, .a ~ .b ~ y, .b ~ .a ~ y, .b.a ~ y' assert_extends 'a.a ~ x', 'b.b ~ y {@extend x}', 'a.a ~ x, a.a ~ b.b ~ y, b.b ~ a.a ~ y' end def test_combinator_unification_tilde_plus assert_extends '.a.b + x', '.a ~ y {@extend x}', '.a.b + x, .a.b + y' assert_extends '.a + x', '.a.b ~ y {@extend x}', '.a + x, .a.b ~ .a + y, .a.b + y' assert_extends '.a + x', '.b ~ y {@extend x}', '.a + x, .b ~ .a + y, .b.a + y' assert_extends 'a.a + x', 'b.b ~ y {@extend x}', 'a.a + x, b.b ~ a.a + y' assert_extends '.a.b ~ x', '.a + y {@extend x}', '.a.b ~ x, .a.b ~ .a + y, .a.b + y' assert_extends '.a ~ x', '.a.b + y {@extend x}', '.a ~ x, .a.b + y' assert_extends '.a ~ x', '.b + y {@extend x}', '.a ~ x, .a ~ .b + y, .a.b + y' assert_extends 'a.a ~ x', 'b.b + y {@extend x}', 'a.a ~ x, a.a ~ b.b + y' end def test_combinator_unification_angle_sibling assert_extends '.a > x', '.b ~ y {@extend x}', '.a > x, .a > .b ~ y' assert_extends '.a > x', '.b + y {@extend x}', '.a > x, .a > .b + y' assert_extends '.a ~ x', '.b > y {@extend x}', '.a ~ x, .b > .a ~ y' assert_extends '.a + x', '.b > y {@extend x}', '.a + x, .b > .a + y' end def test_combinator_unification_double_angle assert_extends '.a.b > x', '.b > y {@extend x}', '.a.b > x, .b.a > y' assert_extends '.a > x', '.a.b > y {@extend x}', '.a > x, .a.b > y' assert_extends '.a > x', '.b > y {@extend x}', '.a > x, .b.a > y' assert_extends 'a.a > x', 'b.b > y {@extend x}', 'a.a > x' end def test_combinator_unification_double_plus assert_extends '.a.b + x', '.b + y {@extend x}', '.a.b + x, .b.a + y' assert_extends '.a + x', '.a.b + y {@extend x}', '.a + x, .a.b + y' assert_extends '.a + x', '.b + y {@extend x}', '.a + x, .b.a + y' assert_extends 'a.a + x', 'b.b + y {@extend x}', 'a.a + x' end def test_combinator_unification_angle_space assert_extends '.a.b > x', '.a y {@extend x}', '.a.b > x, .a.b > y' assert_extends '.a > x', '.a.b y {@extend x}', '.a > x, .a.b .a > y' assert_extends '.a > x', '.b y {@extend x}', '.a > x, .b .a > y' assert_extends '.a.b x', '.a > y {@extend x}', '.a.b x, .a.b .a > y' assert_extends '.a x', '.a.b > y {@extend x}', '.a x, .a.b > y' assert_extends '.a x', '.b > y {@extend x}', '.a x, .a .b > y' end def test_combinator_unification_plus_space assert_extends '.a.b + x', '.a y {@extend x}', '.a.b + x, .a .a.b + y' assert_extends '.a + x', '.a.b y {@extend x}', '.a + x, .a.b .a + y' assert_extends '.a + x', '.b y {@extend x}', '.a + x, .b .a + y' assert_extends '.a.b x', '.a + y {@extend x}', '.a.b x, .a.b .a + y' assert_extends '.a x', '.a.b + y {@extend x}', '.a x, .a .a.b + y' assert_extends '.a x', '.b + y {@extend x}', '.a x, .a .b + y' end def test_combinator_unification_nested assert_extends '.a > .b + x', '.c > .d + y {@extend x}', '.a > .b + x, .c.a > .d.b + y' assert_extends '.a > .b + x', '.c > y {@extend x}', '.a > .b + x, .c.a > .b + y' end def test_combinator_unification_with_newlines assert_equal <<CSS, render(<<SCSS) .a > .b + x, .c.a > .d.b + y { a: b; } CSS .a > .b + x {a: b} .c > .d + y {@extend x} SCSS end # Loops def test_extend_self_loop assert_equal <<CSS, render(<<SCSS) .foo { a: b; } CSS .foo {a: b; @extend .foo} SCSS end def test_basic_extend_loop assert_equal <<CSS, render(<<SCSS) .foo, .bar { a: b; } .bar, .foo { c: d; } CSS .foo {a: b; @extend .bar} .bar {c: d; @extend .foo} SCSS end def test_three_level_extend_loop assert_equal <<CSS, render(<<SCSS) .foo, .baz, .bar { a: b; } .bar, .foo, .baz { c: d; } .baz, .bar, .foo { e: f; } CSS .foo {a: b; @extend .bar} .bar {c: d; @extend .baz} .baz {e: f; @extend .foo} SCSS end def test_nested_extend_loop assert_equal <<CSS, render(<<SCSS) .bar, .bar .foo { a: b; } .bar .foo { c: d; } CSS .bar { a: b; .foo {c: d; @extend .bar} } SCSS end def test_cross_loop # The first law of extend means the selector should stick around. assert_equal <<CSS, render(<<SCSS) .foo.bar, .foo, .bar { a: b; } CSS .foo.bar {a: b} .foo {@extend .bar} .bar {@extend .foo} SCSS end def test_multiple_extender_merges_with_superset_selector assert_equal <<CSS, render(<<SCSS) a.bar.baz, a.foo { a: b; } CSS .foo {@extend .bar; @extend .baz} a.bar.baz {a: b} SCSS end def test_control_flow_if assert_equal <<CSS, render(<<SCSS) .true, .also-true { color: green; } .false, .also-false { color: red; } CSS .true { color: green; } .false { color: red; } .also-true { @if true { @extend .true; } @else { @extend .false; } } .also-false { @if false { @extend .true; } @else { @extend .false; } } SCSS end def test_control_flow_for assert_equal <<CSS, render(<<SCSS) .base-0, .added { color: green; } .base-1, .added { display: block; } .base-2, .added { border: 1px solid blue; } CSS .base-0 { color: green; } .base-1 { display: block; } .base-2 { border: 1px solid blue; } .added { @for $i from 0 to 3 { @extend .base-\#{$i}; } } SCSS end def test_control_flow_while assert_equal <<CSS, render(<<SCSS) .base-0, .added { color: green; } .base-1, .added { display: block; } .base-2, .added { border: 1px solid blue; } CSS .base-0 { color: green; } .base-1 { display: block; } .base-2 { border: 1px solid blue; } .added { $i : 0; @while $i < 3 { @extend .base-\#{$i}; $i : $i + 1; } } SCSS end def test_basic_placeholder_selector assert_extends '%foo', '.bar {@extend %foo}', '.bar' end def test_unused_placeholder_selector assert_equal <<CSS, render(<<SCSS) .baz { color: blue; } CSS %foo {color: blue} %bar {color: red} .baz {@extend %foo} SCSS end def test_placeholder_descendant_selector assert_extends '#context %foo a', '.bar {@extend %foo}', '#context .bar a' end def test_semi_placeholder_selector assert_equal <<CSS, render(<<SCSS) .bar .baz { color: blue; } CSS #context %foo, .bar .baz {color: blue} SCSS end def test_placeholder_selector_with_multiple_extenders assert_equal <<CSS, render(<<SCSS) .bar, .baz { color: blue; } CSS %foo {color: blue} .bar {@extend %foo} .baz {@extend %foo} SCSS end def test_placeholder_selector_as_modifier assert_equal <<CSS, render(<<SCSS) a.baz.bar { color: blue; } CSS a%foo.baz {color: blue} .bar {@extend %foo} div {@extend %foo} SCSS end def test_placeholder_interpolation assert_equal <<CSS, render(<<SCSS) .bar { color: blue; } CSS $foo: foo; %\#{$foo} {color: blue} .bar {@extend %foo} SCSS end def test_placeholder_in_selector_pseudoclass assert_equal <<CSS, render(<<SCSS) :matches(.bar, .baz) { color: blue; } CSS :matches(%foo) {color: blue}
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/test/sass/plugin_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/plugin_test.rb
require File.dirname(__FILE__) + '/../test_helper' require File.dirname(__FILE__) + '/test_helper' require 'sass/plugin' require 'fileutils' module Sass::Script::Functions def filename filename = options[:filename].gsub(%r{.*((/[^/]+){4})}, '\1') Sass::Script::Value::String.new(filename) end def whatever custom = options[:custom] whatever = custom && custom[:whatever] Sass::Script::Value::String.new(whatever || "incorrect") end end class SassPluginTest < MiniTest::Test @@templates = %w{ complex script parent_ref import scss_import alt subdir/subdir subdir/nested_subdir/nested_subdir options import_content filename_fn import_charset import_charset_ibm866 } @@cache_store = Sass::CacheStores::Memory.new def setup Sass::Util.retry_on_windows {FileUtils.mkdir_p tempfile_loc} Sass::Util.retry_on_windows {FileUtils.mkdir_p tempfile_loc(nil,"more_")} set_plugin_opts check_for_updates! reset_mtimes end def teardown clean_up_sassc Sass::Plugin.reset! Sass::Util.retry_on_windows {FileUtils.rm_r tempfile_loc} Sass::Util.retry_on_windows {FileUtils.rm_r tempfile_loc(nil,"more_")} end @@templates.each do |name| define_method("test_template_renders_correctly (#{name})") do silence_warnings {assert_renders_correctly(name)} end end def test_no_update File.delete(tempfile_loc('basic')) assert_needs_update 'basic' check_for_updates! assert_stylesheet_updated 'basic' end def test_update_needed_when_modified touch 'basic' assert_needs_update 'basic' check_for_updates! assert_stylesheet_updated 'basic' end def test_update_needed_when_dependency_modified touch 'basic' assert_needs_update 'import' check_for_updates! assert_stylesheet_updated 'basic' assert_stylesheet_updated 'import' end def test_update_needed_when_scss_dependency_modified touch 'scss_importee' assert_needs_update 'import' check_for_updates! assert_stylesheet_updated 'scss_importee' assert_stylesheet_updated 'import' end def test_scss_update_needed_when_dependency_modified touch 'basic' assert_needs_update 'scss_import' check_for_updates! assert_stylesheet_updated 'basic' assert_stylesheet_updated 'scss_import' end def test_update_needed_when_nested_import_dependency_modified touch 'basic' assert_needs_update 'nested_import' check_for_updates! assert_stylesheet_updated 'basic' assert_stylesheet_updated 'scss_import' end def test_no_updates_when_always_check_and_always_update_both_false Sass::Plugin.options[:always_update] = false Sass::Plugin.options[:always_check] = false touch 'basic' assert_needs_update 'basic' check_for_updates! # Check it's still stale assert_needs_update 'basic' end def test_full_exception_handling File.delete(tempfile_loc('bork1')) check_for_updates! File.open(tempfile_loc('bork1')) do |file| assert_equal(<<CSS.strip, file.read.split("\n")[0...6].join("\n")) /* Error: Undefined variable: "$bork". on line 2 of #{template_loc('bork1')} 1: bork 2: bork: $bork CSS end File.delete(tempfile_loc('bork1')) end def test_full_exception_with_block_comment File.delete(tempfile_loc('bork5')) check_for_updates! File.open(tempfile_loc('bork5')) do |file| assert_equal(<<CSS.strip, file.read.split("\n")[0...7].join("\n")) /* Error: Undefined variable: "$bork". on line 3 of #{template_loc('bork5')} 1: bork 2: /* foo *\\/ 3: bork: $bork CSS end File.delete(tempfile_loc('bork1')) end def test_single_level_import_loop File.delete(tempfile_loc('single_import_loop')) check_for_updates! File.open(tempfile_loc('single_import_loop')) do |file| assert_equal(<<CSS.strip, file.read.split("\n")[0...2].join("\n")) /* Error: An @import loop has been found: #{template_loc('single_import_loop')} imports itself CSS end end def test_double_level_import_loop File.delete(tempfile_loc('double_import_loop1')) check_for_updates! File.open(tempfile_loc('double_import_loop1')) do |file| assert_equal(<<CSS.strip, file.read.split("\n")[0...4].join("\n")) /* Error: An @import loop has been found: #{template_loc('double_import_loop1')} imports #{template_loc('_double_import_loop2')} #{template_loc('_double_import_loop2')} imports #{template_loc('double_import_loop1')} CSS end end def test_import_name_cleanup File.delete(tempfile_loc('subdir/import_up1')) check_for_updates! File.open(tempfile_loc('subdir/import_up1')) do |file| assert_equal(<<CSS.strip, file.read.split("\n")[0...5].join("\n")) /* Error: File to import not found or unreadable: ../subdir/import_up3.scss. Load path: #{template_loc} on line 1 of #{template_loc 'subdir/import_up2'} from line 1 of #{template_loc 'subdir/import_up1'} CSS end end def test_nonfull_exception_handling old_full_exception = Sass::Plugin.options[:full_exception] Sass::Plugin.options[:full_exception] = false File.delete(tempfile_loc('bork1')) assert_raises(Sass::SyntaxError) {check_for_updates!} ensure Sass::Plugin.options[:full_exception] = old_full_exception end def test_two_template_directories set_plugin_opts :template_location => { template_loc => tempfile_loc, template_loc(nil,'more_') => tempfile_loc(nil,'more_') } check_for_updates! ['more1', 'more_import'].each { |name| assert_renders_correctly(name, :prefix => 'more_') } end def test_two_template_directories_with_line_annotations set_plugin_opts :line_comments => true, :style => :nested, :template_location => { template_loc => tempfile_loc, template_loc(nil,'more_') => tempfile_loc(nil,'more_') } check_for_updates! assert_renders_correctly('more1_with_line_comments', 'more1', :prefix => 'more_') end def test_doesnt_render_partials assert !File.exist?(tempfile_loc('_partial')) end def test_template_location_array assert_equal [[template_loc, tempfile_loc]], Sass::Plugin.template_location_array end def test_add_template_location Sass::Plugin.add_template_location(template_loc(nil, "more_"), tempfile_loc(nil, "more_")) assert_equal( [[template_loc, tempfile_loc], [template_loc(nil, "more_"), tempfile_loc(nil, "more_")]], Sass::Plugin.template_location_array) touch 'more1', 'more_' touch 'basic' assert_needs_update "more1", "more_" assert_needs_update "basic" check_for_updates! assert_doesnt_need_update "more1", "more_" assert_doesnt_need_update "basic" end def test_remove_template_location Sass::Plugin.add_template_location(template_loc(nil, "more_"), tempfile_loc(nil, "more_")) Sass::Plugin.remove_template_location(template_loc, tempfile_loc) assert_equal( [[template_loc(nil, "more_"), tempfile_loc(nil, "more_")]], Sass::Plugin.template_location_array) touch 'more1', 'more_' touch 'basic' assert_needs_update "more1", "more_" assert_needs_update "basic" check_for_updates! assert_doesnt_need_update "more1", "more_" assert_needs_update "basic" end def test_import_same_name assert_warning <<WARNING do WARNING: In #{template_loc}: There are multiple files that match the name "same_name_different_partiality.scss": _same_name_different_partiality.scss same_name_different_partiality.scss WARNING touch "_same_name_different_partiality" assert_needs_update "same_name_different_partiality" end end # Callbacks def test_updated_stylesheet_callback_for_updated_template Sass::Plugin.options[:always_update] = false touch 'basic' assert_no_callback :updated_stylesheet, template_loc("complex"), tempfile_loc("complex") do assert_callbacks( [:updated_stylesheet, template_loc("basic"), tempfile_loc("basic")], [:updated_stylesheet, template_loc("import"), tempfile_loc("import")]) end end def test_updated_stylesheet_callback_for_fresh_template Sass::Plugin.options[:always_update] = false assert_no_callback :updated_stylesheet end def test_updated_stylesheet_callback_for_error_template Sass::Plugin.options[:always_update] = false touch 'bork1' assert_no_callback :updated_stylesheet end def test_not_updating_stylesheet_callback_for_fresh_template Sass::Plugin.options[:always_update] = false assert_callback :not_updating_stylesheet, template_loc("basic"), tempfile_loc("basic") end def test_not_updating_stylesheet_callback_for_updated_template Sass::Plugin.options[:always_update] = false assert_callback :not_updating_stylesheet, template_loc("complex"), tempfile_loc("complex") do assert_no_callbacks( [:updated_stylesheet, template_loc("basic"), tempfile_loc("basic")], [:updated_stylesheet, template_loc("import"), tempfile_loc("import")]) end end def test_not_updating_stylesheet_callback_with_never_update Sass::Plugin.options[:never_update] = true assert_no_callback :not_updating_stylesheet end def test_not_updating_stylesheet_callback_for_partial Sass::Plugin.options[:always_update] = false assert_no_callback :not_updating_stylesheet, template_loc("_partial"), tempfile_loc("_partial") end def test_not_updating_stylesheet_callback_for_error Sass::Plugin.options[:always_update] = false touch 'bork1' assert_no_callback :not_updating_stylesheet, template_loc("bork1"), tempfile_loc("bork1") end def test_compilation_error_callback Sass::Plugin.options[:always_update] = false touch 'bork1' assert_callback(:compilation_error, lambda {|e| e.message == 'Undefined variable: "$bork".'}, template_loc("bork1"), tempfile_loc("bork1")) end def test_compilation_error_callback_for_file_access Sass::Plugin.options[:always_update] = false assert_callback(:compilation_error, lambda {|e| e.is_a?(Errno::ENOENT)}, template_loc("nonexistent"), tempfile_loc("nonexistent")) do Sass::Plugin.update_stylesheets([[template_loc("nonexistent"), tempfile_loc("nonexistent")]]) end end def test_creating_directory_callback Sass::Plugin.options[:always_update] = false dir = File.join(tempfile_loc, "subdir", "nested_subdir") FileUtils.rm_r dir assert_callback :creating_directory, dir end ## Regression def test_cached_dependencies_update FileUtils.mv(template_loc("basic"), template_loc("basic", "more_")) set_plugin_opts :load_paths => [template_loc(nil, "more_")] touch 'basic', 'more_' assert_needs_update "import" check_for_updates! assert_renders_correctly("import") ensure FileUtils.mv(template_loc("basic", "more_"), template_loc("basic")) end def test_cached_relative_import old_always_update = Sass::Plugin.options[:always_update] Sass::Plugin.options[:always_update] = true check_for_updates! assert_renders_correctly('subdir/subdir') ensure Sass::Plugin.options[:always_update] = old_always_update end def test_cached_if set_plugin_opts :cache_store => Sass::CacheStores::Filesystem.new(tempfile_loc + '/cache') check_for_updates! assert_renders_correctly 'if' check_for_updates! assert_renders_correctly 'if' ensure set_plugin_opts end def test_cached_import_option set_plugin_opts :custom => {:whatever => "correct"} check_for_updates! assert_renders_correctly "cached_import_option" @@cache_store.reset! set_plugin_opts :custom => nil, :always_update => false check_for_updates! assert_renders_correctly "cached_import_option" set_plugin_opts :custom => {:whatever => "correct"}, :always_update => true check_for_updates! assert_renders_correctly "cached_import_option" ensure set_plugin_opts :custom => nil end private def assert_renders_correctly(*arguments) options = arguments.last.is_a?(Hash) ? arguments.pop : {} prefix = options[:prefix] result_name = arguments.shift tempfile_name = arguments.shift || result_name expected_str = File.read(result_loc(result_name, prefix)) actual_str = File.read(tempfile_loc(tempfile_name, prefix)) expected_str = expected_str.force_encoding('IBM866') if result_name == 'import_charset_ibm866' actual_str = actual_str.force_encoding('IBM866') if tempfile_name == 'import_charset_ibm866' expected_lines = expected_str.split("\n") actual_lines = actual_str.split("\n") if actual_lines.first == "/*" && expected_lines.first != "/*" assert(false, actual_lines[0..actual_lines.each_with_index.find {|l, i| l == "*/"}.last].join("\n")) end expected_lines.zip(actual_lines).each_with_index do |pair, line| message = "template: #{result_name}\nline: #{line + 1}" assert_equal(pair.first, pair.last, message) end if expected_lines.size < actual_lines.size assert(false, "#{actual_lines.size - expected_lines.size} Trailing lines found in #{tempfile_name}.css: #{actual_lines[expected_lines.size..-1].join('\n')}") end end def assert_stylesheet_updated(name) assert_doesnt_need_update name # Make sure it isn't an exception expected_lines = File.read(result_loc(name)).split("\n") actual_lines = File.read(tempfile_loc(name)).split("\n") if actual_lines.first == "/*" && expected_lines.first != "/*" assert(false, actual_lines[0..actual_lines.each_with_index.find {|l, i| l == "*/"}.last].join("\n")) end end def assert_callback(name, *expected_args) run = false received_args = nil Sass::Plugin.send("on_#{name}") do |*args| received_args = args run ||= expected_args.zip(received_args).all? do |ea, ra| ea.respond_to?(:call) ? ea.call(ra) : ea == ra end end if block_given? Sass::Util.silence_sass_warnings {yield} else check_for_updates! end assert run, "Expected #{name} callback to be run with arguments:\n #{expected_args.inspect}\nHowever, it got:\n #{received_args.inspect}" end def assert_no_callback(name, *unexpected_args) Sass::Plugin.send("on_#{name}") do |*a| next unless unexpected_args.empty? || a == unexpected_args msg = "Expected #{name} callback not to be run" if !unexpected_args.empty? msg << " with arguments #{unexpected_args.inspect}" elsif !a.empty? msg << ",\n was run with arguments #{a.inspect}" end flunk msg end if block_given? yield else check_for_updates! end end def assert_callbacks(*args) return check_for_updates! if args.empty? assert_callback(*args.pop) {assert_callbacks(*args)} end def assert_no_callbacks(*args) return check_for_updates! if args.empty? assert_no_callback(*args.pop) {assert_no_callbacks(*args)} end def check_for_updates! Sass::Util.silence_sass_warnings do Sass::Plugin.check_for_updates end end def assert_needs_update(*args) assert(Sass::Plugin::StalenessChecker.stylesheet_needs_update?(tempfile_loc(*args), template_loc(*args)), "Expected #{template_loc(*args)} to need an update.") end def assert_doesnt_need_update(*args) assert(!Sass::Plugin::StalenessChecker.stylesheet_needs_update?(tempfile_loc(*args), template_loc(*args)), "Expected #{template_loc(*args)} not to need an update.") end def touch(*args) FileUtils.touch(template_loc(*args)) end def reset_mtimes Sass::Plugin::StalenessChecker.dependencies_cache = {} atime = Time.now mtime = Time.now - 5 Dir["{#{template_loc},#{tempfile_loc}}/**/*.{css,sass,scss}"].each do |f| Sass::Util.retry_on_windows {File.utime(atime, mtime, f)} end end def template_loc(name = nil, prefix = nil) if name scss = absolutize "#{prefix}templates/#{name}.scss" File.exist?(scss) ? scss : absolutize("#{prefix}templates/#{name}.sass") else absolutize "#{prefix}templates" end end def tempfile_loc(name = nil, prefix = nil) if name absolutize "#{prefix}tmp/#{name}.css" else absolutize "#{prefix}tmp" end end def result_loc(name = nil, prefix = nil) if name absolutize "#{prefix}results/#{name}.css" else absolutize "#{prefix}results" end end def set_plugin_opts(overrides = {}) Sass::Plugin.options.merge!( :template_location => template_loc, :css_location => tempfile_loc, :style => :compact, :always_update => true, :never_update => false, :full_exception => true, :cache_store => @@cache_store, :sourcemap => :none ) Sass::Plugin.options.merge!(overrides) end end class Sass::Engine alias_method :old_render, :render def render raise "bork bork bork!" if @template[0] == "{bork now!}" old_render 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/test/sass/superselector_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/superselector_test.rb
require File.dirname(__FILE__) + '/../test_helper' class SuperselectorTest < MiniTest::Test def test_superselector_reflexivity assert_superselector 'h1', 'h1' assert_superselector '.foo', '.foo' assert_superselector '#foo > .bar, baz', '#foo > .bar, baz' end def test_smaller_compound_superselector assert_strict_superselector '.foo', '.foo.bar' assert_strict_superselector '.bar', '.foo.bar' assert_strict_superselector 'a', 'a#b' assert_strict_superselector '#b', 'a#b' end def test_smaller_complex_superselector assert_strict_superselector '.bar', '.foo .bar' assert_strict_superselector '.bar', '.foo > .bar' assert_strict_superselector '.bar', '.foo + .bar' assert_strict_superselector '.bar', '.foo ~ .bar' end def test_selector_list_subset_superselector assert_strict_superselector '.foo, .bar', '.foo' assert_strict_superselector '.foo, .bar, .baz', '.foo, .baz' assert_strict_superselector '.foo, .baz, .qux', '.foo.bar, .baz.bang' end def test_leading_combinator_superselector refute_superselector '+ .foo', '.foo' refute_superselector '+ .foo', '.bar + .foo' end def test_trailing_combinator_superselector refute_superselector '.foo +', '.foo' refute_superselector '.foo +', '.foo + .bar' end def test_matching_combinator_superselector assert_strict_superselector '.foo + .bar', '.foo + .bar.baz' assert_strict_superselector '.foo + .bar', '.foo.baz + .bar' assert_strict_superselector '.foo > .bar', '.foo > .bar.baz' assert_strict_superselector '.foo > .bar', '.foo.baz > .bar' assert_strict_superselector '.foo ~ .bar', '.foo ~ .bar.baz' assert_strict_superselector '.foo ~ .bar', '.foo.baz ~ .bar' end def test_following_sibling_is_superselector_of_next_sibling assert_strict_superselector '.foo ~ .bar', '.foo + .bar.baz' assert_strict_superselector '.foo ~ .bar', '.foo.baz + .bar' end def test_descendant_is_superselector_of_child assert_strict_superselector '.foo .bar', '.foo > .bar.baz' assert_strict_superselector '.foo .bar', '.foo.baz > .bar' assert_strict_superselector '.foo .baz', '.foo > .bar > .baz' end def test_child_isnt_superselector_of_longer_child refute_superselector '.foo > .baz', '.foo > .bar > .baz' refute_superselector '.foo > .baz', '.foo > .bar .baz' end def test_following_sibling_isnt_superselector_of_longer_following_sibling refute_superselector '.foo + .baz', '.foo + .bar + .baz' refute_superselector '.foo + .baz', '.foo + .bar .baz' end def test_sibling_isnt_superselector_of_longer_sibling # This actually is a superselector, but it's a very narrow edge case and # detecting it is very difficult and may be exponential in the worst case. refute_superselector '.foo ~ .baz', '.foo ~ .bar ~ .baz' refute_superselector '.foo ~ .baz', '.foo ~ .bar .baz' end def test_matches_is_superselector_of_constituent_selectors %w[matches -moz-any].each do |name| assert_strict_superselector ":#{name}(.foo, .bar)", '.foo.baz' assert_strict_superselector ":#{name}(.foo, .bar)", '.bar.baz' assert_strict_superselector ":#{name}(.foo .bar, .baz)", '.x .foo .bar' end end def test_matches_is_superselector_of_subset_matches assert_strict_superselector ':matches(.foo, .bar, .baz)', '#x:matches(.foo.bip, .baz.bang)' assert_strict_superselector ':-moz-any(.foo, .bar, .baz)', '#x:-moz-any(.foo.bip, .baz.bang)' end def test_matches_is_not_superselector_of_any refute_superselector ':matches(.foo, .bar)', ':-moz-any(.foo, .bar)' refute_superselector ':-moz-any(.foo, .bar)', ':matches(.foo, .bar)' end def test_matches_can_be_subselector %w[matches -moz-any].each do |name| assert_superselector '.foo', ":#{name}(.foo.bar)" assert_superselector '.foo.bar', ":#{name}(.foo.bar.baz)" assert_superselector '.foo', ":#{name}(.foo.bar, .foo.baz)" end end def test_any_is_not_superselector_of_different_prefix refute_superselector ':-moz-any(.foo, .bar)', ':-s-any(.foo, .bar)' end def test_not_is_superselector_of_less_complex_not assert_strict_superselector ':not(.foo.bar)', ':not(.foo)' assert_strict_superselector ':not(.foo .bar)', ':not(.bar)' end def test_not_is_superselector_of_superset assert_strict_superselector ':not(.foo.bip, .baz.bang)', ':not(.foo, .bar, .baz)' assert_strict_superselector ':not(.foo.bip, .baz.bang)', ':not(.foo):not(.bar):not(.baz)' end def test_not_is_superselector_of_unique_selectors assert_strict_superselector ':not(h1.foo)', 'a' assert_strict_superselector ':not(.baz #foo)', '#bar' end def test_not_is_not_superselector_of_non_unique_selectors refute_superselector ':not(.foo)', '.bar' refute_superselector ':not(:hover)', ':visited' end def test_current_is_superselector_with_identical_innards assert_superselector ':current(.foo)', ':current(.foo)' end def test_current_is_superselector_with_subselector_innards refute_superselector ':current(.foo)', ':current(.foo.bar)' refute_superselector ':current(.foo.bar)', ':current(.foo)' end def test_nth_match_is_superselector_of_subset_nth_match assert_strict_superselector( ':nth-child(2n of .foo, .bar, .baz)', '#x:nth-child(2n of .foo.bip, .baz.bang)') assert_strict_superselector( ':nth-last-child(2n of .foo, .bar, .baz)', '#x:nth-last-child(2n of .foo.bip, .baz.bang)') end def test_nth_match_is_not_superselector_of_nth_match_with_different_arg refute_superselector( ':nth-child(2n of .foo, .bar, .baz)', '#x:nth-child(2n + 1 of .foo.bip, .baz.bang)') refute_superselector( ':nth-last-child(2n of .foo, .bar, .baz)', '#x:nth-last-child(2n + 1 of .foo.bip, .baz.bang)') end def test_nth_match_is_not_superselector_of_nth_last_match refute_superselector ':nth-child(2n of .foo, .bar)', ':nth-last-child(2n of .foo, .bar)' refute_superselector ':nth-last-child(2n of .foo, .bar)', ':nth-child(2n of .foo, .bar)' end def test_nth_match_can_be_subselector %w[nth-child nth-last-child].each do |name| assert_superselector '.foo', ":#{name}(2n of .foo.bar)" assert_superselector '.foo.bar', ":#{name}(2n of .foo.bar.baz)" assert_superselector '.foo', ":#{name}(2n of .foo.bar, .foo.baz)" end end def has_is_superselector_of_subset_host assert_strict_superselector ':has(.foo, .bar, .baz)', ':has(.foo.bip, .baz.bang)' end def has_isnt_superselector_of_contained_selector assert_strict_superselector ':has(.foo, .bar, .baz)', '.foo' end def host_is_superselector_of_subset_host assert_strict_superselector ':host(.foo, .bar, .baz)', ':host(.foo.bip, .baz.bang)' end def host_isnt_superselector_of_contained_selector assert_strict_superselector ':host(.foo, .bar, .baz)', '.foo' end def host_context_is_superselector_of_subset_host assert_strict_superselector( ':host-context(.foo, .bar, .baz)', ':host-context(.foo.bip, .baz.bang)') end def host_context_isnt_superselector_of_contained_selector assert_strict_superselector ':host-context(.foo, .bar, .baz)', '.foo' end private def assert_superselector(superselector, subselector) assert(parse_selector(superselector).superselector?(parse_selector(subselector)), "Expected #{superselector} to be a superselector of #{subselector}.") end def refute_superselector(superselector, subselector) assert(!parse_selector(superselector).superselector?(parse_selector(subselector)), "Expected #{superselector} not to be a superselector of #{subselector}.") end def assert_strict_superselector(superselector, subselector) assert_superselector(superselector, subselector) refute_superselector(subselector, superselector) end def parse_selector(selector) Sass::SCSS::CssParser.new(selector, filename_for_test, nil).parse_selector 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/test/sass/script_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/script_test.rb
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/../test_helper' require 'sass/engine' module Sass::Script::Functions::UserFunctions def assert_options(val) val.options[:foo] Sass::Script::Value::String.new("Options defined!") end def arg_error assert_options end end module Sass::Script::Functions include Sass::Script::Functions::UserFunctions end class SassScriptTest < MiniTest::Test include Sass::Script def test_color_clamps_input assert_equal 0, Sass::Script::Value::Color.new([1, 2, -1]).blue assert_equal 255, Sass::Script::Value::Color.new([256, 2, 3]).red end def test_color_clamps_rgba_input assert_equal 1, Sass::Script::Value::Color.new([1, 2, 3, 1.1]).alpha assert_equal 0, Sass::Script::Value::Color.new([1, 2, 3, -0.1]).alpha end def test_color_from_hex assert_equal Sass::Script::Value::Color.new([0,0,0]), Sass::Script::Value::Color.from_hex('000000') assert_equal Sass::Script::Value::Color.new([0,0,0]), Sass::Script::Value::Color.from_hex('#000000') end def test_string_escapes assert_equal "'", resolve("\"'\"") assert_equal '"', resolve("\"\\\"\"") assert_equal "\\", resolve("\"\\\\\"") assert_equal "☃", resolve("\"\\2603\"") assert_equal "☃f", resolve("\"\\2603 f\"") assert_equal "☃x", resolve("\"\\2603x\"") assert_equal "\\2603", resolve("\"\\\\2603\"") assert_equal "\#{foo}", resolve("\"\\\#{foo}\"") # U+FFFD is the replacement character, "�". assert_equal [0xFFFD].pack("U"), resolve("\"\\0\"") assert_equal [0xFFFD].pack("U"), resolve("\"\\FFFFFF\"") assert_equal [0xFFFD].pack("U"), resolve("\"\\D800\"") assert_equal [0xD7FF].pack("U"), resolve("\"\\D7FF\"") assert_equal [0xFFFD].pack("U"), resolve("\"\\DFFF\"") assert_equal [0xE000].pack("U"), resolve("\"\\E000\"") end def test_string_escapes_are_resolved_before_operators assert_equal "true", resolve('"abc" == "\61\62\63"') end def test_string_quote assert_equal '"foo"', resolve_quoted('"foo"') assert_equal "'f\"oo'", resolve_quoted('"f\"oo"') assert_equal "\"f'oo\"", resolve_quoted("'f\\'oo'") assert_equal "\"f'o\\\"o\"", resolve_quoted("'f\\'o\"o'") assert_equal '"foo bar"', resolve_quoted('"foo\20 bar"') assert_equal '"foo\a bar"', resolve_quoted('"foo\a bar"') assert_equal '"x\ay"', resolve_quoted('"x\a y"') assert_equal '"\a "', resolve_quoted('"\a\20"') assert_equal '"\a abcdef"', resolve_quoted('"\a abcdef"') assert_equal '"☃abcdef"', resolve_quoted('"\2603 abcdef"') assert_equal '"\\\\"', resolve_quoted('"\\\\"') assert_equal '"foobar"', resolve_quoted("\"foo\\\nbar\"") assert_equal '"#{foo}"', resolve_quoted("\"\\\#{foo}\"") end def test_color_names assert_equal "white", resolve("white") assert_equal "#ffffff", resolve("#ffffff") silence_warnings {assert_equal "#fffffe", resolve("white - #000001")} assert_equal "transparent", resolve("transparent") assert_equal "rgba(0, 0, 0, 0)", resolve("rgba(0, 0, 0, 0)") end def test_rgba_color_literals assert_equal Sass::Script::Value::Color.new([1, 2, 3, 0.75]), eval("rgba(1, 2, 3, 0.75)") assert_equal "rgba(1, 2, 3, 0.75)", resolve("rgba(1, 2, 3, 0.75)") assert_equal Sass::Script::Value::Color.new([1, 2, 3, 0]), eval("rgba(1, 2, 3, 0)") assert_equal "rgba(1, 2, 3, 0)", resolve("rgba(1, 2, 3, 0)") assert_equal Sass::Script::Value::Color.new([1, 2, 3]), eval("rgba(1, 2, 3, 1)") assert_equal Sass::Script::Value::Color.new([1, 2, 3, 1]), eval("rgba(1, 2, 3, 1)") assert_equal "#010203", resolve("rgba(1, 2, 3, 1)") assert_equal "white", resolve("rgba(255, 255, 255, 1)") end def test_rgba_color_math silence_warnings {assert_equal "rgba(50, 50, 100, 0.35)", resolve("rgba(1, 1, 2, 0.35) * rgba(50, 50, 50, 0.35)")} silence_warnings {assert_equal "rgba(52, 52, 52, 0.25)", resolve("rgba(2, 2, 2, 0.25) + rgba(50, 50, 50, 0.25)")} assert_raise_message(Sass::SyntaxError, "Alpha channels must be equal: rgba(1, 2, 3, 0.15) + rgba(50, 50, 50, 0.75)") do silence_warnings {resolve("rgba(1, 2, 3, 0.15) + rgba(50, 50, 50, 0.75)")} end assert_raise_message(Sass::SyntaxError, "Alpha channels must be equal: #123456 * rgba(50, 50, 50, 0.75)") do silence_warnings {resolve("#123456 * rgba(50, 50, 50, 0.75)")} end assert_raise_message(Sass::SyntaxError, "Alpha channels must be equal: rgba(50, 50, 50, 0.75) / #123456") do silence_warnings {resolve("rgba(50, 50, 50, 0.75) / #123456")} end end def test_rgba_number_math silence_warnings {assert_equal "rgba(49, 49, 49, 0.75)", resolve("rgba(50, 50, 50, 0.75) - 1")} silence_warnings {assert_equal "rgba(100, 100, 100, 0.75)", resolve("rgba(50, 50, 50, 0.75) * 2")} end def test_rgba_rounding assert_equal "rgba(10, 1, 0, 0.1234567892)", resolve("rgba(10.0, 1.23456789, 0.0, 0.12345678919)") end def test_rgb_calc assert_equal "rgb(calc(255 - 5), 0, 0)", resolve("rgb(calc(255 - 5), 0, 0)") end def test_rgba_calc assert_equal "rgba(calc(255 - 5), 0, 0, 0.1)", resolve("rgba(calc(255 - 5), 0, 0, 0.1)") assert_equal "rgba(127, 0, 0, calc(0.1 + 0.5))", resolve("rgba(127, 0, 0, calc(0.1 + 0.5))") end def test_rgba_shorthand_calc assert_equal "rgba(255, 0, 0, calc(0.1 + 0.5))", resolve("rgba(red, calc(0.1 + 0.5))") end def test_hsl_calc assert_equal "hsl(calc(360 * 5 / 6), 50%, 50%)", resolve("hsl(calc(360 * 5 / 6), 50%, 50%)") end def test_hsla_calc assert_equal "hsla(calc(360 * 5 / 6), 50%, 50%, 0.1)", resolve("hsla(calc(360 * 5 / 6), 50%, 50%, 0.1)") assert_equal "hsla(270, 50%, 50%, calc(0.1 + 0.1))", resolve("hsla(270, 50%, 50%, calc(0.1 + 0.1))") end def test_compressed_colors assert_equal "#123456", resolve("#123456", :style => :compressed) assert_equal "rgba(1,2,3,0.5)", resolve("rgba(1, 2, 3, 0.5)", :style => :compressed) assert_equal "#123", resolve("#112233", :style => :compressed) assert_equal "#000", resolve("black", :style => :compressed) assert_equal "red", resolve("#f00", :style => :compressed) assert_equal "blue", resolve("blue", :style => :compressed) assert_equal "navy", resolve("#000080", :style => :compressed) assert_equal "navy #fff", resolve("#000080 white", :style => :compressed) assert_equal "This color is #fff", resolve('"This color is #{ white }"', :style => :compressed) assert_equal "transparent", resolve("rgba(0, 0, 0, 0)", :style => :compressed) end def test_compressed_comma # assert_equal "foo,bar,baz", resolve("foo, bar, baz", :style => :compressed) # assert_equal "foo,#baf,baz", resolve("foo, #baf, baz", :style => :compressed) assert_equal "foo,#baf,red", resolve("foo, #baf, #f00", :style => :compressed) end def test_implicit_strings assert_equal Sass::Script::Value::String.new("foo"), eval("foo") assert_equal Sass::Script::Value::String.new("foo/bar"), eval("foo/bar") end def test_basic_interpolation assert_equal "foo3bar", resolve("foo\#{1 + 2}bar") assert_equal "foo3 bar", resolve("foo\#{1 + 2} bar") assert_equal "foo 3bar", resolve("foo \#{1 + 2}bar") assert_equal "foo 3 bar", resolve("foo \#{1 + 2} bar") assert_equal "foo 35 bar", resolve("foo \#{1 + 2}\#{2 + 3} bar") assert_equal "foo 3 5 bar", resolve("foo \#{1 + 2} \#{2 + 3} bar") assert_equal "3bar", resolve("\#{1 + 2}bar") assert_equal "foo3", resolve("foo\#{1 + 2}") assert_equal "3", resolve("\#{1 + 2}") end def test_interpolation_in_function assert_equal 'flabnabbit(1foo)', resolve('flabnabbit(#{1 + "foo"})') assert_equal 'flabnabbit(foo 1foobaz)', resolve('flabnabbit(foo #{1 + "foo"}baz)') assert_equal('flabnabbit(foo 1foo2bar baz)', resolve('flabnabbit(foo #{1 + "foo"}#{2 + "bar"} baz)')) end def test_interpolation_near_operators silence_warnings do assert_equal '3 , 7', resolve('#{1 + 2} , #{3 + 4}') assert_equal '3, 7', resolve('#{1 + 2}, #{3 + 4}') assert_equal '3 ,7', resolve('#{1 + 2} ,#{3 + 4}') assert_equal '3,7', resolve('#{1 + 2},#{3 + 4}') assert_equal '3, 7, 11', resolve('#{1 + 2}, #{3 + 4}, #{5 + 6}') assert_equal '3, 7, 11', resolve('3, #{3 + 4}, 11') assert_equal '3, 7, 11', resolve('3, 7, #{5 + 6}') assert_equal '3 / 7', resolve('3 / #{3 + 4}') assert_equal '3 /7', resolve('3 /#{3 + 4}') assert_equal '3/ 7', resolve('3/ #{3 + 4}') assert_equal '3/7', resolve('3/#{3 + 4}') assert_equal '3 * 7', resolve('#{1 + 2} * 7') assert_equal '3* 7', resolve('#{1 + 2}* 7') assert_equal '3 *7', resolve('#{1 + 2} *7') assert_equal '3*7', resolve('#{1 + 2}*7') assert_equal '-3', resolve('-#{1 + 2}') assert_equal '- 3', resolve('- #{1 + 2}') assert_equal '5 + 3 * 7', resolve('5 + #{1 + 2} * #{3 + 4}') assert_equal '5 +3 * 7', resolve('5 +#{1 + 2} * #{3 + 4}') assert_equal '5+3 * 7', resolve('5+#{1 + 2} * #{3 + 4}') assert_equal '3 * 7 + 5', resolve('#{1 + 2} * #{3 + 4} + 5') assert_equal '3 * 7+ 5', resolve('#{1 + 2} * #{3 + 4}+ 5') assert_equal '3 * 7+5', resolve('#{1 + 2} * #{3 + 4}+5') assert_equal '5/3 + 7', resolve('5 / (#{1 + 2} + #{3 + 4})') assert_equal '5/3 + 7', resolve('5 /(#{1 + 2} + #{3 + 4})') assert_equal '5/3 + 7', resolve('5 /( #{1 + 2} + #{3 + 4} )') assert_equal '3 + 7/5', resolve('(#{1 + 2} + #{3 + 4}) / 5') assert_equal '3 + 7/5', resolve('(#{1 + 2} + #{3 + 4})/ 5') assert_equal '3 + 7/5', resolve('( #{1 + 2} + #{3 + 4} )/ 5') assert_equal '3 + 5', resolve('#{1 + 2} + 2 + 3') assert_equal '3 +5', resolve('#{1 + 2} +2 + 3') end end def test_string_interpolation assert_equal "foo bar, baz bang", resolve('"foo #{"bar"}, #{"baz"} bang"') assert_equal "foo bar baz bang", resolve('"foo #{"#{"ba" + "r"} baz"} bang"') assert_equal 'foo #{bar baz} bang', resolve('"foo \#{#{"ba" + "r"} baz} bang"') assert_equal 'foo #{baz bang', resolve('"foo #{"\#{" + "baz"} bang"') assert_equal "foo2bar", resolve('\'foo#{1 + 1}bar\'') assert_equal "foo2bar", resolve('"foo#{1 + 1}bar"') assert_equal "foo1bar5baz4bang", resolve('\'foo#{1 + "bar#{2 + 3}baz" + 4}bang\'') end def test_interpolation_in_interpolation assert_equal 'foo', resolve('#{#{foo}}') assert_equal 'foo', resolve('"#{#{foo}}"') assert_equal 'foo', resolve('#{"#{foo}"}') assert_equal 'foo', resolve('"#{"#{foo}"}"') end def test_interpolation_with_newline assert_equal "\nbang", resolve('"#{"\a "}bang"') assert_equal "\n\nbang", resolve('"#{"\a "}\a bang"') end def test_rule_interpolation assert_equal(<<CSS, render(<<SASS)) foo bar baz bang { a: b; } CSS foo \#{"\#{"ba" + "r"} baz"} bang a: b SASS assert_equal(<<CSS, render(<<SASS)) foo [bar="\#{bar baz}"] bang { a: b; } CSS foo [bar="\\\#{\#{"ba" + "r"} baz}"] bang a: b SASS assert_equal(<<CSS, render(<<SASS)) foo [bar="\#{baz"] bang { a: b; } CSS foo [bar="\#{"\\\#{" + "baz"}"] bang a: b SASS end def test_inaccessible_functions assert_equal "send(to_s)", resolve("send(to_s)", :line => 2) assert_equal "public_instance_methods()", resolve("public_instance_methods()") end def test_adding_functions_directly_to_functions_module assert !Functions.callable?('nonexistent') Functions.class_eval { def nonexistent; end } assert Functions.callable?('nonexistent') Functions.send :remove_method, :nonexistent end def test_default_functions assert_equal "url(12)", resolve("url(12)") assert_equal 'blam("foo")', resolve('blam("foo")') end def test_function_results_have_options assert_equal "Options defined!", resolve("assert_options(abs(1))") assert_equal "Options defined!", resolve("assert_options(round(1.2))") end def test_funcall_requires_no_whitespace_before_lparen assert_equal "no-repeat 15px", resolve("no-repeat (7px + 8px)") assert_equal "no-repeat(15px)", resolve("no-repeat(7px + 8px)") end def test_dynamic_url assert_equal "url(foo-bar)", resolve("url($foo)", {}, env('foo' => Sass::Script::Value::String.new("foo-bar"))) assert_equal "url(foo-bar baz)", resolve("url($foo $bar)", {}, env('foo' => Sass::Script::Value::String.new("foo-bar"), 'bar' => Sass::Script::Value::String.new("baz"))) assert_equal "url(foo baz)", resolve("url(foo $bar)", {}, env('bar' => Sass::Script::Value::String.new("baz"))) assert_equal "url(foo bar)", resolve("url(foo bar)") end def test_url_with_interpolation assert_equal "url(http://sass-lang.com/images/foo-bar)", resolve("url(http://sass-lang.com/images/\#{foo-bar})") assert_equal 'url("http://sass-lang.com/images/foo-bar")', resolve("url('http://sass-lang.com/images/\#{foo-bar}')") assert_equal 'url("http://sass-lang.com/images/foo-bar")', resolve('url("http://sass-lang.com/images/#{foo-bar}")') assert_unquoted "url(http://sass-lang.com/images/\#{foo-bar})" end def test_hyphenated_variables assert_equal("a-b", resolve("$a-b", {}, env("a-b" => Sass::Script::Value::String.new("a-b")))) end def test_ruby_equality assert_equal eval('"foo"'), eval('"foo"') assert_equal eval('1'), eval('1.0') assert_equal eval('1 2 3.0'), eval('1 2 3') assert_equal eval('1, 2, 3.0'), eval('1, 2, 3') assert_equal eval('(1 2), (3, 4), (5 6)'), eval('(1 2), (3, 4), (5 6)') refute_equal eval('1, 2, 3'), eval('1 2 3') refute_equal eval('1'), eval('"1"') end def test_booleans assert_equal "true", resolve("true") assert_equal "false", resolve("false") end def test_null assert_equal "", resolve("null") end def test_boolean_ops assert_equal "true", resolve("true and true") assert_equal "true", resolve("false or true") assert_equal "true", resolve("true or false") assert_equal "true", resolve("true or true") assert_equal "false", resolve("false or false") assert_equal "false", resolve("false and true") assert_equal "false", resolve("true and false") assert_equal "false", resolve("false and false") assert_equal "true", resolve("not false") assert_equal "false", resolve("not true") assert_equal "true", resolve("not not true") assert_equal "1", resolve("false or 1") assert_equal "false", resolve("false and 1") assert_equal "2", resolve("2 or 3") assert_equal "3", resolve("2 and 3") assert_equal "true", resolve("null or true") assert_equal "true", resolve("true or null") assert_equal "", resolve("null or null") assert_equal "", resolve("null and true") assert_equal "", resolve("true and null") assert_equal "", resolve("null and null") assert_equal "true", resolve("not null") assert_equal "1", resolve("null or 1") assert_equal "", resolve("null and 1") end def test_arithmetic_ops assert_equal "2", resolve("1 + 1") assert_equal "0", resolve("1 - 1") assert_equal "8", resolve("2 * 4") assert_equal "0.5", resolve("(2 / 4)") assert_equal "2", resolve("(4 / 2)") assert_equal "-1", resolve("-1") end def test_subtraction_vs_minus_vs_identifier assert_equal "0.25em", resolve("1em-.75") assert_equal "0.25em", resolve("1em-0.75") assert_equal "1em -0.75", resolve("1em -.75") assert_equal "1em -0.75", resolve("1em -0.75") assert_equal "1em- 0.75", resolve("1em- .75") assert_equal "1em- 0.75", resolve("1em- 0.75") assert_equal "0.25em", resolve("1em - .75") assert_equal "0.25em", resolve("1em - 0.75") end def test_string_ops assert_equal '"foo" "bar"', resolve('"foo" "bar"') assert_equal "true 1", resolve('true 1') assert_equal '"foo", "bar"', resolve("'foo' , 'bar'") assert_equal "true, 1", resolve('true , 1') assert_equal "foobar", resolve('"foo" + "bar"') assert_equal "\nfoo\nxyz", resolve('"\a foo" + "\axyz"') assert_equal "true1", resolve('true + 1') assert_equal '"foo"-"bar"', resolve("'foo' - 'bar'") assert_equal "true-1", resolve('true - 1') assert_equal '"foo"/"bar"', resolve('"foo" / "bar"') assert_equal "true/1", resolve('true / 1') assert_equal '-"bar"', resolve("- 'bar'") assert_equal "-true", resolve('- true') assert_equal '/"bar"', resolve('/ "bar"') assert_equal "/true", resolve('/ true') end def test_relational_ops assert_equal "false", resolve("1 > 2") assert_equal "false", resolve("2 > 2") assert_equal "true", resolve("3 > 2") assert_equal "false", resolve("1 >= 2") assert_equal "true", resolve("2 >= 2") assert_equal "true", resolve("3 >= 2") assert_equal "true", resolve("1 < 2") assert_equal "false", resolve("2 < 2") assert_equal "false", resolve("3 < 2") assert_equal "true", resolve("1 <= 2") assert_equal "true", resolve("2 <= 2") assert_equal "false", resolve("3 <= 2") end def test_null_ops assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "null plus 1".') {eval("null + 1")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "null minus 1".') {eval("null - 1")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "null times 1".') {eval("null * 1")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "null div 1".') {eval("null / 1")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "null mod 1".') {eval("null % 1")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "1 plus null".') {eval("1 + null")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "1 minus null".') {eval("1 - null")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "1 times null".') {eval("1 * null")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "1 div null".') {eval("1 / null")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "1 mod null".') {eval("1 % null")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "1 gt null".') {eval("1 > null")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "null lt 1".') {eval("null < 1")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: "null plus null".') {eval("null + null")} assert_raise_message(Sass::SyntaxError, 'Invalid null operation: ""foo" plus null".') {eval("foo + null")} end def test_equals assert_equal("true", resolve('"foo" == $foo', {}, env("foo" => Sass::Script::Value::String.new("foo")))) assert_equal "true", resolve("1 == 1.0") assert_equal "true", resolve("false != true") assert_equal "false", resolve("1em == 1px") assert_equal "false", resolve("12 != 12") assert_equal "true", resolve("(foo bar baz) == (foo bar baz)") assert_equal "true", resolve("(foo, bar, baz) == (foo, bar, baz)") assert_equal "true", resolve('((1 2), (3, 4), (5 6)) == ((1 2), (3, 4), (5 6))') assert_equal "true", resolve('((1 2), (3 4)) == (1 2, 3 4)') assert_equal "false", resolve('((1 2) 3) == (1 2 3)') assert_equal "false", resolve('(1 (2 3)) == (1 2 3)') assert_equal "false", resolve('((1, 2) (3, 4)) == (1, 2 3, 4)') assert_equal "false", resolve('(1 2 3) == (1, 2, 3)') assert_equal "true", resolve('null == null') assert_equal "false", resolve('"null" == null') assert_equal "false", resolve('0 == null') assert_equal "false", resolve('() == null') assert_equal "false", resolve('null != null') assert_equal "true", resolve('"null" != null') assert_equal "true", resolve('0 != null') assert_equal "true", resolve('() != null') end def test_mod assert_equal "5", resolve("29 % 12") assert_equal "5px", resolve("29px % 12") assert_equal "5px", resolve("29px % 12px") end def test_operation_precedence assert_equal "false true", resolve("true and false false or true") assert_equal "true", resolve("false and true or true and true") assert_equal "true", resolve("1 == 2 or 3 == 3") assert_equal "true", resolve("1 < 2 == 3 >= 3") assert_equal "true", resolve("1 + 3 > 4 - 2") assert_equal "11", resolve("1 + 2 * 3 + 4") end def test_functions assert_equal "#80ff80", resolve("hsl(120, 100%, 75%)") silence_warnings {assert_equal "#81ff81", resolve("hsl(120, 100%, 75%) + #010001")} end def test_operator_unit_conversion assert_equal "1.1cm", resolve("1cm + 1mm") assert_equal "8q", resolve("4q + 1mm") assert_equal "40.025cm", resolve("40cm + 1q") assert_equal "2in", resolve("1in + 96px") assert_equal "true", resolve("2mm < 1cm") assert_equal "true", resolve("10mm == 1cm") assert_equal "true", resolve("1.1cm == 11mm") assert_equal "true", resolve("2mm == 8q") assert_equal "false", resolve("2px > 3q") Sass::Deprecation.allow_double_warnings do assert_warning(<<WARNING) {assert_equal "true", resolve("1 == 1cm")} DEPRECATION WARNING on line 1 of test_operator_unit_conversion_inline.sass: The result of `1 == 1cm` will be `false` in future releases of Sass. Unitless numbers will no longer be equal to the same numbers with units. WARNING assert_warning(<<WARNING) {assert_equal "false", resolve("1 != 1cm")} DEPRECATION WARNING on line 1 of test_operator_unit_conversion_inline.sass: The result of `1 != 1cm` will be `true` in future releases of Sass. Unitless numbers will no longer be equal to the same numbers with units. WARNING end end def test_length_units assert_equal "2.54", resolve("(1in/1cm)") assert_equal "2.3622047244", resolve("(1cm/1pc)") assert_equal "4.2333333333", resolve("(1pc/1mm)") assert_equal "2.8346456693", resolve("(1mm/1pt)") assert_equal "1.3333333333", resolve("(1pt/1px)") assert_equal "0.0104166667", resolve("(1px/1in)") assert_equal "1.0583333333", resolve("(1px/1q)") assert_equal "0.0590551181", resolve("(1q/1pc)") end def test_angle_units assert_equal "1.1111111111", resolve("(1deg/1grad)") assert_equal "0.0157079633", resolve("(1grad/1rad)") assert_equal "0.1591549431", resolve("(1rad/1turn)") assert_equal "360", resolve("(1turn/1deg)") end def test_time_units assert_equal "1000", resolve("(1s/1ms)") end def test_frequency_units assert_equal "0.001", resolve("(1Hz/1kHz)") end def test_resolution_units assert_equal "0.3937007874", resolve("(1dpi/1dpcm)") assert_equal "0.0264583333", resolve("(1dpcm/1dppx)") assert_equal "96", resolve("(1dppx/1dpi)") end def test_operations_have_options assert_equal "Options defined!", resolve("assert_options(1 + 1)") assert_equal "Options defined!", resolve("assert_options('bar' + 'baz')") end def test_slash_compiles_literally_when_left_alone assert_equal "1px/2px", resolve("1px/2px") assert_equal "1px/2px/3px/4px", resolve("1px/2px/3px/4px") assert_equal "1px/2px redpx bluepx", resolve("1px/2px redpx bluepx") assert_equal "foo 1px/2px/3px bar", resolve("foo 1px/2px/3px bar") end def test_slash_divides_with_parens assert_equal "0.5", resolve("(1px/2px)") assert_equal "0.5", resolve("(1px)/2px") assert_equal "0.5", resolve("1px/(2px)") end def test_slash_divides_with_other_arithmetic assert_equal "0.5px", resolve("1px*1px/2px") assert_equal "0.5px", resolve("1px/2px*1px") assert_equal "0.5", resolve("0+1px/2px") assert_equal "0.5", resolve("1px/2px+0") end def test_slash_divides_with_variable assert_equal "0.5", resolve("$var/2px", {}, env("var" => eval("1px"))) assert_equal "0.5", resolve("1px/$var", {}, env("var" => eval("2px"))) assert_equal "0.5", resolve("$var", {}, env("var" => eval("1px/2px"))) end # Regression test for issue 1786. def test_slash_division_within_list assert_equal "1 1/2 1/2", resolve("(1 1/2 1/2)") assert_equal "1/2 1/2", resolve("(1/2 1/2)") assert_equal "1/2", resolve("(1/2,)") end def test_non_ident_colors_with_wrong_number_of_digits assert_raise_message(Sass::SyntaxError, 'Invalid CSS after "": expected expression (e.g. 1px, bold), was "#1"') {eval("#1")} assert_raise_message(Sass::SyntaxError, 'Invalid CSS after "": expected expression (e.g. 1px, bold), was "#12"') {eval("#12")} assert_raise_message(Sass::SyntaxError, 'Invalid CSS after "": expected expression (e.g. 1px, bold), was "#12345"') {eval("#12345")} assert_raise_message(Sass::SyntaxError, 'Invalid CSS after "": expected expression (e.g. ' \ '1px, bold), was "#1234567"') {eval("#1234567")} end def test_case_insensitive_color_names assert_equal "BLUE", resolve("BLUE") assert_equal "rEd", resolve("rEd") assert_equal "#804000", resolve("mix(GrEeN, ReD)") end def test_empty_list assert_equal "1 2 3", resolve("1 2 () 3") assert_equal "1 2 3", resolve("1 2 3 ()") assert_equal "1 2 3", resolve("() 1 2 3") assert_raise_message(Sass::SyntaxError, "() isn't a valid CSS value.") {resolve("()")} assert_raise_message(Sass::SyntaxError, "() isn't a valid CSS value.") {resolve("nth(append((), ()), 1)")} end def test_list_with_nulls assert_equal "1, 2, 3", resolve("1, 2, null, 3") assert_equal "1 2 3", resolve("1 2 null 3") assert_equal "1, 2, 3", resolve("1, 2, 3, null") assert_equal "1 2 3", resolve("1 2 3 null") assert_equal "1, 2, 3", resolve("null, 1, 2, 3") assert_equal "1 2 3", resolve("null 1 2 3") end def test_map_can_have_trailing_comma assert_equal("(foo: 1, bar: 2)", eval("(foo: 1, bar: 2,)").to_sass) end def test_list_can_have_trailing_comma assert_equal("1, 2, 3", resolve("1, 2, 3,")) end def test_trailing_comma_defines_singleton_list assert_equal("1 2 3", resolve("nth((1 2 3,), 1)")) end def test_map_cannot_have_duplicate_keys assert_raise_message(Sass::SyntaxError, 'Duplicate key "foo" in map (foo: bar, foo: baz).') do eval("(foo: bar, foo: baz)") end assert_raise_message(Sass::SyntaxError, 'Duplicate key "foo" in map (foo: bar, fo + o: baz).') do eval("(foo: bar, fo + o: baz)") end assert_raise_message(Sass::SyntaxError, 'Duplicate key "foo" in map (foo: bar, "foo": baz).') do eval("(foo: bar, 'foo': baz)") end assert_raise_message(Sass::SyntaxError, 'Duplicate key 2px in map (2px: bar, 1px + 1px: baz).') do eval("(2px: bar, 1px + 1px: baz)") end assert_raise_message(Sass::SyntaxError, 'Duplicate key #0000ff in map (blue: bar, #00f: baz).') do eval("(blue: bar, #00f: baz)") end end def test_non_duplicate_map_keys # These shouldn't throw errors eval("(foo: foo, bar: bar)") eval("(2px: foo, 2: bar)") eval("(2px: foo, 2em: bar)") eval("('2px': foo, 2px: bar)") end def test_map_syntax_errors assert_raise_message(Sass::SyntaxError, 'Invalid CSS after "(foo:": expected expression (e.g. 1px, bold), was ")"') do eval("(foo:)") end assert_raise_message(Sass::SyntaxError, 'Invalid CSS after "(": expected ")", was ":bar)"') do eval("(:bar)") end assert_raise_message(Sass::SyntaxError, 'Invalid CSS after "(foo, bar": expected ")", was ": baz)"') do eval("(foo, bar: baz)") end assert_raise_message(Sass::SyntaxError, 'Invalid CSS after "(foo: bar, baz": expected ":", was ")"') do eval("(foo: bar, baz)") end end def test_deep_argument_error_not_unwrapped # JRuby (as of 1.6.7.2) offers no way of distinguishing between # argument errors caused by programming errors in a function and # argument errors explicitly thrown within that function. return if RUBY_PLATFORM =~ /java/ # Don't validate the message; it's different on Rubinius. assert_raises(ArgumentError) {resolve("arg-error()")} end def test_shallow_argument_error_unwrapped assert_raise_message(Sass::SyntaxError, "wrong number of arguments (1 for 0) for `arg-error'") {resolve("arg-error(1)")} end def test_boolean_ops_short_circuit assert_equal "false", resolve("$ie and $ie <= 7", {}, env('ie' => Sass::Script::Value::Bool.new(false))) assert_equal "true", resolve("$ie or $undef", {}, env('ie' => Sass::Script::Value::Bool.new(true))) end def test_selector env = Sass::Environment.new assert_equal "true", resolve("& == null", {}, env) env.selector = selector('.foo.bar .baz.bang, .bip.bop') assert_equal ".foo.bar .baz.bang, .bip.bop", resolve("&", {}, env) assert_equal ".foo.bar .baz.bang", resolve("nth(&, 1)", {}, env) assert_equal ".bip.bop", resolve("nth(&, 2)", {}, env) assert_equal ".foo.bar", resolve("nth(nth(&, 1), 1)", {}, env) assert_equal ".baz.bang", resolve("nth(nth(&, 1), 2)", {}, env) assert_equal ".bip.bop", resolve("nth(nth(&, 2), 1)", {}, env) assert_equal "string", resolve("type-of(nth(nth(&, 1), 1))", {}, env) env.selector = selector('.foo > .bar') assert_equal ".foo > .bar", resolve("&", {}, env) assert_equal ".foo > .bar", resolve("nth(&, 1)", {}, env) assert_equal ".foo", resolve("nth(nth(&, 1), 1)", {}, env) assert_equal ">", resolve("nth(nth(&, 1), 2)", {}, env) assert_equal ".bar", resolve("nth(nth(&, 1), 3)", {}, env) end def test_selector_with_newlines env = Sass::Environment.new env.selector = selector(".foo.bar\n.baz.bang,\n\n.bip.bop") assert_equal ".foo.bar .baz.bang, .bip.bop", resolve("&", {}, env) assert_equal ".foo.bar .baz.bang", resolve("nth(&, 1)", {}, env) assert_equal ".bip.bop", resolve("nth(&, 2)", {}, env) assert_equal ".foo.bar", resolve("nth(nth(&, 1), 1)", {}, env) assert_equal ".baz.bang", resolve("nth(nth(&, 1), 2)", {}, env) assert_equal ".bip.bop", resolve("nth(nth(&, 2), 1)", {}, env) assert_equal "string", resolve("type-of(nth(nth(&, 1), 1))", {}, env) end def test_setting_global_variable_globally assert_no_warning {assert_equal(<<CSS, render(<<SCSS, :syntax => :scss))} .foo { a: 1; } .bar { b: 2; } CSS $var: 1; .foo { a: $var; } $var: 2; .bar { b: $var; } SCSS end def test_setting_global_variable_locally assert_no_warning {assert_equal(<<CSS, render(<<SCSS, :syntax => :scss))} .bar { a: x; b: y; c: z; } CSS $var1: 1; $var3: 3; .foo { $var1: x !global; $var2: y !global; @each $var3 in _ { $var3: z !global; } } .bar { a: $var1; b: $var2; c: $var3; } SCSS end def test_setting_global_variable_locally_with_default assert_equal(<<CSS, render(<<SCSS, :syntax => :scss)) .bar { a: 1; b: y; c: z; } CSS $var1: 1; .foo { $var1: x !global !default; $var2: y !global !default; @each $var3 in _ { $var3: z !global !default; } } .bar { a: $var1; b: $var2; c: $var3; } SCSS end def test_setting_local_variable assert_equal(<<CSS, render(<<SCSS, :syntax => :scss)) .a { value: inside; } .b { value: outside; } CSS $var: outside; .a { $var: inside; value: $var; } .b { value: $var; } SCSS end def test_setting_local_variable_from_inner_scope assert_equal(<<CSS, render(<<SCSS, :syntax => :scss)) .a .b { value: inside; } .a .c { value: inside; } CSS .a { $var: outside; .b { $var: inside; value: $var; } .c { value: $var; } } SCSS end def test_if_can_assign_to_global_variables assert_equal <<CSS, render(<<SCSS, :syntax => :scss) .a { b: 2; } CSS $var: 1; @if true {$var: 2} .a {b: $var} SCSS end def test_else_can_assign_to_global_variables assert_equal <<CSS, render(<<SCSS, :syntax => :scss) .a { b: 2; } CSS $var: 1; @if false {} @else {$var: 2} .a {b: $var} SCSS end def test_for_can_assign_to_global_variables assert_equal <<CSS, render(<<SCSS, :syntax => :scss) .a { b: 2; } CSS $var: 1; @for $i from 1 to 2 {$var: 2} .a {b: $var} SCSS end def test_each_can_assign_to_global_variables assert_equal <<CSS, render(<<SCSS, :syntax => :scss) .a { b: 2; } CSS $var: 1; @each $a in 1 {$var: 2} .a {b: $var} SCSS end def test_while_can_assign_to_global_variables assert_equal <<CSS, render(<<SCSS, :syntax => :scss) .a { b: 2; } CSS $var: 1; @while $var != 2 {$var: 2} .a {b: $var} SCSS end def test_if_doesnt_leak_local_variables assert_raise_message(Sass::SyntaxError, 'Undefined variable: "$var".') do render(<<SCSS, :syntax => :scss) @if true {$var: 1} .a {b: $var} SCSS end end def test_else_doesnt_leak_local_variables assert_raise_message(Sass::SyntaxError, 'Undefined variable: "$var".') do
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/test/sass/test_helper.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/test_helper.rb
test_dir = File.dirname(__FILE__) $:.unshift test_dir unless $:.include?(test_dir) class MiniTest::Test def absolutize(file) File.expand_path("#{File.dirname(__FILE__)}/#{file}") 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/test/sass/script_conversion_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/script_conversion_test.rb
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/../test_helper' require 'sass/engine' class SassScriptConversionTest < MiniTest::Test def test_bool assert_renders "true" assert_renders "false" end def test_color assert_renders "#abcdef" assert_renders "blue" assert_renders "rgba(0, 1, 2, 0.2)" assert_renders "#abc" assert_renders "#0000ff" end def test_number assert_renders "10" assert_renders "10.35" assert_renders "12px" assert_renders "12.45px" assert_equal "12.3456789013", render("12.34567890129") end def test_string assert_renders '"foo"' assert_renders '"bar baz"' assert_equal '"baz bang"', render("'baz bang'") end def test_string_quotes assert_equal "'quote\"quote'", render('"quote\\"quote"') assert_equal '"quote\'quote"', render("'quote\\'quote'") assert_renders '"quote\'quote\\"quote"' assert_equal '"quote\'quote\\"quote"', render("'quote\\'quote\"quote'") end def test_string_escapes assert_renders '"foo\\\\bar"' end def test_funcall assert_renders "foo(true, blue)" assert_renders "hsla(20deg, 30%, 50%, 0.3)" assert_renders "blam()" assert_renders "-\xC3\xBFoo(12px)" assert_renders "-foo(12px)" end def test_funcall_with_keyword_args assert_renders "foo(arg1, arg2, $karg1: val, $karg2: val2)" assert_renders "foo($karg1: val, $karg2: val2)" end def test_funcall_with_hyphen_conversion_keyword_arg assert_renders "foo($a-b_c: val)" end def test_url assert_renders "url(foo.gif)" assert_renders "url($var)" assert_renders "url(\#{$var}/flip.gif)" end def test_variable assert_renders "$foo-bar" assert_renders "$flaznicate" end def test_null assert_renders "null" end def test_space_list assert_renders "foo bar baz" assert_renders "foo (bar baz) bip" assert_renders "foo (bar, baz) bip" end def test_comma_list assert_renders "foo, bar, baz" assert_renders "foo, (bar, baz), bip" assert_renders "foo, bar baz, bip" end def test_space_list_adds_parens_for_clarity assert_renders "(1 + 1) (2 / 4) (3 * 5)" end def test_comma_list_doesnt_add_parens assert_renders "1 + 1, 2 / 4, 3 * 5" end def test_empty_list assert_renders "()" end def test_list_in_args assert_renders "foo((a, b, c))" assert_renders "foo($arg: (a, b, c))" assert_renders "foo(a, b, (a, b, c)...)" end def test_singleton_list assert_renders "(1,)" assert_renders "(1 2 3,)" assert_renders "((1, 2, 3),)" end def test_map assert_renders "(foo: bar)" assert_renders "(foo: bar, baz: bip)" assert_renders "(foo: bar, baz: (bip: bap))" end def test_map_in_list assert_renders "(foo: bar) baz" assert_renders "(foo: bar), (baz: bip)" end def test_list_in_map assert_renders "(foo: bar baz)" assert_renders "(foo: (bar, baz), bip: bop)" end def test_selector assert_renders "&" end def self.test_precedence(outer, inner) op_outer = Sass::Script::Lexer::OPERATORS_REVERSE[outer] op_inner = Sass::Script::Lexer::OPERATORS_REVERSE[inner] class_eval <<RUBY def test_precedence_#{outer}_#{inner} assert_renders "$foo #{op_outer} $bar #{op_inner} $baz" assert_renders "$foo #{op_inner} $bar #{op_outer} $baz" assert_renders "($foo #{op_outer} $bar) #{op_inner} $baz" assert_renders "$foo #{op_inner} ($bar #{op_outer} $baz)" assert_equal "$foo #{op_outer} $bar #{op_inner} $baz", render("$foo #{op_outer} ($bar #{op_inner} $baz)") assert_equal "$foo #{op_inner} $bar #{op_outer} $baz", render("($foo #{op_inner} $bar) #{op_outer} $baz") end RUBY end def self.assert_associative(op_name, sibling_name) op = separator_for(op_name) sibling = separator_for(sibling_name) class_eval <<RUBY def test_associative_#{op_name}_#{sibling_name} assert_renders "$foo#{op}$bar#{op}$baz" assert_equal "$foo#{op}$bar#{op}$baz", render("$foo#{op}($bar#{op}$baz)") assert_equal "$foo#{op}$bar#{op}$baz", render("($foo#{op}$bar)#{op}$baz") assert_equal "$foo#{op}$bar#{sibling}$baz", render("$foo#{op}($bar#{sibling}$baz)") assert_equal "$foo#{sibling}$bar#{op}$baz", render("($foo#{sibling}$bar)#{op}$baz") end RUBY end def self.separator_for(op_name) case op_name when :comma; ", " when :space; " " else; " #{Sass::Script::Lexer::OPERATORS_REVERSE[op_name]} " end end def self.assert_non_associative(op_name, sibling_name) op = Sass::Script::Lexer::OPERATORS_REVERSE[op_name] sibling = Sass::Script::Lexer::OPERATORS_REVERSE[sibling_name] class_eval <<RUBY def test_non_associative_#{op_name}_#{sibling_name} assert_renders "$foo #{op} $bar #{op} $baz" assert_renders "$foo #{op} ($bar #{op} $baz)" assert_equal "$foo #{op} $bar #{op} $baz", render("($foo #{op} $bar) #{op} $baz") assert_renders "$foo #{op} ($bar #{sibling} $baz)" assert_equal "$foo #{sibling} $bar #{op} $baz", render("($foo #{sibling} $bar) #{op} $baz") end RUBY end test_precedence :or, :and test_precedence :and, :eq test_precedence :and, :neq test_precedence :eq, :gt test_precedence :eq, :gte test_precedence :eq, :lt test_precedence :eq, :lte test_precedence :gt, :plus test_precedence :gt, :minus test_precedence :plus, :times test_precedence :plus, :div test_precedence :plus, :mod assert_associative :plus, :minus assert_associative :times, :div assert_associative :times, :mod assert_non_associative :minus, :plus assert_non_associative :div, :times assert_non_associative :mod, :times assert_non_associative :gt, :gte assert_non_associative :gte, :lt assert_non_associative :lt, :lte assert_non_associative :lte, :gt def test_comma_precedence assert_renders "$foo, $bar, $baz" assert_renders "$foo ($bar, $baz)" assert_renders "($foo, $bar) $baz" assert_equal "$foo, $bar $baz", render("$foo, ($bar $baz)") assert_equal "$foo $bar, $baz", render("($foo $bar), $baz") assert_equal "$foo, ($bar, $baz)", render("$foo, ($bar, $baz)") assert_equal "($foo, $bar), $baz", render("($foo, $bar), $baz") end def test_space_precedence assert_renders "$foo $bar $baz" assert_renders "$foo or ($bar $baz)" assert_renders "($foo $bar) or $baz" assert_renders "$foo ($bar or $baz)" assert_renders "($foo or $bar) $baz" assert_equal "$foo ($bar $baz)", render("$foo ($bar $baz)") assert_equal "($foo $bar) $baz", render("($foo $bar) $baz") end def test_unary_op assert_renders "-12px" assert_renders '/"foo"' assert_renders 'not true' assert_renders "-(foo(12px))" assert_renders "-(-foo(12px))" assert_renders "-(_foo(12px))" assert_renders "-(\xC3\xBFoo(12px))" assert_renders "-(blue)" assert_equal 'not true or false', render('(not true) or false') assert_equal 'not (true or false)', render('not (true or false)') end def test_interpolation assert_equal 'unquote("#{$foo}#{$bar}#{$baz}")', render("$foo\#{$bar}$baz") assert_equal 'unquote("#{$foo}#{$bar} #{$baz}")', render("$foo\#{$bar} $baz") assert_equal 'unquote("#{$foo} #{$bar}#{$baz}")', render("$foo \#{$bar}$baz") assert_renders "$foo \#{$bar} $baz" assert_renders "$foo \#{$bar}\#{$bang} $baz" assert_renders "$foo \#{$bar} \#{$bang} $baz" assert_equal 'unquote("#{$bar}#{$baz}")', render("\#{$bar}$baz") assert_equal 'unquote("#{$foo}#{$bar}")', render("$foo\#{$bar}") assert_renders "\#{$bar}" end def test_interpolation_in_function assert_renders 'flabnabbit(#{1 + "foo"})' assert_equal 'flabnabbit(unquote("#{$foo} #{1 + "foo"}#{$baz}"))', render('flabnabbit($foo #{1 + "foo"}$baz)') assert_renders 'flabnabbit($foo #{1 + "foo"}#{2 + "bar"} $baz)' end def test_interpolation_in_string_function assert_renders 'calc(#{1 + "foo"})' assert_renders 'calc(foo#{1 + "foo"}baz)' end def test_interpolation_near_operators assert_renders '#{1 + 2} , #{3 + 4}' assert_renders '#{1 + 2}, #{3 + 4}' assert_renders '#{1 + 2} ,#{3 + 4}' assert_renders '#{1 + 2},#{3 + 4}' assert_renders '#{1 + 2}, #{3 + 4}, #{5 + 6}' assert_renders '3, #{3 + 4}, 11' assert_renders '3 / #{3 + 4}' assert_renders '3 /#{3 + 4}' assert_renders '3/ #{3 + 4}' assert_renders '3/#{3 + 4}' assert_equal 'unquote("#{1 + 2} * 7")', render('#{1 + 2} * 7') assert_equal 'unquote("#{1 + 2}* 7")', render('#{1 + 2}* 7') assert_equal 'unquote("#{1 + 2} *7")', render('#{1 + 2} *7') assert_equal 'unquote("#{1 + 2}*7")', render('#{1 + 2}*7') assert_renders '-#{1 + 2}' assert_equal 'unquote("- #{1 + 2}")', render('- #{1 + 2}') assert_equal 'unquote("5 + #{1 + 2} * #{3 + 4}")', render('5 + #{1 + 2} * #{3 + 4}') assert_equal 'unquote("5 +#{1 + 2} * #{3 + 4}")', render('5 +#{1 + 2} * #{3 + 4}') assert_equal 'unquote("5+#{1 + 2} * #{3 + 4}")', render('5+#{1 + 2} * #{3 + 4}') assert_equal 'unquote("#{1 + 2} * #{3 + 4} + 5")', render('#{1 + 2} * #{3 + 4} + 5') assert_equal 'unquote("#{1 + 2} * #{3 + 4}+ 5")', render('#{1 + 2} * #{3 + 4}+ 5') assert_equal 'unquote("#{1 + 2} * #{3 + 4}+5")', render('#{1 + 2} * #{3 + 4}+5') assert_equal '5 / unquote("#{1 + 2} + #{3 + 4}")', render('5 / (#{1 + 2} + #{3 + 4})') assert_equal '5 / unquote("#{1 + 2} + #{3 + 4}")', render('5 /(#{1 + 2} + #{3 + 4})') assert_equal '5 / unquote("#{1 + 2} + #{3 + 4}")', render('5 /( #{1 + 2} + #{3 + 4} )') assert_equal 'unquote("#{1 + 2} + #{3 + 4}") / 5', render('(#{1 + 2} + #{3 + 4}) / 5') assert_equal 'unquote("#{1 + 2} + #{3 + 4}") / 5', render('(#{1 + 2} + #{3 + 4})/ 5') assert_equal 'unquote("#{1 + 2} + #{3 + 4}") / 5', render('( #{1 + 2} + #{3 + 4} )/ 5') assert_equal 'unquote("#{1 + 2} + #{2 + 3}")', render('#{1 + 2} + 2 + 3') assert_equal 'unquote("#{1 + 2} +#{2 + 3}")', render('#{1 + 2} +2 + 3') end def test_string_interpolation assert_renders '"foo#{$bar}baz"' assert_renders '"foo #{$bar}baz"' assert_renders '"foo#{$bar} baz"' assert_renders '"foo #{$bar} baz"' assert_renders '"foo #{$bar}#{$bang} baz"' assert_renders '"foo #{$bar} #{$bang} baz"' assert_renders '"#{$bar}baz"' assert_renders '"foo#{$bar}"' assert_renders '"#{$bar}"' assert_renders "'\"\#{\"bar\"}\"'" assert_renders '"\#{bar}"' assert_equal '"foo#{$bar}baz"', render("'foo\#{$bar}baz'") end def test_bracketed_lists assert_renders("[]") assert_renders("[foo, bar]") assert_renders("[[foo]]") assert_renders("[(foo bar)]") assert_renders("[foo bar,]") assert_renders("[(foo,)]") end private def assert_renders(script, options = {}) assert_equal(script, render(script, options)) end def render(script, options = {}) munge_filename(options) node = Sass::Script.parse(script, 1, 0, options.merge(:_convert => true)) node.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/test/sass/util_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/util_test.rb
require File.dirname(__FILE__) + '/../test_helper' require 'pathname' require 'tmpdir' class UtilTest < MiniTest::Test include Sass::Util def test_scope assert(File.exist?(scope("Rakefile"))) end def test_map_keys assert_equal({ "foo" => 1, "bar" => 2, "baz" => 3 }, map_keys({:foo => 1, :bar => 2, :baz => 3}) {|k| k.to_s}) end def test_map_vals assert_equal({ :foo => "1", :bar => "2", :baz => "3" }, map_vals({:foo => 1, :bar => 2, :baz => 3}) {|k| k.to_s}) end def test_map_hash assert_equal({ "foo" => "1", "bar" => "2", "baz" => "3" }, map_hash({:foo => 1, :bar => 2, :baz => 3}) {|k, v| [k.to_s, v.to_s]}) end def test_map_hash_with_normalized_map map = NormalizedMap.new("foo-bar" => 1, "baz_bang" => 2) result = map_hash(map) {|k, v| [k, v.to_s]} assert_equal("1", result["foo-bar"]) assert_equal("1", result["foo_bar"]) assert_equal("2", result["baz-bang"]) assert_equal("2", result["baz_bang"]) end def test_powerset assert_equal([[].to_set].to_set, powerset([])) assert_equal([[].to_set, [1].to_set].to_set, powerset([1])) assert_equal([[].to_set, [1].to_set, [2].to_set, [1, 2].to_set].to_set, powerset([1, 2])) assert_equal([[].to_set, [1].to_set, [2].to_set, [3].to_set, [1, 2].to_set, [2, 3].to_set, [1, 3].to_set, [1, 2, 3].to_set].to_set, powerset([1, 2, 3])) end def test_restrict assert_equal(0.5, restrict(0.5, 0..1)) assert_equal(1, restrict(2, 0..1)) assert_equal(1.3, restrict(2, 0..1.3)) assert_equal(0, restrict(-1, 0..1)) end def test_merge_adjacent_strings assert_equal(["foo bar baz", :bang, "biz bop", 12], merge_adjacent_strings(["foo ", "bar ", "baz", :bang, "biz", " bop", 12])) str = "foo" assert_equal(["foo foo foo", :bang, "foo foo", 12], merge_adjacent_strings([str, " ", str, " ", str, :bang, str, " ", str, 12])) end def test_replace_subseq assert_equal([1, 2, :a, :b, 5], replace_subseq([1, 2, 3, 4, 5], [3, 4], [:a, :b])) assert_equal([1, 2, 3, 4, 5], replace_subseq([1, 2, 3, 4, 5], [3, 4, 6], [:a, :b])) assert_equal([1, 2, 3, 4, 5], replace_subseq([1, 2, 3, 4, 5], [4, 5, 6], [:a, :b])) end def test_intersperse assert_equal(["foo", " ", "bar", " ", "baz"], intersperse(%w[foo bar baz], " ")) assert_equal([], intersperse([], " ")) end def test_substitute assert_equal(["foo", "bar", "baz", 3, 4], substitute([1, 2, 3, 4], [1, 2], ["foo", "bar", "baz"])) assert_equal([1, "foo", "bar", "baz", 4], substitute([1, 2, 3, 4], [2, 3], ["foo", "bar", "baz"])) assert_equal([1, 2, "foo", "bar", "baz"], substitute([1, 2, 3, 4], [3, 4], ["foo", "bar", "baz"])) assert_equal([1, "foo", "bar", "baz", 2, 3, 4], substitute([1, 2, 2, 2, 3, 4], [2, 2], ["foo", "bar", "baz"])) end def test_strip_string_array assert_equal(["foo ", " bar ", " baz"], strip_string_array([" foo ", " bar ", " baz "])) assert_equal([:foo, " bar ", " baz"], strip_string_array([:foo, " bar ", " baz "])) assert_equal(["foo ", " bar ", :baz], strip_string_array([" foo ", " bar ", :baz])) end def test_paths assert_equal([[1, 3, 5], [2, 3, 5], [1, 4, 5], [2, 4, 5]], paths([[1, 2], [3, 4], [5]])) assert_equal([[]], paths([])) assert_equal([[1, 2, 3]], paths([[1], [2], [3]])) end def test_lcs assert_equal([1, 2, 3], lcs([1, 2, 3], [1, 2, 3])) assert_equal([], lcs([], [1, 2, 3])) assert_equal([], lcs([1, 2, 3], [])) assert_equal([1, 2, 3], lcs([5, 1, 4, 2, 3, 17], [0, 0, 1, 2, 6, 3])) assert_equal([1], lcs([1, 2, 3, 4], [4, 3, 2, 1])) assert_equal([1, 2], lcs([1, 2, 3, 4], [3, 4, 1, 2])) end def test_lcs_with_block assert_equal(["1", "2", "3"], lcs([1, 4, 2, 5, 3], [1, 2, 3]) {|a, b| a == b && a.to_s}) assert_equal([-4, 2, 8], lcs([-5, 3, 2, 8], [-4, 1, 8]) {|a, b| (a - b).abs <= 1 && [a, b].max}) end def test_subsequence assert(subsequence?([1, 2, 3], [1, 2, 3])) assert(subsequence?([1, 2, 3], [1, :a, 2, :b, 3])) assert(subsequence?([1, 2, 3], [:a, 1, :b, :c, 2, :d, 3, :e, :f])) assert(!subsequence?([1, 2, 3], [1, 2])) assert(!subsequence?([1, 2, 3], [1, 3, 2])) assert(!subsequence?([1, 2, 3], [3, 2, 1])) end def test_sass_warn assert_warning("Foo!") {sass_warn "Foo!"} end def test_silence_sass_warnings old_stderr, $stderr = $stderr, StringIO.new silence_sass_warnings {warn "Out"} assert_equal("Out\n", $stderr.string) silence_sass_warnings {sass_warn "In"} assert_equal("Out\n", $stderr.string) ensure $stderr = old_stderr end def test_extract arr = [1, 2, 3, 4, 5] assert_equal([1, 3, 5], extract!(arr) {|e| e % 2 == 1}) assert_equal([2, 4], arr) end def test_flatten_vertically assert_equal([1, 2, 3], flatten_vertically([1, 2, 3])) assert_equal([1, 3, 5, 2, 4, 6], flatten_vertically([[1, 2], [3, 4], [5, 6]])) assert_equal([1, 2, 4, 3, 5, 6], flatten_vertically([1, [2, 3], [4, 5, 6]])) assert_equal([1, 4, 6, 2, 5, 3], flatten_vertically([[1, 2, 3], [4, 5], 6])) end def test_extract_and_inject_values test = lambda {|arr| assert_equal(arr, with_extracted_values(arr) {|str| str})} test[['foo bar']] test[['foo {12} bar']] test[['foo {{12} bar']] test[['foo {{1', 12, '2} bar']] test[['foo 1', 2, '{3', 4, 5, 6, '{7}', 8]] test[['foo 1', [2, 3, 4], ' bar']] test[['foo ', 1, "\n bar\n", [2, 3, 4], "\n baz"]] end def nested_caller_info_fn caller_info end def double_nested_caller_info_fn nested_caller_info_fn end def test_caller_info assert_equal(["/tmp/foo.rb", 12, "fizzle"], caller_info("/tmp/foo.rb:12: in `fizzle'")) assert_equal(["/tmp/foo.rb", 12, nil], caller_info("/tmp/foo.rb:12")) assert_equal(["C:/tmp/foo.rb", 12, nil], caller_info("C:/tmp/foo.rb:12")) assert_equal(["(sass)", 12, "blah"], caller_info("(sass):12: in `blah'")) assert_equal(["", 12, "boop"], caller_info(":12: in `boop'")) assert_equal(["/tmp/foo.rb", -12, "fizzle"], caller_info("/tmp/foo.rb:-12: in `fizzle'")) assert_equal(["/tmp/foo.rb", 12, "fizzle"], caller_info("/tmp/foo.rb:12: in `fizzle {}'")) assert_equal(["C:/tmp/foo.rb", 12, "fizzle"], caller_info("C:/tmp/foo.rb:12: in `fizzle {}'")) info = nested_caller_info_fn assert_equal(__FILE__, info[0]) assert_equal("test_caller_info", info[2]) info = proc {nested_caller_info_fn}.call assert_equal(__FILE__, info[0]) assert_match(/^(block in )?test_caller_info$/, info[2]) info = double_nested_caller_info_fn assert_equal(__FILE__, info[0]) assert_equal("double_nested_caller_info_fn", info[2]) info = proc {double_nested_caller_info_fn}.call assert_equal(__FILE__, info[0]) assert_equal("double_nested_caller_info_fn", info[2]) end def test_version_gt assert_version_gt("2.0.0", "1.0.0") assert_version_gt("1.1.0", "1.0.0") assert_version_gt("1.0.1", "1.0.0") assert_version_gt("1.0.0", "1.0.0.rc") assert_version_gt("1.0.0.1", "1.0.0.rc") assert_version_gt("1.0.0.rc", "0.9.9") assert_version_gt("1.0.0.beta", "1.0.0.alpha") assert_version_eq("1.0.0", "1.0.0") assert_version_eq("1.0.0", "1.0.0.0") end def assert_version_gt(v1, v2) #assert(version_gt(v1, v2), "Expected #{v1} > #{v2}") assert(!version_gt(v2, v1), "Expected #{v2} < #{v1}") end def assert_version_eq(v1, v2) assert(!version_gt(v1, v2), "Expected #{v1} = #{v2}") assert(!version_gt(v2, v1), "Expected #{v2} = #{v1}") end class FooBar def foo Sass::Util.abstract(self) end def old_method Sass::Util.deprecated(self) end def old_method_with_custom_message Sass::Util.deprecated(self, "Call FooBar#new_method instead.") end def self.another_old_method Sass::Util.deprecated(self) end end def test_abstract assert_raise_message(NotImplementedError, "UtilTest::FooBar must implement #foo") {FooBar.new.foo} end def test_deprecated assert_warning("DEPRECATION WARNING: UtilTest::FooBar#old_method will be removed in a future version of Sass.") { FooBar.new.old_method } assert_warning(<<WARNING) { FooBar.new.old_method_with_custom_message } DEPRECATION WARNING: UtilTest::FooBar#old_method_with_custom_message will be removed in a future version of Sass. Call FooBar#new_method instead. WARNING assert_warning("DEPRECATION WARNING: UtilTest::FooBar.another_old_method will be removed in a future version of Sass.") { FooBar.another_old_method } end def test_json_escape_string assert_json_string "", "" alphanum = (("0".."9").to_a).concat(("a".."z").to_a).concat(("A".."Z").to_a).join assert_json_string alphanum, alphanum assert_json_string "'\"\\'", "'\\\"\\\\'" assert_json_string "\b\f\n\r\t", "\\b\\f\\n\\r\\t" end def assert_json_string(source, target) assert_equal target, json_escape_string(source) end def test_json_value_of assert_json_value 0, "0" assert_json_value(-42, "-42") assert_json_value 42, "42" assert_json_value true, "true" assert_json_value false, "false" assert_json_value "", "\"\"" assert_json_value "\"\"", "\"\\\"\\\"\"" assert_json_value "Multi\nLine\rString", "\"Multi\\nLine\\rString\"" assert_json_value [1, "some\nstr,ing", false, nil], "[1,\"some\\nstr,ing\",false,null]" end def assert_json_value(source, target) assert_equal target, json_value_of(source) end def test_vlq assert_equal "A", encode_vlq(0) assert_equal "e", encode_vlq(15) assert_equal "gB", encode_vlq(16) assert_equal "wH", encode_vlq(120) end def assert_vlq_encodes(int, vlq) vlq_from_decimal_array = decimal_array.map {|d| encode_vlq(d)}.join decimal_array_from_vlq = decode_vlq(vlq) assert_equal vlq, vlq_from_decimal_array assert_equal decimal_array, decimal_array_from_vlq end def test_round_respects_precision original_precision = Sass::Script::Value::Number.precision assert_equal 0, Sass::Util.round(0.4999999999) # 10 9s doesn't work because 0.49999999999 - 0.5 is very slightly greater # than -0.1e11 due to float nonsense. assert_equal 1, Sass::Util.round(0.499999999999) Sass::Script::Value::Number.precision = 6 assert_equal 0, Sass::Util.round(0.499999) assert_equal 1, Sass::Util.round(0.49999999) ensure Sass::Script::Value::Number.precision = original_precision end def test_atomic_writes # when using normal writes, this test fails about 90% of the time. filename = File.join(Dir.tmpdir, "test_atomic") 5.times do writes_to_perform = %w(1 2 3 4 5 6 7 8 9).map {|i| "#{i}\n" * 100_000} threads = writes_to_perform.map do |to_write| Thread.new do # To see this test fail with a normal write, # change to the standard file open mechanism: # open(filename, "w") do |f| atomic_create_and_write_file(filename) do |f| f.write(to_write) end end end loop do contents = File.exist?(filename) ? File.read(filename) : nil next if contents.nil? || contents.size == 0 unless writes_to_perform.include?(contents) if contents.size != writes_to_perform.first.size fail "Incomplete write detected: was #{contents.size} characters, " + "should have been #{writes_to_perform.first.size}" else fail "Corrupted read/write detected" end end break if threads.all? {|t| !t.alive?} end threads.each {|t| t.join} end ensure Sass::Util.retry_on_windows {File.delete filename if File.exist?(filename)} end def test_atomic_write_permissions atomic_filename = File.join(Dir.tmpdir, "test_atomic_perms.atomic") normal_filename = File.join(Dir.tmpdir, "test_atomic_perms.normal") atomic_create_and_write_file(atomic_filename) {|f| f.write("whatever\n") } open(normal_filename, "wb") {|f| f.write("whatever\n") } assert_equal File.stat(normal_filename).mode.to_s(8), File.stat(atomic_filename).mode.to_s(8) ensure File.unlink(atomic_filename) rescue nil File.unlink(normal_filename) rescue nil end def test_atomic_writes_respect_umask atomic_filename = File.join(Dir.tmpdir, "test_atomic_perms.atomic") atomic_create_and_write_file(atomic_filename) do |f| f.write("whatever\n") end assert_equal 0, File.stat(atomic_filename).mode & File.umask ensure File.unlink(atomic_filename) end class FakeError < RuntimeError; end def test_atomic_writes_handles_exceptions filename = File.join(Dir.tmpdir, "test_atomic_exception") FileUtils.rm_f(filename) tmp_filename = nil assert_raises FakeError do atomic_create_and_write_file(filename) do |f| tmp_filename = f.path raise FakeError.new "Borken" end end assert !File.exist?(filename) assert !File.exist?(tmp_filename) 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/test/sass/css2sass_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/css2sass_test.rb
require 'minitest/autorun' require File.dirname(__FILE__) + '/../test_helper' require 'sass/css' class CSS2SassTest < MiniTest::Test def test_basic css = <<CSS h1 { color: red; } CSS assert_equal(<<SASS, css2sass(css)) h1 color: red SASS silence_warnings {assert_equal(<<SASS, css2sass(css, :old => true))} h1 :color red SASS end def test_nesting assert_equal(<<SASS, css2sass(<<CSS)) li display: none a text-decoration: none span color: yellow &:hover text-decoration: underline SASS li { display: none; } li a { text-decoration: none; } li a span { color: yellow; } li a:hover { text-decoration: underline; } CSS end def test_no_nesting_around_rules assert_equal(<<SASS, css2sass(<<CSS)) div .warning color: #d21a19 span .debug cursor: crosshair div .debug cursor: default SASS div .warning { color: #d21a19; } span .debug { cursor: crosshair;} div .debug { cursor: default; } CSS end def test_comments_multiline css = <<CSS /* comment */ elephant.rawr { rampages: excessively; } /* actual multiline comment */ span.turkey { isdinner: true; } .turducken { /* Sounds funny doesn't it */ chimera: not_really; } #overhere { bored: sorta; /* it's for a good cause */ better_than: thread_pools; } #one_more { finally: srsly; } /* just a line here */ CSS sass = <<SASS /* comment elephant.rawr rampages: excessively /* actual multiline *comment span.turkey isdinner: true .turducken /* Sounds funny * doesn't it chimera: not_really #overhere bored: sorta /* it's for a good * cause better_than: thread_pools #one_more finally: srsly /* just a line here SASS assert_equal(sass, css2sass(css)) end def test_fold_commas assert_equal(<<SASS, css2sass(<<CSS)) li .one, .two color: red SASS li .one { color: red; } li .two { color: red; } CSS assert_equal(<<SASS, css2sass(<<CSS)) .one color: green .two color: green color: red .three color: red SASS .one, .two { color: green; } .two, .three { color: red; } CSS end def test_bad_formatting assert_equal(<<SASS, css2sass(<<CSS)) hello parent: true there parent: false who hoo: false why y: true when wen: nao down_here yeah: true SASS hello { parent: true; } hello there { parent: false; } hello who { hoo: false; } hello why { y: true; } hello when { wen: nao; } down_here { yeah: true; } CSS end def test_comments_in_selectors assert_equal(<<SASS, css2sass(<<CSS)) .js #location-navigation-form .form-submit, #business-listing-form .form-submit, #detailTabs ul, #detailsEnhanced #addTags, #locationSearchList, #moreHoods display: none #navListLeft display: none SASS .js #location-navigation-form .form-submit, .js #business-listing-form .form-submit, .js #detailTabs ul, /* .js #addReview, */ /* .js #addTags, */ .js #detailsEnhanced #addTags, .js #locationSearchList, .js #moreHoods, #navListLeft { display: none; } CSS end def test_pseudo_classes_are_escaped assert_equal(<<SASS, css2sass(<<CSS)) \\:focus a: b \\:foo bar: baz SASS :focus {a: b;} :focus :foo {bar: baz;} CSS end def test_subject silence_warnings {assert_equal(<<SASS, css2sass(<<CSS))} .foo .bar! .baz a: b .bip c: d .bar .bonk e: f .flip! &.bar a: b &.baz c: d SASS .foo .bar! .baz {a: b;} .foo .bar! .bip {c: d;} .foo .bar .bonk {e: f;} .flip.bar! {a: b;} .flip.baz! {c: d;} CSS end def test_keyframes assert_equal(<<SASS, css2sass(<<CSS)) @keyframes dash from stroke-dasharray: 1,200 stroke-dashoffset: 0 50% stroke-dasharray: 89,200 stroke-dashoffset: -35 to stroke-dasharray: 89,200 stroke-dashoffset: -124 SASS @keyframes dash { from { stroke-dasharray: 1,200; stroke-dashoffset: 0; } 50% { stroke-dasharray: 89,200; stroke-dashoffset: -35; } to { stroke-dasharray: 89,200; stroke-dashoffset: -124; } } CSS end # Regressions def test_nesting_with_matching_property assert_equal(<<SASS, css2sass(<<CSS)) ul width: 10px div width: 20px article width: 10px p width: 20px SASS ul {width: 10px} ul div {width: 20px} article {width: 10px} article p {width: 20px} CSS end def test_empty_rule assert_equal(<<SASS, css2sass(<<CSS)) a SASS a {} CSS end def test_empty_rule_with_selector_combinator assert_equal(<<SASS, css2sass(<<CSS)) a color: red > b SASS a {color: red} a > b {} CSS end def test_nesting_within_media assert_equal(<<SASS, css2sass(<<CSS)) @media all .next .vevent padding-left: 0 padding-right: 0 SASS @media all { .next .vevent { padding-left: 0; padding-right: 0; } } CSS end def test_multiline_selector_within_media_and_with_child_selector assert_equal(<<SASS, css2sass(<<CSS)) @media all foo bar, baz padding-left: 0 padding-right: 0 SASS @media all { foo bar, baz { padding-left: 0; padding-right: 0; } } CSS end def test_double_comma assert_equal(<<SASS, css2sass(<<CSS)) foo, bar a: b SASS foo, , bar { a: b } CSS end def test_selector_splitting assert_equal(<<SASS, css2sass(<<CSS)) .foo > .bar a: b .baz c: d SASS .foo>.bar {a: b} .foo>.baz {c: d} CSS assert_equal(<<SASS, css2sass(<<CSS)) .foo &::bar a: b &::baz c: d SASS .foo::bar {a: b} .foo::baz {c: d} CSS end def test_triple_nesting assert_equal(<<SASS, css2sass(<<CSS)) .foo .bar .baz a: b SASS .foo .bar .baz {a: b} CSS assert_equal(<<SASS, css2sass(<<CSS)) .bar > .baz c: d SASS .bar > .baz {c: d} CSS end # Error reporting def test_error_reporting css2sass("foo") assert(false, "Expected exception") rescue Sass::SyntaxError => err assert_equal(1, err.sass_line) assert_equal('Invalid CSS after "foo": expected "{", was ""', err.message) end def test_error_reporting_in_line css2sass("foo\nbar }\nbaz") assert(false, "Expected exception") rescue Sass::SyntaxError => err assert_equal(2, err.sass_line) assert_equal('Invalid CSS after "bar ": expected "{", was "}"', err.message) end def test_error_truncate_after css2sass("#{"a" * 16}foo") assert(false, "Expected exception") rescue Sass::SyntaxError => err assert_equal(1, err.sass_line) assert_equal('Invalid CSS after "...aaaaaaaaaaaafoo": expected "{", was ""', err.message) end def test_error_truncate_was css2sass("foo }foo#{"a" * 15}") assert(false, "Expected exception") rescue Sass::SyntaxError => err assert_equal(1, err.sass_line) assert_equal('Invalid CSS after "foo ": expected "{", was "}fooaaaaaaaaaaa..."', err.message) end def test_error_doesnt_truncate_after_when_elipsis_would_add_length css2sass("#{"a" * 15}foo") assert(false, "Expected exception") rescue Sass::SyntaxError => err assert_equal(1, err.sass_line) assert_equal('Invalid CSS after "aaaaaaaaaaaaaaafoo": expected "{", was ""', err.message) end def test_error_doesnt_truncate_was_when_elipsis_would_add_length css2sass("foo }foo#{"a" * 14}") assert(false, "Expected exception") rescue Sass::SyntaxError => err assert_equal(1, err.sass_line) assert_equal('Invalid CSS after "foo ": expected "{", was "}fooaaaaaaaaaaaaaa"', err.message) end def test_error_gets_rid_of_trailing_newline_for_after css2sass("foo \n ") assert(false, "Expected exception") rescue Sass::SyntaxError => err assert_equal(2, err.sass_line) assert_equal('Invalid CSS after "foo": expected "{", was ""', err.message) end def test_error_gets_rid_of_trailing_newline_for_was css2sass("foo \n }foo") assert(false, "Expected exception") rescue Sass::SyntaxError => err assert_equal(2, err.sass_line) assert_equal('Invalid CSS after "foo": expected "{", was "}foo"', err.message) end # Encodings def test_encoding_error css2sass("foo\nbar\nb\xFEaz".force_encoding("utf-8")) assert(false, "Expected exception") rescue Sass::SyntaxError => e assert_equal(3, e.sass_line) assert_equal('Invalid UTF-8 character "\xFE"', e.message) end def test_ascii_incompatible_encoding_error template = "foo\nbar\nb_z".encode("utf-16le") template[9] = "\xFE".force_encoding("utf-16le") css2sass(template) assert(false, "Expected exception") rescue Sass::SyntaxError => e assert_equal(3, e.sass_line) assert_equal('Invalid UTF-16LE character "\xFE"', e.message) end private def css2sass(string, opts={}) Sass::CSS.new(string, opts).render 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/test/sass/value_helpers_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/value_helpers_test.rb
require File.dirname(__FILE__) + '/../test_helper' class ValueHelpersTest < MiniTest::Test include Sass::Script include Sass::Script::Value::Helpers def test_bool assert_same Value::Bool::TRUE, bool(true) assert_same Value::Bool::FALSE, bool(false) assert_same Value::Bool::FALSE, bool(nil) assert_same Value::Bool::TRUE, bool(Object.new) end def test_hex_color_with_three_digits color = hex_color("F07") assert_equal 255, color.red assert_equal 0, color.green assert_equal 119, color.blue assert_equal 1, color.alpha end def test_hex_color_without_hash color_without_hash = hex_color("FF007F") assert_equal 255, color_without_hash.red assert_equal 0, color_without_hash.green assert_equal 127, color_without_hash.blue assert_equal 1, color_without_hash.alpha end def test_hex_color_with_hash color_with_hash = hex_color("#FF007F") assert_equal 255, color_with_hash.red assert_equal 0, color_with_hash.green assert_equal 127, color_with_hash.blue assert_equal 1, color_with_hash.alpha end def test_malformed_hex_color assert_raises ArgumentError do hex_color("green") end assert_raises ArgumentError do hex_color("#abcde") end end def test_hex_color_with_alpha color_with_alpha = hex_color("FF007F", 0.5) assert_equal 0.5, color_with_alpha.alpha end def test_hex_color_alpha_clamps_0_to_1 assert_equal 1, hex_color("FF007F", 50).alpha end def test_hsl_color_without_alpha no_alpha = hsl_color(1, 0.5, 1) assert_equal 1, no_alpha.hue assert_equal 0.5, no_alpha.saturation assert_equal 1, no_alpha.lightness assert_equal 1, no_alpha.alpha end def test_hsl_color_with_alpha has_alpha = hsl_color(1, 0.5, 1, 0.5) assert_equal 1, has_alpha.hue assert_equal 0.5, has_alpha.saturation assert_equal 1, has_alpha.lightness assert_equal 0.5, has_alpha.alpha end def test_rgb_color_without_alpha no_alpha = rgb_color(255, 0, 0) assert_equal 255, no_alpha.red assert_equal 0, no_alpha.green assert_equal 0, no_alpha.blue assert_equal 1, no_alpha.alpha end def test_rgb_color_with_alpha has_alpha = rgb_color(255, 255, 255, 0.5) assert_equal 255, has_alpha.red assert_equal 255, has_alpha.green assert_equal 255, has_alpha.blue assert_equal 0.5, has_alpha.alpha end def test_number n = number(1) assert_equal 1, n.value assert_equal "1", n.to_sass end def test_number_with_single_unit n = number(1, "px") assert_equal 1, n.value assert_equal "1px", n.to_sass end def test_number_with_singal_numerator_and_denominator ratio = number(1, "px/em") assert_equal "1px/em", ratio.to_sass end def test_number_with_many_numerator_and_denominator_units complex = number(1, "px*in/em*%") assert_equal "1in*px/%*em", complex.to_sass end def test_number_with_many_numerator_and_denominator_units_with_spaces complex = number(1, "px * in / em * %") assert_equal "1in*px/%*em", complex.to_sass end def test_number_with_malformed_units assert_raises ArgumentError do number(1, "px/em/%") end assert_raises ArgumentError do number(1, "/") end assert_raises ArgumentError do number(1, "px/") end end def test_space_list l = list(number(1, "px"), hex_color("#f71"), :space) l.options = {} assert_kind_of Sass::Script::Value::List, l assert_equal "1px #f71", l.to_sass end def test_comma_list l = list(number(1, "px"), hex_color("#f71"), :comma) l.options = {} assert_kind_of Sass::Script::Value::List, l assert_equal "1px, #f71", l.to_sass end def test_missing_list_type assert_raises ArgumentError do list(number(1, "px"), hex_color("#f71")) end end def test_null assert_kind_of Sass::Script::Value::Null, null end def test_quoted_string s = quoted_string("sassy string") s.options = {} assert_kind_of Sass::Script::Value::String, s assert_equal "sassy string", s.value assert_equal :string, s.type assert_equal '"sassy string"', s.to_sass end def test_identifier s = identifier("a-sass-ident") s.options = {} assert_kind_of Sass::Script::Value::String, s assert_equal "a-sass-ident", s.value assert_equal :identifier, s.type assert_equal "a-sass-ident", s.to_sass end def test_unquoted_string s = unquoted_string("a-sass-ident") s.options = {} assert_kind_of Sass::Script::Value::String, s assert_equal "a-sass-ident", s.value assert_equal :identifier, s.type assert_equal "a-sass-ident", s.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/test/sass/css_variable_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/css_variable_test.rb
require File.dirname(__FILE__) + '/../test_helper' require 'sass/engine' # Most CSS variable tests are in sass-spec, but a few relate to formatting or # conversion and so belong here. class CssVariableTest < MiniTest::Test def test_folded_inline_whitespace assert_variable_value "foo bar baz", "foo bar baz" assert_variable_value "foo bar", "foo \t bar" end def test_folded_multiline_whitespace # We don't want to reformat newlines in nested and expanded mode, so we just # remove trailing whitespace before them. assert_equal <<CSS, render(<<SCSS) .foo { --multiline: foo bar; } CSS .foo { --multiline: foo\s bar; } SCSS assert_equal <<CSS, render(<<SCSS) .foo { --multiline: foo bar; } CSS .foo { --multiline: foo\s bar; } SCSS assert_equal <<CSS, render(<<SCSS, style: :expanded) .foo { --multiline: foo bar; } CSS .foo { --multiline: foo\s bar; } SCSS assert_equal <<CSS, render(<<SCSS, style: :expanded) .foo { --multiline: foo bar; } CSS .foo { --multiline: foo\s bar; } SCSS # In compact and compressed mode, we fold all whitespace around newlines # together. assert_equal <<CSS, render(<<SCSS, style: :compact) .foo { --multiline: foo bar; } CSS .foo { --multiline: foo\s bar; } SCSS assert_equal <<CSS, render(<<SCSS, style: :compact) .foo { --multiline: foo bar; } CSS .foo { --multiline: foo\s bar; } SCSS assert_equal <<CSS, render(<<SCSS, style: :compressed) .foo{--multiline: foo bar} CSS .foo { --multiline: foo\s bar; } SCSS assert_equal <<CSS, render(<<SCSS, style: :compressed) .foo{--multiline: foo bar} CSS .foo { --multiline: foo\s bar; } SCSS end # Conversion. def test_static_values_convert assert_converts <<SASS, <<SCSS .foo --bar: baz SASS .foo { --bar: baz; } SCSS assert_converts <<SASS, <<SCSS .foo --bar: [({{([!;])}})] SASS .foo { --bar: [({{([!;])}})]; } SCSS assert_converts <<SASS, <<SCSS .foo --bar: {a: b; c: d} SASS .foo { --bar: {a: b; c: d}; } SCSS end def test_dynamic_values_convert assert_converts <<SASS, <<SCSS .foo --bar: baz \#{bang} qux SASS .foo { --bar: baz \#{bang} qux; } SCSS assert_converts <<SASS, <<SCSS .foo --bar: "baz \#{bang} qux" SASS .foo { --bar: "baz \#{bang} qux"; } SCSS end def test_multiline_value_converts assert_scss_to_scss <<SCSS .foo { --bar: { a: b; c: d; }; } SCSS assert_scss_to_sass <<SASS, <<SCSS .foo --bar: { a: b; c: d; } SASS .foo { --bar: { a: b; c: d; }; } SCSS end private def assert_variable_value(expected, source) expected = <<CSS x { --variable: #{expected}; } CSS assert_equal expected, render_variable(source) assert_equal expected, render_variable(source, syntax: :sass) end def render_variable(source, syntax: :scss) render(syntax == :scss ? <<SCSS : <<SASS, :syntax => syntax) x { --variable: #{source}; } SCSS x --variable: #{source} SASS end def render(sass, options = {}) options[:syntax] ||= :scss options[:cache] = false munge_filename options Sass::Engine.new(sass, options).render end def resolve(str, opts = {}, environment = env) munge_filename opts val = eval(str, opts, environment) assert_kind_of Sass::Script::Value::Base, val val.options = opts val.is_a?(Sass::Script::Value::String) ? val.value : val.to_s end def eval(str, opts = {}, environment = env) munge_filename opts Sass::Script.parse(str, opts.delete(:line) || 1, opts.delete(:offset) || 0, opts). perform(Sass::Environment.new(environment, opts)) end def env(hash = {}) env = Sass::Environment.new hash.each {|k, v| env.set_var(k, v)} env 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/test/sass/engine_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/engine_test.rb
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/../test_helper' require File.dirname(__FILE__) + '/test_helper' require 'sass/engine' require 'stringio' require 'mock_importer' require 'pathname' module Sass::Script::Functions::UserFunctions def option(name) Sass::Script::Value::String.new(@options[name.value.to_sym].to_s) end def set_a_variable(name, value) environment.set_var(name.value, value) return Sass::Script::Value::Null.new end def set_a_global_variable(name, value) environment.set_global_var(name.value, value) return Sass::Script::Value::Null.new end def get_a_variable(name) environment.var(name.value) || Sass::Script::Value::String.new("undefined") end end module Sass::Script::Functions include Sass::Script::Functions::UserFunctions end class SassEngineTest < MiniTest::Test FAKE_FILE_NAME = __FILE__.gsub(/rb$/,"sass") # A map of erroneous Sass documents to the error messages they should produce. # The error messages may be arrays; # if so, the second element should be the line number that should be reported for the error. # If this isn't provided, the tests will assume the line number should be the last line of the document. EXCEPTION_MAP = { "$a: 1 + " => 'Invalid CSS after "1 +": expected expression (e.g. 1px, bold), was ""', "$a: 1 + 2 +" => 'Invalid CSS after "1 + 2 +": expected expression (e.g. 1px, bold), was ""', "$a: 1 + 2 + %" => 'Invalid CSS after "1 + 2 + ": expected expression (e.g. 1px, bold), was "%"', "$a: foo(\"bar\"" => 'Invalid CSS after "foo("bar"": expected ")", was ""', "$a: 1 }" => 'Invalid CSS after "1 ": expected expression (e.g. 1px, bold), was "}"', "$a: 1 }foo\"" => 'Invalid CSS after "1 ": expected expression (e.g. 1px, bold), was "}foo""', ":" => 'Invalid property: ":".', ": a" => 'Invalid property: ": a".', "a\n :b" => <<MSG, Invalid property: ":b" (no value). If ":b" should be a selector, use "\\:b" instead. MSG "a\n b:" => 'Invalid property: "b:" (no value).', "a\n :b: c" => 'Invalid property: ":b: c".', "a\n :b:c d" => 'Invalid property: ":b:c d".', "a\n :b c;" => 'Invalid CSS after "c": expected expression (e.g. 1px, bold), was ";"', "a\n b: c;" => 'Invalid CSS after "c": expected expression (e.g. 1px, bold), was ";"', ".foo ^bar\n a: b" => ['Invalid CSS after ".foo ": expected selector, was "^bar"', 1], "a\n @extend .foo ^bar" => 'Invalid CSS after ".foo ": expected selector, was "^bar"', "a\n @extend .foo .bar" => "Can't extend .foo .bar: can't extend nested selectors", "a\n @extend >" => "Can't extend >: invalid selector", "a\n @extend &.foo" => "Can't extend &.foo: can't extend parent selectors", "a: b" => 'Properties are only allowed within rules, directives, mixin includes, or other properties.', ":a b" => 'Properties are only allowed within rules, directives, mixin includes, or other properties.', "$" => 'Invalid variable: "$".', "$a" => 'Invalid variable: "$a".', "$ a" => 'Invalid variable: "$ a".', "$a b" => 'Invalid variable: "$a b".', "$a: 1b + 2c" => "Incompatible units: 'c' and 'b'.", "$a: 1b < 2c" => "Incompatible units: 'c' and 'b'.", "$a: 1b > 2c" => "Incompatible units: 'c' and 'b'.", "$a: 1b <= 2c" => "Incompatible units: 'c' and 'b'.", "$a: 1b >= 2c" => "Incompatible units: 'c' and 'b'.", "a\n b: 1b * 2c" => "2b*c isn't a valid CSS value.", "a\n b: 1b % 2c" => "Incompatible units: 'c' and 'b'.", "$a: 2px + #ccc" => "Cannot add a number with units (2px) to a color (#ccc).", "$a: #ccc + 2px" => "Cannot add a number with units (2px) to a color (#ccc).", "& a\n :b c" => ["Base-level rules cannot contain the parent-selector-referencing character '&'.", 1], "a\n :b\n c" => "Illegal nesting: Only properties may be nested beneath properties.", "$a: b\n :c d\n" => "Illegal nesting: Nothing may be nested beneath variable declarations.", "@import templates/basic\n foo" => "Illegal nesting: Nothing may be nested beneath import directives.", "foo\n @import foo.css" => "CSS import directives may only be used at the root of a document.", "@if true\n @import foo" => "Import directives may not be used within control directives or mixins.", "@if true\n .foo\n @import foo" => "Import directives may not be used within control directives or mixins.", "@mixin foo\n @import foo" => "Import directives may not be used within control directives or mixins.", "@mixin foo\n .foo\n @import foo" => "Import directives may not be used within control directives or mixins.", "@import foo;" => "Invalid @import: expected end of line, was \";\".", '$foo: "bar" "baz" !' => %Q{Invalid CSS after ""bar" "baz" ": expected expression (e.g. 1px, bold), was "!"}, '$foo: "bar" "baz" $' => %Q{Invalid CSS after ""bar" "baz" ": expected expression (e.g. 1px, bold), was "$"}, #' "=foo\n :color red\n.bar\n +bang" => "Undefined mixin 'bang'.", "=foo\n :color red\n.bar\n +bang_bop" => "Undefined mixin 'bang_bop'.", "=foo\n :color red\n.bar\n +bang-bop" => "Undefined mixin 'bang-bop'.", ".foo\n =foo\n :color red\n.bar\n +foo" => "Undefined mixin 'foo'.", " a\n b: c" => ["Indenting at the beginning of the document is illegal.", 1], " \n \n\t\n a\n b: c" => ["Indenting at the beginning of the document is illegal.", 4], "a\n b: c\n b: c" => ["Inconsistent indentation: 1 space was used for indentation, but the rest of the document was indented using 2 spaces.", 3], "a\n b: c\na\n b: c" => ["Inconsistent indentation: 1 space was used for indentation, but the rest of the document was indented using 2 spaces.", 4], "a\n\t\tb: c\n\tb: c" => ["Inconsistent indentation: 1 tab was used for indentation, but the rest of the document was indented using 2 tabs.", 3], "a\n b: c\n b: c" => ["Inconsistent indentation: 3 spaces were used for indentation, but the rest of the document was indented using 2 spaces.", 3], "a\n b: c\n a\n d: e" => ["Inconsistent indentation: 3 spaces were used for indentation, but the rest of the document was indented using 2 spaces.", 4], "a\n \tb: c" => ["Indentation can't use both tabs and spaces.", 2], "=a(" => 'Invalid CSS after "(": expected variable (e.g. $foo), was ""', "=a(b)" => 'Invalid CSS after "(": expected variable (e.g. $foo), was "b)"', "=a(,)" => 'Invalid CSS after "(": expected variable (e.g. $foo), was ",)"', "=a($)" => 'Invalid CSS after "(": expected variable (e.g. $foo), was "$)"', "=a($foo bar)" => 'Invalid CSS after "($foo ": expected ")", was "bar)"', "=foo\n bar: baz\n+foo" => ["Properties are only allowed within rules, directives, mixin includes, or other properties.", 2], "a-\#{$b\n c: d" => ['Invalid CSS after "a-#{$b": expected "}", was ""', 1], "=a($b: 1, $c)" => "Required argument $c must come before any optional arguments.", "=a($b: 1)\n a: $b\ndiv\n +a(1,2)" => "Mixin a takes 1 argument but 2 were passed.", "=a($b: 1)\n a: $b\ndiv\n +a(1,$c: 3)" => "Mixin a doesn't have an argument named $c.", "=a($b)\n a: $b\ndiv\n +a" => "Mixin a is missing argument $b.", "@function foo()\n 1 + 2" => "Functions can only contain variable declarations and control directives.", "@function foo()\n foo: bar" => "Functions can only contain variable declarations and control directives.", "@function foo()\n foo: bar\n @return 3" => ["Functions can only contain variable declarations and control directives.", 2], "@function foo\n @return 1" => ['Invalid CSS after "": expected "(", was ""', 1], "@function foo(\n @return 1" => ['Invalid CSS after "(": expected variable (e.g. $foo), was ""', 1], "@function foo(b)\n @return 1" => ['Invalid CSS after "(": expected variable (e.g. $foo), was "b)"', 1], "@function foo(,)\n @return 1" => ['Invalid CSS after "(": expected variable (e.g. $foo), was ",)"', 1], "@function foo($)\n @return 1" => ['Invalid CSS after "(": expected variable (e.g. $foo), was "$)"', 1], "@function foo()\n @return" => 'Invalid @return: expected expression.', "@function foo()\n @return 1\n $var: val" => 'Illegal nesting: Nothing may be nested beneath return directives.', "@function foo($a)\n @return 1\na\n b: foo()" => 'Function foo is missing argument $a.', "@function foo()\n @return 1\na\n b: foo(2)" => 'Function foo takes 0 arguments but 1 was passed.', "@function foo()\n @return 1\na\n b: foo($a: 1)" => "Function foo doesn't have an argument named $a.", "@function foo()\n @return 1\na\n b: foo($a: 1, $b: 2)" => "Function foo doesn't have the following arguments: $a, $b.", "@return 1" => '@return may only be used within a function.', "@if true\n @return 1" => '@return may only be used within a function.', "@mixin foo\n @return 1\n@include foo" => ['@return may only be used within a function.', 2], "@else\n a\n b: c" => ["@else must come after @if.", 1], "@if false\n@else foo" => "Invalid else directive '@else foo': expected 'if <expr>'.", "@if false\n@else if " => "Invalid else directive '@else if': expected 'if <expr>'.", "a\n $b: 12\nc\n d: $b" => 'Undefined variable: "$b".', "=foo\n $b: 12\nc\n +foo\n d: $b" => 'Undefined variable: "$b".', "c\n d: $b-foo" => 'Undefined variable: "$b-foo".', "c\n d: $b_foo" => 'Undefined variable: "$b_foo".', '@for $a from "foo" to 1' => '"foo" is not an integer.', '@for $a from 1 to "2"' => '"2" is not an integer.', '@for $a from 1 to "foo"' => '"foo" is not an integer.', '@for $a from 1 to 1.23232323232' => '1.2323232323 is not an integer.', '@for $a from 1px to 3em' => "Incompatible units: 'em' and 'px'.", '@if' => "Invalid if directive '@if': expected expression.", '@while' => "Invalid while directive '@while': expected expression.", '@debug' => "Invalid debug directive '@debug': expected expression.", %Q{@debug "a message"\n "nested message"} => "Illegal nesting: Nothing may be nested beneath debug directives.", '@error' => "Invalid error directive '@error': expected expression.", %Q{@error "a message"\n "nested message"} => "Illegal nesting: Nothing may be nested beneath error directives.", '@warn' => "Invalid warn directive '@warn': expected expression.", %Q{@warn "a message"\n "nested message"} => "Illegal nesting: Nothing may be nested beneath warn directives.", "/* foo\n bar\n baz" => "Inconsistent indentation: previous line was indented by 4 spaces, but this line was indented by 2 spaces.", '+foo(1 + 1: 2)' => 'Invalid CSS after "(1 + 1": expected comma, was ": 2)"', '+foo($var: )' => 'Invalid CSS after "($var: ": expected mixin argument, was ")"', '+foo($var: a, $var: b)' => 'Keyword argument "$var" passed more than once', '+foo($var-var: a, $var_var: b)' => 'Keyword argument "$var_var" passed more than once', '+foo($var_var: a, $var-var: b)' => 'Keyword argument "$var-var" passed more than once', "a\n b: foo(1 + 1: 2)" => 'Invalid CSS after "foo(1 + 1": expected comma, was ": 2)"', "a\n b: foo($var: )" => 'Invalid CSS after "foo($var: ": expected function argument, was ")"', "a\n b: foo($var: a, $var: b)" => 'Keyword argument "$var" passed more than once', "a\n b: foo($var-var: a, $var_var: b)" => 'Keyword argument "$var_var" passed more than once', "a\n b: foo($var_var: a, $var-var: b)" => 'Keyword argument "$var-var" passed more than once', "@if foo\n @extend .bar" => ["Extend directives may only be used within rules.", 2], "$var: true\n@while $var\n @extend .bar\n $var: false" => ["Extend directives may only be used within rules.", 3], "@for $i from 0 to 1\n @extend .bar" => ["Extend directives may only be used within rules.", 2], "@mixin foo\n @extend .bar\n@include foo" => ["Extend directives may only be used within rules.", 2], "foo %\n a: b" => ['Invalid CSS after "foo %": expected placeholder name, was ""', 1], "=foo\n @content error" => "Invalid content directive. Trailing characters found: \"error\".", "=foo\n @content\n b: c" => "Illegal nesting: Nothing may be nested beneath @content directives.", "@content" => '@content may only be used within a mixin.', "=simple\n .simple\n color: red\n+simple\n color: blue" => ['Mixin "simple" does not accept a content block.', 4], "@import \"foo\" // bar" => "Invalid CSS after \"\"foo\" \": expected media query list, was \"// bar\"", "@at-root\n a: b" => "Properties are only allowed within rules, directives, mixin includes, or other properties.", # Regression tests "a\n b:\n c\n d" => ["Illegal nesting: Only properties may be nested beneath properties.", 3], "& foo\n bar: baz\n blat: bang" => ["Base-level rules cannot contain the parent-selector-referencing character '&'.", 1], "a\n b: c\n& foo\n bar: baz\n blat: bang" => ["Base-level rules cannot contain the parent-selector-referencing character '&'.", 3], "@" => "Invalid directive: '@'.", "$r: 20em * #ccc" => ["Cannot multiply a number with units (20em) to a color (#ccc).", 1], "$r: #ccc / 1em" => ["Cannot divide a number with units (1em) to a color (#ccc).", 1], } def teardown clean_up_sassc end def test_basic_render renders_correctly "basic", { :style => :compact } end def test_empty_render assert_equal "", render("") end def test_multiple_calls_to_render sass = Sass::Engine.new("a\n b: c") assert_equal sass.render, sass.render end def test_alternate_styles renders_correctly "expanded", { :style => :expanded } renders_correctly "compact", { :style => :compact } renders_correctly "nested", { :style => :nested } renders_correctly "compressed", { :style => :compressed } end def test_compile assert_equal "div { hello: world; }\n", Sass.compile("$who: world\ndiv\n hello: $who", :syntax => :sass, :style => :compact) assert_equal "div { hello: world; }\n", Sass.compile("$who: world; div { hello: $who }", :style => :compact) end def test_compile_file FileUtils.mkdir_p(absolutize("tmp")) open(absolutize("tmp/test_compile_file.sass"), "w") {|f| f.write("$who: world\ndiv\n hello: $who")} open(absolutize("tmp/test_compile_file.scss"), "w") {|f| f.write("$who: world; div { hello: $who }")} assert_equal "div { hello: world; }\n", Sass.compile_file(absolutize("tmp/test_compile_file.sass"), :style => :compact) assert_equal "div { hello: world; }\n", Sass.compile_file(absolutize("tmp/test_compile_file.scss"), :style => :compact) ensure FileUtils.rm_rf(absolutize("tmp")) end def test_compile_file_to_css_file FileUtils.mkdir_p(absolutize("tmp")) open(absolutize("tmp/test_compile_file.sass"), "w") {|f| f.write("$who: world\ndiv\n hello: $who")} open(absolutize("tmp/test_compile_file.scss"), "w") {|f| f.write("$who: world; div { hello: $who }")} Sass.compile_file(absolutize("tmp/test_compile_file.sass"), absolutize("tmp/test_compile_file_sass.css"), :style => :compact) Sass.compile_file(absolutize("tmp/test_compile_file.scss"), absolutize("tmp/test_compile_file_scss.css"), :style => :compact) assert_equal "div { hello: world; }\n", File.read(absolutize("tmp/test_compile_file_sass.css")) assert_equal "div { hello: world; }\n", File.read(absolutize("tmp/test_compile_file_scss.css")) ensure FileUtils.rm_rf(absolutize("tmp")) end def test_flexible_tabulation assert_equal("p {\n a: b; }\n p q {\n c: d; }\n", render("p\n a: b\n q\n c: d\n")) assert_equal("p {\n a: b; }\n p q {\n c: d; }\n", render("p\n\ta: b\n\tq\n\t\tc: d\n")) end def test_import_same_name_different_ext assert_raise_message Sass::SyntaxError, <<ERROR do It's not clear which file to import for '@import "same_name_different_ext"'. Candidates: same_name_different_ext.sass same_name_different_ext.scss Please delete or rename all but one of these files. ERROR options = {:load_paths => [File.dirname(__FILE__) + '/templates/']} munge_filename options Sass::Engine.new("@import 'same_name_different_ext'", options).render end end def test_import_same_name_different_partiality assert_raise_message Sass::SyntaxError, <<ERROR do It's not clear which file to import for '@import "same_name_different_partiality"'. Candidates: _same_name_different_partiality.scss same_name_different_partiality.scss Please delete or rename all but one of these files. ERROR options = {:load_paths => [File.dirname(__FILE__) + '/templates/']} munge_filename options Sass::Engine.new("@import 'same_name_different_partiality'", options).render end end EXCEPTION_MAP.each do |key, value| define_method("test_exception (#{key.inspect})") do line = 10 begin silence_warnings {Sass::Engine.new(key, :filename => FAKE_FILE_NAME, :line => line).render} rescue Sass::SyntaxError => err value = [value] unless value.is_a?(Array) assert_equal(value.first.rstrip, err.message, "Line: #{key}") assert_equal(FAKE_FILE_NAME, err.sass_filename) assert_equal((value[1] || key.split("\n").length) + line - 1, err.sass_line, "Line: #{key}") assert_match(/#{Regexp.escape(FAKE_FILE_NAME)}:[0-9]+/, err.backtrace[0], "Line: #{key}") else assert(false, "Exception not raised for\n#{key}") end end end def test_exception_line to_render = <<SASS rule prop: val // comment! broken: SASS begin Sass::Engine.new(to_render).render rescue Sass::SyntaxError => err assert_equal(5, err.sass_line) else assert(false, "Exception not raised for '#{to_render}'!") end end def test_exception_location to_render = <<SASS rule prop: val // comment! broken: SASS begin Sass::Engine.new(to_render, :filename => FAKE_FILE_NAME, :line => (__LINE__-7)).render rescue Sass::SyntaxError => err assert_equal(FAKE_FILE_NAME, err.sass_filename) assert_equal((__LINE__-6), err.sass_line) else assert(false, "Exception not raised for '#{to_render}'!") end end def test_imported_exception [1, 2, 3, 4].each do |i| begin Sass::Engine.new("@import bork#{i}", :load_paths => [File.dirname(__FILE__) + '/templates/']).render rescue Sass::SyntaxError => err assert_equal(2, err.sass_line) assert_match(/(\/|^)bork#{i}\.sass$/, err.sass_filename) assert_hash_has(err.sass_backtrace.first, :filename => err.sass_filename, :line => err.sass_line) assert_nil(err.sass_backtrace[1][:filename]) assert_equal(1, err.sass_backtrace[1][:line]) assert_match(/(\/|^)bork#{i}\.sass:2$/, err.backtrace.first) assert_equal("(sass):1", err.backtrace[1]) else assert(false, "Exception not raised for imported template: bork#{i}") end end end def test_double_imported_exception [1, 2, 3, 4].each do |i| begin Sass::Engine.new("@import nested_bork#{i}", :load_paths => [File.dirname(__FILE__) + '/templates/']).render rescue Sass::SyntaxError => err assert_equal(2, err.sass_line) assert_match(/(\/|^)bork#{i}\.sass$/, err.sass_filename) assert_hash_has(err.sass_backtrace.first, :filename => err.sass_filename, :line => err.sass_line) assert_match(/(\/|^)nested_bork#{i}\.sass$/, err.sass_backtrace[1][:filename]) assert_equal(2, err.sass_backtrace[1][:line]) assert_nil(err.sass_backtrace[2][:filename]) assert_equal(1, err.sass_backtrace[2][:line]) assert_match(/(\/|^)bork#{i}\.sass:2$/, err.backtrace.first) assert_match(/(\/|^)nested_bork#{i}\.sass:2$/, err.backtrace[1]) assert_equal("(sass):1", err.backtrace[2]) else assert(false, "Exception not raised for imported template: bork#{i}") end end end def test_selector_tracing actual_css = render(<<-SCSS, :syntax => :scss, :trace_selectors => true) @mixin mixed { .mixed { color: red; } } .context { @include mixed; } SCSS assert_equal(<<CSS,actual_css) /* on line 2 of test_selector_tracing_inline.scss, in `mixed' from line 5 of test_selector_tracing_inline.scss */ .context .mixed { color: red; } CSS end def test_mixin_exception render(<<SASS) =error-mixin($a) color: $a * 1em * 1px =outer-mixin($a) +error-mixin($a) .error +outer-mixin(12) SASS assert(false, "Exception not raised") rescue Sass::SyntaxError => err assert_equal(2, err.sass_line) assert_equal(filename_for_test, err.sass_filename) assert_equal("error-mixin", err.sass_mixin) assert_hash_has(err.sass_backtrace.first, :line => err.sass_line, :filename => err.sass_filename, :mixin => err.sass_mixin) assert_hash_has(err.sass_backtrace[1], :line => 5, :filename => filename_for_test, :mixin => "outer-mixin") assert_hash_has(err.sass_backtrace[2], :line => 8, :filename => filename_for_test, :mixin => nil) assert_equal("#{filename_for_test}:2:in `error-mixin'", err.backtrace.first) assert_equal("#{filename_for_test}:5:in `outer-mixin'", err.backtrace[1]) assert_equal("#{filename_for_test}:8", err.backtrace[2]) end def test_mixin_callsite_exception render(<<SASS) =one-arg-mixin($a) color: $a =outer-mixin($a) +one-arg-mixin($a, 12) .error +outer-mixin(12) SASS assert(false, "Exception not raised") rescue Sass::SyntaxError => err assert_hash_has(err.sass_backtrace.first, :line => 5, :filename => filename_for_test, :mixin => "one-arg-mixin") assert_hash_has(err.sass_backtrace[1], :line => 5, :filename => filename_for_test, :mixin => "outer-mixin") assert_hash_has(err.sass_backtrace[2], :line => 8, :filename => filename_for_test, :mixin => nil) end def test_mixin_exception_cssize render(<<SASS) =parent-ref-mixin & foo a: b =outer-mixin +parent-ref-mixin +outer-mixin SASS assert(false, "Exception not raised") rescue Sass::SyntaxError => err assert_hash_has(err.sass_backtrace.first, :line => 2, :filename => filename_for_test, :mixin => "parent-ref-mixin") assert_hash_has(err.sass_backtrace[1], :line => 6, :filename => filename_for_test, :mixin => "outer-mixin") assert_hash_has(err.sass_backtrace[2], :line => 8, :filename => filename_for_test, :mixin => nil) end def test_mixin_and_import_exception Sass::Engine.new("@import nested_mixin_bork", :load_paths => [File.dirname(__FILE__) + '/templates/']).render assert(false, "Exception not raised") rescue Sass::SyntaxError => err assert_match(/(\/|^)nested_mixin_bork\.sass$/, err.sass_backtrace.first[:filename]) assert_hash_has(err.sass_backtrace.first, :mixin => "error-mixin", :line => 4) assert_match(/(\/|^)mixin_bork\.sass$/, err.sass_backtrace[1][:filename]) assert_hash_has(err.sass_backtrace[1], :mixin => "outer-mixin", :line => 2) assert_match(/(\/|^)mixin_bork\.sass$/, err.sass_backtrace[2][:filename]) assert_hash_has(err.sass_backtrace[2], :mixin => nil, :line => 5) assert_match(/(\/|^)nested_mixin_bork\.sass$/, err.sass_backtrace[3][:filename]) assert_hash_has(err.sass_backtrace[3], :mixin => nil, :line => 6) assert_hash_has(err.sass_backtrace[4], :filename => nil, :mixin => nil, :line => 1) end def test_recursive_mixin assert_equal <<CSS, render(<<SASS) .foo .bar .baz { color: blue; } .foo .bar .qux { color: red; } .foo .zap { color: green; } CSS @mixin map-to-rule($map-or-color) @if type-of($map-or-color) == map @each $key, $value in $map-or-color .\#{$key} @include map-to-rule($value) @else color: $map-or-color @include map-to-rule((foo: (bar: (baz: blue, qux: red), zap: green))) SASS end def test_double_import_loop_exception importer = MockImporter.new importer.add_import("foo", "@import 'bar'") importer.add_import("bar", "@import 'foo'") engine = Sass::Engine.new('@import "foo"', :filename => filename_for_test, :load_paths => [importer], :importer => importer) assert_raise_message(Sass::SyntaxError, <<ERR.rstrip) {engine.render} An @import loop has been found: #{filename_for_test} imports foo foo imports bar bar imports foo ERR end def test_deep_import_loop_exception importer = MockImporter.new importer.add_import("foo", "@import 'bar'") importer.add_import("bar", "@import 'baz'") importer.add_import("baz", "@import 'foo'") engine = Sass::Engine.new('@import "foo"', :filename => filename_for_test, :load_paths => [importer], :importer => importer) assert_raise_message(Sass::SyntaxError, <<ERR.rstrip) {engine.render} An @import loop has been found: #{filename_for_test} imports foo foo imports bar bar imports baz baz imports foo ERR end def test_exception_css_with_offset opts = {:full_exception => true, :line => 362} render(("a\n b: c\n" * 10) + "d\n e:\n" + ("f\n g: h\n" * 10), opts) rescue Sass::SyntaxError => e assert_equal(<<CSS, Sass::SyntaxError.exception_to_css(e, opts[:line]).split("\n")[0..15].join("\n")) /* Error: Invalid property: "e:" (no value). on line 383 of test_exception_css_with_offset_inline.sass 378: a 379: b: c 380: a 381: b: c 382: d 383: e: 384: f 385: g: h 386: f 387: g: h 388: f CSS else assert(false, "Exception not raised for test_exception_css_with_offset") end def test_exception_css_with_mixins render(<<SASS, :full_exception => true) =error-mixin($a) color: $a * 1em * 1px =outer-mixin($a) +error-mixin($a) .error +outer-mixin(12) SASS rescue Sass::SyntaxError => e assert_equal(<<CSS, Sass::SyntaxError.exception_to_css(e).split("\n")[0..13].join("\n")) /* Error: 12em*px isn't a valid CSS value. on line 2 of test_exception_css_with_mixins_inline.sass, in `error-mixin' from line 5 of test_exception_css_with_mixins_inline.sass, in `outer-mixin' from line 8 of test_exception_css_with_mixins_inline.sass 1: =error-mixin($a) 2: color: $a * 1em * 1px 3: 4: =outer-mixin($a) 5: +error-mixin($a) 6: 7: .error CSS else assert(false, "Exception not raised") end def test_cssize_exception_css render(<<SASS, :full_exception => true) .filler stuff: "stuff!" a: b .more.filler a: b SASS rescue Sass::SyntaxError => e assert_equal(<<CSS, Sass::SyntaxError.exception_to_css(e).split("\n")[0..11].join("\n")) /* Error: Properties are only allowed within rules, directives, mixin includes, or other properties. on line 4 of test_cssize_exception_css_inline.sass 1: .filler 2: stuff: "stuff!" 3: 4: a: b 5: 6: .more.filler 7: a: b CSS else assert(false, "Exception not raised") end def test_css_import assert_equal("@import url(./fonts.css);\n", render("@import \"./fonts.css\"")) end def test_http_import assert_equal("@import \"http://fonts.googleapis.com/css?family=Droid+Sans\";\n", render("@import \"http://fonts.googleapis.com/css?family=Droid+Sans\"")) end def test_protocol_relative_import assert_equal("@import \"//fonts.googleapis.com/css?family=Droid+Sans\";\n", render("@import \"//fonts.googleapis.com/css?family=Droid+Sans\"")) end def test_import_with_interpolation assert_equal(<<CSS, render(<<SASS)) @import url("http://fonts.googleapis.com/css?family=Droid+Sans"); CSS $family: unquote("Droid+Sans") @import url("http://fonts.googleapis.com/css?family=\#{$family}") SASS end def test_import_with_dynamic_media_query assert_equal(<<CSS, render(<<SASS)) @import "foo" print and (-webkit-min-device-pixel-ratio-foo: 25); CSS $media: print $key: -webkit-min-device-pixel-ratio $value: 20 @import "foo" \#{$media} and ($key + "-foo": $value + 5) SASS end def test_url_import assert_equal("@import url(fonts.sass);\n", render("@import url(fonts.sass)")) end def test_sass_import sassc_file = sassc_path("importee") assert !File.exist?(sassc_file) renders_correctly "import", { :style => :compact, :load_paths => [File.dirname(__FILE__) + "/templates"] } assert File.exist?(sassc_file) end def test_sass_pathname_import sassc_file = sassc_path("importee") assert !File.exist?(sassc_file) renders_correctly("import", :style => :compact, :load_paths => [Pathname.new(File.dirname(__FILE__) + "/templates")]) assert File.exist?(sassc_file) end def test_import_from_global_load_paths importer = MockImporter.new importer.add_import("imported", "div{color:red}") Sass.load_paths << importer assert_equal "div {\n color: red; }\n", Sass::Engine.new('@import "imported"', :importer => importer).render ensure Sass.load_paths.clear end def test_nonexistent_import assert_raise_message(Sass::SyntaxError, <<ERR.rstrip) do File to import not found or unreadable: nonexistent.sass. ERR render("@import nonexistent.sass") end end def test_nonexistent_extensionless_import assert_raise_message(Sass::SyntaxError, <<ERR.rstrip) do File to import not found or unreadable: nonexistent. ERR render("@import nonexistent") end end def test_no_cache assert !File.exist?(sassc_path("importee")) renders_correctly("import", { :style => :compact, :cache => false, :load_paths => [File.dirname(__FILE__) + "/templates"], }) assert !File.exist?(sassc_path("importee")) end def test_import_in_rule assert_equal(<<CSS, render(<<SASS, :load_paths => [File.dirname(__FILE__) + '/templates/'])) .foo #foo { background-color: #baf; } .bar { a: b; } .bar #foo { background-color: #baf; } CSS .foo @import partial .bar a: b @import partial SASS end def test_units renders_correctly "units" end def test_default_function assert_equal(<<CSS, render(<<SASS)) foo { bar: url("foo.png"); } CSS foo bar: url("foo.png") SASS assert_equal("foo {\n bar: url(); }\n", render("foo\n bar: url()\n")); end def test_string_minus assert_equal("foo {\n bar: baz-boom-bat; }\n", render(%Q{foo\n bar: baz-boom-bat})) assert_equal("foo {\n bar: -baz-boom; }\n", render(%Q{foo\n bar: -baz-boom})) end def test_string_div assert_equal("foo {\n bar: baz/boom/bat; }\n", render(%Q{foo\n bar: baz/boom/bat})) assert_equal("foo {\n bar: /baz/boom; }\n", render(%Q{foo\n bar: /baz/boom})) end def test_basic_multiline_selector assert_equal("#foo #bar,\n#baz #boom {\n foo: bar; }\n", render("#foo #bar,\n#baz #boom\n foo: bar")) assert_equal("#foo #bar,\n#foo #baz {\n foo: bar; }\n", render("#foo\n #bar,\n #baz\n foo: bar")) assert_equal("#foo,\n#bar {\n foo: bar; }\n #foo #baz,\n #bar #baz {\n foo: bar; }\n", render("#foo,\n#bar\n foo: bar\n #baz\n foo: bar")) assert_equal("#foo #bar, #baz #boom { foo: bar; }\n", render("#foo #bar,\n#baz #boom\n foo: bar", :style => :compact)) assert_equal("#foo #bar,#baz #boom{foo:bar}\n", render("#foo #bar,\n#baz #boom\n foo: bar", :style => :compressed)) assert_equal("#foo #bar,\n#baz #boom {\n foo: bar; }\n", render("#foo #bar,,\n,#baz #boom,\n foo: bar")) assert_equal("#bip #bop {\n foo: bar; }\n", render("#bip #bop,, ,\n foo: bar")) end def test_complex_multiline_selector renders_correctly "multiline" end def test_colon_only begin render("a\n b: c", :property_syntax => :old) rescue Sass::SyntaxError => e assert_equal("Illegal property syntax: can't use new syntax when :property_syntax => :old is set.", e.message) assert_equal(2, e.sass_line) else assert(false, "SyntaxError not raised for :property_syntax => :old") end begin silence_warnings {render("a\n :b c", :property_syntax => :new)} assert_equal(2, e.sass_line) rescue Sass::SyntaxError => e assert_equal("Illegal property syntax: can't use old syntax when :property_syntax => :new is set.", e.message) else assert(false, "SyntaxError not raised for :property_syntax => :new") end end def test_pseudo_elements assert_equal(<<CSS, render(<<SASS)) ::first-line { size: 10em; } CSS ::first-line size: 10em SASS end def test_directive
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/test/sass/exec_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/exec_test.rb
require File.dirname(__FILE__) + '/../test_helper' require 'fileutils' require 'sass/util/test' require 'tmpdir' class ExecTest < MiniTest::Test include Sass::Util::Test def setup @dir = Dir.mktmpdir end def teardown FileUtils.rm_rf(@dir) clean_up_sassc end def test_scss_t_expanded src = get_path("src.scss") dest = get_path("dest.css") write(src, ".ruleset { margin: 0 }") assert(exec(*%w[scss --sourcemap=none -t expanded --unix-newlines].push(src, dest))) assert_equal(".ruleset {\n margin: 0;\n}\n", read(dest)) end def test_sass_convert_T_sass src = get_path("src.scss") dest = get_path("dest.css") write(src, ".ruleset { margin: 0 }") assert(exec(*%w[sass-convert -T sass --unix-newlines].push(src, dest))) assert_equal(".ruleset\n margin: 0\n", read(dest)) end def test_sass_convert_T_sass_in_place src = get_path("src.scss") write(src, ".ruleset { margin: 0 }") assert(exec(*%w[sass-convert -T sass --in-place --unix-newlines].push(src))) assert_equal(".ruleset\n margin: 0\n", read(src)) end def test_scss_t_expanded_no_unix_newlines return skip "Can be run on Windows only" unless Sass::Util.windows? src = get_path("src.scss") dest = get_path("dest.css") write(src, ".ruleset { margin: 0 }") assert(exec(*%w[scss -t expanded].push(src, dest))) assert_equal(".ruleset {\r\n margin: 0;\r\n}\r\n", read(dest)) end def test_sass_convert_T_sass_no_unix_newlines return skip "Can be run on Windows only" unless Sass::Util.windows? src = get_path("src.scss") dest = get_path("dest.sass") write(src, ".ruleset { margin: 0 }") assert(exec(*%w[sass-convert -T sass].push(src, dest))) assert_equal(".ruleset\r\n margin: 0\r\n", read(dest)) end def test_sass_convert_T_sass_in_place_no_unix_newlines return skip "Can be run on Windows only" unless Sass::Util.windows? src = get_path("src.scss") write(src, ".ruleset { margin: 0 }") assert(exec(*%w[sass-convert -T sass --in-place].push(src))) assert_equal(".ruleset\r\n margin: 0\r\n", read(src)) end def test_sass_convert_R Dir.chdir(@dir) do src = get_path("styles/src.css") write(src, ".ruleset { margin: 0 }") assert(exec(*%w[sass-convert -Rq --from css --to scss --trace styles])) end end private def get_path(name) File.join(@dir, name) end def read(file) open(file, 'rb') {|f| f.read} end def write(file, content) FileUtils.mkdir_p(File.dirname(file)) open(file, 'wb') {|f| f.write(content)} end def exec(script, *args) script = File.dirname(__FILE__) + '/../../bin/' + script ruby = File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT']) system(ruby, script, *args) 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/test/sass/conversion_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/conversion_test.rb
require File.dirname(__FILE__) + '/../test_helper' class ConversionTest < MiniTest::Test def test_basic assert_converts <<SASS, <<SCSS foo bar baz: bang bip: bop SASS foo bar { baz: bang; bip: bop; } SCSS silence_warnings {assert_converts <<SASS, <<SCSS, options: {old: true}} foo bar :baz bang :bip bop SASS foo bar { baz: bang; bip: bop; } SCSS end def test_empty_selector assert_converts "foo bar", "foo bar {}" end def test_empty_directive assert_converts "@media screen", "@media screen {}" end def test_empty_control_directive assert_converts "@if false", "@if false {}" end def test_nesting assert_converts <<SASS, <<SCSS foo bar baz bang baz: bang bip: bop blat: boo SASS foo bar { baz bang { baz: bang; bip: bop; } blat: boo; } SCSS end def test_nesting_with_parent_ref assert_converts <<SASS, <<SCSS foo bar &:hover baz: bang SASS foo bar { &:hover { baz: bang; } } SCSS end def test_selector_interpolation assert_converts <<SASS, <<SCSS foo \#{$bar + "baz"}.bip baz: bang foo /\#{$bar + "baz"}/ .bip baz: bang SASS foo \#{$bar + "baz"}.bip { baz: bang; } foo /\#{$bar + "baz"}/ .bip { baz: bang; } SCSS end def test_multiline_selector_with_commas assert_converts <<SASS, <<SCSS foo bar, baz bang baz: bang SASS foo bar, baz bang { baz: bang; } SCSS assert_converts <<SASS, <<SCSS blat foo bar, baz bang baz: bang SASS blat { foo bar, baz bang { baz: bang; } } SCSS end def test_multiline_selector_without_commas assert_scss_to_sass <<SASS, <<SCSS foo bar baz bang baz: bang SASS foo bar baz bang { baz: bang; } SCSS assert_scss_to_scss <<SCSS foo bar baz bang { baz: bang; } SCSS end def test_escaped_selector assert_converts <<SASS, <<SCSS foo bar \\:hover baz: bang SASS foo bar { :hover { baz: bang; } } SCSS end def test_property_name_interpolation assert_converts <<SASS, <<SCSS foo bar baz\#{$bang}bip\#{$bop}: 12 SASS foo bar { baz\#{$bang}bip\#{$bop}: 12; } SCSS end def test_property_value_interpolation assert_converts <<SASS, <<SCSS foo bar baz: 12 \#{$bang} bip \#{"bop"} blat SASS foo bar { baz: 12 \#{$bang} bip \#{"bop"} blat; } SCSS end def test_dynamic_properties assert_converts <<SASS, <<SCSS foo bar baz: 12 $bang "bip" SASS foo bar { baz: 12 $bang "bip"; } SCSS end def test_dynamic_properties_with_old silence_warnings {assert_converts <<SASS, <<SCSS, options: {old: true}} foo bar :baz 12 $bang "bip" SASS foo bar { baz: 12 $bang "bip"; } SCSS end def test_multiline_properties assert_scss_to_sass <<SASS, <<SCSS foo bar baz: bip bam boon SASS foo bar { baz: bip bam boon; } SCSS assert_scss_to_scss <<OUT, source: <<IN foo bar { baz: bip bam boon; } OUT foo bar { baz: bip bam boon; } IN end def test_multiline_dynamic_properties assert_scss_to_sass <<SASS, <<SCSS foo bar baz: $bip "bam" 12px SASS foo bar { baz: $bip "bam" 12px; } SCSS assert_scss_to_scss <<OUT, source: <<IN foo bar { baz: $bip "bam" 12px; } OUT foo bar { baz: $bip "bam" 12px; } IN end def test_silent_comments assert_converts <<SASS, <<SCSS // foo // bar // baz foo bar a: b SASS // foo // bar // baz foo bar { a: b; } SCSS assert_converts <<SASS, <<SCSS // foo // bar // baz // bang foo bar a: b SASS // foo // bar // baz // bang foo bar { a: b; } SCSS assert_converts <<SASS, <<SCSS // foo // bar // baz // bang foo bar a: b SASS // foo // bar // baz // bang foo bar { a: b; } SCSS end def test_nested_silent_comments assert_converts <<SASS, <<SCSS foo bar: baz // bip bop // beep boop bang: bizz // bubble bubble // toil trouble SASS foo { bar: baz; // bip bop // beep boop bang: bizz; // bubble bubble // toil trouble } SCSS assert_sass_to_scss <<SCSS, <<SASS foo { bar: baz; // bip bop // beep boop // bap blimp bang: bizz; // bubble bubble // toil trouble // gorp } SCSS foo bar: baz // bip bop beep boop bap blimp bang: bizz // bubble bubble toil trouble gorp SASS end def test_preserves_triple_slash_comments assert_converts <<SASS, <<SCSS /// foo /// bar foo /// bip bop /// beep boop SASS /// foo /// bar foo { /// bip bop /// beep boop } SCSS end def test_loud_comments assert_converts <<SASS, <<SCSS /* foo /* bar /* baz foo bar a: b SASS /* foo */ /* bar */ /* baz */ foo bar { a: b; } SCSS assert_scss_to_sass <<SASS, <<SCSS /* foo * bar * baz * bang foo bar a: b SASS /* foo bar baz bang */ foo bar { a: b; } SCSS assert_scss_to_scss <<SCSS /* foo bar baz bang */ foo bar { a: b; } SCSS assert_converts <<SASS, <<SCSS /* foo * bar * baz * bang foo bar a: b SASS /* foo * bar * baz * bang */ foo bar { a: b; } SCSS end def test_nested_loud_comments assert_converts <<SASS, <<SCSS foo bar: baz /* bip bop * beep boop bang: bizz /* bubble bubble * toil trouble SASS foo { bar: baz; /* bip bop * beep boop */ bang: bizz; /* bubble bubble * toil trouble */ } SCSS assert_sass_to_scss <<SCSS, <<SASS foo { bar: baz; /* bip bop * beep boop * bap blimp */ bang: bizz; /* bubble bubble * toil trouble * gorp */ } SCSS foo bar: baz /* bip bop beep boop bap blimp bang: bizz /* bubble bubble toil trouble gorp SASS end def test_preserves_double_star_comments assert_converts <<SASS, <<SCSS /** foo * bar foo /** bip bop * beep boop SASS /** foo * bar */ foo { /** bip bop * beep boop */ } SCSS end def test_loud_comments_with_weird_indentation assert_scss_to_sass <<SASS, <<SCSS foo /* foo * bar * baz a: b SASS foo { /* foo bar baz */ a: b; } SCSS assert_sass_to_scss <<SCSS, <<SASS foo { /* foo * bar * baz */ a: b; } SCSS foo /* foo bar baz a: b SASS end def test_loud_comment_containing_silent_comment assert_scss_to_sass <<SASS, <<SCSS /* *// foo bar SASS /* // foo bar */ SCSS end def test_silent_comment_containing_loud_comment assert_scss_to_sass <<SASS, <<SCSS // /* // * foo bar // */ SASS // /* // * foo bar // */ SCSS end def test_immediately_preceding_comments assert_converts <<SASS, <<SCSS /* Foo * Bar * Baz .foo#bar a: b SASS /* Foo * Bar * Baz */ .foo#bar { a: b; } SCSS assert_converts <<SASS, <<SCSS // Foo // Bar // Baz =foo a: b SASS // Foo // Bar // Baz @mixin foo { a: b; } SCSS end def test_immediately_following_comments assert_sass_to_scss <<SCSS, <<SASS .foobar { // trailing comment a: 1px; } SCSS .foobar // trailing comment a: 1px SASS assert_sass_to_scss <<SCSS, <<SASS .foobar { // trailing comment a: 1px; } SCSS .foobar /* trailing comment */ a: 1px SASS end def test_debug assert_converts <<SASS, <<SCSS foo @debug 12px bar: baz SASS foo { @debug 12px; bar: baz; } SCSS end def test_error assert_converts <<SASS, <<SCSS foo @error "oh no!" bar: baz SASS foo { @error "oh no!"; bar: baz; } SCSS end def test_directive_without_children assert_converts <<SASS, <<SCSS foo @foo #bar "baz" bar: baz SASS foo { @foo #bar "baz"; bar: baz; } SCSS end def test_directive_with_prop_children assert_converts <<SASS, <<SCSS foo @foo #bar "baz" a: b c: d bar: baz SASS foo { @foo #bar "baz" { a: b; c: d; } bar: baz; } SCSS end def test_directive_with_rule_children assert_converts <<SASS, <<SCSS foo @foo #bar "baz" #blat a: b .bang c: d e: f bar: baz SASS foo { @foo #bar "baz" { #blat { a: b; } .bang { c: d; e: f; } } bar: baz; } SCSS end def test_directive_with_rule_and_prop_children assert_converts <<SASS, <<SCSS foo @foo #bar "baz" g: h #blat a: b .bang c: d e: f i: j bar: baz SASS foo { @foo #bar "baz" { g: h; #blat { a: b; } .bang { c: d; e: f; } i: j; } bar: baz; } SCSS end def test_charset assert_converts <<SASS, <<SCSS @charset "utf-8" SASS @charset "utf-8"; SCSS end def test_for assert_converts <<SASS, <<SCSS foo @for $a from $b to $c a: b @for $c from 1 to 16 d: e f: g SASS foo { @for $a from $b to $c { a: b; } @for $c from 1 to 16 { d: e; f: g; } } SCSS end def test_while assert_converts <<SASS, <<SCSS foo @while flaz($a + $b) a: b @while 1 d: e f: g SASS foo { @while flaz($a + $b) { a: b; } @while 1 { d: e; f: g; } } SCSS end def test_if assert_converts <<SASS, <<SCSS foo @if $foo or $bar a: b @if $baz d: e @else if $bang f: g @else h: i SASS foo { @if $foo or $bar { a: b; } @if $baz { d: e; } @else if $bang { f: g; } @else { h: i; } } SCSS end def test_each assert_converts <<SASS, <<SCSS a @each $number in 1px 2px 3px 4px b: $number c @each $str in foo, bar, baz, bang d: $str c @each $key, $value in (foo: 1, bar: 2, baz: 3) \#{$key}: $value SASS a { @each $number in 1px 2px 3px 4px { b: $number; } } c { @each $str in foo, bar, baz, bang { d: $str; } } c { @each $key, $value in (foo: 1, bar: 2, baz: 3) { \#{$key}: $value; } } SCSS end def test_import assert_converts <<SASS, <<SCSS @import foo @import url(bar.css) foo bar: baz SASS @import "foo"; @import url(bar.css); foo { bar: baz; } SCSS assert_converts <<SASS, <<SCSS @import foo.css @import url(bar.css) foo bar: baz SASS @import "foo.css"; @import url(bar.css); foo { bar: baz; } SCSS end def test_import_as_directive_in_sass assert_equal "@import foo.css\n", to_sass('@import "foo.css"') end def test_import_as_directive_in_scss assert_converts <<SASS, <<SCSS @import "foo.css" print SASS @import "foo.css" print; SCSS assert_converts <<SASS, <<SCSS @import url(foo.css) screen, print SASS @import url(foo.css) screen, print; SCSS end def test_adjacent_imports assert_converts <<SASS, <<SCSS @import foo.sass @import bar.scss @import baz SASS @import "foo.sass"; @import "bar.scss"; @import "baz"; SCSS end def test_non_adjacent_imports assert_converts <<SASS, <<SCSS @import foo.sass @import bar.scss @import baz SASS @import "foo.sass"; @import "bar.scss"; @import "baz"; SCSS end def test_import_with_interpolation assert_converts <<SASS, <<SCSS $family: unquote("Droid+Sans") @import url("http://fonts.googleapis.com/css?family=\#{$family}") SASS $family: unquote("Droid+Sans"); @import url("http://fonts.googleapis.com/css?family=\#{$family}"); SCSS end def test_extend assert_converts <<SASS, <<SCSS .foo @extend .bar @extend .baz:bang SASS .foo { @extend .bar; @extend .baz:bang; } SCSS end def test_comma_extendee assert_converts <<SASS, <<SCSS .baz @extend .foo, .bar SASS .baz { @extend .foo, .bar; } SCSS end def test_argless_mixin_definition assert_converts <<SASS, <<SCSS =foo-bar baz a: b SASS @mixin foo-bar { baz { a: b; } } SCSS assert_scss_to_sass <<SASS, <<SCSS =foo-bar baz a: b SASS @mixin foo-bar() { baz { a: b; } } SCSS assert_sass_to_scss <<SCSS, <<SASS @mixin foo-bar { baz { a: b; } } SCSS =foo-bar() baz a: b SASS end def test_mixin_definition_without_defaults assert_converts <<SASS, <<SCSS =foo-bar($baz, $bang) baz a: $baz $bang SASS @mixin foo-bar($baz, $bang) { baz { a: $baz $bang; } } SCSS end def test_mixin_definition_with_defaults assert_converts <<SASS, <<SCSS =foo-bar($baz, $bang: 12px) baz a: $baz $bang SASS @mixin foo-bar($baz, $bang: 12px) { baz { a: $baz $bang; } } SCSS assert_sass_to_scss <<SCSS, <<SASS @mixin foo-bar($baz, $bang: foo) { baz { a: $baz $bang; } } SCSS =foo-bar($baz, $bang: foo) baz a: $baz $bang SASS end def test_argless_mixin_include assert_converts <<SASS, <<SCSS foo +foo-bar a: blip SASS foo { @include foo-bar; a: blip; } SCSS end def test_mixin_include assert_converts <<SASS, <<SCSS foo +foo-bar(12px, "blaz") a: blip SASS foo { @include foo-bar(12px, "blaz"); a: blip; } SCSS end def test_mixin_include_with_keyword_args assert_converts <<SASS, <<SCSS foo +foo-bar(12px, "blaz", $blip: blap, $bloop: blop) +foo-bar($blip: blap, $bloop: blop) a: blip SASS foo { @include foo-bar(12px, "blaz", $blip: blap, $bloop: blop); @include foo-bar($blip: blap, $bloop: blop); a: blip; } SCSS end def test_consecutive_mixin_includes assert_converts <<SASS, <<SCSS foo +foo-bar +foo-bar a: blip SASS foo { @include foo-bar; @include foo-bar; a: blip; } SCSS end def test_mixin_include_with_hyphen_conversion_keyword_arg assert_converts <<SASS, <<SCSS foo +foo-bar($a-b_c: val) a: blip SASS foo { @include foo-bar($a-b_c: val); a: blip; } SCSS end def test_argless_function_definition assert_converts <<SASS, <<SCSS @function foo() $var: 1 + 1 @return $var SASS @function foo() { $var: 1 + 1; @return $var; } SCSS end def test_function_definition_without_defaults assert_converts <<SASS, <<SCSS @function foo($var1, $var2) @if $var1 @return $var1 + $var2 SASS @function foo($var1, $var2) { @if $var1 { @return $var1 + $var2; } } SCSS end def test_function_definition_with_defaults assert_converts <<SASS, <<SCSS @function foo($var1, $var2: foo) @if $var1 @return $var1 + $var2 SASS @function foo($var1, $var2: foo) { @if $var1 { @return $var1 + $var2; } } SCSS end def test_variable_definition assert_converts <<SASS, <<SCSS $var1: 12px + 15px foo $var2: flaz(#abcdef) val: $var1 $var2 SASS $var1: 12px + 15px; foo { $var2: flaz(#abcdef); val: $var1 $var2; } SCSS end def test_guarded_variable_definition assert_converts <<SASS, <<SCSS $var1: 12px + 15px !default foo $var2: flaz(#abcdef) !default val: $var1 $var2 SASS $var1: 12px + 15px !default; foo { $var2: flaz(#abcdef) !default; val: $var1 $var2; } SCSS end def test_multiple_variable_definitions assert_converts <<SASS, <<SCSS $var1: foo $var2: bar $var3: baz $var4: bip $var5: bap SASS $var1: foo; $var2: bar; $var3: baz; $var4: bip; $var5: bap; SCSS end def test_division_asserted_with_parens assert_converts <<SASS, <<SCSS foo a: (1px / 2px) SASS foo { a: (1px / 2px); } SCSS end def test_division_not_asserted_when_unnecessary assert_converts <<SASS, <<SCSS $var: 1px / 2px foo a: $var SASS $var: 1px / 2px; foo { a: $var; } SCSS assert_converts <<SASS, <<SCSS $var: 1px foo a: $var / 2px SASS $var: 1px; foo { a: $var / 2px; } SCSS assert_converts <<SASS, <<SCSS foo a: 1 + 1px / 2px SASS foo { a: 1 + 1px / 2px; } SCSS end def test_literal_slash assert_converts <<SASS, <<SCSS foo a: 1px / 2px SASS foo { a: 1px / 2px; } SCSS # Regression test for issue 1787 assert_converts <<SASS, <<SCSS foo a: 1px / 2px 3px SASS foo { a: 1px / 2px 3px; } SCSS end def test_directive_with_interpolation assert_converts <<SASS, <<SCSS $baz: 12 @foo bar\#{$baz} qux a: b SASS $baz: 12; @foo bar\#{$baz} qux { a: b; } SCSS end def test_media_with_interpolation assert_converts <<SASS, <<SCSS $baz: 12 @media bar\#{$baz} a: b SASS $baz: 12; @media bar\#{$baz} { a: b; } SCSS end def test_media_with_expressions assert_converts <<SASS, <<SCSS $media1: screen $media2: print $var: -webkit-min-device-pixel-ratio $val: 20 @media \#{$media1} and ($var + "-foo": $val + 5), only \#{$media2} a: b SASS $media1: screen; $media2: print; $var: -webkit-min-device-pixel-ratio; $val: 20; @media \#{$media1} and ($var + "-foo": $val + 5), only \#{$media2} { a: b; } SCSS end def test_media_with_feature assert_converts <<SASS, <<SCSS @media screen and (-webkit-transform-3d) a: b SASS @media screen and (-webkit-transform-3d) { a: b; } SCSS end def test_supports_with_expressions assert_converts <<SASS, <<SCSS $query: "(feature1: val)" $feature: feature2 $val: val @supports (\#{$query} and ($feature: $val)) or (not ($feature + 3: $val + 4)) foo a: b SASS $query: "(feature1: val)"; $feature: feature2; $val: val; @supports (\#{$query} and ($feature: $val)) or (not ($feature + 3: $val + 4)) { foo { a: b; } } SCSS end # Hacks def test_declaration_hacks assert_converts <<SASS, <<SCSS foo _name: val *name: val #name: val .name: val name/**/: val name/*\\**/: val name: val SASS foo { _name: val; *name: val; #name: val; .name: val; name/**/: val; name/*\\**/: val; name: val; } SCSS end def test_old_declaration_hacks silence_warnings {assert_converts <<SASS, <<SCSS, options: {old: true}} foo :_name val :*name val :#name val :.name val :name val SASS foo { _name: val; *name: val; #name: val; .name: val; name: val; } SCSS end def test_selector_hacks assert_selector_renders = lambda do |s| assert_converts <<SASS, <<SCSS #{s} a: b SASS #{s} { a: b; } SCSS end assert_selector_renders['> E'] assert_selector_renders['+ E'] assert_selector_renders['~ E'] assert_selector_renders['> > E'] assert_selector_renders['E*'] assert_selector_renders['E*.foo'] assert_selector_renders['E*:hover'] end def test_disallowed_colon_hack assert_raise_message(Sass::SyntaxError, 'The ":name: val" hack is not allowed in the Sass indented syntax') do to_sass("foo {:name: val;}", :syntax => :scss) end end def test_nested_properties assert_converts <<SASS, <<SCSS div before: before background: color: blue repeat: no-repeat after: after SASS div { before: before; background: { color: blue; repeat: no-repeat; }; after: after; } SCSS end def test_dasherize assert_sass_to_scss(<<SCSS, <<SASS, options: {dasherize: true}) @mixin under-scored-mixin($under-scored-arg: $under-scored-default) { bar: $under-scored-arg; } div { foo: under-scored-fn($under-scored-var + "before\#{$another-under-scored-var}after"); @include under-scored-mixin($passed-arg); selector-\#{$under-scored-interp}: bold; } @if $under-scored { @for $for-var from $from-var to $to-var { @while $while-var == true { $while-var: false; } } } SCSS =under_scored_mixin($under_scored_arg: $under_scored_default) bar: $under_scored_arg div foo: under_scored_fn($under_scored_var + "before\#{$another_under_scored_var}after") +under_scored_mixin($passed_arg) selector-\#{$under_scored_interp}: bold @if $under_scored @for $for_var from $from_var to $to_var @while $while_var == true $while_var : false SASS end def test_loud_comment_conversion assert_converts(<<SASS, <<SCSS) /*! \#{"interpolated"} SASS /*! \#{"interpolated"} */ SCSS end def test_content_conversion assert_converts(<<SASS, <<SCSS) $color: blue =context($class, $color: red) .\#{$class} background-color: $color @content border-color: $color +context(parent) +context(child, $color: yellow) color: $color SASS $color: blue; @mixin context($class, $color: red) { .\#{$class} { background-color: $color; @content; border-color: $color; } } @include context(parent) { @include context(child, $color: yellow) { color: $color; } } SCSS end def test_empty_content assert_scss_to_scss(<<SCSS) @mixin foo { @content; } @include foo {} SCSS end def test_placeholder_conversion assert_converts(<<SASS, <<SCSS) #content a%foo.bar color: blue SASS #content a%foo.bar { color: blue; } SCSS end def test_reference_selector assert_converts(<<SASS, <<SCSS) foo /bar|baz/ bang a: b SASS foo /bar|baz/ bang { a: b; } SCSS end def test_subject assert_converts(<<SASS, <<SCSS) foo bar! baz a: b SASS foo bar! baz { a: b; } SCSS end def test_placeholder_interoplation_conversion assert_converts(<<SASS, <<SCSS) $foo: foo %\#{$foo} color: blue .bar @extend %foo SASS $foo: foo; %\#{$foo} { color: blue; } .bar { @extend %foo; } SCSS end def test_indent assert_converts <<SASS, <<SCSS, options: {indent: " "} foo bar baz bang baz: bang bip: bop blat: boo SASS foo bar { baz bang { baz: bang; bip: bop; } blat: boo; } SCSS assert_converts <<SASS, <<SCSS, options: {indent: "\t"} foo bar baz bang baz: bang bip: bop blat: boo SASS foo bar { baz bang { baz: bang; bip: bop; } blat: boo; } SCSS assert_sass_to_scss <<SCSS, <<SASS, options: {indent: " "} foo bar { baz bang { baz: bang; bip: bop; } blat: boo; } SCSS foo bar baz bang baz: bang bip: bop blat: boo SASS assert_sass_to_scss <<SCSS, <<SASS, options: {indent: "\t"} foo bar { baz bang { baz: bang; bip: bop; } blat: boo; } SCSS foo bar baz bang baz: bang bip: bop blat: boo SASS assert_scss_to_sass <<SASS, <<SCSS, options: {indent: " "} foo bar baz bang baz: bang bip: bop blat: boo SASS foo bar { baz bang { baz: bang; bip: bop; } blat: boo; } SCSS assert_scss_to_sass <<SASS, <<SCSS, options: {indent: "\t"} foo bar baz bang baz: bang bip: bop blat: boo SASS foo bar { baz bang { baz: bang; bip: bop; } blat: boo; } SCSS end def test_extend_with_optional assert_converts <<SASS, <<SCSS foo @extend .bar !optional SASS foo { @extend .bar !optional; } SCSS end def test_mixin_var_args assert_converts <<SASS, <<SCSS =foo($args...) a: b =bar($a, $args...) a: b .foo +foo($list...) +bar(1, $list...) SASS @mixin foo($args...) { a: b; } @mixin bar($a, $args...) { a: b; } .foo { @include foo($list...); @include bar(1, $list...); } SCSS end def test_mixin_var_kwargs assert_converts <<SASS, <<SCSS =foo($a: b, $c: d) a: $a c: $c .foo +foo($list..., $map...) +foo(pos, $list..., $kwd: val, $map...) SASS @mixin foo($a: b, $c: d) { a: $a; c: $c; } .foo { @include foo($list..., $map...); @include foo(pos, $list..., $kwd: val, $map...); } SCSS end def test_function_var_args assert_converts <<SASS, <<SCSS @function foo($args...) @return foo @function bar($a, $args...) @return bar .foo a: foo($list...) b: bar(1, $list...) SASS @function foo($args...) { @return foo; } @function bar($a, $args...) { @return bar; } .foo { a: foo($list...); b: bar(1, $list...); } SCSS end def test_function_var_kwargs assert_converts <<SASS, <<SCSS @function foo($a: b, $c: d) @return foo .foo a: foo($list..., $map...) b: foo(pos, $list..., $kwd: val, $map...) SASS @function foo($a: b, $c: d) { @return foo; } .foo { a: foo($list..., $map...); b: foo(pos, $list..., $kwd: val, $map...); } SCSS end def test_at_root assert_converts <<SASS, <<SCSS .foo @at-root .bar a: b .baz c: d SASS .foo { @at-root { .bar { a: b; } .baz { c: d; } } } SCSS end def test_at_root_with_selector assert_converts <<SASS, <<SCSS .foo @at-root .bar a: b SASS .foo { @at-root .bar { a: b; } } SCSS end def test_at_root_without assert_converts <<SASS, <<SCSS .foo @at-root (without: media rule) a: b SASS .foo { @at-root (without: media rule) { a: b; } } SCSS end def test_at_root_with assert_converts <<SASS, <<SCSS .foo @at-root (with: media rule) a: b SASS .foo { @at-root (with: media rule) { a: b; } } SCSS end def test_function_var_kwargs_with_list assert_converts <<SASS, <<SCSS @function foo($a: b, $c: d) @return $a, $c .foo a: foo($list..., $map...) SASS @function foo($a: b, $c: d) { @return $a, $c; } .foo { a: foo($list..., $map...); } SCSS end def test_keyframes assert_converts(<<SASS, <<SCSS) @keyframes identifier 0% top: 0 left: 0 30% top: 50px 68%, 72% left: 50px 100% top: 100px left: 100% SASS @keyframes identifier { 0% { top: 0; left: 0; } 30% { top: 50px; } 68%, 72% { left: 50px; } 100% { top: 100px; left: 100%; } } SCSS end ## Regression Tests def test_list_in_args assert_converts(<<SASS, <<SCSS) +mixin((a, b, c)) +mixin($arg: (a, b, c)) +mixin(a, b, (c, d, e)...) SASS @include mixin((a, b, c)); @include mixin($arg: (a, b, c)); @include mixin(a, b, (c, d, e)...); SCSS end def test_media_query_with_expr assert_converts <<SASS, <<SCSS @media foo and (bar: baz) a: b SASS @media foo and (bar: baz) { a: b; } SCSS end def test_nested_if_statements assert_converts(<<SASS, <<SCSS) @if $foo one a: b @else @if $bar two a: b @else three a: b SASS @if $foo { one { a: b; } } @else { @if $bar { two { a: b; } } @else { three { a: b; } } } SCSS end def test_comment_indentation assert_converts(<<SASS, <<SCSS, options: {indent: ' '}) foo // bar /* baz a: b SASS foo { // bar /* baz */ a: b; } SCSS end def test_keyword_arguments assert_converts(<<SASS, <<SCSS, options: {dasherize: true}) $foo: foo($dash-ed: 2px) SASS $foo: foo($dash-ed: 2px); SCSS assert_scss_to_sass(<<SASS, <<SCSS, options: {dasherize: true}) $foo: foo($dash-ed: 2px) SASS $foo: foo($dash_ed: 2px); SCSS assert_sass_to_scss(<<SCSS, <<SASS, options: {dasherize: true}) $foo: foo($dash-ed: 2px); SCSS $foo: foo($dash_ed: 2px) SASS assert_converts(<<SASS, <<SCSS) $foo: foo($under_scored: 1px) SASS $foo: foo($under_scored: 1px); SCSS assert_converts(<<SASS, <<SCSS) $foo: foo($dash-ed: 2px, $under_scored: 1px) SASS $foo: foo($dash-ed: 2px, $under_scored: 1px); SCSS end def test_ambiguous_negation assert_converts(<<SASS, <<SCSS, options: {indent: ' '}) foo ok: -$foo comma: 10px, -$foo needs-parens: 10px (-$foo) SASS foo { ok: -$foo; comma: 10px, -$foo; needs-parens: 10px (-$foo); } SCSS end def test_variable_with_global assert_converts(<<SASS, <<SCSS) $var: 1 foo $var: 2 !global $var: 3 !global !default SASS $var: 1; foo { $var: 2 !global; $var: 3 !global !default; } SCSS end def test_import_with_supports_clause assert_converts(<<'SASS', <<'SCSS') @import url("fallback-layout.css") supports(not (display: #{$display-type})) SASS @import url("fallback-layout.css") supports(not (display: #{$display-type})); SCSS 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/test/sass/callbacks_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/callbacks_test.rb
require File.dirname(__FILE__) + '/../test_helper' require 'sass/callbacks' class CallerBack extend Sass::Callbacks define_callback :foo define_callback :bar def do_foo run_foo end def do_bar run_bar 12 end end module ClassLevelCallerBack extend Sass::Callbacks define_callback :foo extend self def do_foo run_foo end end class SassCallbacksTest < MiniTest::Test def test_simple_callback cb = CallerBack.new there = false cb.on_foo {there = true} cb.do_foo assert there, "Expected callback to be called." end def test_multiple_callbacks cb = CallerBack.new str = "" cb.on_foo {str += "first"} cb.on_foo {str += " second"} cb.do_foo assert_equal "first second", str end def test_callback_with_arg cb = CallerBack.new val = nil cb.on_bar {|a| val = a} cb.do_bar assert_equal 12, val end def test_class_level_callback there = false ClassLevelCallerBack.on_foo {there = true} ClassLevelCallerBack.do_foo assert there, "Expected callback to be called." 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/test/sass/cache_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/cache_test.rb
require File.dirname(__FILE__) + '/../test_helper' require File.dirname(__FILE__) + '/test_helper' require 'sass/engine' class CacheTest < MiniTest::Test @@cache_dir = "tmp/file_cache" def setup FileUtils.mkdir_p @@cache_dir end def teardown FileUtils.rm_rf @@cache_dir clean_up_sassc end def test_file_cache_writes_a_file file_store = Sass::CacheStores::Filesystem.new(@@cache_dir) file_store.store("asdf/foo.scssc", "fakesha1", root_node) assert File.exist?("#{@@cache_dir}/asdf/foo.scssc") end def test_file_cache_reads_a_file file_store = Sass::CacheStores::Filesystem.new(@@cache_dir) assert !File.exist?("#{@@cache_dir}/asdf/foo.scssc") file_store.store("asdf/foo.scssc", "fakesha1", root_node) assert File.exist?("#{@@cache_dir}/asdf/foo.scssc") assert_kind_of Sass::Tree::RootNode, file_store.retrieve("asdf/foo.scssc", "fakesha1") end def test_file_cache_miss_returns_nil file_store = Sass::CacheStores::Filesystem.new(@@cache_dir) assert !File.exist?("#{@@cache_dir}/asdf/foo.scssc") assert_nil file_store.retrieve("asdf/foo.scssc", "fakesha1") end def test_sha_change_invalidates_cache_and_cleans_up file_store = Sass::CacheStores::Filesystem.new(@@cache_dir) assert !File.exist?("#{@@cache_dir}/asdf/foo.scssc") file_store.store("asdf/foo.scssc", "fakesha1", root_node) assert File.exist?("#{@@cache_dir}/asdf/foo.scssc") assert_nil file_store.retrieve("asdf/foo.scssc", "differentsha1") assert !File.exist?("#{@@cache_dir}/asdf/foo.scssc") end def test_version_change_invalidates_cache_and_cleans_up file_store = Sass::CacheStores::Filesystem.new(@@cache_dir) assert !File.exist?("#{@@cache_dir}/asdf/foo.scssc") file_store.store("asdf/foo.scssc", "fakesha1", root_node) assert File.exist?("#{@@cache_dir}/asdf/foo.scssc") real_version = Sass::VERSION begin Sass::VERSION.replace("a different version") assert_nil file_store.retrieve("asdf/foo.scssc", "fakesha1") assert !File.exist?("#{@@cache_dir}/asdf/foo.scssc") ensure Sass::VERSION.replace(real_version) end end def test_arbitrary_objects_can_go_into_cache cache = Sass::CacheStores::Memory.new an_object = {:foo => :bar} cache.store("an_object", "", an_object) assert_equal an_object, cache.retrieve("an_object", "") end def test_cache_node_with_unmarshalable_option engine_with_unmarshalable_options("foo {a: b + c}").to_tree end # Regression tests def test_cache_mixin_def_splat_sass_node_with_unmarshalable_option engine_with_unmarshalable_options(<<SASS, :syntax => :sass).to_tree =color($args...) color: red SASS end def test_cache_mixin_def_splat_scss_node_with_unmarshalable_option engine_with_unmarshalable_options(<<SCSS, :syntax => :scss).to_tree @mixin color($args...) { color: red; } SCSS end def test_cache_function_splat_sass_node_with_unmarshalable_option engine_with_unmarshalable_options(<<SASS, :syntax => :sass).to_tree @function color($args...) @return red SASS end def test_cache_function_splat_scss_node_with_unmarshalable_option engine_with_unmarshalable_options(<<SCSS, :syntax => :scss).to_tree @function color($args...) { @return red; } SCSS end def test_cache_include_splat_sass_node_with_unmarshalable_option engine_with_unmarshalable_options(<<SASS, :syntax => :sass).to_tree @include color($args..., $kwargs...) SASS end def test_cache_include_splat_scss_node_with_unmarshalable_option engine_with_unmarshalable_options(<<SCSS, :syntax => :scss).to_tree @include color($args..., $kwargs...); SCSS end private def root_node Sass::Engine.new(<<-SCSS, :syntax => :scss).to_tree @mixin color($c) { color: $c} div { @include color(red); } SCSS end def engine_with_unmarshalable_options(src, options={}) Sass::Engine.new(src, { :syntax => :scss, :object => Class.new.new, :filename => 'file.scss', :importer => Sass::Importers::Filesystem.new(absolutize('templates')) }.merge(options)) 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/test/sass/util/normalized_map_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/util/normalized_map_test.rb
require File.dirname(__FILE__) + '/../../test_helper' require 'sass/util/normalized_map' class NormalizedMapTest < MiniTest::Test extend PublicApiLinter lint_api Hash, Sass::Util::NormalizedMap def lint_instance Sass::Util::NormalizedMap.new end def test_normalized_map_errors_unless_explicitly_implemented assert Sass.tests_running assert_raise_message(ArgumentError, "The method invert must be implemented explicitly") do Sass::Util::NormalizedMap.new.invert end end def test_normalized_map_does_not_error_when_released Sass.tests_running = false assert_equal({}, Sass::Util::NormalizedMap.new.invert) ensure Sass.tests_running = true end def test_basic_lifecycle m = Sass::Util::NormalizedMap.new m["a-b"] = 1 assert_equal ["a_b"], m.keys assert_equal 1, m["a_b"] assert_equal 1, m["a-b"] assert m.has_key?("a_b") assert m.has_key?("a-b") assert_equal({"a-b" => 1}, m.as_stored) assert_equal 1, m.delete("a-b") assert !m.has_key?("a-b") m["a_b"] = 2 assert_equal({"a_b" => 2}, m.as_stored) end def test_dup m = Sass::Util::NormalizedMap.new m["a-b"] = 1 m2 = m.dup m.delete("a-b") assert !m.has_key?("a-b") assert m2.has_key?("a-b") 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/test/sass/util/multibyte_string_scanner_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/util/multibyte_string_scanner_test.rb
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/../../test_helper' class MultibyteStringScannerTest < MiniTest::Test def setup @scanner = Sass::Util::MultibyteStringScanner.new("cölorfül") end def test_initial assert_scanner_state 0, 0, nil, nil end def test_check assert_equal 'cö', @scanner.check(/../) assert_scanner_state 0, 0, 2, 3 assert_equal 0, @scanner.pos assert_equal 0, @scanner.pos assert_equal 2, @scanner.matched_size assert_equal 3, @scanner.byte_matched_size end def test_check_until assert_equal 'cölorfü', @scanner.check_until(/f./) assert_scanner_state 0, 0, 2, 3 end def test_getch assert_equal 'c', @scanner.getch assert_equal 'ö', @scanner.getch assert_scanner_state 2, 3, 1, 2 end def test_match? assert_equal 2, @scanner.match?(/../) assert_scanner_state 0, 0, 2, 3 end def test_peek assert_equal 'cö', @scanner.peek(2) assert_scanner_state 0, 0, nil, nil end def test_rest_size assert_equal 'cö', @scanner.scan(/../) assert_equal 6, @scanner.rest_size end def test_scan assert_equal 'cö', @scanner.scan(/../) assert_scanner_state 2, 3, 2, 3 end def test_scan_until assert_equal 'cölorfü', @scanner.scan_until(/f./) assert_scanner_state 7, 9, 2, 3 end def test_skip assert_equal 2, @scanner.skip(/../) assert_scanner_state 2, 3, 2, 3 end def test_skip_until assert_equal 7, @scanner.skip_until(/f./) assert_scanner_state 7, 9, 2, 3 end def test_set_pos @scanner.pos = 7 assert_scanner_state 7, 9, nil, nil @scanner.pos = 6 assert_scanner_state 6, 7, nil, nil @scanner.pos = 1 assert_scanner_state 1, 1, nil, nil end def test_reset @scanner.scan(/../) @scanner.reset assert_scanner_state 0, 0, nil, nil end def test_scan_full assert_equal 'cö', @scanner.scan_full(/../, true, true) assert_scanner_state 2, 3, 2, 3 @scanner.reset assert_equal 'cö', @scanner.scan_full(/../, false, true) assert_scanner_state 0, 0, 2, 3 @scanner.reset assert_nil @scanner.scan_full(/../, true, false) assert_scanner_state 2, 3, 2, 3 @scanner.reset assert_nil @scanner.scan_full(/../, false, false) assert_scanner_state 0, 0, 2, 3 end def test_search_full assert_equal 'cölorfü', @scanner.search_full(/f./, true, true) assert_scanner_state 7, 9, 2, 3 @scanner.reset assert_equal 'cölorfü', @scanner.search_full(/f./, false, true) assert_scanner_state 0, 0, 2, 3 @scanner.reset assert_nil @scanner.search_full(/f./, true, false) assert_scanner_state 7, 9, 2, 3 @scanner.reset assert_nil @scanner.search_full(/f./, false, false) assert_scanner_state 0, 0, 2, 3 end def test_set_string @scanner.scan(/../) @scanner.string = 'föóbâr' assert_scanner_state 0, 0, nil, nil end def test_terminate @scanner.scan(/../) @scanner.terminate assert_scanner_state 8, 10, nil, nil end def test_unscan @scanner.scan(/../) @scanner.scan_until(/f./) @scanner.unscan assert_scanner_state 2, 3, nil, nil end private def assert_scanner_state(pos, byte_pos, matched_size, byte_matched_size) assert_equal pos, @scanner.pos, 'pos' assert_equal byte_pos, @scanner.byte_pos, 'byte_pos' if matched_size.nil? assert_nil @scanner.matched_size, 'matched_size' else assert_equal matched_size, @scanner.matched_size, 'matched_size' end if byte_matched_size.nil? assert_nil @scanner.byte_matched_size, 'byte_matched_size' else assert_equal byte_matched_size, @scanner.byte_matched_size, 'byte_matched_size' 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/test/sass/util/subset_map_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/util/subset_map_test.rb
require File.dirname(__FILE__) + '/../../test_helper' class SubsetMapTest < MiniTest::Test def setup @ssm = Sass::Util::SubsetMap.new @ssm[Set[1, 2]] = "Foo" @ssm[Set["fizz", "fazz"]] = "Bar" @ssm[Set[:foo, :bar]] = "Baz" @ssm[Set[:foo, :bar, :baz]] = "Bang" @ssm[Set[:bip, :bop, :blip]] = "Qux" @ssm[Set[:bip, :bop]] = "Thram" end def test_equal_keys assert_equal [["Foo", Set[1, 2]]], @ssm.get(Set[1, 2]) assert_equal [["Bar", Set["fizz", "fazz"]]], @ssm.get(Set["fizz", "fazz"]) end def test_subset_keys assert_equal [["Foo", Set[1, 2]]], @ssm.get(Set[1, 2, "fuzz"]) assert_equal [["Bar", Set["fizz", "fazz"]]], @ssm.get(Set["fizz", "fazz", 3]) end def test_superset_keys assert_equal [], @ssm.get(Set[1]) assert_equal [], @ssm.get(Set[2]) assert_equal [], @ssm.get(Set["fizz"]) assert_equal [], @ssm.get(Set["fazz"]) end def test_disjoint_keys assert_equal [], @ssm.get(Set[3, 4]) assert_equal [], @ssm.get(Set["fuzz", "frizz"]) assert_equal [], @ssm.get(Set["gran", 15]) end def test_semi_disjoint_keys assert_equal [], @ssm.get(Set[2, 3]) assert_equal [], @ssm.get(Set["fizz", "fuzz"]) assert_equal [], @ssm.get(Set[1, "fazz"]) end def test_empty_key_set assert_raises(ArgumentError) {@ssm[Set[]] = "Fail"} end def test_empty_key_get assert_equal [], @ssm.get(Set[]) end def test_multiple_subsets assert_equal [["Foo", Set[1, 2]], ["Bar", Set["fizz", "fazz"]]], @ssm.get(Set[1, 2, "fizz", "fazz"]) assert_equal [["Foo", Set[1, 2]], ["Bar", Set["fizz", "fazz"]]], @ssm.get(Set[1, 2, 3, "fizz", "fazz", "fuzz"]) assert_equal [["Baz", Set[:foo, :bar]]], @ssm.get(Set[:foo, :bar]) assert_equal [["Baz", Set[:foo, :bar]], ["Bang", Set[:foo, :bar, :baz]]], @ssm.get(Set[:foo, :bar, :baz]) end def test_bracket_bracket assert_equal ["Foo"], @ssm[Set[1, 2, "fuzz"]] assert_equal ["Baz", "Bang"], @ssm[Set[:foo, :bar, :baz]] end def test_order_preserved @ssm[Set[10, 11, 12]] = 1 @ssm[Set[10, 11]] = 2 @ssm[Set[11]] = 3 @ssm[Set[11, 12]] = 4 @ssm[Set[9, 10, 11, 12, 13]] = 5 @ssm[Set[10, 13]] = 6 assert_equal( [[1, Set[10, 11, 12]], [2, Set[10, 11]], [3, Set[11]], [4, Set[11, 12]], [5, Set[9, 10, 11, 12, 13]], [6, Set[10, 13]]], @ssm.get(Set[9, 10, 11, 12, 13])) end def test_multiple_equal_values @ssm[Set[11, 12]] = 1 @ssm[Set[12, 13]] = 2 @ssm[Set[13, 14]] = 1 @ssm[Set[14, 15]] = 1 assert_equal( [[1, Set[11, 12]], [2, Set[12, 13]], [1, Set[13, 14]], [1, Set[14, 15]]], @ssm.get(Set[11, 12, 13, 14, 15])) 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/test/sass/scss/test_helper.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/scss/test_helper.rb
require File.dirname(__FILE__) + '/../../test_helper' require 'sass/engine' module ScssTestHelper def assert_parses(scss) assert_equal scss.rstrip, render(scss).rstrip end def assert_not_parses(expected, scss) raise "Template must include <err> where an error is expected" unless scss.include?("<err>") after, was = scss.split("<err>") line = after.count("\n") + 1 after.gsub!(/\s*\n\s*$/, '') after.gsub!(/.*\n/, '') after = "..." + after[-15..-1] if after.size > 18 was.gsub!(/^\s*\n\s*/, '') was.gsub!(/\n.*/, '') was = was[0...15] + "..." if was.size > 18 to_render = scss.sub("<err>", "") render(to_render) assert(false, "Expected syntax error for:\n#{to_render}\n") rescue Sass::SyntaxError => err assert_equal("Invalid CSS after \"#{after}\": expected #{expected}, was \"#{was}\"", err.message) assert_equal line, err.sass_line end def render(scss, options = {}) options[:syntax] ||= :scss munge_filename options Sass::Engine.new(scss, options).render 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/test/sass/scss/css_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/scss/css_test.rb
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/test_helper' require 'sass/scss/css_parser' # These tests just test the parsing of CSS # (both standard and any hacks we intend to support). # Tests of SCSS-specific behavior go in scss_test.rb. class ScssCssTest < MiniTest::Test include ScssTestHelper def test_basic_scss assert_parses <<SCSS selector { property: value; property2: value; } SCSS assert_equal <<CSS, render('sel{p:v}') sel { p: v; } CSS end def test_empty_rule assert_equal "", render("#foo .bar {}") assert_equal "", render(<<SCSS) #foo .bar { } SCSS end def test_cdo_and_cdc_ignored_at_toplevel assert_equal <<CSS, render(<<SCSS) foo { bar: baz; } bar { bar: baz; } baz { bar: baz; } CSS foo {bar: baz} <!-- bar {bar: baz} --> baz {bar: baz} SCSS end def test_unicode assert_parses <<SCSS @charset "UTF-8"; foo { bar: föö bâr; } SCSS assert_equal <<CSS, render(<<SCSS) @charset "UTF-8"; foo { bar: föö bâr; } CSS foo { bar: föö bâr; } SCSS end def test_invisible_comments assert_equal <<CSS, render(<<SCSS) foo { a: d; } CSS foo {a: /* b; c: */ d} SCSS assert_equal <<CSS, render(<<SCSS) foo { a: d; } CSS foo {a /*: b; c */: d} SCSS end def test_crazy_comments # http://www.w3.org/Style/CSS/Test/CSS2.1/current/xhtml1/t040109-c17-comments-00-b.xht assert_equal <<CSS, render(<<SCSS) /* This is a CSS comment. */ .one { color: green; } /* Another comment */ /* The following should not be used: .two {color: red;} */ .three { color: green; /* color: red; */ } /** .four {color: red;} */ .five { color: green; } /**/ .six { color: green; } /*********/ .seven { color: green; } /* a comment **/ .eight { color: green; } CSS /* This is a CSS comment. */ .one {color: green;} /* Another comment */ /* The following should not be used: .two {color: red;} */ .three {color: green; /* color: red; */} /** .four {color: red;} */ .five {color: green;} /**/ .six {color: green;} /*********/ .seven {color: green;} /* a comment **/ .eight {color: green;} SCSS end def test_rule_comments assert_parses <<SCSS /* Foo */ .foo { a: b; } SCSS assert_equal <<CSS, render(<<SCSS) /* Foo * Bar */ .foo { a: b; } CSS /* Foo * Bar */.foo { a: b; } SCSS end def test_property_comments assert_parses <<SCSS .foo { /* Foo */ a: b; } SCSS assert_equal <<CSS, render(<<SCSS) .foo { /* Foo * Bar */ a: b; } CSS .foo { /* Foo * Bar */a: b; } SCSS end def test_selector_comments assert_equal <<CSS, render(<<SCSS) .foo #bar:baz(bip) { a: b; } CSS .foo /* .a #foo */ #bar:baz(/* bang )*/ bip) { a: b; } SCSS end def test_lonely_comments assert_parses <<SCSS /* Foo * Bar */ SCSS assert_parses <<SCSS .foo { /* Foo * Bar */ } SCSS end def test_multiple_comments assert_parses <<SCSS /* Foo * Bar */ /* Baz * Bang */ SCSS assert_parses <<SCSS .foo { /* Foo * Bar */ /* Baz * Bang */ } SCSS assert_equal <<CSS, render(<<SCSS) .foo { /* Foo Bar */ /* Baz Bang */ } CSS .foo { /* Foo Bar *//* Baz Bang */ } SCSS end def test_bizarrely_formatted_comments assert_parses <<SCSS .foo { /* Foo Bar Baz */ a: b; } SCSS assert_parses <<SCSS .foo { /* Foo Bar Baz */ a: b; } SCSS assert_equal <<CSS, render(<<SCSS) .foo { /* Foo Bar */ a: b; } CSS .foo {/* Foo Bar */ a: b; } SCSS assert_equal <<CSS, render(<<SCSS) .foo { /* Foo Bar Baz */ a: b; } CSS .foo {/* Foo Bar Baz */ a: b; } SCSS end ## Declarations def test_vendor_properties assert_parses <<SCSS foo { -moz-foo-bar: blat; -o-flat-blang: wibble; } SCSS end def test_empty_declarations assert_equal <<CSS, render(<<SCSS) foo { bar: baz; } CSS foo {;;;; bar: baz;;;; ;;} SCSS end def test_basic_property_types assert_parses <<SCSS foo { a: 2; b: 2.3em; c: 50%; d: "fraz bran"; e: flanny-blanny-blan; f: url(http://sass-lang.com); g: U+ffa?; h: #aabbcc; } SCSS end def test_functions assert_parses <<SCSS foo { a: foo-bar(12); b: -foo-bar-baz(13, 14 15); } SCSS end def test_unary_minus assert_parses <<SCSS foo { a: -2; b: -2.3em; c: -50%; d: -foo(bar baz); } SCSS end def test_operators assert_parses <<SCSS foo { a: foo bar baz; b: foo, #aabbcc, -12; c: 1px/2px/-3px; d: foo bar, baz/bang; } SCSS end def test_important assert_parses <<SCSS foo { a: foo !important; b: foo bar !important; b: foo, bar !important; } SCSS end def test_initial_hyphen assert_parses <<SCSS foo { a: -moz-bar-baz; b: foo -o-bar-baz; } SCSS end def test_ms_long_filter_syntax assert_equal <<CSS, render(<<SCSS) foo { filter: progid:DXImageTransform.Microsoft.gradient(GradientType=1, startColorstr=#c0ff3300, endColorstr=#ff000000); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=1, startColorstr=#c0ff3300, endColorstr=#ff000000); } CSS foo { filter: progid:DXImageTransform.Microsoft.gradient(GradientType=1, startColorstr=#c0ff3300, endColorstr=#ff000000); filter:progid:DXImageTransform.Microsoft.gradient(GradientType=1, startColorstr=#c0ff3300, endColorstr=#ff000000); } SCSS end def test_ms_short_filter_syntax assert_parses <<SCSS foo { filter: alpha(opacity=20); filter: alpha(opacity=20, enabled=true); filter: blaznicate(foo=bar, baz=bang bip, bart=#fa4600); } SCSS end def test_declaration_hacks assert_parses <<SCSS foo { _name: val; *name: val; :name: val; .name: val; #name: val; name/**/: val; name/*\\**/: val; name: val; } SCSS end def test_trailing_hash_hack assert_parses <<SCSS foo { foo: bar; #baz: bang; #bip: bop; } SCSS end def test_zero_arg_functions assert_parses <<SCSS foo { a: foo(); b: bar baz-bang() bip; } SCSS end def test_expression_function assert_parses <<SCSS foo { a: 12px expression(1 + (3 / Foo.bar("baz" + "bang") + function() {return 12;}) % 12); } SCSS end def test_calc_function assert_parses <<SCSS foo { a: 12px calc(100%/3 - 2*1em - 2*1px); b: 12px -moz-calc(100%/3 - 2*1em - 2*1px); b: 12px -webkit-calc(100%/3 - 2*1em - 2*1px); b: 12px -foobar-calc(100%/3 - 2*1em - 2*1px); } SCSS end def test_element_function assert_parses <<SCSS foo { a: -moz-element(#foo); b: -webkit-element(#foo); b: -foobar-element(#foo); } SCSS end def test_unary_ops assert_equal <<CSS, render(<<SCSS) foo { a: -0.5em; b: +0.5em; c: -foo(12px); d: +foo(12px); } CSS foo { a: -0.5em; b: +0.5em; c: -foo(12px); d: +foo(12px); } SCSS end def test_css_string_escapes assert_parses <<SCSS foo { a: "\\foo bar"; b: "foo\\ bar"; c: "\\2022 \\0020"; d: "foo\\\\bar"; e: "foo\\"'bar"; } SCSS end def test_css_ident_escapes assert_parses <<SCSS foo { a: \\foo bar; b: foo\\ bar; c: \\2022 \\0020; d: foo\\\\bar; e: foo\\"\\'bar; } SCSS end ## Directives def test_namespace_directive assert_parses '@namespace "http://www.w3.org/Profiles/xhtml1-strict";' assert_parses '@namespace url(http://www.w3.org/Profiles/xhtml1-strict);' assert_parses '@namespace html url("http://www.w3.org/Profiles/xhtml1-strict");' end def test_media_directive assert_parses <<SCSS @media all { rule1 { prop: val; } rule2 { prop: val; } } SCSS assert_parses <<SCSS @media screen, print { rule1 { prop: val; } rule2 { prop: val; } } SCSS end def test_media_directive_with_keywords assert_parses <<SCSS @media screen and (-webkit-min-device-pixel-ratio: 0) { a: b; } SCSS assert_parses <<SCSS @media only screen, print and (foo: 0px) and (bar: flam(12px solid)) { a: b; } SCSS end def test_import_directive assert_parses '@import "foo.css";' assert_parses '@import url("foo.css");' assert_parses "@import url('foo.css');" assert_parses '@import url(foo.css);' assert_equal <<CSS, render(<<SCSS) @import "foo.css"; CSS @import 'foo.css'; SCSS end def test_import_directive_with_backslash_newline assert_equal <<CSS, render(<<SCSS) @import "foobar.css"; CSS @import "foo\\ bar.css"; SCSS end def test_string_import_directive_with_media assert_parses '@import "foo.css" screen;' assert_parses '@import "foo.css" screen, print;' assert_parses '@import "foo.css" screen, print and (foo: 0);' assert_parses '@import "foo.css" screen, only print, screen and (foo: 0);' end def test_url_import_directive_with_media assert_parses '@import url("foo.css") screen;' assert_parses '@import url("foo.css") screen, print;' assert_parses '@import url("foo.css") screen, print and (foo: 0);' assert_parses '@import url("foo.css") screen, only print, screen and (foo: 0);' end def test_page_directive assert_parses <<SCSS @page { prop1: val; prop2: val; } SCSS assert_parses <<SCSS @page flap { prop1: val; prop2: val; } SCSS assert_parses <<SCSS @page :first { prop1: val; prop2: val; } SCSS assert_parses <<SCSS @page flap:first { prop1: val; prop2: val; } SCSS end def test_blockless_directive_without_semicolon assert_equal "@foo \"bar\";\n", render('@foo "bar"') end def test_directive_with_lots_of_whitespace assert_equal "@foo \"bar\";\n", render('@foo "bar" ;') end def test_empty_blockless_directive assert_parses "@foo;" end def test_multiple_blockless_directives assert_parses <<SCSS @foo bar; @bar baz; SCSS end def test_empty_block_directive assert_parses "@foo {}" assert_equal "@foo {}\n", render(<<SCSS) @foo { } SCSS end def test_multiple_block_directives assert_parses <<SCSS @foo bar { a: b; } @bar baz { c: d; } SCSS end def test_block_directive_with_rule_and_property assert_parses <<SCSS @foo { rule { a: b; } a: b; } SCSS end def test_block_directive_with_semicolon assert_equal <<CSS, render(<<SCSS) @foo { a: b; } @bar { a: b; } CSS @foo {a:b}; @bar {a:b}; SCSS end def test_moz_document_directive assert_equal <<CSS, render(<<SCSS) @-moz-document url(http://www.w3.org/), url-prefix(http://www.w3.org/Style/), domain(mozilla.org), regexp("^https:.*") { .foo { a: b; } } CSS @-moz-document url(http://www.w3.org/), url-prefix(http://www.w3.org/Style/), domain(mozilla.org), regexp("^https:.*") { .foo {a: b} } SCSS end def test_supports assert_equal <<CSS, render(<<SCSS) @supports (((a: b) and (c: d)) or (not (d: e))) and ((not (f: g)) or (not ((h: i) and (j: k)))) { .foo { a: b; } } @supports (a: b) { .foo { a: b; } } CSS @supports (((a: b) and (c: d)) or (not (d: e))) and ((not (f: g)) or (not ((h: i) and (j: k)))) { .foo { a: b; } } @supports (a: b) { .foo { a: b; } } SCSS end def test_supports_with_prefix assert_equal <<CSS, render(<<SCSS) @-prefix-supports (((a: b) and (c: d)) or (not (d: e))) and ((not (f: g)) or (not ((h: i) and (j: k)))) { .foo { a: b; } } CSS @-prefix-supports (((a: b) and (c: d)) or (not (d: e))) and ((not (f: g)) or (not ((h: i) and (j: k)))) { .foo { a: b; } } SCSS end def test_supports_allows_similar_operators_without_parens assert_equal <<CSS, render(<<SCSS) @supports (a: b) and (c: d) and (e: f) { .foo { a: b; } } @supports (a: b) or (c: d) or (e: f) { .foo { a: b; } } CSS @supports (a: b) and (c: d) and (e: f) { .foo { a: b; } } @supports (a: b) or (c: d) or (e: f) { .foo { a: b; } } SCSS end def test_keyframes assert_equal <<CSS, render(<<SCSS) @keyframes identifier { 0% { top: 0; left: 0; } 30% { top: 50px; } 68%, 72% { left: 50px; } 100% { top: 100px; left: 100%; } } CSS @keyframes identifier { 0% {top: 0; left: 0} 30% {top: 50px} 68%, 72% {left: 50px} 100% {top: 100px; left: 100%} } SCSS end def test_keyframes_with_empty_rules assert_equal <<CSS, render(<<SCSS) @keyframes identifier { 50% { background-color: black; } } CSS @keyframes identifier { 0% {} 50% {background-color: black} 100% {} } SCSS end def test_keyframes_with_custom_identifiers assert_equal <<CSS, render(<<SCSS) @-skrollr-keyframes identifier { center-top { left: 100%; } top-bottom { left: 0%; } } CSS @-skrollr-keyframes identifier { center-top { left: 100%; } top-bottom { left: 0%; } } SCSS end ## Selectors # Taken from http://dev.w3.org/csswg/selectors4/#overview def test_summarized_selectors_with_element assert_selector_parses('*') assert_selector_parses('E') assert_selector_parses('E:not(s)') assert_selector_parses('E:not(s1, s2)') assert_selector_parses('E:matches(s1, s2)') assert_selector_parses('E:has(s1, s2)') assert_selector_parses('E:has(> s1, > s2)') assert_selector_parses('E.warning') assert_selector_parses('E#myid') assert_selector_parses('E[foo]') assert_selector_parses('E[foo="bar"]') assert_selector_parses('E[foo="bar" i]') assert_selector_parses('E[foo~="bar"]') assert_selector_parses('E[foo^="bar"]') assert_selector_parses('E[foo$="bar"]') assert_selector_parses('E[foo*="bar"]') assert_selector_parses('E[foo|="en"]') assert_selector_parses('E:dir(ltr)') assert_selector_parses('E:lang(fr)') assert_selector_parses('E:lang(zh, *-hant)') assert_selector_parses('E:any-link') assert_selector_parses('E:link') assert_selector_parses('E:visited') assert_selector_parses('E:local-link') assert_selector_parses('E:local-link(0)') assert_selector_parses('E:target') assert_selector_parses('E:scope') assert_selector_parses('E:current') assert_selector_parses('E:current(s)') assert_selector_parses('E:past') assert_selector_parses('E:future') assert_selector_parses('E:active') assert_selector_parses('E:hover') assert_selector_parses('E:focus') assert_selector_parses('E:enabled') assert_selector_parses('E:disabled') assert_selector_parses('E:checked') assert_selector_parses('E:indeterminate') assert_selector_parses('E:default') assert_selector_parses('E:in-range') assert_selector_parses('E:out-of-range') assert_selector_parses('E:required') assert_selector_parses('E:optional') assert_selector_parses('E:read-only') assert_selector_parses('E:read-write') assert_selector_parses('E:root') assert_selector_parses('E:empty') assert_selector_parses('E:first-child') assert_selector_parses('E:nth-child(n)') assert_selector_parses('E:last-child') assert_selector_parses('E:nth-last-child(n)') assert_selector_parses('E:only-child') assert_selector_parses('E:first-of-type') assert_selector_parses('E:nth-of-type(n)') assert_selector_parses('E:last-of-type') assert_selector_parses('E:nth-last-of-type(n)') assert_selector_parses('E:only-of-type') assert_selector_parses('E:nth-child(n of selector)') assert_selector_parses('E:nth-last-child(n of selector)') assert_selector_parses('E:nth-child(n)') assert_selector_parses('E:nth-last-child(n)') assert_selector_parses('E F') assert_selector_parses('E > F') assert_selector_parses('E + F') assert_selector_parses('E ~ F') silence_warnings {assert_selector_parses('E /foo/ F')} silence_warnings {assert_selector_parses('E! > F')} silence_warnings {assert_selector_parses('E /ns|foo/ F')} # From http://dev.w3.org/csswg/css-scoping-1/ assert_selector_parses('E:host(s)') assert_selector_parses('E:host-context(s)') end # Taken from http://dev.w3.org/csswg/selectors4/#overview, but without element # names. def test_more_summarized_selectors assert_selector_parses(':not(s)') assert_selector_parses(':not(s1, s2)') assert_selector_parses(':matches(s1, s2)') assert_selector_parses(':has(s1, s2)') assert_selector_parses(':has(> s1, > s2)') assert_selector_parses('.warning') assert_selector_parses('#myid') assert_selector_parses('[foo]') assert_selector_parses('[foo="bar"]') assert_selector_parses('[foo="bar" i]') assert_selector_parses('[foo~="bar"]') assert_selector_parses('[foo^="bar"]') assert_selector_parses('[foo$="bar"]') assert_selector_parses('[foo*="bar"]') assert_selector_parses('[foo|="en"]') assert_selector_parses(':dir(ltr)') assert_selector_parses(':lang(fr)') assert_selector_parses(':lang(zh, *-hant)') assert_selector_parses(':any-link') assert_selector_parses(':link') assert_selector_parses(':visited') assert_selector_parses(':local-link') assert_selector_parses(':local-link(0)') assert_selector_parses(':target') assert_selector_parses(':scope') assert_selector_parses(':current') assert_selector_parses(':current(s)') assert_selector_parses(':past') assert_selector_parses(':future') assert_selector_parses(':active') assert_selector_parses(':hover') assert_selector_parses(':focus') assert_selector_parses(':enabled') assert_selector_parses(':disabled') assert_selector_parses(':checked') assert_selector_parses(':indeterminate') assert_selector_parses(':default') assert_selector_parses(':in-range') assert_selector_parses(':out-of-range') assert_selector_parses(':required') assert_selector_parses(':optional') assert_selector_parses(':read-only') assert_selector_parses(':read-write') assert_selector_parses(':root') assert_selector_parses(':empty') assert_selector_parses(':first-child') assert_selector_parses(':nth-child(n)') assert_selector_parses(':last-child') assert_selector_parses(':nth-last-child(n)') assert_selector_parses(':only-child') assert_selector_parses(':first-of-type') assert_selector_parses(':nth-of-type(n)') assert_selector_parses(':last-of-type') assert_selector_parses(':nth-last-of-type(n)') assert_selector_parses(':only-of-type') assert_selector_parses(':nth-child(n of selector)') assert_selector_parses(':nth-last-child(n of selector)') assert_selector_parses(':nth-child(n)') assert_selector_parses(':nth-last-child(n)') # From http://dev.w3.org/csswg/css-scoping-1/ assert_selector_parses(':host(s)') assert_selector_parses(':host-context(s)') end def test_attribute_selectors_with_identifiers assert_selector_parses('[foo~=bar]') assert_selector_parses('[foo^=bar]') assert_selector_parses('[foo$=bar]') assert_selector_parses('[foo*=bar]') assert_selector_parses('[foo|=en]') end def test_nth_selectors assert_selector_parses(':nth-child(-n)') assert_selector_parses(':nth-child(+n)') assert_selector_parses(':nth-child(even)') assert_selector_parses(':nth-child(odd)') assert_selector_parses(':nth-child(50)') assert_selector_parses(':nth-child(-50)') assert_selector_parses(':nth-child(+50)') assert_selector_parses(':nth-child(2n+3)') assert_selector_parses(':nth-child(2n-3)') assert_selector_parses(':nth-child(+2n-3)') assert_selector_parses(':nth-child(-2n+3)') assert_selector_parses(':nth-child(-2n+ 3)') assert_equal(<<CSS, render(<<SCSS)) :nth-child(2n + 3) { a: b; } CSS :nth-child( 2n + 3 ) { a: b; } SCSS end def test_selectors_containing_selectors assert_selector_can_contain_selectors(':not(<sel>)') assert_selector_can_contain_selectors(':current(<sel>)') assert_selector_can_contain_selectors(':nth-child(n of <sel>)') assert_selector_can_contain_selectors(':nth-last-child(n of <sel>)') assert_selector_can_contain_selectors(':-moz-any(<sel>)') assert_selector_can_contain_selectors(':has(<sel>)') assert_selector_can_contain_selectors(':has(+ <sel>)') assert_selector_can_contain_selectors(':host(<sel>)') assert_selector_can_contain_selectors(':host-context(<sel>)') end def assert_selector_can_contain_selectors(sel) try = lambda {|subsel| assert_selector_parses(sel.gsub('<sel>', subsel))} try['foo|bar'] try['*|bar'] try['foo|*'] try['*|*'] try['#blah'] try['.blah'] try['[foo]'] try['[foo^="bar"]'] try['[baz|foo~="bar"]'] try[':hover'] try[':nth-child(2n + 3)'] try['h1, h2, h3'] try['#foo, bar, [baz]'] # Not technically allowed for most selectors, but what the heck try[':not(#foo)'] try['a#foo.bar'] try['#foo .bar > baz'] end def test_namespaced_selectors assert_selector_parses('foo|E') assert_selector_parses('*|E') assert_selector_parses('foo|*') assert_selector_parses('*|*') end def test_namespaced_attribute_selectors assert_selector_parses('[foo|bar=baz]') assert_selector_parses('[*|bar=baz]') assert_selector_parses('[foo|bar|=baz]') end def test_comma_selectors assert_selector_parses('E, F') assert_selector_parses('E F, G H') assert_selector_parses('E > F, G > H') end def test_selectors_with_newlines assert_selector_parses("E,\nF") assert_selector_parses("E\nF") assert_selector_parses("E, F\nG, H") end def test_expression_fallback_selectors assert_directive_parses('0%') assert_directive_parses('60%') assert_directive_parses('100%') assert_directive_parses('12px') assert_directive_parses('"foo"') end def test_functional_pseudo_selectors assert_selector_parses(':foo("bar")') assert_selector_parses(':foo(bar)') assert_selector_parses(':foo(12px)') assert_selector_parses(':foo(+)') assert_selector_parses(':foo(-)') assert_selector_parses(':foo(+"bar")') assert_selector_parses(':foo(-++--baz-"bar"12px)') end def test_selector_hacks assert_selector_parses('> E') assert_selector_parses('+ E') assert_selector_parses('~ E') assert_selector_parses('> > E') assert_equal <<CSS, render(<<SCSS) > > E { a: b; } CSS >> E { a: b; } SCSS assert_selector_parses('E*') assert_selector_parses('E*.foo') assert_selector_parses('E*:hover') end def test_spaceless_combo_selectors assert_equal "E > F {\n a: b; }\n", render("E>F { a: b;} ") assert_equal "E ~ F {\n a: b; }\n", render("E~F { a: b;} ") assert_equal "E + F {\n a: b; }\n", render("E+F { a: b;} ") end def test_escapes_in_selectors assert_selector_parses('.\!foo') assert_selector_parses('.\66 foo') assert_selector_parses('.\21 foo') end def test_subject_selector_deprecation assert_warning(<<WARNING) {render(".foo .bar! .baz {a: b}")} DEPRECATION WARNING on line 1, column 1: 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: .foo .bar:has(.baz) WARNING assert_warning(<<WARNING) {render(".foo .bar! > .baz {a: b}")} DEPRECATION WARNING on line 1, column 1: 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: .foo .bar:has(> .baz) WARNING assert_warning(<<WARNING) {render(".foo .bar! {a: b}")} DEPRECATION WARNING on line 1, column 1: 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: .foo .bar WARNING end ## Errors def test_invalid_directives assert_not_parses("identifier", '@<err> import "foo";') assert_not_parses("identifier", '@<err>12 "foo";') end def test_invalid_classes assert_not_parses("class name", 'p.<err> foo {a: b}') assert_not_parses("class name", 'p.<err>1foo {a: b}') end def test_invalid_ids assert_not_parses("id name", 'p#<err> foo {a: b}') end def test_no_properties_at_toplevel assert_not_parses('pseudoclass or pseudoelement', 'a:<err> b;') end def test_no_scss_directives assert_parses('@import "foo.sass";') assert_parses <<SCSS @mixin foo { a: b; } SCSS end def test_no_variables assert_not_parses("selector or at-rule", "<err>$var = 12;") assert_not_parses('"}"', "foo { <err>!var = 12; }") end def test_no_parent_selectors assert_not_parses('"{"', "foo <err>&.bar {a: b}") end def test_no_selector_interpolation assert_not_parses('"{"', 'foo <err>#{"bar"}.baz {a: b}') end def test_no_prop_name_interpolation assert_not_parses('":"', 'foo {a<err>#{"bar"}baz: b}') end def test_no_prop_val_interpolation assert_not_parses('"}"', 'foo {a: b <err>#{"bar"} c}') end def test_no_string_interpolation assert_parses <<SCSS foo { a: "bang \#{1 + " bar "} bip"; } SCSS end def test_no_sass_script_values assert_not_parses('"}"', 'foo {a: b <err>* c}') end def test_no_nested_rules assert_not_parses('":"', 'foo {bar <err>{a: b}}') assert_not_parses('"}"', 'foo {<err>[bar=baz] {a: b}}') end def test_no_nested_properties assert_not_parses('expression (e.g. 1px, bold)', 'foo {bar: <err>{a: b}}') assert_not_parses('expression (e.g. 1px, bold)', 'foo {bar: bang <err>{a: b}}') end def test_no_nested_directives assert_not_parses('"}"', 'foo {<err>@bar {a: b}}') end def test_error_with_windows_newlines render <<SCSS foo {bar}\r baz {a: b} SCSS assert(false, "Expected syntax error") rescue Sass::SyntaxError => e assert_equal 'Invalid CSS after "foo {bar": expected ":", was "}"', e.message assert_equal 1, e.sass_line end def test_newline_in_property_value assert_equal(<<CSS, render(<<SCSS)) .foo { bar: "bazbang"; } CSS .foo { bar: "baz\\ bang"; } SCSS end ## Regressions def test_very_long_comment_doesnt_take_forever string = 'asdf' * (100000) assert_equal(<<CSS, render(<<SCSS)) /* #{string} */ CSS /* #{string} */ SCSS end def test_long_unclosed_comment_doesnt_take_forever assert_raise_message(Sass::SyntaxError, 'Invalid CSS after "/*": expected "/", was "//*************..."') {render(<<SCSS)} /* //************************************************************************** SCSS end def test_double_space_string assert_equal(<<CSS, render(<<SCSS)) .a { content: " a"; } CSS .a { content: " a"; } SCSS end def test_very_long_number_with_important_doesnt_take_forever assert_equal(<<CSS, render(<<SCSS)) .foo { width: 97.916666666666666666666666666667% !important; } CSS .foo { width: 97.916666666666666666666666666667% !important; } SCSS end def test_selector_without_closing_bracket assert_not_parses('"]"', "foo[bar <err>{a: b}") end def test_closing_line_comment_end_with_compact_output assert_equal(<<CSS, render(<<SCSS, :style => :compact)) /* foo */ bar { baz: bang; } CSS /* * foo */ bar {baz: bang} SCSS end def test_single_line_comment_within_multiline_comment assert_equal(<<CSS, render(<<SCSS)) body { /* //comment here */ } CSS body { /* //comment here */ } SCSS end def test_malformed_media render <<SCSS @media { margin: 0; } SCSS assert(false, "Expected syntax error") rescue Sass::SyntaxError => e assert_equal 'Invalid CSS after "@media ": expected media query (e.g. print, screen, print and screen), was "{"', e.message assert_equal 1, e.sass_line end private def assert_selector_parses(selector) assert_parses <<SCSS #{selector} { a: b; } SCSS assert_parses <<SCSS :not(#{selector}) { a: b; } SCSS end def assert_directive_parses(param) assert_parses <<SCSS @unknown #{param} { a: b; } SCSS end def render(scss, options = {}) tree = Sass::SCSS::CssParser.new(scss, options[:filename], nil).parse tree.options = Sass::Engine::DEFAULT_OPTIONS.merge(options) tree.render 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/test/sass/scss/rx_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/scss/rx_test.rb
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/../../test_helper' require 'sass/engine' class ScssRxTest < MiniTest::Test include Sass::SCSS::RX def test_identifiers assert_match IDENT, "foo" assert_match IDENT, "\xC3\xBFoo" # Initial char can be nonascii assert_match IDENT, "\\123abcoo" # Initial char can be unicode escape assert_match IDENT, "\\f oo" # Unicode escapes can be followed by whitespace assert_match IDENT, "\\fa\too" assert_match IDENT, "\\ff2\roo" assert_match IDENT, "\\f13a\foo" assert_match IDENT, "\\f13abcoo" assert_match IDENT, "\\ oo" # Initial char can be a plain escape as well assert_match IDENT, "\\~oo" assert_match IDENT, "\\\\oo" assert_match IDENT, "\\{oo" assert_match IDENT, "\\\xC3\xBFoo" assert_match IDENT, "-foo" # Can put a - before anything assert_match IDENT, "-\xC3\xBFoo" assert_match IDENT, "-\\f oo" assert_match IDENT, "_foo" # Can put a _ before anything assert_match IDENT, "_\xC3\xBFoo" assert_match IDENT, "_\\f oo" assert_match IDENT, "--foo" # "Custom" identifier assert_match IDENT, "foo-bar" assert_match IDENT, "f012-23" assert_match IDENT, "foo_-_bar" assert_match IDENT, "f012_23" # http://www.w3.org/Style/CSS/Test/CSS2.1/current/xhtml1/escapes-003.xht assert_match IDENT, "c\\lass" # http://www.w3.org/Style/CSS/Test/CSS2.1/current/xhtml1/escapes-004.xht assert_match IDENT, "c\\00006Cas\\000073" # http://www.w3.org/Style/CSS/Test/CSS2.1/current/xhtml1/ident-001.xht assert_match IDENT, "IdE6n-3t0_6" # http://www.w3.org/Style/CSS/Test/CSS2.1/current/xhtml1/ident-006.xht assert_match IDENT, "\\6000ident" # http://www.w3.org/Style/CSS/Test/CSS2.1/current/xhtml1/ident-007.xht assert_match IDENT, "iden\\6000t\\6000" # http://www.w3.org/Style/CSS/Test/CSS2.1/current/xhtml1/ident-013.xht assert_match IDENT, "\\-ident" end def test_underscores_in_identifiers assert_match IDENT, "foo_bar" assert_match IDENT, "_\xC3\xBFfoo" assert_match IDENT, "__foo" assert_match IDENT, "_1foo" assert_match IDENT, "-_foo" assert_match IDENT, "_-foo" end def test_invalid_identifiers assert_no_match IDENT, "" assert_no_match IDENT, "1foo" assert_no_match IDENT, "-1foo" assert_no_match IDENT, "foo bar" assert_no_match IDENT, "foo~bar" # http://www.w3.org/Style/CSS/Test/CSS2.1/current/xhtml1/escapes-008.xht assert_no_match IDENT, "c\\06C ass" assert_no_match IDENT, "back\\67\n round" end def test_double_quote_strings assert_match STRING, '"foo bar"' assert_match STRING, '"foo\\\nbar"' assert_match STRING, "\"\\\"\"" assert_match STRING, '"\t !#$%&(-~()*+,-./0123456789~"' end def test_single_quote_strings assert_match STRING, "'foo bar'" assert_match STRING, "'foo\\\nbar'" assert_match STRING, "'\\''" assert_match STRING, "'\t !#\$%&(-~()*+,-./0123456789~'" end def test_invalid_strings assert_no_match STRING, "\"foo\nbar\"" assert_no_match STRING, "\"foo\"bar\"" assert_no_match STRING, "'foo\nbar'" assert_no_match STRING, "'foo'bar'" end def test_uri assert_match URI, 'url("foo bar)")' assert_match URI, "url('foo bar)')" assert_match URI, 'url( "foo bar)" )' assert_match URI, "url(#\\%&**+,-./0123456789~)" end def test_invalid_uri assert_no_match URI, 'url(foo)bar)' end def test_unicode_range assert_match UNICODERANGE, 'U+00-Ff' assert_match UNICODERANGE, 'u+980-9FF' assert_match UNICODERANGE, 'U+9aF??' assert_match UNICODERANGE, 'U+??' end def test_escape_empty_ident assert_equal "", Sass::SCSS::RX.escape_ident("") end def test_escape_just_prefix_ident assert_equal "\\-", Sass::SCSS::RX.escape_ident("-") assert_equal "\\_", Sass::SCSS::RX.escape_ident("_") end def test_escape_plain_ident assert_equal "foo", Sass::SCSS::RX.escape_ident("foo") assert_equal "foo-1bar", Sass::SCSS::RX.escape_ident("foo-1bar") assert_equal "-foo-bar", Sass::SCSS::RX.escape_ident("-foo-bar") assert_equal "f2oo_bar", Sass::SCSS::RX.escape_ident("f2oo_bar") assert_equal "_foo_bar", Sass::SCSS::RX.escape_ident("_foo_bar") end def test_escape_initial_funky_ident assert_equal "\\000035foo", Sass::SCSS::RX.escape_ident("5foo") assert_equal "-\\000035foo", Sass::SCSS::RX.escape_ident("-5foo") assert_equal "_\\000035foo", Sass::SCSS::RX.escape_ident("_5foo") assert_equal "\\&foo", Sass::SCSS::RX.escape_ident("&foo") assert_equal "-\\&foo", Sass::SCSS::RX.escape_ident("-&foo") assert_equal "-\\ foo", Sass::SCSS::RX.escape_ident("- foo") end def test_escape_mid_funky_ident assert_equal "foo\\&bar", Sass::SCSS::RX.escape_ident("foo&bar") assert_equal "foo\\ \\ bar", Sass::SCSS::RX.escape_ident("foo bar") assert_equal "foo\\00007fbar", Sass::SCSS::RX.escape_ident("foo\177bar") end def test_no_static_hyphenated_units assert_no_match STATIC_VALUE, "20px-20px" end private def assert_match(rx, str) refute_nil(match = rx.match(str)) assert_equal str.size, match[0].size end def assert_no_match(rx, str) match = rx.match(str) refute_equal str.size, match && match[0].size 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/test/sass/scss/scss_test.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/test/sass/scss/scss_test.rb
# -*- coding: utf-8 -*- require File.dirname(__FILE__) + '/test_helper' class ScssTest < MiniTest::Test include ScssTestHelper ## One-Line Comments def test_one_line_comments assert_equal <<CSS, render(<<SCSS) .foo { baz: bang; } CSS .foo {// bar: baz;} baz: bang; //} } SCSS assert_equal <<CSS, render(<<SCSS) .foo bar[val="//"] { baz: bang; } CSS .foo bar[val="//"] { baz: bang; //} } SCSS end ## Script def test_variables assert_equal <<CSS, render(<<SCSS) blat { a: foo; } CSS $var: foo; blat {a: $var} SCSS assert_equal <<CSS, render(<<SCSS) foo { a: 2; b: 6; } CSS foo { $var: 2; $another-var: 4; a: $var; b: $var + $another-var;} SCSS end def test_unicode_variables assert_equal <<CSS, render(<<SCSS) blat { a: foo; } CSS $vär: foo; blat {a: $vär} SCSS end def test_guard_assign assert_equal <<CSS, render(<<SCSS) foo { a: 1; } CSS $var: 1; $var: 2 !default; foo {a: $var} SCSS assert_equal <<CSS, render(<<SCSS) foo { a: 2; } CSS $var: 2 !default; foo {a: $var} SCSS end def test_sass_script assert_equal <<CSS, render(<<SCSS) foo { a: 3; b: -1; c: foobar; d: 12px; } CSS foo { a: 1 + 2; b: 1 - 2; c: foo + bar; d: floor(12.3px); } SCSS end def test_debug_directive assert_warning "test_debug_directive_inline.scss:2 DEBUG: hello world!" do assert_equal <<CSS, render(<<SCSS) foo { a: b; } bar { c: d; } CSS foo {a: b} @debug "hello world!"; bar {c: d} SCSS end end def test_error_directive assert_raise_message(Sass::SyntaxError, "hello world!") {render(<<SCSS)} foo {a: b} @error "hello world!"; bar {c: d} SCSS end def test_warn_directive expected_warning = <<EXPECTATION WARNING: this is a warning on line 2 of test_warn_directive_inline.scss WARNING: this is a mixin on line 1 of test_warn_directive_inline.scss, in `foo' from line 3 of test_warn_directive_inline.scss EXPECTATION assert_warning expected_warning do assert_equal <<CSS, render(<<SCSS) bar { c: d; } CSS @mixin foo { @warn "this is a mixin";} @warn "this is a warning"; bar {c: d; @include foo;} SCSS end end def test_for_directive assert_equal <<CSS, render(<<SCSS) .foo { a: 1; a: 2; a: 3; a: 4; } CSS .foo { @for $var from 1 to 5 {a: $var;} } SCSS assert_equal <<CSS, render(<<SCSS) .foo { a: 1; a: 2; a: 3; a: 4; a: 5; } CSS .foo { @for $var from 1 through 5 {a: $var;} } SCSS end def test_for_directive_with_same_start_and_end assert_equal <<CSS, render(<<SCSS) CSS .foo { @for $var from 1 to 1 {a: $var;} } SCSS assert_equal <<CSS, render(<<SCSS) .foo { a: 1; } CSS .foo { @for $var from 1 through 1 {a: $var;} } SCSS end def test_decrementing_estfor_directive assert_equal <<CSS, render(<<SCSS) .foo { a: 5; a: 4; a: 3; a: 2; a: 1; } CSS .foo { @for $var from 5 through 1 {a: $var;} } SCSS assert_equal <<CSS, render(<<SCSS) .foo { a: 5; a: 4; a: 3; a: 2; } CSS .foo { @for $var from 5 to 1 {a: $var;} } SCSS end def test_if_directive assert_equal <<CSS, render(<<SCSS) foo { a: b; } CSS @if "foo" == "foo" {foo {a: b}} @if "foo" != "foo" {bar {a: b}} SCSS assert_equal <<CSS, render(<<SCSS) bar { a: b; } CSS @if "foo" != "foo" {foo {a: b}} @else if "foo" == "foo" {bar {a: b}} @else if true {baz {a: b}} SCSS assert_equal <<CSS, render(<<SCSS) bar { a: b; } CSS @if "foo" != "foo" {foo {a: b}} @else {bar {a: b}} SCSS end def test_comment_after_if_directive assert_equal <<CSS, render(<<SCSS) foo { a: b; /* This is a comment */ c: d; } CSS foo { @if true {a: b} /* This is a comment */ c: d } SCSS assert_equal <<CSS, render(<<SCSS) foo { a: b; /* This is a comment */ c: d; } CSS foo { @if true {a: b} @else {x: y} /* This is a comment */ c: d } SCSS end def test_while_directive assert_equal <<CSS, render(<<SCSS) .foo { a: 1; a: 2; a: 3; a: 4; } CSS $i: 1; .foo { @while $i != 5 { a: $i; $i: $i + 1 !global; } } SCSS end def test_each_directive assert_equal <<CSS, render(<<SCSS) a { b: 1px; b: 2px; b: 3px; b: 4px; } c { d: foo; d: bar; d: baz; d: bang; } CSS a { @each $number in 1px 2px 3px 4px { b: $number; } } c { @each $str in foo, bar, baz, bang { d: $str; } } SCSS end def test_destructuring_each_directive assert_equal <<CSS, render(<<SCSS) a { foo: 1px; bar: 2px; baz: 3px; } c { foo: "Value is bar"; bar: "Value is baz"; bang: "Value is "; } CSS a { @each $name, $number in (foo: 1px, bar: 2px, baz: 3px) { \#{$name}: $number; } } c { @each $key, $value in (foo bar) (bar, baz) bang { \#{$key}: "Value is \#{$value}"; } } SCSS end def test_css_import_directive assert_equal "@import url(foo.css);\n", render('@import "foo.css";') assert_equal "@import url(foo.css);\n", render("@import 'foo.css';") assert_equal "@import url(\"foo.css\");\n", render('@import url("foo.css");') assert_equal "@import url(\"foo.css\");\n", render('@import url("foo.css");') assert_equal "@import url(foo.css);\n", render('@import url(foo.css);') end def test_css_string_import_directive_with_media assert_parses '@import "foo.css" screen;' assert_parses '@import "foo.css" screen, print;' assert_parses '@import "foo.css" screen, print and (foo: 0);' assert_parses '@import "foo.css" screen, only print, screen and (foo: 0);' end def test_css_url_import_directive_with_media assert_parses '@import url("foo.css") screen;' assert_parses '@import url("foo.css") screen, print;' assert_parses '@import url("foo.css") screen, print and (foo: 0);' assert_parses '@import url("foo.css") screen, only print, screen and (foo: 0);' end def test_media_import assert_equal("@import \"./fonts.sass\" all;\n", render("@import \"./fonts.sass\" all;")) end def test_dynamic_media_import assert_equal(<<CSS, render(<<SCSS)) @import "foo" print and (-webkit-min-device-pixel-ratio-foo: 25); CSS $media: print; $key: -webkit-min-device-pixel-ratio; $value: 20; @import "foo" \#{$media} and ($key + "-foo": $value + 5); SCSS end def test_http_import assert_equal("@import \"http://fonts.googleapis.com/css?family=Droid+Sans\";\n", render("@import \"http://fonts.googleapis.com/css?family=Droid+Sans\";")) end def test_protocol_relative_import assert_equal("@import \"//fonts.googleapis.com/css?family=Droid+Sans\";\n", render("@import \"//fonts.googleapis.com/css?family=Droid+Sans\";")) end def test_import_with_interpolation assert_equal <<CSS, render(<<SCSS) @import url("http://fonts.googleapis.com/css?family=Droid+Sans"); CSS $family: unquote("Droid+Sans"); @import url("http://fonts.googleapis.com/css?family=\#{$family}"); SCSS end def test_url_import assert_equal("@import url(fonts.sass);\n", render("@import url(fonts.sass);")) end def test_css_import_doesnt_move_through_comments assert_equal <<CSS, render(<<SCSS) /* Comment 1 */ @import url("foo.css"); /* Comment 2 */ @import url("bar.css"); CSS /* Comment 1 */ @import url("foo.css"); /* Comment 2 */ @import url("bar.css"); SCSS end def test_css_import_movement_stops_at_comments assert_equal <<CSS, render(<<SCSS) /* Comment 1 */ @import url("foo.css"); /* Comment 2 */ @import url("bar.css"); .foo { a: b; } /* Comment 3 */ CSS /* Comment 1 */ @import url("foo.css"); /* Comment 2 */ .foo {a: b} /* Comment 3 */ @import url("bar.css"); SCSS end def test_block_comment_in_script assert_equal <<CSS, render(<<SCSS) foo { a: 1bar; } CSS foo {a: 1 + /* flang */ bar} SCSS end def test_line_comment_in_script assert_equal <<CSS, render(<<SCSS) foo { a: 1blang; } CSS foo {a: 1 + // flang } blang } SCSS end def test_static_hyphenated_unit assert_equal <<CSS, render(<<SCSS) foo { a: 0px; } CSS foo {a: 10px-10px } SCSS end ## Nested Rules def test_nested_rules assert_equal <<CSS, render(<<SCSS) foo bar { a: b; } CSS foo {bar {a: b}} SCSS assert_equal <<CSS, render(<<SCSS) foo bar { a: b; } foo baz { b: c; } CSS foo { bar {a: b} baz {b: c}} SCSS assert_equal <<CSS, render(<<SCSS) foo bar baz { a: b; } foo bang bip { a: b; } CSS foo { bar {baz {a: b}} bang {bip {a: b}}} SCSS end def test_nested_rules_with_declarations assert_equal <<CSS, render(<<SCSS) foo { a: b; } foo bar { c: d; } CSS foo { a: b; bar {c: d}} SCSS assert_equal <<CSS, render(<<SCSS) foo { a: b; } foo bar { c: d; } CSS foo { bar {c: d} a: b} SCSS assert_equal <<CSS, render(<<SCSS) foo { ump: nump; grump: clump; } foo bar { blat: bang; habit: rabbit; } foo bar baz { a: b; } foo bar bip { c: d; } foo bibble bap { e: f; } CSS foo { ump: nump; grump: clump; bar { blat: bang; habit: rabbit; baz {a: b} bip {c: d}} bibble { bap {e: f}}} SCSS end def test_nested_rules_with_fancy_selectors assert_equal <<CSS, render(<<SCSS) foo .bar { a: b; } foo :baz { c: d; } foo bang:bop { e: f; } foo ::qux { g: h; } foo zap::fblthp { i: j; } CSS foo { .bar {a: b} :baz {c: d} bang:bop {e: f} ::qux {g: h} zap::fblthp {i: j}} SCSS end def test_almost_ambiguous_nested_rules_and_declarations assert_equal <<CSS, render(<<SCSS) foo { bar: baz bang bop biddle woo look at all these elems; } foo bar:baz:bang:bop:biddle:woo:look:at:all:these:pseudoclasses { a: b; } foo bar:baz bang bop biddle woo look at all these elems { a: b; } CSS foo { bar:baz:bang:bop:biddle:woo:look:at:all:these:pseudoclasses {a: b}; bar:baz bang bop biddle woo look at all these elems {a: b}; bar:baz bang bop biddle woo look at all these elems; } SCSS end def test_newlines_in_selectors assert_equal <<CSS, render(<<SCSS) foo bar { a: b; } CSS foo bar {a: b} SCSS assert_equal <<CSS, render(<<SCSS) foo baz, foo bang, bar baz, bar bang { a: b; } CSS foo, bar { baz, bang {a: b}} SCSS assert_equal <<CSS, render(<<SCSS) foo bar baz bang { a: b; } foo bar bip bop { c: d; } CSS foo bar { baz bang {a: b} bip bop {c: d}} SCSS assert_equal <<CSS, render(<<SCSS) foo bang, foo bip bop, bar baz bang, bar baz bip bop { a: b; } CSS foo, bar baz { bang, bip bop {a: b}} SCSS end def test_trailing_comma_in_selector assert_equal <<CSS, render(<<SCSS) #foo #bar, #baz #boom { a: b; } #bip #bop { c: d; } CSS #foo #bar,, ,#baz #boom, {a: b} #bip #bop, ,, {c: d} SCSS end def test_parent_selectors assert_equal <<CSS, render(<<SCSS) foo:hover { a: b; } bar foo.baz { c: d; } CSS foo { &:hover {a: b} bar &.baz {c: d}} SCSS end def test_parent_selector_with_subject silence_warnings {assert_equal <<CSS, render(<<SCSS)} bar foo.baz! .bip { a: b; } bar foo bar.baz! .bip { c: d; } CSS foo { bar &.baz! .bip {a: b}} foo bar { bar &.baz! .bip {c: d}} SCSS end def test_parent_selector_with_suffix assert_equal <<CSS, render(<<SCSS) .foo-bar { a: b; } .foo_bar { c: d; } .foobar { e: f; } .foo123 { e: f; } :hover-suffix { g: h; } CSS .foo { &-bar {a: b} &_bar {c: d} &bar {e: f} &123 {e: f} } :hover { &-suffix {g: h} } SCSS end def test_unknown_directive_bubbling assert_equal(<<CSS, render(<<SCSS, :style => :nested)) @fblthp { .foo .bar { a: b; } } CSS .foo { @fblthp { .bar {a: b} } } SCSS end def test_keyframe_bubbling assert_equal(<<CSS, render(<<SCSS, :style => :nested)) @keyframes spin { 0% { transform: rotate(0deg); } } @-webkit-keyframes spin { 0% { transform: rotate(0deg); } } CSS .foo { @keyframes spin { 0% {transform: rotate(0deg)} } @-webkit-keyframes spin { 0% {transform: rotate(0deg)} } } SCSS end ## Namespace Properties def test_namespace_properties assert_equal <<CSS, render(<<SCSS) foo { bar: baz; bang-bip: 1px; bang-bop: bar; } CSS foo { bar: baz; bang: { bip: 1px; bop: bar;}} SCSS end def test_several_namespace_properties assert_equal <<CSS, render(<<SCSS) foo { bar: baz; bang-bip: 1px; bang-bop: bar; buzz-fram: "foo"; buzz-frum: moo; } CSS foo { bar: baz; bang: { bip: 1px; bop: bar;} buzz: { fram: "foo"; frum: moo; } } SCSS end def test_nested_namespace_properties assert_equal <<CSS, render(<<SCSS) foo { bar: baz; bang-bip: 1px; bang-bop: bar; bang-blat-baf: bort; } CSS foo { bar: baz; bang: { bip: 1px; bop: bar; blat:{baf:bort}}} SCSS end def test_namespace_properties_with_value assert_equal <<CSS, render(<<SCSS) foo { bar: baz; bar-bip: bop; bar-bing: bop; } CSS foo { bar: baz { bip: bop; bing: bop; }} SCSS end def test_namespace_properties_with_script_value assert_equal <<CSS, render(<<SCSS) foo { bar: bazbang; bar-bip: bop; bar-bing: bop; } CSS foo { bar: baz + bang { bip: bop; bing: bop; }} SCSS end def test_no_namespace_properties_without_space assert_equal <<CSS, render(<<SCSS) foo bar:baz { bip: bop; } CSS foo { bar:baz { bip: bop }} SCSS end def test_no_namespace_properties_without_space_even_when_its_unambiguous render(<<SCSS) foo { bar:baz calc(1 + 2) { bip: bop }} SCSS assert(false, "Expected syntax error") rescue Sass::SyntaxError => e assert_equal 'Invalid CSS after "bar:baz calc": expected selector, was "(1 + 2)"', e.message assert_equal 2, e.sass_line end def test_namespace_properties_without_space_allowed_for_non_identifier assert_equal <<CSS, render(<<SCSS) foo { bar: 1px; bar-bip: bop; } CSS foo { bar:1px { bip: bop }} SCSS end ## Mixins def test_basic_mixins assert_equal <<CSS, render(<<SCSS) .foo { a: b; } CSS @mixin foo { .foo {a: b}} @include foo; SCSS assert_equal <<CSS, render(<<SCSS) bar { c: d; } bar .foo { a: b; } CSS @mixin foo { .foo {a: b}} bar { @include foo; c: d; } SCSS assert_equal <<CSS, render(<<SCSS) bar { a: b; c: d; } CSS @mixin foo {a: b} bar { @include foo; c: d; } SCSS end def test_mixins_with_empty_args assert_equal <<CSS, render(<<SCSS) .foo { a: b; } CSS @mixin foo() {a: b} .foo {@include foo();} SCSS assert_equal <<CSS, render(<<SCSS) .foo { a: b; } CSS @mixin foo() {a: b} .foo {@include foo;} SCSS assert_equal <<CSS, render(<<SCSS) .foo { a: b; } CSS @mixin foo {a: b} .foo {@include foo();} SCSS end def test_mixins_with_args assert_equal <<CSS, render(<<SCSS) .foo { a: bar; } CSS @mixin foo($a) {a: $a} .foo {@include foo(bar)} SCSS assert_equal <<CSS, render(<<SCSS) .foo { a: bar; b: 12px; } CSS @mixin foo($a, $b) { a: $a; b: $b; } .foo {@include foo(bar, 12px)} SCSS end def test_keyframes_rules_in_content assert_equal <<CSS, render(<<SCSS) @keyframes identifier { 0% { top: 0; left: 0; } 30% { top: 50px; } 68%, 72% { left: 50px; } 100% { top: 100px; left: 100%; } } CSS @mixin keyframes { @keyframes identifier { @content } } @include keyframes { 0% {top: 0; left: 0} \#{"30%"} {top: 50px} 68%, 72% {left: 50px} 100% {top: 100px; left: 100%} } SCSS end ## Functions def test_basic_function assert_equal(<<CSS, render(<<SASS)) bar { a: 3; } CSS @function foo() { @return 1 + 2; } bar { a: foo(); } SASS end def test_function_args assert_equal(<<CSS, render(<<SASS)) bar { a: 3; } CSS @function plus($var1, $var2) { @return $var1 + $var2; } bar { a: plus(1, 2); } SASS end def test_disallowed_function_names Sass::Deprecation.allow_double_warnings do assert_warning(<<WARNING) {render(<<SCSS)} DEPRECATION WARNING on line 1 of test_disallowed_function_names_inline.scss: Naming a function "calc" is disallowed and will be an error in future versions of Sass. This name conflicts with an existing CSS function with special parse rules. WARNING @function calc() {} SCSS assert_warning(<<WARNING) {render(<<SCSS)} DEPRECATION WARNING on line 1 of test_disallowed_function_names_inline.scss: Naming a function "-my-calc" is disallowed and will be an error in future versions of Sass. This name conflicts with an existing CSS function with special parse rules. WARNING @function -my-calc() {} SCSS assert_warning(<<WARNING) {render(<<SCSS)} DEPRECATION WARNING on line 1 of test_disallowed_function_names_inline.scss: Naming a function "element" is disallowed and will be an error in future versions of Sass. This name conflicts with an existing CSS function with special parse rules. WARNING @function element() {} SCSS assert_warning(<<WARNING) {render(<<SCSS)} DEPRECATION WARNING on line 1 of test_disallowed_function_names_inline.scss: Naming a function "-my-element" is disallowed and will be an error in future versions of Sass. This name conflicts with an existing CSS function with special parse rules. WARNING @function -my-element() {} SCSS assert_warning(<<WARNING) {render(<<SCSS)} DEPRECATION WARNING on line 1 of test_disallowed_function_names_inline.scss: Naming a function "expression" is disallowed and will be an error in future versions of Sass. This name conflicts with an existing CSS function with special parse rules. WARNING @function expression() {} SCSS assert_warning(<<WARNING) {render(<<SCSS)} DEPRECATION WARNING on line 1 of test_disallowed_function_names_inline.scss: Naming a function "url" is disallowed and will be an error in future versions of Sass. This name conflicts with an existing CSS function with special parse rules. WARNING @function url() {} SCSS end end def test_allowed_function_names assert_no_warning {assert_equal(<<CSS, render(<<SCSS))} .a { b: c; } CSS @function -my-expression() {@return c} .a {b: -my-expression()} SCSS assert_no_warning {assert_equal(<<CSS, render(<<SCSS))} .a { b: c; } CSS @function -my-url() {@return c} .a {b: -my-url()} SCSS end ## Var Args def test_mixin_var_args assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2, 3, 4; } CSS @mixin foo($a, $b...) { a: $a; b: $b; } .foo {@include foo(1, 2, 3, 4)} SCSS end def test_mixin_empty_var_args assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 0; } CSS @mixin foo($a, $b...) { a: $a; b: length($b); } .foo {@include foo(1)} SCSS end def test_mixin_var_args_act_like_list assert_equal <<CSS, render(<<SCSS) .foo { a: 3; b: 3; } CSS @mixin foo($a, $b...) { a: length($b); b: nth($b, 2); } .foo {@include foo(1, 2, 3, 4)} SCSS end def test_mixin_splat_args assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: 3; d: 4; } CSS @mixin foo($a, $b, $c, $d) { a: $a; b: $b; c: $c; d: $d; } $list: 2, 3, 4; .foo {@include foo(1, $list...)} SCSS end def test_mixin_splat_expression assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: 3; d: 4; } CSS @mixin foo($a, $b, $c, $d) { a: $a; b: $b; c: $c; d: $d; } .foo {@include foo(1, (2, 3, 4)...)} SCSS end def test_mixin_splat_args_with_var_args assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2, 3, 4; } CSS @mixin foo($a, $b...) { a: $a; b: $b; } $list: 2, 3, 4; .foo {@include foo(1, $list...)} SCSS end def test_mixin_splat_args_with_var_args_and_normal_args assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: 3, 4; } CSS @mixin foo($a, $b, $c...) { a: $a; b: $b; c: $c; } $list: 2, 3, 4; .foo {@include foo(1, $list...)} SCSS end def test_mixin_splat_args_with_var_args_preserves_separator assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2 3 4 5; } CSS @mixin foo($a, $b...) { a: $a; b: $b; } $list: 3 4 5; .foo {@include foo(1, 2, $list...)} SCSS end def test_mixin_var_and_splat_args_pass_through_keywords assert_equal <<CSS, render(<<SCSS) .foo { a: 3; b: 1; c: 2; } CSS @mixin foo($a...) { @include bar($a...); } @mixin bar($b, $c, $a) { a: $a; b: $b; c: $c; } .foo {@include foo(1, $c: 2, $a: 3)} SCSS end def test_mixin_var_keyword_args assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: 3; } CSS @mixin foo($args...) { a: map-get(keywords($args), a); b: map-get(keywords($args), b); c: map-get(keywords($args), c); } .foo {@include foo($a: 1, $b: 2, $c: 3)} SCSS end def test_mixin_empty_var_keyword_args assert_equal <<CSS, render(<<SCSS) .foo { length: 0; } CSS @mixin foo($args...) { length: length(keywords($args)); } .foo {@include foo} SCSS end def test_mixin_map_splat assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: 3; } CSS @mixin foo($a, $b, $c) { a: $a; b: $b; c: $c; } .foo { $map: (a: 1, b: 2, c: 3); @include foo($map...); } SCSS end def test_mixin_map_and_list_splat assert_equal <<CSS, render(<<SCSS) .foo { a: x; b: y; c: z; d: 1; e: 2; f: 3; } CSS @mixin foo($a, $b, $c, $d, $e, $f) { a: $a; b: $b; c: $c; d: $d; e: $e; f: $f; } .foo { $list: x y z; $map: (d: 1, e: 2, f: 3); @include foo($list..., $map...); } SCSS end def test_mixin_map_splat_takes_precedence_over_pass_through assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: z; } CSS @mixin foo($args...) { $map: (c: z); @include bar($args..., $map...); } @mixin bar($a, $b, $c) { a: $a; b: $b; c: $c; } .foo { @include foo(1, $b: 2, $c: 3); } SCSS end def test_mixin_list_of_pairs_splat_treated_as_list assert_equal <<CSS, render(<<SCSS) .foo { a: a 1; b: b 2; c: c 3; } CSS @mixin foo($a, $b, $c) { a: $a; b: $b; c: $c; } .foo { @include foo((a 1, b 2, c 3)...); } SCSS end def test_mixin_splat_after_keyword_args assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: 3; } CSS @mixin foo($a, $b, $c) { a: 1; b: 2; c: 3; } .foo { @include foo(1, $c: 3, 2...); } SCSS end def test_mixin_keyword_args_after_splat assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: 3; } CSS @mixin foo($a, $b, $c) { a: 1; b: 2; c: 3; } .foo { @include foo(1, 2..., $c: 3); } SCSS end def test_mixin_keyword_splat_after_keyword_args assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: 3; } CSS @mixin foo($a, $b, $c) { a: 1; b: 2; c: 3; } .foo { @include foo(1, $b: 2, (c: 3)...); } SCSS end def test_mixin_triple_keyword_splat_merge assert_equal <<CSS, render(<<SCSS) .foo { foo: 1; bar: 2; kwarg: 3; a: 3; b: 2; c: 3; } CSS @mixin foo($foo, $bar, $kwarg, $a, $b, $c) { foo: $foo; bar: $bar; kwarg: $kwarg; a: $a; b: $b; c: $c; } @mixin bar($args...) { @include foo($args..., $bar: 2, $a: 2, $b: 2, (kwarg: 3, a: 3, c: 3)...); } .foo { @include bar($foo: 1, $a: 1, $b: 1, $c: 1); } SCSS end def test_mixin_map_splat_converts_hyphens_and_underscores_for_real_args assert_equal <<CSS, render(<<SCSS) .foo { a: 1; b: 2; c: 3; d: 4; } CSS @mixin foo($a-1, $b-2, $c_3, $d_4) { a: $a-1; b: $b-2; c: $c_3; d: $d_4; } .foo { $map: (a-1: 1, b_2: 2, c-3: 3, d_4: 4); @include foo($map...); } SCSS end def test_mixin_map_splat_doesnt_convert_hyphens_and_underscores_for_var_args assert_equal <<CSS, render(<<SCSS) .foo { a-1: 1; b_2: 2; c-3: 3; d_4: 4; } CSS @mixin foo($args...) { @each $key, $value in keywords($args) { \#{$key}: $value; } } .foo { $map: (a-1: 1, b_2: 2, c-3: 3, d_4: 4); @include foo($map...); } SCSS end def test_mixin_conflicting_splat_after_keyword_args assert_raise_message(Sass::SyntaxError, <<MESSAGE.rstrip) {render(<<SCSS)} Mixin foo was passed argument $b both by position and by name. MESSAGE @mixin foo($a, $b, $c) { a: 1; b: 2; c: 3; } .foo { @include foo(1, $b: 2, 3...); } SCSS end def test_mixin_keyword_splat_must_have_string_keys assert_raise_message(Sass::SyntaxError, <<MESSAGE.rstrip) {render <<SCSS} Variable keyword argument map must have string keys. 12 is not a string in (12: 1). MESSAGE @mixin foo($a) { a: $a; } .foo {@include foo((12: 1)...)} SCSS end def test_mixin_positional_arg_after_splat assert_raise_message(Sass::SyntaxError, <<MESSAGE.rstrip) {render(<<SCSS)} Only keyword arguments may follow variable arguments (...). MESSAGE @mixin foo($a, $b, $c) { a: 1; b: 2; c: 3; } .foo { @include foo(1, 2..., 3); } SCSS end def test_mixin_var_args_with_keyword assert_raise_message(Sass::SyntaxError, "Positional arguments must come before keyword arguments.") {render <<SCSS} @mixin foo($a, $b...) { a: $a; b: $b; } .foo {@include foo($a: 1, 2, 3, 4)} SCSS end def test_mixin_keyword_for_var_arg assert_raise_message(Sass::SyntaxError, "Argument $b of mixin foo cannot be used as a named argument.") {render <<SCSS} @mixin foo($a, $b...) { a: $a; b: $b; } .foo {@include foo(1, $b: 2 3 4)} SCSS end def test_mixin_keyword_for_unknown_arg_with_var_args assert_raise_message(Sass::SyntaxError, "Mixin foo doesn't have an argument named $c.") {render <<SCSS} @mixin foo($a, $b...) { a: $a; b: $b; } .foo {@include foo(1, $c: 2 3 4)} SCSS end def test_mixin_map_splat_before_list_splat assert_raise_message(Sass::SyntaxError, "Variable keyword arguments must be a map (was (2 3)).") {render <<SCSS} @mixin foo($a, $b, $c) { a: $a; b: $b; c: $c; } .foo { @include foo((a: 1)..., (2 3)...); } SCSS end def test_mixin_map_splat_with_unknown_keyword assert_raise_message(Sass::SyntaxError, "Mixin foo doesn't have an argument named $c.") {render <<SCSS} @mixin foo($a, $b) { a: $a; b: $b; } .foo { @include foo(1, 2, (c: 1)...); } SCSS end def test_mixin_map_splat_with_wrong_type assert_raise_message(Sass::SyntaxError, "Variable keyword arguments must be a map (was 12).") {render <<SCSS} @mixin foo($a, $b) { a: $a; b: $b; } .foo { @include foo((1, 2)..., 12...); } SCSS end def test_mixin_splat_too_many_args assert_warning(<<WARNING) {render <<SCSS} WARNING: Mixin foo takes 2 arguments but 4 were passed. on line 2 of #{filename_for_test(:scss)} This will be an error in future versions of Sass. WARNING @mixin foo($a, $b) {} @include foo((1, 2, 3, 4)...); SCSS end def test_function_var_args assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, 3, 4"; } CSS @function foo($a, $b...) { @return "a: \#{$a}, b: \#{$b}"; } .foo {val: foo(1, 2, 3, 4)} SCSS end def test_function_empty_var_args assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 0"; } CSS @function foo($a, $b...) { @return "a: \#{$a}, b: \#{length($b)}"; } .foo {val: foo(1)} SCSS end def test_function_var_args_act_like_list assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 3, b: 3"; } CSS @function foo($a, $b...) { @return "a: \#{length($b)}, b: \#{nth($b, 2)}"; } .foo {val: foo(1, 2, 3, 4)} SCSS end def test_function_splat_args assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, c: 3, d: 4"; } CSS @function foo($a, $b, $c, $d) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}, d: \#{$d}"; } $list: 2, 3, 4; .foo {val: foo(1, $list...)} SCSS end def test_function_splat_expression assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, c: 3, d: 4"; } CSS @function foo($a, $b, $c, $d) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}, d: \#{$d}"; } .foo {val: foo(1, (2, 3, 4)...)} SCSS end def test_function_splat_args_with_var_args assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, 3, 4"; } CSS @function foo($a, $b...) { @return "a: \#{$a}, b: \#{$b}"; } $list: 2, 3, 4; .foo {val: foo(1, $list...)} SCSS end def test_function_splat_args_with_var_args_and_normal_args assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, c: 3, 4"; } CSS @function foo($a, $b, $c...) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } $list: 2, 3, 4; .foo {val: foo(1, $list...)} SCSS end def test_function_splat_args_with_var_args_preserves_separator assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2 3 4 5"; } CSS @function foo($a, $b...) { @return "a: \#{$a}, b: \#{$b}"; } $list: 3 4 5; .foo {val: foo(1, 2, $list...)} SCSS end def test_function_var_and_splat_args_pass_through_keywords assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 3, b: 1, c: 2"; } CSS @function foo($a...) { @return bar($a...); } @function bar($b, $c, $a) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } .foo {val: foo(1, $c: 2, $a: 3)} SCSS end def test_function_var_keyword_args assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, c: 3"; } CSS @function foo($args...) { @return "a: \#{map-get(keywords($args), a)}, " + "b: \#{map-get(keywords($args), b)}, " + "c: \#{map-get(keywords($args), c)}"; } .foo {val: foo($a: 1, $b: 2, $c: 3)} SCSS end def test_function_empty_var_keyword_args assert_equal <<CSS, render(<<SCSS) .foo { length: 0; } CSS @function foo($args...) { @return length(keywords($args)); } .foo {length: foo()} SCSS end def test_function_map_splat assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, c: 3"; } CSS @function foo($a, $b, $c) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } .foo { $map: (a: 1, b: 2, c: 3); val: foo($map...); } SCSS end def test_function_map_and_list_splat assert_equal <<CSS, render(<<SCSS) .foo { val: "a: x, b: y, c: z, d: 1, e: 2, f: 3"; } CSS @function foo($a, $b, $c, $d, $e, $f) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}, d: \#{$d}, e: \#{$e}, f: \#{$f}"; } .foo { $list: x y z; $map: (d: 1, e: 2, f: 3); val: foo($list..., $map...); } SCSS end def test_function_map_splat_takes_precedence_over_pass_through assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, c: z"; } CSS @function foo($args...) { $map: (c: z); @return bar($args..., $map...); } @function bar($a, $b, $c) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } .foo { val: foo(1, $b: 2, $c: 3); } SCSS end def test_ruby_function_map_splat_takes_precedence_over_pass_through assert_equal <<CSS, render(<<SCSS) .foo { val: 1 2 3 z; } CSS @function foo($args...) { $map: (val: z); @return append($args..., $map...); } .foo { val: foo(1 2 3, $val: 4) } SCSS end def test_function_list_of_pairs_splat_treated_as_list assert_equal <<CSS, render(<<SCSS) .foo { val: "a: a 1, b: b 2, c: c 3"; } CSS @function foo($a, $b, $c) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } .foo { val: foo((a 1, b 2, c 3)...); } SCSS end def test_function_splat_after_keyword_args assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, c: 3"; } CSS @function foo($a, $b, $c) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } .foo { val: foo(1, $c: 3, 2...); } SCSS end def test_function_keyword_args_after_splat assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, c: 3"; } CSS @function foo($a, $b, $c) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } .foo { val: foo(1, 2..., $c: 3); } SCSS end def test_function_keyword_splat_after_keyword_args assert_equal <<CSS, render(<<SCSS) .foo { val: "a: 1, b: 2, c: 3"; } CSS @function foo($a, $b, $c) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } .foo { val: foo(1, $b: 2, (c: 3)...); } SCSS end def test_function_triple_keyword_splat_merge assert_equal <<CSS, render(<<SCSS) .foo { val: "foo: 1, bar: 2, kwarg: 3, a: 3, b: 2, c: 3"; } CSS @function foo($foo, $bar, $kwarg, $a, $b, $c) { @return "foo: \#{$foo}, bar: \#{$bar}, kwarg: \#{$kwarg}, a: \#{$a}, b: \#{$b}, c: \#{$c}"; } @function bar($args...) { @return foo($args..., $bar: 2, $a: 2, $b: 2, (kwarg: 3, a: 3, c: 3)...); } .foo { val: bar($foo: 1, $a: 1, $b: 1, $c: 1); } SCSS end def test_function_conflicting_splat_after_keyword_args assert_raise_message(Sass::SyntaxError, <<MESSAGE.rstrip) {render(<<SCSS)} Function foo was passed argument $b both by position and by name. MESSAGE @function foo($a, $b, $c) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } .foo { val: foo(1, $b: 2, 3...); } SCSS end def test_function_positional_arg_after_splat assert_raise_message(Sass::SyntaxError, <<MESSAGE.rstrip) {render(<<SCSS)} Only keyword arguments may follow variable arguments (...). MESSAGE @function foo($a, $b, $c) { @return "a: \#{$a}, b: \#{$b}, c: \#{$c}"; } .foo { val: foo(1, 2..., 3); } SCSS end def test_function_var_args_with_keyword assert_raise_message(Sass::SyntaxError, "Positional arguments must come before keyword arguments.") {render <<SCSS}
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/extra/update_watch.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/extra/update_watch.rb
require 'rubygems' require 'sinatra' require 'json' set :port, 3124 set :environment, :production enable :lock Dir.chdir(File.dirname(__FILE__) + "/..") post "/" do puts "Received payload!" puts "Rev: #{`git name-rev HEAD`.strip}" system %{rake handle_update --trace REF=#{JSON.parse(params["payload"])["ref"].inspect}} 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.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass.rb
dir = File.dirname(__FILE__) $LOAD_PATH.unshift dir unless $LOAD_PATH.include?(dir) require 'sass/version' # The module that contains everything Sass-related: # # * {Sass::Engine} is the class used to render Sass/SCSS within Ruby code. # * {Sass::Plugin} is interfaces with web frameworks (Rails and Merb in particular). # * {Sass::SyntaxError} is raised when Sass encounters an error. # * {Sass::CSS} handles conversion of CSS to Sass. # # Also see the {file:SASS_REFERENCE.md full Sass reference}. module Sass class << self # @private attr_accessor :tests_running end # The global load paths for Sass files. This is meant for plugins and # libraries to register the paths to their Sass stylesheets to that they may # be `@imported`. This load path is used by every instance of {Sass::Engine}. # They are lower-precedence than any load paths passed in via the # {file:SASS_REFERENCE.md#load_paths-option `:load_paths` option}. # # If the `SASS_PATH` environment variable is set, # the initial value of `load_paths` will be initialized based on that. # The variable should be a colon-separated list of path names # (semicolon-separated on Windows). # # Note that files on the global load path are never compiled to CSS # themselves, even if they aren't partials. They exist only to be imported. # # @example # Sass.load_paths << File.dirname(__FILE__ + '/sass') # @return [Array<String, Pathname, Sass::Importers::Base>] def self.load_paths @load_paths ||= if ENV['SASS_PATH'] ENV['SASS_PATH'].split(Sass::Util.windows? ? ';' : ':') else [] end end # Compile a Sass or SCSS string to CSS. # Defaults to SCSS. # # @param contents [String] The contents of the Sass file. # @param options [{Symbol => Object}] An options hash; # see {file:SASS_REFERENCE.md#Options the Sass options documentation} # @raise [Sass::SyntaxError] if there's an error in the document # @raise [Encoding::UndefinedConversionError] if the source encoding # cannot be converted to UTF-8 # @raise [ArgumentError] if the document uses an unknown encoding with `@charset` def self.compile(contents, options = {}) options[:syntax] ||= :scss Engine.new(contents, options).to_css end # Compile a file on disk to CSS. # # @raise [Sass::SyntaxError] if there's an error in the document # @raise [Encoding::UndefinedConversionError] if the source encoding # cannot be converted to UTF-8 # @raise [ArgumentError] if the document uses an unknown encoding with `@charset` # # @overload compile_file(filename, options = {}) # Return the compiled CSS rather than writing it to a file. # # @param filename [String] The path to the Sass, SCSS, or CSS file on disk. # @param options [{Symbol => Object}] An options hash; # see {file:SASS_REFERENCE.md#Options the Sass options documentation} # @return [String] The compiled CSS. # # @overload compile_file(filename, css_filename, options = {}) # Write the compiled CSS to a file. # # @param filename [String] The path to the Sass, SCSS, or CSS file on disk. # @param options [{Symbol => Object}] An options hash; # see {file:SASS_REFERENCE.md#Options the Sass options documentation} # @param css_filename [String] The location to which to write the compiled CSS. def self.compile_file(filename, *args) options = args.last.is_a?(Hash) ? args.pop : {} css_filename = args.shift result = Sass::Engine.for_file(filename, options).render if css_filename options[:css_filename] ||= css_filename open(css_filename, "w") {|css_file| css_file.write(result)} nil else result end end end require 'sass/logger' require 'sass/util' require 'sass/engine' require 'sass/plugin' if defined?(Merb::Plugins) require 'sass/railtie' require 'sass/features'
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.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/selector.rb
require 'sass/selector/simple' require 'sass/selector/abstract_sequence' require 'sass/selector/comma_sequence' require 'sass/selector/pseudo' require 'sass/selector/sequence' require 'sass/selector/simple_sequence' module Sass # A namespace for nodes in the parse tree for selectors. # # {CommaSequence} is the toplevel selector, # representing a comma-separated sequence of {Sequence}s, # such as `foo bar, baz bang`. # {Sequence} is the next level, # representing {SimpleSequence}s separated by combinators (e.g. descendant or child), # such as `foo bar` or `foo > bar baz`. # {SimpleSequence} is a sequence of selectors that all apply to a single element, # such as `foo.bar[attr=val]`. # Finally, {Simple} is the superclass of the simplest selectors, # such as `.foo` or `#bar`. module Selector # The base used for calculating selector specificity. The spec says this # should be "sufficiently high"; it's extremely unlikely that any single # selector sequence will contain 1,000 simple selectors. SPECIFICITY_BASE = 1_000 # A parent-referencing selector (`&` in Sass). # The function of this is to be replaced by the parent selector # in the nested hierarchy. class Parent < Simple # The identifier following the `&`. `nil` indicates no suffix. # # @return [String, nil] attr_reader :suffix # @param name [String, nil] See \{#suffix} def initialize(suffix = nil) @suffix = suffix end # @see Selector#to_s def to_s(opts = {}) "&" + (@suffix || '') end # Always raises an exception. # # @raise [Sass::SyntaxError] Parent selectors should be resolved before unification # @see Selector#unify def unify(sels) raise Sass::SyntaxError.new("[BUG] Cannot unify parent selectors.") end end # A class selector (e.g. `.foo`). class Class < Simple # The class name. # # @return [String] attr_reader :name # @param name [String] The class name def initialize(name) @name = name end # @see Selector#to_s def to_s(opts = {}) "." + @name end # @see AbstractSequence#specificity def specificity SPECIFICITY_BASE end end # An id selector (e.g. `#foo`). class Id < Simple # The id name. # # @return [String] attr_reader :name # @param name [String] The id name def initialize(name) @name = name end def unique? true end # @see Selector#to_s def to_s(opts = {}) "#" + @name end # Returns `nil` if `sels` contains an {Id} selector # with a different name than this one. # # @see Selector#unify def unify(sels) return if sels.any? {|sel2| sel2.is_a?(Id) && name != sel2.name} super end # @see AbstractSequence#specificity def specificity SPECIFICITY_BASE**2 end end # A placeholder selector (e.g. `%foo`). # This exists to be replaced via `@extend`. # Rulesets using this selector will not be printed, but can be extended. # Otherwise, this acts just like a class selector. class Placeholder < Simple # The placeholder name. # # @return [String] attr_reader :name # @param name [String] The placeholder name def initialize(name) @name = name end # @see Selector#to_s def to_s(opts = {}) "%" + @name end # @see AbstractSequence#specificity def specificity SPECIFICITY_BASE end end # A universal selector (`*` in CSS). class Universal < Simple # The selector namespace. `nil` means the default namespace, `""` means no # namespace, `"*"` means any namespace. # # @return [String, nil] attr_reader :namespace # @param namespace [String, nil] See \{#namespace} def initialize(namespace) @namespace = namespace end # @see Selector#to_s def to_s(opts = {}) @namespace ? "#{@namespace}|*" : "*" end # Unification of a universal selector is somewhat complicated, # especially when a namespace is specified. # If there is no namespace specified # or any namespace is specified (namespace `"*"`), # then `sel` is returned without change # (unless it's empty, in which case `"*"` is required). # # If a namespace is specified # but `sel` does not specify a namespace, # then the given namespace is applied to `sel`, # either by adding this {Universal} selector # or applying this namespace to an existing {Element} selector. # # If both this selector *and* `sel` specify namespaces, # those namespaces are unified via {Simple#unify_namespaces} # and the unified namespace is used, if possible. # # @todo There are lots of cases that this documentation specifies; # make sure we thoroughly test **all of them**. # @todo Keep track of whether a default namespace has been declared # and handle namespace-unspecified selectors accordingly. # @todo If any branch of a CommaSequence ends up being just `"*"`, # then all other branches should be eliminated # # @see Selector#unify def unify(sels) name = case sels.first when Universal; :universal when Element; sels.first.name else return [self] + sels unless namespace.nil? || namespace == '*' return sels unless sels.empty? return [self] end ns, accept = unify_namespaces(namespace, sels.first.namespace) return unless accept [name == :universal ? Universal.new(ns) : Element.new(name, ns)] + sels[1..-1] end # @see AbstractSequence#specificity def specificity 0 end end # An element selector (e.g. `h1`). class Element < Simple # The element name. # # @return [String] attr_reader :name # The selector namespace. `nil` means the default namespace, `""` means no # namespace, `"*"` means any namespace. # # @return [String, nil] attr_reader :namespace # @param name [String] The element name # @param namespace [String, nil] See \{#namespace} def initialize(name, namespace) @name = name @namespace = namespace end # @see Selector#to_s def to_s(opts = {}) @namespace ? "#{@namespace}|#{@name}" : @name end # Unification of an element selector is somewhat complicated, # especially when a namespace is specified. # First, if `sel` contains another {Element} with a different \{#name}, # then the selectors can't be unified and `nil` is returned. # # Otherwise, if `sel` doesn't specify a namespace, # or it specifies any namespace (via `"*"`), # then it's returned with this element selector # (e.g. `.foo` becomes `a.foo` or `svg|a.foo`). # Similarly, if this selector doesn't specify a namespace, # the namespace from `sel` is used. # # If both this selector *and* `sel` specify namespaces, # those namespaces are unified via {Simple#unify_namespaces} # and the unified namespace is used, if possible. # # @todo There are lots of cases that this documentation specifies; # make sure we thoroughly test **all of them**. # @todo Keep track of whether a default namespace has been declared # and handle namespace-unspecified selectors accordingly. # # @see Selector#unify def unify(sels) case sels.first when Universal; when Element; return unless name == sels.first.name else return [self] + sels end ns, accept = unify_namespaces(namespace, sels.first.namespace) return unless accept [Element.new(name, ns)] + sels[1..-1] end # @see AbstractSequence#specificity def specificity 1 end end # An attribute selector (e.g. `[href^="http://"]`). class Attribute < Simple # The attribute name. # # @return [Array<String, Sass::Script::Tree::Node>] attr_reader :name # The attribute namespace. `nil` means the default namespace, `""` means # no namespace, `"*"` means any namespace. # # @return [String, nil] attr_reader :namespace # The matching operator, e.g. `"="` or `"^="`. # # @return [String] attr_reader :operator # The right-hand side of the operator. # # @return [String] attr_reader :value # Flags for the attribute selector (e.g. `i`). # # @return [String] attr_reader :flags # @param name [String] The attribute name # @param namespace [String, nil] See \{#namespace} # @param operator [String] The matching operator, e.g. `"="` or `"^="` # @param value [String] See \{#value} # @param flags [String] See \{#flags} def initialize(name, namespace, operator, value, flags) @name = name @namespace = namespace @operator = operator @value = value @flags = flags end # @see Selector#to_s def to_s(opts = {}) res = "[" res << @namespace << "|" if @namespace res << @name res << @operator << @value if @value res << " " << @flags if @flags res << "]" end # @see AbstractSequence#specificity def specificity SPECIFICITY_BASE 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.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/script.rb
require 'sass/scss/rx' module Sass # SassScript is code that's embedded in Sass documents # to allow for property values to be computed from variables. # # This module contains code that handles the parsing and evaluation of SassScript. module Script # The regular expression used to parse variables. MATCH = /^\$(#{Sass::SCSS::RX::IDENT})\s*:\s*(.+?) (!#{Sass::SCSS::RX::IDENT}(?:\s+!#{Sass::SCSS::RX::IDENT})*)?$/x # The regular expression used to validate variables without matching. VALIDATE = /^\$#{Sass::SCSS::RX::IDENT}$/ # Parses a string of SassScript # # @param value [String] The SassScript # @param line [Integer] The number of the line on which the SassScript appeared. # Used for error reporting # @param offset [Integer] The number of characters in on `line` that the SassScript started. # Used for error reporting # @param options [{Symbol => Object}] An options hash; # see {file:SASS_REFERENCE.md#Options the Sass options documentation} # @return [Script::Tree::Node] The root node of the parse tree def self.parse(value, line, offset, options = {}) Parser.parse(value, line, offset, options) rescue Sass::SyntaxError => e e.message << ": #{value.inspect}." if e.message == "SassScript error" e.modify_backtrace(:line => line, :filename => options[:filename]) raise e end require 'sass/script/functions' require 'sass/script/parser' require 'sass/script/tree' require 'sass/script/value' # @private CONST_RENAMES = { :Literal => Sass::Script::Value::Base, :ArgList => Sass::Script::Value::ArgList, :Bool => Sass::Script::Value::Bool, :Color => Sass::Script::Value::Color, :List => Sass::Script::Value::List, :Null => Sass::Script::Value::Null, :Number => Sass::Script::Value::Number, :String => Sass::Script::Value::String, :Node => Sass::Script::Tree::Node, :Funcall => Sass::Script::Tree::Funcall, :Interpolation => Sass::Script::Tree::Interpolation, :Operation => Sass::Script::Tree::Operation, :StringInterpolation => Sass::Script::Tree::StringInterpolation, :UnaryOperation => Sass::Script::Tree::UnaryOperation, :Variable => Sass::Script::Tree::Variable, } # @private def self.const_missing(name) klass = CONST_RENAMES[name] super unless klass CONST_RENAMES.each {|n, k| const_set(n, k)} klass 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/deprecation.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/deprecation.rb
module Sass # A deprecation warning that should only be printed once for a given line in a # given file. # # A global Deprecation instance should be created for each type of deprecation # warning, and `warn` should be called each time a warning is needed. class Deprecation @@allow_double_warnings = false # Runs a block in which double deprecation warnings for the same location # are allowed. def self.allow_double_warnings old_allow_double_warnings = @@allow_double_warnings @@allow_double_warnings = true yield ensure @@allow_double_warnings = old_allow_double_warnings end def initialize # A set of filename, line pairs for which warnings have been emitted. @seen = Set.new end # Prints `message` as a deprecation warning associated with `filename`, # `line`, and optionally `column`. # # This ensures that only one message will be printed for each line of a # given file. # # @overload warn(filename, line, message) # @param filename [String, nil] # @param line [Number] # @param message [String] # @overload warn(filename, line, column, message) # @param filename [String, nil] # @param line [Number] # @param column [Number] # @param message [String] def warn(filename, line, column_or_message, message = nil) return if !@@allow_double_warnings && @seen.add?([filename, line]).nil? if message column = column_or_message else message = column_or_message end location = "line #{line}" location << ", column #{column}" if column location << " of #{filename}" if filename Sass::Util.sass_warn("DEPRECATION WARNING on #{location}:\n#{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/version.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/version.rb
require 'date' require 'sass/util' module Sass # Handles Sass version-reporting. # Sass not only reports the standard three version numbers, # but its Git revision hash as well, # if it was installed from Git. module Version # Returns a hash representing the version of Sass. # The `:major`, `:minor`, and `:teeny` keys have their respective numbers as Integers. # The `:name` key has the name of the version. # The `:string` key contains a human-readable string representation of the version. # The `:number` key is the major, minor, and teeny keys separated by periods. # The `:date` key, which is not guaranteed to be defined, is the `DateTime` # at which this release was cut. # If Sass is checked out from Git, the `:rev` key will have the revision hash. # For example: # # { # :string => "2.1.0.9616393", # :rev => "9616393b8924ef36639c7e82aa88a51a24d16949", # :number => "2.1.0", # :date => DateTime.parse("Apr 30 13:52:01 2009 -0700"), # :major => 2, :minor => 1, :teeny => 0 # } # # If a prerelease version of Sass is being used, # the `:string` and `:number` fields will reflect the full version # (e.g. `"2.2.beta.1"`), and the `:teeny` field will be `-1`. # A `:prerelease` key will contain the name of the prerelease (e.g. `"beta"`), # and a `:prerelease_number` key will contain the rerelease number. # For example: # # { # :string => "3.0.beta.1", # :number => "3.0.beta.1", # :date => DateTime.parse("Mar 31 00:38:04 2010 -0700"), # :major => 3, :minor => 0, :teeny => -1, # :prerelease => "beta", # :prerelease_number => 1 # } # # @return [{Symbol => String/Integer}] The version hash def version return @@version if defined?(@@version) numbers = File.read(Sass::Util.scope('VERSION')).strip.split('.'). map {|n| n =~ /^[0-9]+$/ ? n.to_i : n} name = File.read(Sass::Util.scope('VERSION_NAME')).strip @@version = { :major => numbers[0], :minor => numbers[1], :teeny => numbers[2], :name => name } if (date = version_date) @@version[:date] = date end if numbers[3].is_a?(String) @@version[:teeny] = -1 @@version[:prerelease] = numbers[3] @@version[:prerelease_number] = numbers[4] end @@version[:number] = numbers.join('.') @@version[:string] = @@version[:number].dup if (rev = revision_number) @@version[:rev] = rev unless rev[0] == ?( @@version[:string] << "." << rev[0...7] end end @@version end private def revision_number if File.exist?(Sass::Util.scope('REVISION')) rev = File.read(Sass::Util.scope('REVISION')).strip return rev unless rev =~ /^([a-f0-9]+|\(.*\))$/ || rev == '(unknown)' end return unless File.exist?(Sass::Util.scope('.git/HEAD')) rev = File.read(Sass::Util.scope('.git/HEAD')).strip return rev unless rev =~ /^ref: (.*)$/ ref_name = $1 ref_file = Sass::Util.scope(".git/#{ref_name}") info_file = Sass::Util.scope(".git/info/refs") return File.read(ref_file).strip if File.exist?(ref_file) return unless File.exist?(info_file) File.open(info_file) do |f| f.each do |l| sha, ref = l.strip.split("\t", 2) next unless ref == ref_name return sha end end nil end def version_date return unless File.exist?(Sass::Util.scope('VERSION_DATE')) DateTime.parse(File.read(Sass::Util.scope('VERSION_DATE')).strip) end end extend Sass::Version # A string representing the version of Sass. # A more fine-grained representation is available from Sass.version. # @api public VERSION = version[:string] unless defined?(Sass::VERSION) 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/media.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/media.rb
# A namespace for the `@media` query parse tree. module Sass::Media # A comma-separated list of queries. # # media_query [ ',' S* media_query ]* class QueryList # The queries contained in this list. # # @return [Array<Query>] attr_accessor :queries # @param queries [Array<Query>] See \{#queries} def initialize(queries) @queries = queries end # Merges this query list with another. The returned query list # queries for the intersection between the two inputs. # # Both query lists should be resolved. # # @param other [QueryList] # @return [QueryList?] The merged list, or nil if there is no intersection. def merge(other) new_queries = queries.map {|q1| other.queries.map {|q2| q1.merge(q2)}}.flatten.compact return if new_queries.empty? QueryList.new(new_queries) end # Returns the CSS for the media query list. # # @return [String] def to_css queries.map {|q| q.to_css}.join(', ') end # Returns the Sass/SCSS code for the media query list. # # @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}). # @return [String] def to_src(options) queries.map {|q| q.to_src(options)}.join(', ') end # Returns a representation of the query as an array of strings and # potentially {Sass::Script::Tree::Node}s (if there's interpolation in it). # When the interpolation is resolved and the strings are joined together, # this will be the string representation of this query. # # @return [Array<String, Sass::Script::Tree::Node>] def to_a Sass::Util.intersperse(queries.map {|q| q.to_a}, ', ').flatten end # Returns a deep copy of this query list and all its children. # # @return [QueryList] def deep_copy QueryList.new(queries.map {|q| q.deep_copy}) end end # A single media query. # # [ [ONLY | NOT]? S* media_type S* | expression ] [ AND S* expression ]* class Query # The modifier for the query. # # When parsed as Sass code, this contains strings and SassScript nodes. When # parsed as CSS, it contains a single string (accessible via # \{#resolved_modifier}). # # @return [Array<String, Sass::Script::Tree::Node>] attr_accessor :modifier # The type of the query (e.g. `"screen"` or `"print"`). # # When parsed as Sass code, this contains strings and SassScript nodes. When # parsed as CSS, it contains a single string (accessible via # \{#resolved_type}). # # @return [Array<String, Sass::Script::Tree::Node>] attr_accessor :type # The trailing expressions in the query. # # When parsed as Sass code, each expression contains strings and SassScript # nodes. When parsed as CSS, each one contains a single string. # # @return [Array<Array<String, Sass::Script::Tree::Node>>] attr_accessor :expressions # @param modifier [Array<String, Sass::Script::Tree::Node>] See \{#modifier} # @param type [Array<String, Sass::Script::Tree::Node>] See \{#type} # @param expressions [Array<Array<String, Sass::Script::Tree::Node>>] See \{#expressions} def initialize(modifier, type, expressions) @modifier = modifier @type = type @expressions = expressions end # See \{#modifier}. # @return [String] def resolved_modifier # modifier should contain only a single string modifier.first || '' end # See \{#type}. # @return [String] def resolved_type # type should contain only a single string type.first || '' end # Merges this query with another. The returned query queries for # the intersection between the two inputs. # # Both queries should be resolved. # # @param other [Query] # @return [Query?] The merged query, or nil if there is no intersection. def merge(other) m1, t1 = resolved_modifier.downcase, resolved_type.downcase m2, t2 = other.resolved_modifier.downcase, other.resolved_type.downcase t1 = t2 if t1.empty? t2 = t1 if t2.empty? if (m1 == 'not') ^ (m2 == 'not') return if t1 == t2 type = m1 == 'not' ? t2 : t1 mod = m1 == 'not' ? m2 : m1 elsif m1 == 'not' && m2 == 'not' # CSS has no way of representing "neither screen nor print" return unless t1 == t2 type = t1 mod = 'not' elsif t1 != t2 return else # t1 == t2, neither m1 nor m2 are "not" type = t1 mod = m1.empty? ? m2 : m1 end Query.new([mod], [type], other.expressions + expressions) end # Returns the CSS for the media query. # # @return [String] def to_css css = '' css << resolved_modifier css << ' ' unless resolved_modifier.empty? css << resolved_type css << ' and ' unless resolved_type.empty? || expressions.empty? css << expressions.map do |e| # It's possible for there to be script nodes in Expressions even when # we're converting to CSS in the case where we parsed the document as # CSS originally (as in css_test.rb). e.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.to_sass : c.to_s}.join end.join(' and ') css end # Returns the Sass/SCSS code for the media query. # # @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}). # @return [String] def to_src(options) src = '' src << Sass::Media._interp_to_src(modifier, options) src << ' ' unless modifier.empty? src << Sass::Media._interp_to_src(type, options) src << ' and ' unless type.empty? || expressions.empty? src << expressions.map do |e| Sass::Media._interp_to_src(e, options) end.join(' and ') src end # @see \{MediaQuery#to\_a} def to_a res = [] res += modifier res << ' ' unless modifier.empty? res += type res << ' and ' unless type.empty? || expressions.empty? res += Sass::Util.intersperse(expressions, ' and ').flatten res end # Returns a deep copy of this query and all its children. # # @return [Query] def deep_copy Query.new( modifier.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.deep_copy : c}, type.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.deep_copy : c}, expressions.map {|e| e.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.deep_copy : c}}) end end # Converts an interpolation array to source. # # @param interp [Array<String, Sass::Script::Tree::Node>] The interpolation array to convert. # @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}). # @return [String] def self._interp_to_src(interp, options) interp.map {|r| r.is_a?(String) ? r : r.to_sass(options)}.join 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/css.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/css.rb
require File.dirname(__FILE__) + '/../sass' require 'sass/tree/node' require 'sass/scss/css_parser' module Sass # This class converts CSS documents into Sass or SCSS templates. # It works by parsing the CSS document into a {Sass::Tree} structure, # and then applying various transformations to the structure # to produce more concise and idiomatic Sass/SCSS. # # Example usage: # # Sass::CSS.new("p { color: blue }").render(:sass) #=> "p\n color: blue" # Sass::CSS.new("p { color: blue }").render(:scss) #=> "p {\n color: blue; }" class CSS # @param template [String] The CSS stylesheet. # This stylesheet can be encoded using any encoding # that can be converted to Unicode. # If the stylesheet contains an `@charset` declaration, # that overrides the Ruby encoding # (see {file:SASS_REFERENCE.md#Encodings the encoding documentation}) # @option options :old [Boolean] (false) # Whether or not to output old property syntax # (`:color blue` as opposed to `color: blue`). # This is only meaningful when generating Sass code, # rather than SCSS. # @option options :indent [String] (" ") # The string to use for indenting each line. Defaults to two spaces. def initialize(template, options = {}) if template.is_a? IO template = template.read end @options = options.merge(:_convert => true) # Backwards compatibility @options[:old] = true if @options[:alternate] == false @template = template @checked_encoding = false end # Converts the CSS template into Sass or SCSS code. # # @param fmt [Symbol] `:sass` or `:scss`, designating the format to return. # @return [String] The resulting Sass or SCSS code # @raise [Sass::SyntaxError] if there's an error parsing the CSS template def render(fmt = :sass) check_encoding! build_tree.send("to_#{fmt}", @options).strip + "\n" rescue Sass::SyntaxError => err err.modify_backtrace(:filename => @options[:filename] || '(css)') raise err end # Returns the original encoding of the document. # # @return [Encoding, nil] # @raise [Encoding::UndefinedConversionError] if the source encoding # cannot be converted to UTF-8 # @raise [ArgumentError] if the document uses an unknown encoding with `@charset` def source_encoding check_encoding! @original_encoding end private def check_encoding! return if @checked_encoding @checked_encoding = true @template, @original_encoding = Sass::Util.check_sass_encoding(@template) end # Parses the CSS template and applies various transformations # # @return [Tree::Node] The root node of the parsed tree def build_tree root = Sass::SCSS::CssParser.new(@template, @options[:filename], nil).parse parse_selectors(root) expand_commas(root) nest_seqs(root) parent_ref_rules(root) flatten_rules(root) bubble_subject(root) fold_commas(root) dump_selectors(root) root end # Parse all the selectors in the document and assign them to # {Sass::Tree::RuleNode#parsed_rules}. # # @param root [Tree::Node] The parent node def parse_selectors(root) root.children.each do |child| next parse_selectors(child) if child.is_a?(Tree::DirectiveNode) next unless child.is_a?(Tree::RuleNode) parser = Sass::SCSS::CssParser.new(child.rule.first, child.filename, nil, child.line) child.parsed_rules = parser.parse_selector end end # Transform # # foo, bar, baz # color: blue # # into # # foo # color: blue # bar # color: blue # baz # color: blue # # @param root [Tree::Node] The parent node def expand_commas(root) root.children.map! do |child| # child.parsed_rules.members.size > 1 iff the rule contains a comma unless child.is_a?(Tree::RuleNode) && child.parsed_rules.members.size > 1 expand_commas(child) if child.is_a?(Tree::DirectiveNode) next child end child.parsed_rules.members.map do |seq| node = Tree::RuleNode.new([]) node.parsed_rules = make_cseq(seq) node.children = child.children node end end root.children.flatten! end # Make rules use nesting so that # # foo # color: green # foo bar # color: red # foo baz # color: blue # # becomes # # foo # color: green # bar # color: red # baz # color: blue # # @param root [Tree::Node] The parent node def nest_seqs(root) current_rule = nil root.children.map! do |child| unless child.is_a?(Tree::RuleNode) nest_seqs(child) if child.is_a?(Tree::DirectiveNode) next child end seq = first_seq(child) seq.members.reject! {|sseq| sseq == "\n"} first, rest = seq.members.first, seq.members[1..-1] if current_rule.nil? || first_sseq(current_rule) != first current_rule = Tree::RuleNode.new([]) current_rule.parsed_rules = make_seq(first) end if rest.empty? current_rule.children += child.children else child.parsed_rules = make_seq(*rest) current_rule << child end current_rule end root.children.compact! root.children.uniq! root.children.each {|v| nest_seqs(v)} end # Make rules use parent refs so that # # foo # color: green # foo.bar # color: blue # # becomes # # foo # color: green # &.bar # color: blue # # @param root [Tree::Node] The parent node def parent_ref_rules(root) current_rule = nil root.children.map! do |child| unless child.is_a?(Tree::RuleNode) parent_ref_rules(child) if child.is_a?(Tree::DirectiveNode) next child end sseq = first_sseq(child) next child unless sseq.is_a?(Sass::Selector::SimpleSequence) firsts, rest = [sseq.members.first], sseq.members[1..-1] firsts.push rest.shift if firsts.first.is_a?(Sass::Selector::Parent) last_simple_subject = rest.empty? && sseq.subject? if current_rule.nil? || first_sseq(current_rule).members != firsts || !!first_sseq(current_rule).subject? != !!last_simple_subject current_rule = Tree::RuleNode.new([]) current_rule.parsed_rules = make_sseq(last_simple_subject, *firsts) end if rest.empty? current_rule.children += child.children else rest.unshift Sass::Selector::Parent.new child.parsed_rules = make_sseq(sseq.subject?, *rest) current_rule << child end current_rule end root.children.compact! root.children.uniq! root.children.each {|v| parent_ref_rules(v)} end # Flatten rules so that # # foo # bar # color: red # # becomes # # foo bar # color: red # # and # # foo # &.bar # color: blue # # becomes # # foo.bar # color: blue # # @param root [Tree::Node] The parent node def flatten_rules(root) root.children.each do |child| case child when Tree::RuleNode flatten_rule(child) when Tree::DirectiveNode flatten_rules(child) end end end # Flattens a single rule. # # @param rule [Tree::RuleNode] The candidate for flattening # @see #flatten_rules def flatten_rule(rule) while rule.children.size == 1 && rule.children.first.is_a?(Tree::RuleNode) child = rule.children.first if first_simple_sel(child).is_a?(Sass::Selector::Parent) rule.parsed_rules = child.parsed_rules.resolve_parent_refs(rule.parsed_rules) else rule.parsed_rules = make_seq(*(first_seq(rule).members + first_seq(child).members)) end rule.children = child.children end flatten_rules(rule) end def bubble_subject(root) root.children.each do |child| bubble_subject(child) if child.is_a?(Tree::RuleNode) || child.is_a?(Tree::DirectiveNode) next unless child.is_a?(Tree::RuleNode) && !child.children.empty? next unless child.children.all? do |c| next unless c.is_a?(Tree::RuleNode) first_simple_sel(c).is_a?(Sass::Selector::Parent) && first_sseq(c).subject? end first_sseq(child).subject = true child.children.each {|c| first_sseq(c).subject = false} end end # Transform # # foo # bar # color: blue # baz # color: blue # # into # # foo # bar, baz # color: blue # # @param root [Tree::Node] The parent node def fold_commas(root) prev_rule = nil root.children.map! do |child| unless child.is_a?(Tree::RuleNode) fold_commas(child) if child.is_a?(Tree::DirectiveNode) next child end if prev_rule && prev_rule.children.map {|c| c.to_sass} == child.children.map {|c| c.to_sass} prev_rule.parsed_rules.members << first_seq(child) next nil end fold_commas(child) prev_rule = child child end root.children.compact! end # Dump all the parsed {Sass::Tree::RuleNode} selectors to strings. # # @param root [Tree::Node] The parent node def dump_selectors(root) root.children.each do |child| next dump_selectors(child) if child.is_a?(Tree::DirectiveNode) next unless child.is_a?(Tree::RuleNode) child.rule = [child.parsed_rules.to_s] dump_selectors(child) end end # Create a {Sass::Selector::CommaSequence}. # # @param seqs [Array<Sass::Selector::Sequence>] # @return [Sass::Selector::CommaSequence] def make_cseq(*seqs) Sass::Selector::CommaSequence.new(seqs) end # Create a {Sass::Selector::CommaSequence} containing only a single # {Sass::Selector::Sequence}. # # @param sseqs [Array<Sass::Selector::Sequence, String>] # @return [Sass::Selector::CommaSequence] def make_seq(*sseqs) make_cseq(Sass::Selector::Sequence.new(sseqs)) end # Create a {Sass::Selector::CommaSequence} containing only a single # {Sass::Selector::Sequence} which in turn contains only a single # {Sass::Selector::SimpleSequence}. # # @param subject [Boolean] Whether this is a subject selector # @param sseqs [Array<Sass::Selector::Sequence, String>] # @return [Sass::Selector::CommaSequence] def make_sseq(subject, *sseqs) make_seq(Sass::Selector::SimpleSequence.new(sseqs, subject)) end # Return the first {Sass::Selector::Sequence} in a {Sass::Tree::RuleNode}. # # @param rule [Sass::Tree::RuleNode] # @return [Sass::Selector::Sequence] def first_seq(rule) rule.parsed_rules.members.first end # Return the first {Sass::Selector::SimpleSequence} in a # {Sass::Tree::RuleNode}. # # @param rule [Sass::Tree::RuleNode] # @return [Sass::Selector::SimpleSequence, String] def first_sseq(rule) first_seq(rule).members.first end # Return the first {Sass::Selector::Simple} in a {Sass::Tree::RuleNode}, # unless the rule begins with a combinator. # # @param rule [Sass::Tree::RuleNode] # @return [Sass::Selector::Simple?] def first_simple_sel(rule) sseq = first_sseq(rule) return unless sseq.is_a?(Sass::Selector::SimpleSequence) sseq.members.first 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/environment.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/environment.rb
require 'set' module Sass # The abstract base class for lexical environments for SassScript. class BaseEnvironment class << self # Note: when updating this, # update sass/yard/inherited_hash.rb as well. def inherited_hash_accessor(name) inherited_hash_reader(name) inherited_hash_writer(name) end def inherited_hash_reader(name) class_eval <<-RUBY, __FILE__, __LINE__ + 1 def #{name}(name) _#{name}(name.tr('_', '-')) end def _#{name}(name) (@#{name}s && @#{name}s[name]) || @parent && @parent._#{name}(name) end protected :_#{name} def is_#{name}_global?(name) return !@parent if @#{name}s && @#{name}s.has_key?(name) @parent && @parent.is_#{name}_global?(name) end RUBY end def inherited_hash_writer(name) class_eval <<-RUBY, __FILE__, __LINE__ + 1 def set_#{name}(name, value) name = name.tr('_', '-') @#{name}s[name] = value unless try_set_#{name}(name, value) end def try_set_#{name}(name, value) @#{name}s ||= {} if @#{name}s.include?(name) @#{name}s[name] = value true elsif @parent && !@parent.global? @parent.try_set_#{name}(name, value) else false end end protected :try_set_#{name} def set_local_#{name}(name, value) @#{name}s ||= {} @#{name}s[name.tr('_', '-')] = value end def set_global_#{name}(name, value) global_env.set_#{name}(name, value) end RUBY end end # The options passed to the Sass Engine. attr_reader :options attr_writer :caller attr_writer :content attr_writer :selector # variable # Script::Value inherited_hash_reader :var # mixin # Sass::Callable inherited_hash_reader :mixin # function # Sass::Callable inherited_hash_reader :function # @param options [{Symbol => Object}] The options hash. See # {file:SASS_REFERENCE.md#Options the Sass options documentation}. # @param parent [Environment] See \{#parent} def initialize(parent = nil, options = nil) @parent = parent @options = options || (parent && parent.options) || {} @stack = @parent.nil? ? Sass::Stack.new : nil @caller = nil @content = nil @filename = nil @functions = nil @mixins = nil @selector = nil @vars = nil end # Returns whether this is the global environment. # # @return [Boolean] def global? @parent.nil? end # The environment of the caller of this environment's mixin or function. # @return {Environment?} def caller @caller || (@parent && @parent.caller) end # The content passed to this environment. This is naturally only set # for mixin body environments with content passed in. # # @return {[Array<Sass::Tree::Node>, Environment]?} The content nodes and # the lexical environment of the content block. def content @content || (@parent && @parent.content) end # The selector for the current CSS rule, or nil if there is no # current CSS rule. # # @return [Selector::CommaSequence?] The current selector, with any # nesting fully resolved. def selector @selector || (@caller && @caller.selector) || (@parent && @parent.selector) end # The top-level Environment object. # # @return [Environment] def global_env @global_env ||= global? ? self : @parent.global_env end # The import/mixin stack. # # @return [Sass::Stack] def stack @stack || global_env.stack end end # The lexical environment for SassScript. # This keeps track of variable, mixin, and function definitions. # # A new environment is created for each level of Sass nesting. # This allows variables to be lexically scoped. # The new environment refers to the environment in the upper scope, # so it has access to variables defined in enclosing scopes, # but new variables are defined locally. # # Environment also keeps track of the {Engine} options # so that they can be made available to {Sass::Script::Functions}. class Environment < BaseEnvironment # The enclosing environment, # or nil if this is the global environment. # # @return [Environment] attr_reader :parent # variable # Script::Value inherited_hash_writer :var # mixin # Sass::Callable inherited_hash_writer :mixin # function # Sass::Callable inherited_hash_writer :function end # A read-only wrapper for a lexical environment for SassScript. class ReadOnlyEnvironment < BaseEnvironment def initialize(parent = nil, options = nil) super @content_cached = nil end # The read-only environment of the caller of this environment's mixin or function. # # @see BaseEnvironment#caller # @return {ReadOnlyEnvironment} def caller return @caller if @caller env = super @caller ||= env.is_a?(ReadOnlyEnvironment) ? env : ReadOnlyEnvironment.new(env, env.options) end # The content passed to this environment. If the content's environment isn't already # read-only, it's made read-only. # # @see BaseEnvironment#content # # @return {[Array<Sass::Tree::Node>, ReadOnlyEnvironment]?} The content nodes and # the lexical environment of the content block. # Returns `nil` when there is no content in this environment. def content # Return the cached content from a previous invocation if any return @content if @content_cached # get the content with a read-write environment from the superclass read_write_content = super if read_write_content tree, env = read_write_content # make the content's environment read-only if env && !env.is_a?(ReadOnlyEnvironment) env = ReadOnlyEnvironment.new(env, env.options) end @content_cached = true @content = [tree, env] else @content_cached = true @content = nil end end end # An environment that can write to in-scope global variables, but doesn't # create new variables in the global scope. Useful for top-level control # directives. class SemiGlobalEnvironment < Environment def try_set_var(name, value) @vars ||= {} if @vars.include?(name) @vars[name] = value true elsif @parent @parent.try_set_var(name, value) else 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/logger.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/logger.rb
module Sass::Logger; end require "sass/logger/log_level" require "sass/logger/base" require "sass/logger/delayed" module Sass class << self def logger=(l) Thread.current[:sass_logger] = l end def logger Thread.current[:sass_logger] ||= Sass::Logger::Base.new 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/supports.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/supports.rb
# A namespace for the `@supports` condition parse tree. module Sass::Supports # The abstract superclass of all Supports conditions. class Condition # Runs the SassScript in the supports condition. # # @param environment [Sass::Environment] The environment in which to run the script. def perform(environment); Sass::Util.abstract(self); end # Returns the CSS for this condition. # # @return [String] def to_css; Sass::Util.abstract(self); end # Returns the Sass/CSS code for this condition. # # @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}). # @return [String] def to_src(options); Sass::Util.abstract(self); end # Returns a deep copy of this condition and all its children. # # @return [Condition] def deep_copy; Sass::Util.abstract(self); end # Sets the options hash for the script nodes in the supports condition. # # @param options [{Symbol => Object}] The options has to set. def options=(options); Sass::Util.abstract(self); end end # An operator condition (e.g. `CONDITION1 and CONDITION2`). class Operator < Condition # The left-hand condition. # # @return [Sass::Supports::Condition] attr_accessor :left # The right-hand condition. # # @return [Sass::Supports::Condition] attr_accessor :right # The operator ("and" or "or"). # # @return [String] attr_accessor :op def initialize(left, right, op) @left = left @right = right @op = op end def perform(env) @left.perform(env) @right.perform(env) end def to_css "#{parens @left, @left.to_css} #{op} #{parens @right, @right.to_css}" end def to_src(options) "#{parens @left, @left.to_src(options)} #{op} #{parens @right, @right.to_src(options)}" end def deep_copy copy = dup copy.left = @left.deep_copy copy.right = @right.deep_copy copy end def options=(options) @left.options = options @right.options = options end private def parens(condition, str) if condition.is_a?(Negation) || (condition.is_a?(Operator) && condition.op != op) return "(#{str})" else return str end end end # A negation condition (`not CONDITION`). class Negation < Condition # The condition being negated. # # @return [Sass::Supports::Condition] attr_accessor :condition def initialize(condition) @condition = condition end def perform(env) @condition.perform(env) end def to_css "not #{parens @condition.to_css}" end def to_src(options) "not #{parens @condition.to_src(options)}" end def deep_copy copy = dup copy.condition = condition.deep_copy copy end def options=(options) condition.options = options end private def parens(str) return "(#{str})" if @condition.is_a?(Negation) || @condition.is_a?(Operator) str end end # A declaration condition (e.g. `(feature: value)`). class Declaration < Condition # @return [Sass::Script::Tree::Node] The feature name. attr_accessor :name # @!attribute resolved_name # The name of the feature after any SassScript has been resolved. # Only set once \{Tree::Visitors::Perform} has been run. # # @return [String] attr_accessor :resolved_name # The feature value. # # @return [Sass::Script::Tree::Node] attr_accessor :value # The value of the feature after any SassScript has been resolved. # Only set once \{Tree::Visitors::Perform} has been run. # # @return [String] attr_accessor :resolved_value def initialize(name, value) @name = name @value = value end def perform(env) @resolved_name = name.perform(env) @resolved_value = value.perform(env) end def to_css "(#{@resolved_name}: #{@resolved_value})" end def to_src(options) "(#{@name.to_sass(options)}: #{@value.to_sass(options)})" end def deep_copy copy = dup copy.name = @name.deep_copy copy.value = @value.deep_copy copy end def options=(options) @name.options = options @value.options = options end end # An interpolation condition (e.g. `#{$var}`). class Interpolation < Condition # The SassScript expression in the interpolation. # # @return [Sass::Script::Tree::Node] attr_accessor :value # The value of the expression after it's been resolved. # Only set once \{Tree::Visitors::Perform} has been run. # # @return [String] attr_accessor :resolved_value def initialize(value) @value = value end def perform(env) @resolved_value = value.perform(env).to_s(:quote => :none) end def to_css @resolved_value end def to_src(options) @value.to_sass(options) end def deep_copy copy = dup copy.value = @value.deep_copy copy end def options=(options) @value.options = options 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.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/plugin.rb
require 'fileutils' require 'sass' require 'sass/plugin/compiler' module Sass # This module provides a single interface to the compilation of Sass/SCSS files # for an application. It provides global options and checks whether CSS files # need to be updated. # # This module is used as the primary interface with Sass # when it's used as a plugin for various frameworks. # All Rack-enabled frameworks are supported out of the box. # The plugin is # {file:SASS_REFERENCE.md#Rack_Rails_Merb_Plugin automatically activated for Rails and Merb}. # Other frameworks must enable it explicitly; see {Sass::Plugin::Rack}. # # This module has a large set of callbacks available # to allow users to run code (such as logging) when certain things happen. # All callback methods are of the form `on_#{name}`, # and they all take a block that's called when the given action occurs. # # Note that this class proxies almost all methods to its {Sass::Plugin::Compiler} instance. # See \{#compiler}. # # @example Using a callback # Sass::Plugin.on_updating_stylesheet do |template, css| # puts "Compiling #{template} to #{css}" # end # Sass::Plugin.update_stylesheets # #=> Compiling app/sass/screen.scss to public/stylesheets/screen.css # #=> Compiling app/sass/print.scss to public/stylesheets/print.css # #=> Compiling app/sass/ie.scss to public/stylesheets/ie.css # @see Sass::Plugin::Compiler module Plugin extend self @checked_for_updates = false # Whether or not Sass has **ever** checked if the stylesheets need to be updated # (in this Ruby instance). # # @return [Boolean] attr_accessor :checked_for_updates # Same as \{#update\_stylesheets}, but respects \{#checked\_for\_updates} # and the {file:SASS_REFERENCE.md#always_update-option `:always_update`} # and {file:SASS_REFERENCE.md#always_check-option `:always_check`} options. # # @see #update_stylesheets def check_for_updates return unless !Sass::Plugin.checked_for_updates || Sass::Plugin.options[:always_update] || Sass::Plugin.options[:always_check] update_stylesheets end # Returns the singleton compiler instance. # This compiler has been pre-configured according # to the plugin configuration. # # @return [Sass::Plugin::Compiler] def compiler @compiler ||= Compiler.new end # 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)>] # 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. def update_stylesheets(individual_files = []) return if options[:never_update] compiler.update_stylesheets(individual_files) end # Updates all stylesheets, even those that aren't out-of-date. # Ignores the cache. # # @param individual_files [Array<(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. # @see #update_stylesheets def force_update_stylesheets(individual_files = []) Compiler.new( options.dup.merge( :never_update => false, :always_update => true, :cache => false)).update_stylesheets(individual_files) end # All other method invocations are proxied to the \{#compiler}. # # @see #compiler # @see Sass::Plugin::Compiler def method_missing(method, *args, &block) if compiler.respond_to?(method) compiler.send(method, *args, &block) else super end end # For parity with method_missing def respond_to?(method) super || compiler.respond_to?(method) end # There's a small speedup by not using method missing for frequently delegated methods. def options compiler.options end end end if defined?(ActionController) # On Rails 3+ the rails plugin is loaded at the right time in railtie.rb require 'sass/plugin/rails' unless Sass::Util.ap_geq_3? elsif defined?(Merb::Plugins) require 'sass/plugin/merb' else require 'sass/plugin/generic' 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/callbacks.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/callbacks.rb
module Sass # A lightweight infrastructure for defining and running callbacks. # Callbacks are defined using \{#define\_callback\} at the class level, # and called using `run_#{name}` at the instance level. # # Clients can add callbacks by calling the generated `on_#{name}` method, # and passing in a block that's run when the callback is activated. # # @example Define a callback # class Munger # extend Sass::Callbacks # define_callback :string_munged # # def munge(str) # res = str.gsub(/[a-z]/, '\1\1') # run_string_munged str, res # res # end # end # # @example Use a callback # m = Munger.new # m.on_string_munged {|str, res| puts "#{str} was munged into #{res}!"} # m.munge "bar" #=> bar was munged into bbaarr! module Callbacks # Automatically includes {InstanceMethods} # when something extends this module. # # @param base [Module] def self.extended(base) base.send(:include, InstanceMethods) end protected module InstanceMethods # Removes all callbacks registered against this object. def clear_callbacks! @_sass_callbacks = {} end end # Define a callback with the given name. # This will define an `on_#{name}` method # that registers a block, # and a `run_#{name}` method that runs that block # (optionall with some arguments). # # @param name [Symbol] The name of the callback # @return [void] def define_callback(name) class_eval <<RUBY, __FILE__, __LINE__ + 1 def on_#{name}(&block) @_sass_callbacks = {} unless defined? @_sass_callbacks (@_sass_callbacks[#{name.inspect}] ||= []) << block end def run_#{name}(*args) return unless defined? @_sass_callbacks return unless @_sass_callbacks[#{name.inspect}] @_sass_callbacks[#{name.inspect}].each {|c| c[*args]} end private :run_#{name} RUBY 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/repl.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/repl.rb
require 'readline' module Sass # Runs a SassScript read-eval-print loop. # It presents a prompt on the terminal, # reads in SassScript expressions, # evaluates them, # and prints the result. class Repl # @param options [{Symbol => Object}] An options hash. def initialize(options = {}) @options = options end # Starts the read-eval-print loop. def run environment = Environment.new @line = 0 loop do @line += 1 unless (text = Readline.readline('>> ')) puts return end Readline::HISTORY << text parse_input(environment, text) end end private def parse_input(environment, text) case text when Script::MATCH name = $1 guarded = !!$3 val = Script::Parser.parse($2, @line, text.size - ($3 || '').size - $2.size) unless guarded && environment.var(name) environment.set_var(name, val.perform(environment)) end p environment.var(name) else p Script::Parser.parse(text, @line, 0).perform(environment) end rescue Sass::SyntaxError => e puts "SyntaxError: #{e.message}" if @options[:trace] e.backtrace.each do |line| puts "\tfrom #{line}" 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/stack.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/stack.rb
module Sass # A class representing the stack when compiling a Sass file. class Stack # TODO: use this to generate stack information for Sass::SyntaxErrors. # A single stack frame. class Frame # The filename of the file in which this stack frame was created. # # @return [String] attr_reader :filename # The line number on which this stack frame was created. # # @return [String] attr_reader :line # The type of this stack frame. This can be `:import`, `:mixin`, or # `:base`. # # `:base` indicates that this is the bottom-most frame, meaning that it # represents a single line of code rather than a nested context. The stack # will only ever have one base frame, and it will always be the most # deeply-nested frame. # # @return [Symbol?] attr_reader :type # The name of the stack frame. For mixin frames, this is the mixin name; # otherwise, it's `nil`. # # @return [String?] attr_reader :name def initialize(filename, line, type, name = nil) @filename = filename @line = line @type = type @name = name end # Whether this frame represents an import. # # @return [Boolean] def is_import? type == :import end # Whether this frame represents a mixin. # # @return [Boolean] def is_mixin? type == :mixin end # Whether this is the base frame. # # @return [Boolean] def is_base? type == :base end end # The stack frames. The last frame is the most deeply-nested. # # @return [Array<Frame>] attr_reader :frames def initialize @frames = [] end # Pushes a base frame onto the stack. # # @param filename [String] See \{Frame#filename}. # @param line [String] See \{Frame#line}. # @yield [] A block in which the new frame is on the stack. def with_base(filename, line) with_frame(filename, line, :base) {yield} end # Pushes an import frame onto the stack. # # @param filename [String] See \{Frame#filename}. # @param line [String] See \{Frame#line}. # @yield [] A block in which the new frame is on the stack. def with_import(filename, line) with_frame(filename, line, :import) {yield} end # Pushes a mixin frame onto the stack. # # @param filename [String] See \{Frame#filename}. # @param line [String] See \{Frame#line}. # @param name [String] See \{Frame#name}. # @yield [] A block in which the new frame is on the stack. def with_mixin(filename, line, name) with_frame(filename, line, :mixin, name) {yield} end # Pushes a function frame onto the stack. # # @param filename [String] See \{Frame#filename}. # @param line [String] See \{Frame#line}. # @param name [String] See \{Frame#name}. # @yield [] A block in which the new frame is on the stack. def with_function(filename, line, name) with_frame(filename, line, :function, name) {yield} end # Pushes a function frame onto the stack. # # @param filename [String] See \{Frame#filename}. # @param line [String] See \{Frame#line}. # @param name [String] See \{Frame#name}. # @yield [] A block in which the new frame is on the stack. def with_directive(filename, line, name) with_frame(filename, line, :directive, name) {yield} end def to_s (frames.reverse + [nil]).each_cons(2).each_with_index. map do |(frame, caller), i| "#{i == 0 ? 'on' : 'from'} line #{frame.line}" + " of #{frame.filename || 'an unknown file'}" + (caller && caller.name ? ", in `#{caller.name}'" : "") end.join("\n") end private def with_frame(filename, line, type, name = nil) @frames.pop if @frames.last && @frames.last.type == :base @frames.push(Frame.new(filename, line, type, name)) yield ensure @frames.pop unless type == :base && @frames.last && @frames.last.type != :base 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.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/importers.rb
module Sass # Sass importers are in charge of taking paths passed to `@import` # and finding the appropriate Sass code for those paths. # By default, this code is always loaded from the filesystem, # but importers could be added to load from a database or over HTTP. # # Each importer is in charge of a single load path # (or whatever the corresponding notion is for the backend). # Importers can be placed in the {file:SASS_REFERENCE.md#load_paths-option `:load_paths` array} # alongside normal filesystem paths. # # When resolving an `@import`, Sass will go through the load paths # looking for an importer that successfully imports the path. # Once one is found, the imported file is used. # # User-created importers must inherit from {Importers::Base}. module Importers end end require 'sass/importers/base' require 'sass/importers/filesystem' require 'sass/importers/deprecated_path'
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.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/exec.rb
module Sass # This module handles the Sass executables (`sass` and `sass-convert`). module Exec end end require 'sass/exec/base' require 'sass/exec/sass_scss' require 'sass/exec/sass_convert'
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/railtie.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/railtie.rb
# Rails 3.0.0.beta.2+, < 3.1 if defined?(ActiveSupport) && ActiveSupport.public_methods.include?(:on_load) && !Sass::Util.ap_geq?('3.1.0.beta') require 'sass/plugin/configuration' ActiveSupport.on_load(:before_configuration) do require 'sass' require 'sass/plugin' require 'sass/plugin/rails' 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/root.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/root.rb
module Sass # The root directory of the Sass source tree. # This may be overridden by the package manager # if the lib directory is separated from the main source tree. # @api public ROOT_DIR = File.expand_path(File.join(__FILE__, "../../..")) 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.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/scss.rb
require 'sass/scss/rx' require 'sass/scss/parser' require 'sass/scss/static_parser' require 'sass/scss/css_parser' module Sass # SCSS is the CSS syntax for Sass. # It parses into the same syntax tree as Sass, # and generates the same sort of output CSS. # # This module contains code for the parsing of SCSS. # The evaluation is handled by the broader {Sass} module. module SCSS; 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/engine.rb
_vendor/ruby/2.6.0/gems/sass-3.6.0/lib/sass/engine.rb
require 'set' require 'digest/sha1' require 'sass/cache_stores' require 'sass/deprecation' require 'sass/source/position' require 'sass/source/range' require 'sass/source/map' require 'sass/tree/node' require 'sass/tree/root_node' require 'sass/tree/rule_node' require 'sass/tree/comment_node' require 'sass/tree/prop_node' require 'sass/tree/directive_node' require 'sass/tree/media_node' require 'sass/tree/supports_node' require 'sass/tree/css_import_node' require 'sass/tree/variable_node' require 'sass/tree/mixin_def_node' require 'sass/tree/mixin_node' require 'sass/tree/trace_node' require 'sass/tree/content_node' require 'sass/tree/function_node' require 'sass/tree/return_node' require 'sass/tree/extend_node' require 'sass/tree/if_node' require 'sass/tree/while_node' require 'sass/tree/for_node' require 'sass/tree/each_node' require 'sass/tree/debug_node' require 'sass/tree/warn_node' require 'sass/tree/import_node' require 'sass/tree/charset_node' require 'sass/tree/at_root_node' require 'sass/tree/keyframe_rule_node' require 'sass/tree/error_node' require 'sass/tree/visitors/base' require 'sass/tree/visitors/perform' require 'sass/tree/visitors/cssize' require 'sass/tree/visitors/extend' require 'sass/tree/visitors/convert' require 'sass/tree/visitors/to_css' require 'sass/tree/visitors/deep_copy' require 'sass/tree/visitors/set_options' require 'sass/tree/visitors/check_nesting' require 'sass/selector' require 'sass/environment' require 'sass/script' require 'sass/scss' require 'sass/stack' require 'sass/error' require 'sass/importers' require 'sass/shared' require 'sass/media' require 'sass/supports' module Sass # A Sass mixin or function. # # `name`: `String` # : The name of the mixin/function. # # `args`: `Array<(Script::Tree::Node, Script::Tree::Node)>` # : The arguments for the mixin/function. # Each element is a tuple containing the variable node of the argument # and the parse tree for the default value of the argument. # # `splat`: `Script::Tree::Node?` # : The variable node of the splat argument for this callable, or null. # # `environment`: {Sass::Environment} # : The environment in which the mixin/function was defined. # This is captured so that the mixin/function can have access # to local variables defined in its scope. # # `tree`: `Array<Tree::Node>` # : The parse tree for the mixin/function. # # `has_content`: `Boolean` # : Whether the callable accepts a content block. # # `type`: `String` # : The user-friendly name of the type of the callable. # # `origin`: `Symbol` # : From whence comes the callable: `:stylesheet`, `:builtin`, `:css` # A callable with an origin of `:stylesheet` was defined in the stylesheet itself. # A callable with an origin of `:builtin` was defined in ruby. # A callable (function) with an origin of `:css` returns a function call with arguments to CSS. Callable = Struct.new(:name, :args, :splat, :environment, :tree, :has_content, :type, :origin) # This class handles the parsing and compilation of the Sass template. # Example usage: # # template = File.read('stylesheets/sassy.sass') # sass_engine = Sass::Engine.new(template) # output = sass_engine.render # puts output class Engine @@old_property_deprecation = Deprecation.new # A line of Sass code. # # `text`: `String` # : The text in the line, without any whitespace at the beginning or end. # # `tabs`: `Integer` # : The level of indentation of the line. # # `index`: `Integer` # : The line number in the original document. # # `offset`: `Integer` # : The number of bytes in on the line that the text begins. # This ends up being the number of bytes of leading whitespace. # # `filename`: `String` # : The name of the file in which this line appeared. # # `children`: `Array<Line>` # : The lines nested below this one. # # `comment_tab_str`: `String?` # : The prefix indentation for this comment, if it is a comment. class Line < Struct.new(:text, :tabs, :index, :offset, :filename, :children, :comment_tab_str) def comment? text[0] == COMMENT_CHAR && (text[1] == SASS_COMMENT_CHAR || text[1] == CSS_COMMENT_CHAR) end end # The character that begins a CSS property. PROPERTY_CHAR = ?: # The character that designates the beginning of a comment, # either Sass or CSS. COMMENT_CHAR = ?/ # The character that follows the general COMMENT_CHAR and designates a Sass comment, # which is not output as a CSS comment. SASS_COMMENT_CHAR = ?/ # The character that indicates that a comment allows interpolation # and should be preserved even in `:compressed` mode. SASS_LOUD_COMMENT_CHAR = ?! # The character that follows the general COMMENT_CHAR and designates a CSS comment, # which is embedded in the CSS document. CSS_COMMENT_CHAR = ?* # The character used to denote a compiler directive. DIRECTIVE_CHAR = ?@ # Designates a non-parsed rule. ESCAPE_CHAR = ?\\ # Designates block as mixin definition rather than CSS rules to output MIXIN_DEFINITION_CHAR = ?= # Includes named mixin declared using MIXIN_DEFINITION_CHAR MIXIN_INCLUDE_CHAR = ?+ # The regex that matches and extracts data from # properties of the form `:name prop`. PROPERTY_OLD = /^:([^\s=:"]+)\s*(?:\s+|$)(.*)/ # The default options for Sass::Engine. # @api public DEFAULT_OPTIONS = { :style => :nested, :load_paths => [], :cache => true, :cache_location => './.sass-cache', :syntax => :sass, :filesystem_importer => Sass::Importers::Filesystem }.freeze # Converts a Sass options hash into a standard form, filling in # default values and resolving aliases. # # @param options [{Symbol => Object}] The options hash; # see {file:SASS_REFERENCE.md#Options the Sass options documentation} # @return [{Symbol => Object}] The normalized options hash. # @private def self.normalize_options(options) options = DEFAULT_OPTIONS.merge(options.reject {|_k, v| v.nil?}) # If the `:filename` option is passed in without an importer, # assume it's using the default filesystem importer. options[:importer] ||= options[:filesystem_importer].new(".") if options[:filename] # Tracks the original filename of the top-level Sass file options[:original_filename] ||= options[:filename] options[:cache_store] ||= Sass::CacheStores::Chain.new( Sass::CacheStores::Memory.new, Sass::CacheStores::Filesystem.new(options[:cache_location])) # Support both, because the docs said one and the other actually worked # for quite a long time. options[:line_comments] ||= options[:line_numbers] options[:load_paths] = (options[:load_paths] + Sass.load_paths).map do |p| next p unless p.is_a?(String) || (defined?(Pathname) && p.is_a?(Pathname)) options[:filesystem_importer].new(p.to_s) end # Remove any deprecated importers if the location is imported explicitly options[:load_paths].reject! do |importer| importer.is_a?(Sass::Importers::DeprecatedPath) && options[:load_paths].find do |other_importer| other_importer.is_a?(Sass::Importers::Filesystem) && other_importer != importer && other_importer.root == importer.root end end # Backwards compatibility options[:property_syntax] ||= options[:attribute_syntax] case options[:property_syntax] when :alternate; options[:property_syntax] = :new when :normal; options[:property_syntax] = :old end options[:sourcemap] = :auto if options[:sourcemap] == true options[:sourcemap] = :none if options[:sourcemap] == false options end # Returns the {Sass::Engine} for the given file. # This is preferable to Sass::Engine.new when reading from a file # because it properly sets up the Engine's metadata, # enables parse-tree caching, # and infers the syntax from the filename. # # @param filename [String] The path to the Sass or SCSS file # @param options [{Symbol => Object}] The options hash; # See {file:SASS_REFERENCE.md#Options the Sass options documentation}. # @return [Sass::Engine] The Engine for the given Sass or SCSS file. # @raise [Sass::SyntaxError] if there's an error in the document. def self.for_file(filename, options) had_syntax = options[:syntax] if had_syntax # Use what was explicitly specified elsif filename =~ /\.scss$/ options.merge!(:syntax => :scss) elsif filename =~ /\.sass$/ options.merge!(:syntax => :sass) end Sass::Engine.new(File.read(filename), options.merge(:filename => filename)) end # The options for the Sass engine. # See {file:SASS_REFERENCE.md#Options the Sass options documentation}. # # @return [{Symbol => Object}] attr_reader :options # Creates a new Engine. Note that Engine should only be used directly # when compiling in-memory Sass code. # If you're compiling a single Sass file from the filesystem, # use \{Sass::Engine.for\_file}. # If you're compiling multiple files from the filesystem, # use {Sass::Plugin}. # # @param template [String] The Sass template. # This template can be encoded using any encoding # that can be converted to Unicode. # If the template contains an `@charset` declaration, # that overrides the Ruby encoding # (see {file:SASS_REFERENCE.md#Encodings the encoding documentation}) # @param options [{Symbol => Object}] An options hash. # See {file:SASS_REFERENCE.md#Options the Sass options documentation}. # @see {Sass::Engine.for_file} # @see {Sass::Plugin} def initialize(template, options = {}) @options = self.class.normalize_options(options) @template = template @checked_encoding = false @filename = nil @line = nil end # Render the template to CSS. # # @return [String] The CSS # @raise [Sass::SyntaxError] if there's an error in the document # @raise [Encoding::UndefinedConversionError] if the source encoding # cannot be converted to UTF-8 # @raise [ArgumentError] if the document uses an unknown encoding with `@charset` def render return _to_tree.render unless @options[:quiet] Sass::Util.silence_sass_warnings {_to_tree.render} end # Render the template to CSS and return the source map. # # @param sourcemap_uri [String] The sourcemap URI to use in the # `@sourceMappingURL` comment. If this is relative, it should be relative # to the location of the CSS file. # @return [(String, Sass::Source::Map)] The rendered CSS and the associated # source map # @raise [Sass::SyntaxError] if there's an error in the document, or if the # public URL for this document couldn't be determined. # @raise [Encoding::UndefinedConversionError] if the source encoding # cannot be converted to UTF-8 # @raise [ArgumentError] if the document uses an unknown encoding with `@charset` def render_with_sourcemap(sourcemap_uri) return _render_with_sourcemap(sourcemap_uri) unless @options[:quiet] Sass::Util.silence_sass_warnings {_render_with_sourcemap(sourcemap_uri)} end alias_method :to_css, :render # Parses the document into its parse tree. Memoized. # # @return [Sass::Tree::Node] The root of the parse tree. # @raise [Sass::SyntaxError] if there's an error in the document def to_tree @tree ||= if @options[:quiet] Sass::Util.silence_sass_warnings {_to_tree} else _to_tree end end # Returns the original encoding of the document. # # @return [Encoding, nil] # @raise [Encoding::UndefinedConversionError] if the source encoding # cannot be converted to UTF-8 # @raise [ArgumentError] if the document uses an unknown encoding with `@charset` def source_encoding check_encoding! @source_encoding end # Gets a set of all the documents # that are (transitive) dependencies of this document, # not including the document itself. # # @return [[Sass::Engine]] The dependency documents. def dependencies _dependencies(Set.new, engines = Set.new) Sass::Util.array_minus(engines, [self]) end # Helper for \{#dependencies}. # # @private def _dependencies(seen, engines) key = [@options[:filename], @options[:importer]] return if seen.include?(key) seen << key engines << self to_tree.grep(Tree::ImportNode) do |n| next if n.css_import? n.imported_file._dependencies(seen, engines) end end private def _render_with_sourcemap(sourcemap_uri) filename = @options[:filename] importer = @options[:importer] sourcemap_dir = @options[:sourcemap_filename] && File.dirname(File.expand_path(@options[:sourcemap_filename])) if filename.nil? raise Sass::SyntaxError.new(<<ERR) Error generating source map: couldn't determine public URL for the source stylesheet. No filename is available so there's nothing for the source map to link to. ERR elsif importer.nil? raise Sass::SyntaxError.new(<<ERR) Error generating source map: couldn't determine public URL for "#{filename}". Without a public URL, there's nothing for the source map to link to. An importer was not set for this file. ERR elsif Sass::Util.silence_sass_warnings do sourcemap_dir = nil if @options[:sourcemap] == :file importer.public_url(filename, sourcemap_dir).nil? end raise Sass::SyntaxError.new(<<ERR) Error generating source map: couldn't determine public URL for "#{filename}". Without a public URL, there's nothing for the source map to link to. Custom importers should define the #public_url method. ERR end rendered, sourcemap = _to_tree.render_with_sourcemap compressed = @options[:style] == :compressed rendered << "\n" if rendered[-1] != ?\n rendered << "\n" unless compressed rendered << "/*# sourceMappingURL=" rendered << URI::DEFAULT_PARSER.escape(sourcemap_uri) rendered << " */\n" return rendered, sourcemap end def _to_tree check_encoding! if (@options[:cache] || @options[:read_cache]) && @options[:filename] && @options[:importer] key = sassc_key sha = Digest::SHA1.hexdigest(@template) if (root = @options[:cache_store].retrieve(key, sha)) root.options = @options return root end end if @options[:syntax] == :scss root = Sass::SCSS::Parser.new(@template, @options[:filename], @options[:importer]).parse else root = Tree::RootNode.new(@template) append_children(root, tree(tabulate(@template)).first, true) end root.options = @options if @options[:cache] && key && sha begin old_options = root.options root.options = {} @options[:cache_store].store(key, sha, root) ensure root.options = old_options end end root rescue SyntaxError => e e.modify_backtrace(:filename => @options[:filename], :line => @line) e.sass_template = @template raise e end def sassc_key @options[:cache_store].key(*@options[:importer].key(@options[:filename], @options)) end def check_encoding! return if @checked_encoding @checked_encoding = true @template, @source_encoding = Sass::Util.check_sass_encoding(@template) end def tabulate(string) tab_str = nil comment_tab_str = nil first = true lines = [] string.scan(/^[^\n]*?$/).each_with_index do |line, index| index += (@options[:line] || 1) if line.strip.empty? lines.last.text << "\n" if lines.last && lines.last.comment? next end line_tab_str = line[/^\s*/] unless line_tab_str.empty? if tab_str.nil? comment_tab_str ||= line_tab_str next if try_comment(line, lines.last, "", comment_tab_str, index) comment_tab_str = nil end tab_str ||= line_tab_str raise SyntaxError.new("Indenting at the beginning of the document is illegal.", :line => index) if first raise SyntaxError.new("Indentation can't use both tabs and spaces.", :line => index) if tab_str.include?(?\s) && tab_str.include?(?\t) end first &&= !tab_str.nil? if tab_str.nil? lines << Line.new(line.strip, 0, index, 0, @options[:filename], []) next end comment_tab_str ||= line_tab_str if try_comment(line, lines.last, tab_str * lines.last.tabs, comment_tab_str, index) next else comment_tab_str = nil end line_tabs = line_tab_str.scan(tab_str).size if tab_str * line_tabs != line_tab_str message = <<END.strip.tr("\n", ' ') Inconsistent indentation: #{Sass::Shared.human_indentation line_tab_str, true} used for indentation, but the rest of the document was indented using #{Sass::Shared.human_indentation tab_str}. END raise SyntaxError.new(message, :line => index) end lines << Line.new(line.strip, line_tabs, index, line_tab_str.size, @options[:filename], []) end lines end def try_comment(line, last, tab_str, comment_tab_str, index) return unless last && last.comment? # Nested comment stuff must be at least one whitespace char deeper # than the normal indentation return unless line =~ /^#{tab_str}\s/ unless line =~ /^(?:#{comment_tab_str})(.*)$/ raise SyntaxError.new(<<MSG.strip.tr("\n", " "), :line => index) Inconsistent indentation: previous line was indented by #{Sass::Shared.human_indentation comment_tab_str}, but this line was indented by #{Sass::Shared.human_indentation line[/^\s*/]}. MSG end last.comment_tab_str ||= comment_tab_str last.text << "\n" << line true end def tree(arr, i = 0) return [], i if arr[i].nil? base = arr[i].tabs nodes = [] while (line = arr[i]) && line.tabs >= base if line.tabs > base nodes.last.children, i = tree(arr, i) else nodes << line i += 1 end end return nodes, i end def build_tree(parent, line, root = false) @line = line.index @offset = line.offset node_or_nodes = parse_line(parent, line, root) Array(node_or_nodes).each do |node| # Node is a symbol if it's non-outputting, like a variable assignment next unless node.is_a? Tree::Node node.line = line.index node.filename = line.filename append_children(node, line.children, false) end node_or_nodes end def append_children(parent, children, root) continued_rule = nil continued_comment = nil children.each do |line| child = build_tree(parent, line, root) if child.is_a?(Tree::RuleNode) if child.continued? && child.children.empty? if continued_rule continued_rule.add_rules child else continued_rule = child end next elsif continued_rule continued_rule.add_rules child continued_rule.children = child.children continued_rule, child = nil, continued_rule end elsif continued_rule continued_rule = nil end if child.is_a?(Tree::CommentNode) && child.type == :silent if continued_comment && child.line == continued_comment.line + continued_comment.lines + 1 continued_comment.value.last.sub!(%r{ \*/\Z}, '') child.value.first.gsub!(%r{\A/\*}, ' *') continued_comment.value += ["\n"] + child.value next end continued_comment = child end check_for_no_children(child) validate_and_append_child(parent, child, line, root) end parent end def validate_and_append_child(parent, child, line, root) case child when Array child.each {|c| validate_and_append_child(parent, c, line, root)} when Tree::Node parent << child end end def check_for_no_children(node) return unless node.is_a?(Tree::RuleNode) && node.children.empty? Sass::Util.sass_warn(<<WARNING.strip) WARNING on line #{node.line}#{" of #{node.filename}" if node.filename}: This selector doesn't have any properties and will not be rendered. WARNING end def parse_line(parent, line, root) case line.text[0] when PROPERTY_CHAR if line.text[1] == PROPERTY_CHAR || (@options[:property_syntax] == :new && line.text =~ PROPERTY_OLD && $2.empty?) # Support CSS3-style pseudo-elements, # which begin with ::, # as well as pseudo-classes # if we're using the new property syntax Tree::RuleNode.new(parse_interp(line.text), full_line_range(line)) else name_start_offset = line.offset + 1 # +1 for the leading ':' name, value = line.text.scan(PROPERTY_OLD)[0] raise SyntaxError.new("Invalid property: \"#{line.text}\".", :line => @line) if name.nil? || value.nil? @@old_property_deprecation.warn(@options[:filename], @line, <<WARNING) Old-style properties like "#{line.text}" are deprecated and will be an error in future versions of Sass. Use "#{name}: #{value}" instead. WARNING value_start_offset = name_end_offset = name_start_offset + name.length unless value.empty? # +1 and -1 both compensate for the leading ':', which is part of line.text value_start_offset = name_start_offset + line.text.index(value, name.length + 1) - 1 end property = parse_property(name, parse_interp(name), value, :old, line, value_start_offset) property.name_source_range = Sass::Source::Range.new( Sass::Source::Position.new(@line, to_parser_offset(name_start_offset)), Sass::Source::Position.new(@line, to_parser_offset(name_end_offset)), @options[:filename], @options[:importer]) property end when ?$ parse_variable(line) when COMMENT_CHAR parse_comment(line) when DIRECTIVE_CHAR parse_directive(parent, line, root) when ESCAPE_CHAR Tree::RuleNode.new(parse_interp(line.text[1..-1]), full_line_range(line)) when MIXIN_DEFINITION_CHAR parse_mixin_definition(line) when MIXIN_INCLUDE_CHAR if line.text[1].nil? || line.text[1] == ?\s Tree::RuleNode.new(parse_interp(line.text), full_line_range(line)) else parse_mixin_include(line, root) end else parse_property_or_rule(line) end end def parse_property_or_rule(line) scanner = Sass::Util::MultibyteStringScanner.new(line.text) hack_char = scanner.scan(/[:\*\.]|\#(?!\{)/) offset = line.offset offset += hack_char.length if hack_char parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @options[:importer], @line, to_parser_offset(offset)) unless (res = parser.parse_interp_ident) parsed = parse_interp(line.text, line.offset) return Tree::RuleNode.new(parsed, full_line_range(line)) end ident_range = Sass::Source::Range.new( Sass::Source::Position.new(@line, to_parser_offset(line.offset)), Sass::Source::Position.new(@line, parser.offset), @options[:filename], @options[:importer]) offset = parser.offset - 1 res.unshift(hack_char) if hack_char # Handle comments after a property name but before the colon. if (comment = scanner.scan(Sass::SCSS::RX::COMMENT)) res << comment offset += comment.length end name = line.text[0...scanner.pos] could_be_property = if name.start_with?('--') (scanned = scanner.scan(/\s*:/)) else (scanned = scanner.scan(/\s*:(?:\s+|$)/)) end if could_be_property # test for a property offset += scanned.length property = parse_property(name, res, scanner.rest, :new, line, offset) property.name_source_range = ident_range property else res.pop if comment if (trailing = (scanner.scan(/\s*#{Sass::SCSS::RX::COMMENT}/) || scanner.scan(/\s*#{Sass::SCSS::RX::SINGLE_LINE_COMMENT}/))) trailing.strip! end interp_parsed = parse_interp(scanner.rest) selector_range = Sass::Source::Range.new( ident_range.start_pos, Sass::Source::Position.new(@line, to_parser_offset(line.offset) + line.text.length), @options[:filename], @options[:importer]) rule = Tree::RuleNode.new(res + interp_parsed, selector_range) rule << Tree::CommentNode.new([trailing], :silent) if trailing rule end end def parse_property(name, parsed_name, value, prop, line, start_offset) if name.start_with?('--') unless line.children.empty? raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath custom properties.", :line => @line + 1) end parser = Sass::SCSS::Parser.new(value, @options[:filename], @options[:importer], @line, to_parser_offset(@offset)) parsed_value = parser.parse_declaration_value end_offset = start_offset + value.length elsif value.strip.empty? parsed_value = [Sass::Script::Tree::Literal.new(Sass::Script::Value::String.new(""))] end_offset = start_offset else expr = parse_script(value, :offset => to_parser_offset(start_offset)) end_offset = expr.source_range.end_pos.offset - 1 parsed_value = [expr] end node = Tree::PropNode.new(parse_interp(name), parsed_value, prop) node.value_source_range = Sass::Source::Range.new( Sass::Source::Position.new(line.index, to_parser_offset(start_offset)), Sass::Source::Position.new(line.index, to_parser_offset(end_offset)), @options[:filename], @options[:importer]) if !node.custom_property? && value.strip.empty? && line.children.empty? raise SyntaxError.new( "Invalid property: \"#{node.declaration}\" (no value)." + node.pseudo_class_selector_message) end node end def parse_variable(line) name, value, flags = line.text.scan(Script::MATCH)[0] raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath variable declarations.", :line => @line + 1) unless line.children.empty? raise SyntaxError.new("Invalid variable: \"#{line.text}\".", :line => @line) unless name && value flags = flags ? flags.split(/\s+/) : [] if (invalid_flag = flags.find {|f| f != '!default' && f != '!global'}) raise SyntaxError.new("Invalid flag \"#{invalid_flag}\".", :line => @line) end # This workaround is needed for the case when the variable value is part of the identifier, # otherwise we end up with the offset equal to the value index inside the name: # $red_color: red; var_lhs_length = 1 + name.length # 1 stands for '$' index = line.text.index(value, line.offset + var_lhs_length) || 0 expr = parse_script(value, :offset => to_parser_offset(line.offset + index)) Tree::VariableNode.new(name, expr, flags.include?('!default'), flags.include?('!global')) end def parse_comment(line) if line.text[1] == CSS_COMMENT_CHAR || line.text[1] == SASS_COMMENT_CHAR silent = line.text[1] == SASS_COMMENT_CHAR loud = !silent && line.text[2] == SASS_LOUD_COMMENT_CHAR if silent value = [line.text] else value = self.class.parse_interp( line.text, line.index, to_parser_offset(line.offset), :filename => @filename) end value = Sass::Util.with_extracted_values(value) do |str| str = str.gsub(/^#{line.comment_tab_str}/m, '')[2..-1] # get rid of // or /* format_comment_text(str, silent) end type = if silent :silent elsif loud :loud else :normal end comment = Tree::CommentNode.new(value, type) comment.line = line.index text = line.text.rstrip if text.include?("\n") end_offset = text.length - text.rindex("\n") else end_offset = to_parser_offset(line.offset + text.length) end comment.source_range = Sass::Source::Range.new( Sass::Source::Position.new(@line, to_parser_offset(line.offset)), Sass::Source::Position.new(@line + text.count("\n"), end_offset), @options[:filename]) comment else Tree::RuleNode.new(parse_interp(line.text), full_line_range(line)) end end DIRECTIVES = Set[:mixin, :include, :function, :return, :debug, :warn, :for, :each, :while, :if, :else, :extend, :import, :media, :charset, :content, :at_root, :error] def parse_directive(parent, line, root) directive, whitespace, value = line.text[1..-1].split(/(\s+)/, 2) raise SyntaxError.new("Invalid directive: '@'.") unless directive offset = directive.size + whitespace.size + 1 if whitespace directive_name = directive.tr('-', '_').to_sym if DIRECTIVES.include?(directive_name) return send("parse_#{directive_name}_directive", parent, line, root, value, offset) end unprefixed_directive = directive.gsub(/^-[a-z0-9]+-/i, '') if unprefixed_directive == 'supports' parser = Sass::SCSS::Parser.new(value, @options[:filename], @line) return Tree::SupportsNode.new(directive, parser.parse_supports_condition) end Tree::DirectiveNode.new( value.nil? ? ["@#{directive}"] : ["@#{directive} "] + parse_interp(value, offset)) end def parse_while_directive(parent, line, root, value, offset) raise SyntaxError.new("Invalid while directive '@while': expected expression.") unless value Tree::WhileNode.new(parse_script(value, :offset => offset)) end def parse_if_directive(parent, line, root, value, offset) raise SyntaxError.new("Invalid if directive '@if': expected expression.") unless value Tree::IfNode.new(parse_script(value, :offset => offset)) end def parse_debug_directive(parent, line, root, value, offset) raise SyntaxError.new("Invalid debug directive '@debug': expected expression.") unless value raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath debug directives.", :line => @line + 1) unless line.children.empty? offset = line.offset + line.text.index(value).to_i Tree::DebugNode.new(parse_script(value, :offset => offset)) end def parse_error_directive(parent, line, root, value, offset) raise SyntaxError.new("Invalid error directive '@error': expected expression.") unless value raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath error directives.", :line => @line + 1) unless line.children.empty? offset = line.offset + line.text.index(value).to_i Tree::ErrorNode.new(parse_script(value, :offset => offset)) end def parse_extend_directive(parent, line, root, value, offset) raise SyntaxError.new("Invalid extend directive '@extend': expected expression.") unless value raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath extend directives.", :line => @line + 1) unless line.children.empty? optional = !!value.gsub!(/\s+#{Sass::SCSS::RX::OPTIONAL}$/, '') offset = line.offset + line.text.index(value).to_i interp_parsed = parse_interp(value, offset) selector_range = Sass::Source::Range.new( Sass::Source::Position.new(@line, to_parser_offset(offset)),
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
true