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/pathutil-0.16.2/lib/pathutil/version.rb
_vendor/ruby/2.6.0/gems/pathutil-0.16.2/lib/pathutil/version.rb
# Frozen-string-literal: true # Copyright: 2015 - 2017 Jordon Bedwell - MIT License # Encoding: utf-8 class Pathutil VERSION = "0.16.2" 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/pathutil-0.16.2/lib/pathutil/helpers.rb
_vendor/ruby/2.6.0/gems/pathutil-0.16.2/lib/pathutil/helpers.rb
# Frozen-string-literal: true # Copyright: 2015 - 2017 Jordon Bedwell - MIT License # Encoding: utf-8 class Pathutil module Helpers extend self # -- def allowed return @allowed ||= begin { :yaml => { :classes => [], :symbols => [] } } end end # -- # Wraps around YAML and SafeYAML to provide alternatives to Rubies. # @note We default aliases to yes so we can detect if you explicit true. # @return Hash # -- def load_yaml(data, safe: true, whitelist_classes: allowed[:yaml][:classes], \ whitelist_symbols: allowed[:yaml][:symbols], aliases: :yes) require "yaml" unless safe return YAML.load( data ) end if !YAML.respond_to?(:safe_load) setup_safe_yaml whitelist_classes, aliases SafeYAML.load( data ) else YAML.safe_load( data, whitelist_classes, whitelist_symbols, aliases ) end end # -- # Make a temporary name suitable for temporary files and directories. # @return String # -- def make_tmpname(prefix = "", suffix = nil, root = nil) prefix = tmpname_prefix(prefix) suffix = tmpname_suffix(suffix) root ||= Dir::Tmpname.tmpdir File.join(root, __make_tmpname( prefix, suffix )) end # -- private def __make_tmpname((prefix, suffix), number) prefix &&= String.try_convert(prefix) || tmpname_agerr(:prefix, prefix) suffix &&= String.try_convert(suffix) || tmpname_agerr(:suffix, suffix) time = Time.now.strftime("%Y%m%d") path = "#{prefix}#{time}-#{$$}-#{rand(0x100000000).to_s(36)}".dup path << "-#{number}" if number path << suffix if suffix path end private def tmpname_agerr(type, val) raise ArgumentError, "unexpected #{type}: #{val.inspect}" end # -- private def tmpname_suffix(suffix) suffix = suffix.join("-") if suffix.is_a?(Array) suffix = suffix.gsub(/\A\-/, "") unless !suffix || suffix.empty? suffix end # -- # Cleanup the temp name prefix, joining if necessary. # rubocop:disable Style/ParallelAssignment # -- private def tmpname_prefix(prefix) ext, prefix = prefix, "" if !prefix.is_a?(Array) && prefix.start_with?(".") ext = prefix.pop if prefix.is_a?(Array) && prefix[-1].start_with?(".") prefix = prefix.join("-") if prefix.is_a?(Array) unless prefix.empty? prefix = prefix.gsub(/\-\Z/, "") \ + "-" end return [ prefix, ext || "" ] end # -- # Wrap around, cleanup, deprecate and use SafeYAML. # rubocop:enable Style/ParallelAssignment # -- private def setup_safe_yaml(whitelist_classes, aliases) warn "WARN: SafeYAML does not support disabling of aliases." if aliases && aliases != :yes warn "WARN: SafeYAML will be removed when Ruby 2.0 goes EOL." require "safe_yaml/load" SafeYAML.restore_defaults! whitelist_classes.map(&SafeYAML.method( :whitelist_class! )) 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/forwardable-extended-2.6.0/lib/forwardable/extended.rb
_vendor/ruby/2.6.0/gems/forwardable-extended-2.6.0/lib/forwardable/extended.rb
# ---------------------------------------------------------------------------- # Frozen-string-literal: true # Copyright: 2015-2016 Jordon Bedwell - MIT License # Encoding: utf-8 # ---------------------------------------------------------------------------- require "forwardable/extended/version" require "forwardable" module Forwardable module Extended # ------------------------------------------------------------------------ # Make our methods private on the class, there is no reason for public. # ------------------------------------------------------------------------ def self.extended(klass) instance_methods.each do |method| klass.private_class_method( method ) end end # ------------------------------------------------------------------------ # Delegate using a Rails-like interface. # ------------------------------------------------------------------------ def rb_delegate(method, to: nil, alias_of: method, **kwd) raise ArgumentError, "to must be provided" unless to def_delegator( to, alias_of, method, **kwd ) end # ------------------------------------------------------------------------ # Delegate a method to a hash and key. # ------------------------------------------------------------------------ def def_hash_delegator(hash, method, key: method, **kwd) prefix, suffix, wrap = prepare_delegate(**kwd) if suffix method = method.to_s.gsub( /\?$/, "" ) end class_eval delegate_debug(<<-STR), __FILE__, __LINE__ - 9 def #{method}#{suffix}(*args) #{wrap}( #{prefix}#{hash}[#{key.inspect}] ) rescue Exception if !Forwardable.debug && $@ && $@.respond_to?(:delete_if) $@.delete_if do |source| source =~ %r"#{Regexp.escape(__FILE__)}"o end end raise end STR end # ------------------------------------------------------------------------ # Delegate a method to an instance variable. # ------------------------------------------------------------------------ def def_ivar_delegator(ivar, alias_ = ivar, **kwd) prefix, suffix, wrap = prepare_delegate(**kwd) if suffix alias_ = alias_.to_s.gsub( /\?$/, "" ) end class_eval delegate_debug(<<-STR), __FILE__, __LINE__ - 9 def #{alias_.to_s.gsub(/\A@/, "")}#{suffix} #{wrap}( #{prefix}#{ivar} ) rescue Exception if !Forwardable.debug && $@ && $@.respond_to?(:delete_if) $@.delete_if do |source| source =~ %r"#{Regexp.escape(__FILE__)}"o end end raise end STR end # ------------------------------------------------------------------------ # Like def_delegator but allows you to send args and do other stuff. # ------------------------------------------------------------------------ def def_modern_delegator(accessor, method, alias_ = method, args: \ { :before => [], :after => [] }, **kwd) prefix, suffix, wrap = prepare_delegate(**kwd) args = { :before => args } unless args.is_a?(Hash) b = [args[:before]].flatten.compact.map(&:to_s).join(", ") a = [args[ :after]].flatten.compact.map(&:to_s).join(", ") b = b + ", " unless args[:before].nil? || args[:before].empty? a = ", " + a unless args[ :after].nil? || args[ :after].empty? alias_ = alias_.to_s.gsub(/\?$/, "") if suffix class_eval delegate_debug(<<-STR), __FILE__, __LINE__ - 10 def #{alias_}#{suffix}(*args, &block) #{wrap}(#{prefix}#{accessor}.send( #{method.inspect}, #{b}*args#{a}, &block )) rescue Exception if !Forwardable.debug && $@ && $@.respond_to?(:delete_if) $@.delete_if do |source| source =~ %r"#{Regexp.escape(__FILE__)}"o end end raise end STR end # ------------------------------------------------------------------------ # Wraps around traditional delegation and modern delegation. # ------------------------------------------------------------------------ def def_delegator(accessor, method, alias_ = method, **kwd) kwd, alias_ = alias_, method if alias_.is_a?(Hash) && !kwd.any? if alias_.is_a?(Hash) || !kwd.any? Forwardable.instance_method(:def_delegator).bind(self) \ .call(accessor, method, alias_) elsif !kwd[:type] def_modern_delegator( accessor, method, alias_, **kwd ) else raise ArgumentError, "Alias not supported." if alias_ != method send("def_#{kwd[:type]}_delegator", accessor, method, **kwd.tap do |obj| obj.delete(:type) end) end end # ------------------------------------------------------------------------ # Create multiple delegates at once. # ------------------------------------------------------------------------ def def_delegators(accessor, *methods) kwd = methods.shift if methods.first.is_a?(Hash) kwd = methods.pop if methods. last.is_a?(Hash) kwd = {} unless kwd methods.each do |method| def_delegator accessor, method, **kwd end end # ------------------------------------------------------------------------ # Prepares a delegate and it's few arguments. # ------------------------------------------------------------------------ private def prepare_delegate(wrap: nil, bool: false) prefix = (bool == :reverse ? "!!!" : "!!") if bool wrap = "self.class.new" if wrap.is_a?(TrueClass) suffix = "?" if bool return [ prefix, suffix, wrap ] end # ------------------------------------------------------------------------ private def delegate_debug(str) if Forwardable.debug && !Forwardable.debug.is_a?(TrueClass) then Forwardable.debug.debug( str ) elsif Forwardable.debug $stdout.puts( "\n# ------\n\n", str ) end str 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/forwardable-extended-2.6.0/lib/forwardable/extended/version.rb
_vendor/ruby/2.6.0/gems/forwardable-extended-2.6.0/lib/forwardable/extended/version.rb
# Frozen-string-literal: true # Copyright: 2015-2016 Jordon Bedwell - MIT License # Encoding: utf-8 module Forwardable module Extended VERSION = "2.6.0" 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/ruby_dep-1.5.0/lib/ruby_dep.rb
_vendor/ruby/2.6.0/gems/ruby_dep-1.5.0/lib/ruby_dep.rb
require 'ruby_dep/version' require 'ruby_dep/travis'
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/ruby_dep-1.5.0/lib/ruby_dep/quiet.rb
_vendor/ruby/2.6.0/gems/ruby_dep-1.5.0/lib/ruby_dep/quiet.rb
require 'ruby_dep/warning' RubyDep::Warning.new.silence!
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/ruby_dep-1.5.0/lib/ruby_dep/travis.rb
_vendor/ruby/2.6.0/gems/ruby_dep-1.5.0/lib/ruby_dep/travis.rb
require 'yaml' require 'ruby_dep/travis/ruby_version' module RubyDep class Travis def version_constraint(filename = '.travis.yml') yaml = YAML.load(IO.read(filename)) versions = supported_versions(yaml) selected = versions_for_latest_major(versions) lowest = lowest_supported(selected) ["~> #{lowest[0..1].join('.')}", ">= #{lowest.join('.')}"] rescue RubyVersion::Error => ex abort("RubyDep Error: #{ex.message}") end private def versions_for_latest_major(versions) by_major = versions.map do |x| RubyVersion.new(x).segments[0..2] end.group_by(&:first) last_supported_major = by_major.keys.sort.last by_major[last_supported_major] end def lowest_supported(versions) selected = versions.sort.reverse! grouped_by_minor = selected.group_by { |x| x[1] } lowest_minor = lowest_minor_without_skipping(grouped_by_minor) grouped_by_minor[lowest_minor].sort.first end def failable(yaml) matrix = yaml.fetch('matrix', {}) allowed = matrix.fetch('allow_failures', []) allowed.map(&:values).flatten end def supported_versions(yaml) yaml['rvm'] - failable(yaml) end def lowest_minor_without_skipping(grouped_by_minor) minors = grouped_by_minor.keys.flatten lowest = minors.shift current = lowest while (lower = minors.shift) (current -= 1) == lower ? lowest = lower : break end lowest 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/ruby_dep-1.5.0/lib/ruby_dep/version.rb
_vendor/ruby/2.6.0/gems/ruby_dep-1.5.0/lib/ruby_dep/version.rb
module RubyDep VERSION = '1.5.0'.freeze 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/ruby_dep-1.5.0/lib/ruby_dep/logger.rb
_vendor/ruby/2.6.0/gems/ruby_dep-1.5.0/lib/ruby_dep/logger.rb
require 'logger' module RubyDep def self.logger @logger ||= stderr_logger end def self.logger=(new_logger) @logger = new_logger.nil? ? NullLogger.new : new_logger end def self.stderr_logger ::Logger.new(STDERR).tap do |logger| logger.formatter = proc { |_,_,_,msg| "#{msg}\n" } end end # Shamelessly stolen from https://github.com/karafka/null-logger class NullLogger LOG_LEVELS = %w(unknown fatal error warn info debug).freeze def respond_to_missing?(method_name, include_private = false) LOG_LEVELS.include?(method_name.to_s) || super end def method_missing(method_name, *args, &block) LOG_LEVELS.include?(method_name.to_s) ? nil : super end end # TODO: not used, but kept for the sake of SemVer # TODO: remove in next major version class Logger def initialize(device, prefix) @device = device @prefix = prefix ::RubyDep.logger.warn("The RubyDep::Logger class is deprecated") end def warning(msg) @device.puts @prefix + msg end def notice(msg) @device.puts @prefix + msg 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/ruby_dep-1.5.0/lib/ruby_dep/warning.rb
_vendor/ruby/2.6.0/gems/ruby_dep-1.5.0/lib/ruby_dep/warning.rb
require 'ruby_dep/logger' require 'ruby_dep/ruby_version' module RubyDep PROJECT_URL = 'http://github.com/e2/ruby_dep'.freeze class Warning DISABLING_ENVIRONMENT_VAR = 'RUBY_DEP_GEM_SILENCE_WARNINGS'.freeze PREFIX = 'RubyDep: WARNING: '.freeze WARNING = { insecure: 'Your Ruby has security vulnerabilities!'.freeze, buggy: 'Your Ruby is outdated/buggy.'.freeze, untracked: 'Your Ruby may not be supported.'.freeze }.freeze NOTICE_RECOMMENDATION = 'Your Ruby is: %s (%s).'\ ' Recommendation: upgrade to %s.'.freeze NOTICE_BUGGY_ALTERNATIVE = '(Or, at least to %s)'.freeze NOTICE_HOW_TO_DISABLE = '(To disable warnings, see:'\ "#{PROJECT_URL}/wiki/Disabling-warnings )".freeze NOTICE_OPEN_ISSUE = 'If you need this version supported,'\ " please open an issue at #{PROJECT_URL}".freeze def initialize @version = RubyVersion.new(RUBY_VERSION, RUBY_ENGINE) end def show_warnings return if silenced? return warn_ruby(WARNING[status]) if WARNING.key?(status) return if status == :unknown raise "Unknown problem type: #{problem.inspect}" end def silence! ENV[DISABLING_ENVIRONMENT_VAR] = '1' end private def silenced? value = ENV[DISABLING_ENVIRONMENT_VAR] (value || '0') !~ /^0|false|no|n$/ end def status @version.status end def warn_ruby(msg) RubyDep.logger.tap do |logger| logger.warn(PREFIX + msg) logger.info(PREFIX + recommendation) logger.info(PREFIX + NOTICE_HOW_TO_DISABLE) end end def recommendation return unrecognized_msg unless @version.recognized? return recommendation_msg unless status == :insecure [recommendation_msg, safer_alternatives_msg].join(' ') end def unrecognized_msg format( "Your Ruby is: %s '%s' (unrecognized). %s", @version.version, @version.engine, NOTICE_OPEN_ISSUE ) end def recommended_versions @version.recommended(:unknown) end def buggy_alternatives @version.recommended(:buggy) end def recommendation_msg format( NOTICE_RECOMMENDATION, @version.version, status, recommended_versions.join(' or ') ) end def safer_alternatives_msg format(NOTICE_BUGGY_ALTERNATIVE, buggy_alternatives.join(' or ')) 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/ruby_dep-1.5.0/lib/ruby_dep/ruby_version.rb
_vendor/ruby/2.6.0/gems/ruby_dep-1.5.0/lib/ruby_dep/ruby_version.rb
module RubyDep class RubyVersion attr_reader :status # NOTE: monkey-patched by acceptance tests attr_reader :version attr_reader :engine def initialize(ruby_version, engine) @engine = engine @version = Gem::Version.new(ruby_version) @status = detect_status end def recognized? info.any? end def recommended(status) current = Gem::Version.new(@version) info.select do |key, value| value == status && Gem::Version.new(key) > current end.keys.reverse end private VERSION_INFO = { 'ruby' => { '2.3.1' => :unknown, '2.3.0' => :buggy, '2.2.5' => :unknown, '2.2.4' => :buggy, '2.2.0' => :insecure, '2.1.9' => :buggy, '2.0.0' => :insecure }, 'jruby' => { '2.3.0' => :unknown, # jruby-9.1.2.0, jruby-9.1.0.0 '2.2.3' => :buggy, # jruby-9.0.5.0 '2.2.0' => :insecure } }.freeze def info @info ||= VERSION_INFO[@engine] || {} end def detect_status return :untracked unless recognized? info.each do |ruby, status| return status if @version >= Gem::Version.new(ruby) end :insecure 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/ruby_dep-1.5.0/lib/ruby_dep/travis/ruby_version.rb
_vendor/ruby/2.6.0/gems/ruby_dep-1.5.0/lib/ruby_dep/travis/ruby_version.rb
module RubyDep class Travis class RubyVersion REGEXP = /^ (?: (?<engine>ruby|jruby) -)? (?<version>\d+\.\d+\.\d+(?:\.\d+)?) (?:-p\d+)? (?:-clang)? $/x class Error < RuntimeError class Unrecognized < Error def initialize(invalid_version_string) @invalid_version_string = invalid_version_string end def message "Unrecognized Ruby version: #{@invalid_version_string.inspect}" end class JRubyVersion < Unrecognized def message "Unrecognized JRuby version: #{@invalid_version_string.inspect}" end end end end def initialize(travis_version_string) ruby_version_string = version_for(travis_version_string) @version = Gem::Version.new(ruby_version_string) end def segments @version.segments end private def version_for(travis_version_string) match = REGEXP.match(travis_version_string) raise Error::Unrecognized, travis_version_string unless match return match[:version] unless match[:engine] return jruby_version(match[:version]) if match[:engine] == 'jruby' match[:version] # if match[:engine] == 'ruby' end def jruby_version(version) return '2.3.0' if version == '9.1.2.0' return '2.3.0' if version == '9.1.0.0' return '2.2.3' if version == '9.0.5.0' return '2.2.2' if version == '9.0.4.0' raise Error::Unrecognized::JRubyVersion, version 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/http_parser.rb-0.6.0/bench/thin.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/bench/thin.rb
$:.unshift File.dirname(__FILE__) + "/../lib" require "rubygems" require "thin_parser" require "http_parser" require "benchmark" require "stringio" data = "POST /postit HTTP/1.1\r\n" + "Host: localhost:3000\r\n" + "User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9\r\n" + "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n" + "Accept-Language: en-us,en;q=0.5\r\n" + "Accept-Encoding: gzip,deflate\r\n" + "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" + "Keep-Alive: 300\r\n" + "Connection: keep-alive\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 37\r\n" + "\r\n" + "name=marc&email=macournoyer@gmail.com" def thin(data) env = {"rack.input" => StringIO.new} Thin::HttpParser.new.execute(env, data, 0) env end def http_parser(data) body = StringIO.new env = nil parser = HTTP::RequestParser.new parser.on_headers_complete = proc { |e| env = e } parser.on_body = proc { |c| body << c } parser << data env["rack-input"] = body env end # p thin(data) # p http_parser(data) TESTS = 30_000 Benchmark.bmbm do |results| results.report("thin:") { TESTS.times { thin data } } results.report("http-parser:") { TESTS.times { http_parser data } } end # On my MBP core duo 2.2Ghz # Rehearsal ------------------------------------------------ # thin: 1.470000 0.000000 1.470000 ( 1.474737) # http-parser: 1.270000 0.020000 1.290000 ( 1.292758) # --------------------------------------- total: 2.760000sec # # user system total real # thin: 1.150000 0.030000 1.180000 ( 1.173767) # http-parser: 1.250000 0.010000 1.260000 ( 1.263796)
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/http_parser.rb-0.6.0/bench/standalone.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/bench/standalone.rb
#!/usr/bin/env ruby $:.unshift File.dirname(__FILE__) + "/../lib" require "rubygems" require "http/parser" require "benchmark/ips" request = <<-REQUEST GET / HTTP/1.1 Host: www.example.com Connection: keep-alive User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.78 S Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 REQUEST request.gsub!(/\n/m, "\r\n") Benchmark.ips do |ips| ips.report("instance") { Http::Parser.new } ips.report("parsing") { Http::Parser.new << request } 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/http_parser.rb-0.6.0/ext/ruby_http_parser/extconf.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser/extconf.rb
require 'mkmf' # check out code if it hasn't been already if Dir[File.expand_path('../vendor/http-parser/*', __FILE__)].empty? Dir.chdir(File.expand_path('../../../', __FILE__)) do xsystem 'git submodule init' xsystem 'git submodule update' end end # mongrel and http-parser both define http_parser_(init|execute), so we # rename functions in http-parser before using them. vendor_dir = File.expand_path('../vendor/http-parser/', __FILE__) src_dir = File.expand_path('../', __FILE__) %w[ http_parser.c http_parser.h ].each do |file| File.open(File.join(src_dir, "ryah_#{file}"), 'w'){ |f| f.write File.read(File.join(vendor_dir, file)).gsub('http_parser', 'ryah_http_parser') } end $CFLAGS << " -I#{src_dir}" dir_config("ruby_http_parser") create_makefile("ruby_http_parser")
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/http_parser.rb-0.6.0/ext/ruby_http_parser/vendor/http-parser-java/tools/lowcase.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser/vendor/http-parser-java/tools/lowcase.rb
0.upto(255) { |i| printf "\n" if i%16 == 0 printf " " if i%8 == 0 s = ("" << i) if s =~ /[A-Z0-9\-_\/ ]/ print "0x#{i.to_s(16)}," elsif s =~ /[a-z]/ print "0x#{s.upcase[0].to_s(16)}," else print "0x00," 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/http_parser.rb-0.6.0/ext/ruby_http_parser/vendor/http-parser-java/tools/const_char.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser/vendor/http-parser-java/tools/const_char.rb
def printbytes str str.each_byte { |b| print "0x#{b.to_s(16)}, " } end if $0 == __FILE__ printf "static final byte [] #{ARGV[0]} = {\n" printbytes ARGV[0] printf "\n};\n" 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/http_parser.rb-0.6.0/ext/ruby_http_parser/vendor/http-parser-java/tools/byte_constants.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser/vendor/http-parser-java/tools/byte_constants.rb
"A".upto("Z") {|c| puts "public static final byte #{c} = 0x#{c[0].to_s(16)};" }
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/http_parser.rb-0.6.0/ext/ruby_http_parser/vendor/http-parser-java/tools/parse_tests.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser/vendor/http-parser-java/tools/parse_tests.rb
# name : 200 trailing space on chunked body # raw : "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n25 \r\nThis is the data in the first chunk\r\n\r\n1C\r\nand this is the second one\r\n\r\n0 \r\n\r\n" # type : HTTP_RESPONSE # method: HTTP_DELETE # status code :200 # request_path: # request_url : # fragment : # query_string: # body :"This is the data in the first chunk\r\nand this is the second one\r\n" # body_size :65 # header_0 :{ "Content-Type": "text/plain"} # header_1 :{ "Transfer-Encoding": "chunked"} # should_keep_alive :1 # upgrade :0 # http_major :1 # http_minor :1 class ParserTest attr_accessor :name attr_accessor :raw attr_accessor :type attr_accessor :method attr_accessor :status_code attr_accessor :request_path attr_accessor :method 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/http_parser.rb-0.6.0/spec/parser_spec.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/spec/parser_spec.rb
require "spec_helper" require "json" describe HTTP::Parser do before do @parser = HTTP::Parser.new @headers = nil @body = "" @started = false @done = false @parser.on_message_begin = proc{ @started = true } @parser.on_headers_complete = proc { |e| @headers = e } @parser.on_body = proc { |chunk| @body << chunk } @parser.on_message_complete = proc{ @done = true } end it "should have initial state" do @parser.headers.should be_nil @parser.http_version.should be_nil @parser.http_method.should be_nil @parser.status_code.should be_nil @parser.request_url.should be_nil @parser.header_value_type.should == :mixed end it "should allow us to set the header value type" do [:mixed, :arrays, :strings].each do |type| @parser.header_value_type = type @parser.header_value_type.should == type parser_tmp = HTTP::Parser.new(nil, type) parser_tmp.header_value_type.should == type end end it "should allow us to set the default header value type" do [:mixed, :arrays, :strings].each do |type| HTTP::Parser.default_header_value_type = type parser = HTTP::Parser.new parser.header_value_type.should == type end end it "should throw an Argument Error if header value type is invalid" do proc{ @parser.header_value_type = 'bob' }.should raise_error(ArgumentError) end it "should throw an Argument Error if default header value type is invalid" do proc{ HTTP::Parser.default_header_value_type = 'bob' }.should raise_error(ArgumentError) end it "should implement basic api" do @parser << "GET /test?ok=1 HTTP/1.1\r\n" + "User-Agent: curl/7.18.0\r\n" + "Host: 0.0.0.0:5000\r\n" + "Accept: */*\r\n" + "Content-Length: 5\r\n" + "\r\n" + "World" @started.should be_true @done.should be_true @parser.http_major.should == 1 @parser.http_minor.should == 1 @parser.http_version.should == [1,1] @parser.http_method.should == 'GET' @parser.status_code.should be_nil @parser.request_url.should == '/test?ok=1' @parser.headers.should == @headers @parser.headers['User-Agent'].should == 'curl/7.18.0' @parser.headers['Host'].should == '0.0.0.0:5000' @body.should == "World" end it "should raise errors on invalid data" do proc{ @parser << "BLAH" }.should raise_error(HTTP::Parser::Error) end it "should abort parser via callback" do @parser.on_headers_complete = proc { |e| @headers = e; :stop } data = "GET / HTTP/1.0\r\n" + "Content-Length: 5\r\n" + "\r\n" + "World" bytes = @parser << data bytes.should == 37 data[bytes..-1].should == 'World' @headers.should == {'Content-Length' => '5'} @body.should be_empty @done.should be_false end it "should reset to initial state" do @parser << "GET / HTTP/1.0\r\n\r\n" @parser.http_method.should == 'GET' @parser.http_version.should == [1,0] @parser.request_url.should == '/' @parser.reset!.should be_true @parser.http_version.should be_nil @parser.http_method.should be_nil @parser.status_code.should be_nil @parser.request_url.should be_nil end it "should optionally reset parser state on no-body responses" do @parser.reset!.should be_true @head, @complete = 0, 0 @parser.on_headers_complete = proc {|h| @head += 1; :reset } @parser.on_message_complete = proc { @complete += 1 } @parser.on_body = proc {|b| fail } head_response = "HTTP/1.1 200 OK\r\nContent-Length:10\r\n\r\n" @parser << head_response @head.should == 1 @complete.should == 1 @parser << head_response @head.should == 2 @complete.should == 2 end it "should retain callbacks after reset" do @parser.reset!.should be_true @parser << "GET / HTTP/1.0\r\n\r\n" @started.should be_true @headers.should == {} @done.should be_true end it "should parse headers incrementally" do request = "GET / HTTP/1.0\r\n" + "Header1: value 1\r\n" + "Header2: value 2\r\n" + "\r\n" while chunk = request.slice!(0,2) and !chunk.empty? @parser << chunk end @parser.headers.should == { 'Header1' => 'value 1', 'Header2' => 'value 2' } end it "should handle multiple headers using strings" do @parser.header_value_type = :strings @parser << "GET / HTTP/1.0\r\n" + "Set-Cookie: PREF=ID=a7d2c98; expires=Fri, 05-Apr-2013 05:00:45 GMT; path=/; domain=.bob.com\r\n" + "Set-Cookie: NID=46jSHxPM; path=/; domain=.bob.com; HttpOnly\r\n" + "\r\n" @parser.headers["Set-Cookie"].should == "PREF=ID=a7d2c98; expires=Fri, 05-Apr-2013 05:00:45 GMT; path=/; domain=.bob.com, NID=46jSHxPM; path=/; domain=.bob.com; HttpOnly" end it "should handle multiple headers using strings" do @parser.header_value_type = :arrays @parser << "GET / HTTP/1.0\r\n" + "Set-Cookie: PREF=ID=a7d2c98; expires=Fri, 05-Apr-2013 05:00:45 GMT; path=/; domain=.bob.com\r\n" + "Set-Cookie: NID=46jSHxPM; path=/; domain=.bob.com; HttpOnly\r\n" + "\r\n" @parser.headers["Set-Cookie"].should == [ "PREF=ID=a7d2c98; expires=Fri, 05-Apr-2013 05:00:45 GMT; path=/; domain=.bob.com", "NID=46jSHxPM; path=/; domain=.bob.com; HttpOnly" ] end it "should handle multiple headers using mixed" do @parser.header_value_type = :mixed @parser << "GET / HTTP/1.0\r\n" + "Set-Cookie: PREF=ID=a7d2c98; expires=Fri, 05-Apr-2013 05:00:45 GMT; path=/; domain=.bob.com\r\n" + "Set-Cookie: NID=46jSHxPM; path=/; domain=.bob.com; HttpOnly\r\n" + "\r\n" @parser.headers["Set-Cookie"].should == [ "PREF=ID=a7d2c98; expires=Fri, 05-Apr-2013 05:00:45 GMT; path=/; domain=.bob.com", "NID=46jSHxPM; path=/; domain=.bob.com; HttpOnly" ] end it "should handle a single cookie using mixed" do @parser.header_value_type = :mixed @parser << "GET / HTTP/1.0\r\n" + "Set-Cookie: PREF=ID=a7d2c98; expires=Fri, 05-Apr-2013 05:00:45 GMT; path=/; domain=.bob.com\r\n" + "\r\n" @parser.headers["Set-Cookie"].should == "PREF=ID=a7d2c98; expires=Fri, 05-Apr-2013 05:00:45 GMT; path=/; domain=.bob.com" end it "should support alternative api" do callbacks = double('callbacks') callbacks.stub(:on_message_begin){ @started = true } callbacks.stub(:on_headers_complete){ |e| @headers = e } callbacks.stub(:on_body){ |chunk| @body << chunk } callbacks.stub(:on_message_complete){ @done = true } @parser = HTTP::Parser.new(callbacks) @parser << "GET / HTTP/1.0\r\n\r\n" @started.should be_true @headers.should == {} @body.should == '' @done.should be_true end it "should ignore extra content beyond specified length" do @parser << "GET / HTTP/1.0\r\n" + "Content-Length: 5\r\n" + "\r\n" + "hello" + " \n" @body.should == 'hello' @done.should be_true end it 'sets upgrade_data if available' do @parser << "GET /demo HTTP/1.1\r\n" + "Connection: Upgrade\r\n" + "Upgrade: WebSocket\r\n\r\n" + "third key data" @parser.upgrade?.should be_true @parser.upgrade_data.should == 'third key data' end it 'sets upgrade_data to blank if un-available' do @parser << "GET /demo HTTP/1.1\r\n" + "Connection: Upgrade\r\n" + "Upgrade: WebSocket\r\n\r\n" @parser.upgrade?.should be_true @parser.upgrade_data.should == '' end it 'should stop parsing headers when instructed' do request = "GET /websocket HTTP/1.1\r\n" + "host: localhost\r\n" + "connection: Upgrade\r\n" + "upgrade: websocket\r\n" + "sec-websocket-key: SD6/hpYbKjQ6Sown7pBbWQ==\r\n" + "sec-websocket-version: 13\r\n" + "\r\n" @parser.on_headers_complete = proc { |e| :stop } offset = (@parser << request) @parser.upgrade?.should be_true @parser.upgrade_data.should == '' offset.should == request.length end it "should execute on_body on requests with no content-length" do @parser.reset!.should be_true @head, @complete, @body = 0, 0, 0 @parser.on_headers_complete = proc {|h| @head += 1 } @parser.on_message_complete = proc { @complete += 1 } @parser.on_body = proc {|b| @body += 1 } head_response = "HTTP/1.1 200 OK\r\n\r\nstuff" @parser << head_response @parser << '' @head.should == 1 @complete.should == 1 @body.should == 1 end %w[ request response ].each do |type| JSON.parse(File.read(File.expand_path("../support/#{type}s.json", __FILE__))).each do |test| test['headers'] ||= {} next if !defined?(JRUBY_VERSION) and HTTP::Parser.strict? != test['strict'] it "should parse #{type}: #{test['name']}" do @parser << test['raw'] @parser.http_method.should == test['method'] @parser.keep_alive?.should == test['should_keep_alive'] if test.has_key?('upgrade') and test['upgrade'] != 0 @parser.upgrade?.should be_true @parser.upgrade_data.should == test['upgrade'] end fields = %w[ http_major http_minor ] if test['type'] == 'HTTP_REQUEST' fields += %w[ request_url ] else fields += %w[ status_code ] end fields.each do |field| @parser.send(field).should == test[field] end @headers.size.should == test['num_headers'] @headers.should == test['headers'] @body.should == test['body'] @body.size.should == test['body_size'] if test['body_size'] 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/http_parser.rb-0.6.0/spec/spec_helper.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/spec/spec_helper.rb
require "http_parser"
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/http_parser.rb-0.6.0/lib/http_parser.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/lib/http_parser.rb
$:.unshift File.expand_path('../', __FILE__) require 'ruby_http_parser' Http = HTTP module HTTP class Parser class << self attr_reader :default_header_value_type def default_header_value_type=(val) if (val != :mixed && val != :strings && val != :arrays) raise ArgumentError, "Invalid header value type" end @default_header_value_type = val end end end end HTTP::Parser.default_header_value_type = :mixed
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/http_parser.rb-0.6.0/lib/http/parser.rb
_vendor/ruby/2.6.0/gems/http_parser.rb-0.6.0/lib/http/parser.rb
require 'http_parser'
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.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true # stdlib require 'pathname' # The containing module for Rouge module Rouge class << self def reload! Object.send :remove_const, :Rouge load __FILE__ end # Highlight some text with a given lexer and formatter. # # @example # Rouge.highlight('@foo = 1', 'ruby', 'html') # Rouge.highlight('var foo = 1;', 'js', 'terminal256') # # # streaming - chunks become available as they are lexed # Rouge.highlight(large_string, 'ruby', 'html') do |chunk| # $stdout.print chunk # end def highlight(text, lexer, formatter, &b) lexer = Lexer.find(lexer) unless lexer.respond_to? :lex raise "unknown lexer #{lexer}" unless lexer formatter = Formatter.find(formatter) unless formatter.respond_to? :format raise "unknown formatter #{formatter}" unless formatter formatter.format(lexer.lex(text), &b) end end end load_dir = Pathname.new(__FILE__).dirname load load_dir.join('rouge/version.rb') load load_dir.join('rouge/util.rb') load load_dir.join('rouge/text_analyzer.rb') load load_dir.join('rouge/token.rb') load load_dir.join('rouge/lexer.rb') load load_dir.join('rouge/regex_lexer.rb') load load_dir.join('rouge/template_lexer.rb') lexers_dir = load_dir.join('rouge/lexers') Dir.glob(lexers_dir.join('*.rb')).each do |f| Rouge::Lexers.load_lexer(Pathname.new(f).relative_path_from(lexers_dir).to_s) end load load_dir.join('rouge/guesser.rb') load load_dir.join('rouge/guessers/util.rb') load load_dir.join('rouge/guessers/glob_mapping.rb') load load_dir.join('rouge/guessers/modeline.rb') load load_dir.join('rouge/guessers/filename.rb') load load_dir.join('rouge/guessers/mimetype.rb') load load_dir.join('rouge/guessers/source.rb') load load_dir.join('rouge/guessers/disambiguation.rb') load load_dir.join('rouge/formatter.rb') load load_dir.join('rouge/formatters/html.rb') load load_dir.join('rouge/formatters/html_table.rb') load load_dir.join('rouge/formatters/html_pygments.rb') load load_dir.join('rouge/formatters/html_legacy.rb') load load_dir.join('rouge/formatters/html_linewise.rb') load load_dir.join('rouge/formatters/html_inline.rb') load load_dir.join('rouge/formatters/terminal256.rb') load load_dir.join('rouge/formatters/null.rb') load load_dir.join('rouge/theme.rb') load load_dir.join('rouge/themes/thankful_eyes.rb') load load_dir.join('rouge/themes/colorful.rb') load load_dir.join('rouge/themes/base16.rb') load load_dir.join('rouge/themes/github.rb') load load_dir.join('rouge/themes/igor_pro.rb') load load_dir.join('rouge/themes/monokai.rb') load load_dir.join('rouge/themes/molokai.rb') load load_dir.join('rouge/themes/monokai_sublime.rb') load load_dir.join('rouge/themes/gruvbox.rb') load load_dir.join('rouge/themes/tulip.rb') load load_dir.join('rouge/themes/pastie.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/rouge-3.3.0/lib/rouge/version.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/version.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge def self.version "3.3.0" 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/guesser.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/guesser.rb
# frozen_string_literal: true module Rouge class Guesser class Ambiguous < StandardError attr_reader :alternatives def initialize(alternatives); @alternatives = alternatives; end def message "Ambiguous guess: can't decide between #{alternatives.map(&:tag).inspect}" end end def self.guess(guessers, lexers) original_size = lexers.size guessers.each do |g| new_lexers = case g when Guesser then g.filter(lexers) when proc { |x| x.respond_to? :call } then g.call(lexers) else raise "bad guesser: #{g}" end lexers = new_lexers && new_lexers.any? ? new_lexers : lexers end # if we haven't filtered the input at *all*, # then we have no idea what language it is, # so we bail and return []. lexers.size < original_size ? lexers : [] end def collect_best(lexers, opts={}, &scorer) best = [] best_score = opts[:threshold] lexers.each do |lexer| score = scorer.call(lexer) next if score.nil? if best_score.nil? || score > best_score best_score = score best = [lexer] elsif score == best_score best << lexer end end best end def filter(lexers) raise 'abstract' 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/theme.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/theme.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge class Theme include Token::Tokens class Style < Hash def initialize(theme, hsh={}) super() @theme = theme merge!(hsh) end [:fg, :bg].each do |mode| define_method mode do return self[mode] unless @theme @theme.palette(self[mode]) if self[mode] end end def render(selector, &b) return enum_for(:render, selector).to_a.join("\n") unless b return if empty? yield "#{selector} {" rendered_rules.each do |rule| yield " #{rule};" end yield "}" end def rendered_rules(&b) return enum_for(:rendered_rules) unless b yield "color: #{fg}" if fg yield "background-color: #{bg}" if bg yield "font-weight: bold" if self[:bold] yield "font-style: italic" if self[:italic] yield "text-decoration: underline" if self[:underline] (self[:rules] || []).each(&b) end end def styles @styles ||= self.class.styles.dup end @palette = {} def self.palette(arg={}) @palette ||= InheritableHash.new(superclass.palette) if arg.is_a? Hash @palette.merge! arg @palette else case arg when /#[0-9a-f]+/i arg else @palette[arg] or raise "not in palette: #{arg.inspect}" end end end def palette(*a) self.class.palette(*a) end @styles = {} def self.styles @styles ||= InheritableHash.new(superclass.styles) end def self.render(opts={}, &b) new(opts).render(&b) end def get_own_style(token) self.class.get_own_style(token) end def get_style(token) self.class.get_style(token) end class << self def style(*tokens) style = tokens.last.is_a?(Hash) ? tokens.pop : {} tokens.each do |tok| styles[tok] = style end end def get_own_style(token) token.token_chain.reverse_each do |anc| return Style.new(self, styles[anc]) if styles[anc] end nil end def get_style(token) get_own_style(token) || base_style end def base_style get_own_style(Token::Tokens::Text) end def name(n=nil) return @name if n.nil? @name = n.to_s register(@name) end def register(name) Theme.registry[name.to_s] = self end def find(n) registry[n.to_s] end def registry @registry ||= {} end end end module HasModes def mode(arg=:absent) return @mode if arg == :absent @modes ||= {} @modes[arg] ||= get_mode(arg) end def get_mode(mode) return self if self.mode == mode new_name = "#{self.name}.#{mode}" Class.new(self) { name(new_name); set_mode!(mode) } end def set_mode!(mode) @mode = mode send("make_#{mode}!") end def mode!(arg) alt_name = "#{self.name}.#{arg}" register(alt_name) set_mode!(arg) end end class CSSTheme < Theme def initialize(opts={}) @scope = opts[:scope] || '.highlight' end def render(&b) return enum_for(:render).to_a.join("\n") unless b # shared styles for tableized line numbers yield "#{@scope} table td { padding: 5px; }" yield "#{@scope} table pre { margin: 0; }" styles.each do |tok, style| Style.new(self, style).render(css_selector(tok), &b) end end def render_base(selector, &b) self.class.base_style.render(selector, &b) end def style_for(tok) self.class.get_style(tok) end private def css_selector(token) inflate_token(token).map do |tok| raise "unknown token: #{tok.inspect}" if tok.shortname.nil? single_css_selector(tok) end.join(', ') end def single_css_selector(token) return @scope if token == Text "#{@scope} .#{token.shortname}" end # yield all of the tokens that should be styled the same # as the given token. Essentially this recursively all of # the subtokens, except those which are more specifically # styled. def inflate_token(tok, &b) return enum_for(:inflate_token, tok) unless block_given? yield tok tok.sub_tokens.each do |(_, st)| next if styles[st] inflate_token(st, &b) 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/lexer.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexer.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true # stdlib require 'strscan' require 'cgi' require 'set' module Rouge # @abstract # A lexer transforms text into a stream of `[token, chunk]` pairs. class Lexer include Token::Tokens @option_docs = {} class << self # Lexes `stream` with the given options. The lex is delegated to a # new instance. # # @see #lex def lex(stream, opts={}, &b) new(opts).lex(stream, &b) end # Given a name in string, return the correct lexer class. # @param [String] name # @return [Class<Rouge::Lexer>,nil] def find(name) registry[name.to_s] end # Find a lexer, with fancy shiny features. # # * The string you pass can include CGI-style options # # Lexer.find_fancy('erb?parent=tex') # # * You can pass the special name 'guess' so we guess for you, # and you can pass a second argument of the code to guess by # # Lexer.find_fancy('guess', "#!/bin/bash\necho Hello, world") # # This is used in the Redcarpet plugin as well as Rouge's own # markdown lexer for highlighting internal code blocks. # def find_fancy(str, code=nil, additional_options={}) if str && !str.include?('?') && str != 'guess' lexer_class = find(str) return lexer_class && lexer_class.new(additional_options) end name, opts = str ? str.split('?', 2) : [nil, ''] # parse the options hash from a cgi-style string opts = CGI.parse(opts || '').map do |k, vals| val = case vals.size when 0 then true when 1 then vals[0] else vals end [ k.to_s, val ] end opts = additional_options.merge(Hash[opts]) lexer_class = case name when 'guess', nil self.guess(:source => code, :mimetype => opts['mimetype']) when String self.find(name) end lexer_class && lexer_class.new(opts) end # Specify or get this lexer's title. Meant to be human-readable. def title(t=nil) if t.nil? t = tag.capitalize end @title ||= t end # Specify or get this lexer's description. def desc(arg=:absent) if arg == :absent @desc else @desc = arg end end def option_docs @option_docs ||= InheritableHash.new(superclass.option_docs) end def option(name, desc) option_docs[name.to_s] = desc end # Specify or get the path name containing a small demo for # this lexer (can be overriden by {demo}). def demo_file(arg=:absent) return @demo_file = Pathname.new(arg) unless arg == :absent @demo_file = Pathname.new(__FILE__).dirname.join('demos', tag) end # Specify or get a small demo string for this lexer def demo(arg=:absent) return @demo = arg unless arg == :absent @demo = File.read(demo_file, mode: 'rt:bom|utf-8') end # @return a list of all lexers. def all registry.values.uniq end # Guess which lexer to use based on a hash of info. # # This accepts the same arguments as Lexer.guess, but will never throw # an error. It will return a (possibly empty) list of potential lexers # to use. def guesses(info={}) mimetype, filename, source = info.values_at(:mimetype, :filename, :source) custom_globs = info[:custom_globs] guessers = (info[:guessers] || []).dup guessers << Guessers::Mimetype.new(mimetype) if mimetype guessers << Guessers::GlobMapping.by_pairs(custom_globs, filename) if custom_globs && filename guessers << Guessers::Filename.new(filename) if filename guessers << Guessers::Modeline.new(source) if source guessers << Guessers::Source.new(source) if source guessers << Guessers::Disambiguation.new(filename, source) if source && filename Guesser.guess(guessers, Lexer.all) end # Guess which lexer to use based on a hash of info. # # @option info :mimetype # A mimetype to guess by # @option info :filename # A filename to guess by # @option info :source # The source itself, which, if guessing by mimetype or filename # fails, will be searched for shebangs, <!DOCTYPE ...> tags, and # other hints. # @param [Proc] fallback called if multiple lexers are detected. # If omitted, Guesser::Ambiguous is raised. # # @see Lexer.detect? # @see Lexer.guesses # @return [Class<Rouge::Lexer>] def guess(info={}, &fallback) lexers = guesses(info) return Lexers::PlainText if lexers.empty? return lexers[0] if lexers.size == 1 if fallback fallback.call(lexers) else raise Guesser::Ambiguous.new(lexers) end end def guess_by_mimetype(mt) guess :mimetype => mt end def guess_by_filename(fname) guess :filename => fname end def guess_by_source(source) guess :source => source end def enable_debug! @debug_enabled = true end def disable_debug! @debug_enabled = false end def debug_enabled? !!@debug_enabled end protected # @private def register(name, lexer) registry[name.to_s] = lexer end public # Used to specify or get the canonical name of this lexer class. # # @example # class MyLexer < Lexer # tag 'foo' # end # # MyLexer.tag # => 'foo' # # Lexer.find('foo') # => MyLexer def tag(t=nil) return @tag if t.nil? @tag = t.to_s Lexer.register(@tag, self) end # Used to specify alternate names this lexer class may be found by. # # @example # class Erb < Lexer # tag 'erb' # aliases 'eruby', 'rhtml' # end # # Lexer.find('eruby') # => Erb def aliases(*args) args.map!(&:to_s) args.each { |arg| Lexer.register(arg, self) } (@aliases ||= []).concat(args) end # Specify a list of filename globs associated with this lexer. # # @example # class Ruby < Lexer # filenames '*.rb', '*.ruby', 'Gemfile', 'Rakefile' # end def filenames(*fnames) (@filenames ||= []).concat(fnames) end # Specify a list of mimetypes associated with this lexer. # # @example # class Html < Lexer # mimetypes 'text/html', 'application/xhtml+xml' # end def mimetypes(*mts) (@mimetypes ||= []).concat(mts) end # @private def assert_utf8!(str) return if %w(US-ASCII UTF-8 ASCII-8BIT).include? str.encoding.name raise EncodingError.new( "Bad encoding: #{str.encoding.names.join(',')}. " + "Please convert your string to UTF-8." ) end private def registry @registry ||= {} end end # -*- instance methods -*- # attr_reader :options # Create a new lexer with the given options. Individual lexers may # specify extra options. The only current globally accepted option # is `:debug`. # # @option opts :debug # Prints debug information to stdout. The particular info depends # on the lexer in question. In regex lexers, this will log the # state stack at the beginning of each step, along with each regex # tried and each stream consumed. Try it, it's pretty useful. def initialize(opts={}) @options = {} opts.each { |k, v| @options[k.to_s] = v } @debug = Lexer.debug_enabled? && bool_option(:debug) end def as_bool(val) case val when nil, false, 0, '0', 'off' false when Array val.empty? ? true : as_bool(val.last) else true end end def as_string(val) return as_string(val.last) if val.is_a?(Array) val ? val.to_s : nil end def as_list(val) case val when Array val.flat_map { |v| as_list(v) } when String val.split(',') else [] end end def as_lexer(val) return as_lexer(val.last) if val.is_a?(Array) return val.new(@options) if val.is_a?(Class) && val < Lexer case val when Lexer val when String lexer_class = Lexer.find(val) lexer_class && lexer_class.new(@options) end end def as_token(val) return as_token(val.last) if val.is_a?(Array) case val when Token val else Token[val] end end def bool_option(name, &default) if @options.key?(name.to_s) as_bool(@options[name.to_s]) else default ? default.call : false end end def string_option(name, &default) as_string(@options.delete(name.to_s, &default)) end def lexer_option(name, &default) as_lexer(@options.delete(name.to_s, &default)) end def list_option(name, &default) as_list(@options.delete(name.to_s, &default)) end def token_option(name, &default) as_token(@options.delete(name.to_s, &default)) end def hash_option(name, defaults, &val_cast) name = name.to_s out = defaults.dup base = @options.delete(name.to_s) base = {} unless base.is_a?(Hash) base.each { |k, v| out[k.to_s] = val_cast ? val_cast.call(v) : v } @options.keys.each do |key| next unless key =~ /(\w+)\[(\w+)\]/ and $1 == name value = @options.delete(key) out[$2] = val_cast ? val_cast.call(value) : value end out end # @abstract # # Called after each lex is finished. The default implementation # is a noop. def reset! end # Given a string, yield [token, chunk] pairs. If no block is given, # an enumerator is returned. # # @option opts :continue # Continue the lex from the previous state (i.e. don't call #reset!) def lex(string, opts={}, &b) return enum_for(:lex, string, opts) unless block_given? Lexer.assert_utf8!(string) reset! unless opts[:continue] # consolidate consecutive tokens of the same type last_token = nil last_val = nil stream_tokens(string) do |tok, val| next if val.empty? if tok == last_token last_val << val next end b.call(last_token, last_val) if last_token last_token = tok last_val = val end b.call(last_token, last_val) if last_token end # delegated to {Lexer.tag} def tag self.class.tag end # @abstract # # Yield `[token, chunk]` pairs, given a prepared input stream. This # must be implemented. # # @param [StringScanner] stream # the stream def stream_tokens(stream, &b) raise 'abstract' end # @abstract # # Return true if there is an in-text indication (such as a shebang # or DOCTYPE declaration) that this lexer should be used. # # @param [TextAnalyzer] text # the text to be analyzed, with a couple of handy methods on it, # like {TextAnalyzer#shebang?} and {TextAnalyzer#doctype?} def self.detect?(text) false end end module Lexers @_loaded_lexers = {} def self.load_lexer(relpath) return if @_loaded_lexers.key?(relpath) @_loaded_lexers[relpath] = true root = Pathname.new(__FILE__).dirname.join('lexers') load root.join(relpath) 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/cli.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/cli.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true # not required by the main lib. # to use this module, require 'rouge/cli'. module Rouge class FileReader attr_reader :input def initialize(input) @input = input end def file case input when '-' IO.new($stdin.fileno, 'rt:bom|utf-8') when String File.new(input, 'rt:bom|utf-8') when ->(i){ i.respond_to? :read } input end end def read @read ||= begin file.read rescue => e $stderr.puts "unable to open #{input}: #{e.message}" exit 1 ensure file.close end end end class CLI def self.doc return enum_for(:doc) unless block_given? yield %|usage: rougify [command] [args...]| yield %|| yield %|where <command> is one of:| yield %| highlight #{Highlight.desc}| yield %| help #{Help.desc}| yield %| style #{Style.desc}| yield %| list #{List.desc}| yield %| guess #{Guess.desc}| yield %| version #{Version.desc}| yield %|| yield %|See `rougify help <command>` for more info.| end class Error < StandardError attr_reader :message, :status def initialize(message, status=1) @message = message @status = status end end def self.parse(argv=ARGV) argv = normalize_syntax(argv) mode = argv.shift klass = class_from_arg(mode) return klass.parse(argv) if klass case mode when '-h', '--help', 'help', '-help', nil Help.parse(argv) else argv.unshift(mode) if mode Highlight.parse(argv) end end def initialize(options={}) end def self.error!(msg, status=1) raise Error.new(msg, status) end def error!(*a) self.class.error!(*a) end def self.class_from_arg(arg) case arg when 'version', '--version', '-v' Version when 'help' Help when 'highlight', 'hi' Highlight when 'style' Style when 'list' List when 'guess' Guess end end class Version < CLI def self.desc "print the rouge version number" end def self.parse(*); new; end def run puts Rouge.version end end class Help < CLI def self.desc "print help info" end def self.doc return enum_for(:doc) unless block_given? yield %|usage: rougify help <command>| yield %|| yield %|print help info for <command>.| end def self.parse(argv) opts = { :mode => CLI } until argv.empty? arg = argv.shift klass = class_from_arg(arg) if klass opts[:mode] = klass next end end new(opts) end def initialize(opts={}) @mode = opts[:mode] end def run @mode.doc.each(&method(:puts)) end end class Highlight < CLI def self.desc "highlight code" end def self.doc return enum_for(:doc) unless block_given? yield %[usage: rougify highlight <filename> [options...]] yield %[ rougify highlight [options...]] yield %[] yield %[--input-file|-i <filename> specify a file to read, or - to use stdin] yield %[] yield %[--lexer|-l <lexer> specify the lexer to use.] yield %[ If not provided, rougify will try to guess] yield %[ based on --mimetype, the filename, and the] yield %[ file contents.] yield %[] yield %[--formatter|-f <opts> specify the output formatter to use.] yield %[ If not provided, rougify will default to] yield %[ terminal256.] yield %[] yield %[--theme|-t <theme> specify the theme to use for highlighting] yield %[ the file. (only applies to some formatters)] yield %[] yield %[--mimetype|-m <mimetype> specify a mimetype for lexer guessing] yield %[] yield %[--lexer-opts|-L <opts> specify lexer options in CGI format] yield %[ (opt1=val1&opt2=val2)] yield %[] yield %[--formatter-opts|-F <opts> specify formatter options in CGI format] yield %[ (opt1=val1&opt2=val2)] yield %[] yield %[--require|-r <filename> require a filename or library before] yield %[ highlighting] end def self.parse(argv) opts = { :formatter => 'terminal256', :theme => 'thankful_eyes', :css_class => 'codehilite', :input_file => '-', :lexer_opts => {}, :formatter_opts => {}, :requires => [], } until argv.empty? arg = argv.shift case arg when '-r', '--require' opts[:requires] << argv.shift when '--input-file', '-i' opts[:input_file] = argv.shift when '--mimetype', '-m' opts[:mimetype] = argv.shift when '--lexer', '-l' opts[:lexer] = argv.shift when '--formatter-preset', '-f' opts[:formatter] = argv.shift when '--theme', '-t' opts[:theme] = argv.shift when '--css-class', '-c' opts[:css_class] = argv.shift when '--lexer-opts', '-L' opts[:lexer_opts] = parse_cgi(argv.shift) when /^--/ error! "unknown option #{arg.inspect}" else opts[:input_file] = arg end end new(opts) end def input_stream @input_stream ||= FileReader.new(@input_file) end def input @input ||= input_stream.read end def lexer_class @lexer_class ||= Lexer.guess( :filename => @input_file, :mimetype => @mimetype, :source => input_stream, ) end def lexer @lexer ||= lexer_class.new(@lexer_opts) end attr_reader :input_file, :lexer_name, :mimetype, :formatter def initialize(opts={}) Rouge::Lexer.enable_debug! opts[:requires].each do |r| require r end @input_file = opts[:input_file] if opts[:lexer] @lexer_class = Lexer.find(opts[:lexer]) \ or error! "unknown lexer #{opts[:lexer].inspect}" else @lexer_name = opts[:lexer] @mimetype = opts[:mimetype] end @lexer_opts = opts[:lexer_opts] theme = Theme.find(opts[:theme]).new or error! "unknown theme #{opts[:theme]}" @formatter = case opts[:formatter] when 'terminal256' then Formatters::Terminal256.new(theme) when 'html' then Formatters::HTML.new when 'html-pygments' then Formatters::HTMLPygments.new(Formatters::HTML.new, opts[:css_class]) when 'html-inline' then Formatters::HTMLInline.new(theme) when 'html-table' then Formatters::HTMLTable.new(Formatters::HTML.new) when 'null', 'raw', 'tokens' then Formatters::Null.new else error! "unknown formatter preset #{opts[:formatter]}" end end def run formatter.format(lexer.lex(input), &method(:print)) end private_class_method def self.parse_cgi(str) pairs = CGI.parse(str).map { |k, v| [k.to_sym, v.first] } Hash[pairs] end end class Style < CLI def self.desc "print CSS styles" end def self.doc return enum_for(:doc) unless block_given? yield %|usage: rougify style [<theme-name>] [<options>]| yield %|| yield %|Print CSS styles for the given theme. Extra options are| yield %|passed to the theme. To select a mode (light/dark) for the| yield %|theme, append '.light' or '.dark' to the <theme-name>| yield %|respectively. Theme defaults to thankful_eyes.| yield %|| yield %|options:| yield %| --scope (default: .highlight) a css selector to scope by| yield %|| yield %|available themes:| yield %| #{Theme.registry.keys.sort.join(', ')}| end def self.parse(argv) opts = { :theme_name => 'thankful_eyes' } until argv.empty? arg = argv.shift case arg when /--(\w+)/ opts[$1.tr('-', '_').to_sym] = argv.shift else opts[:theme_name] = arg end end new(opts) end def initialize(opts) theme_name = opts.delete(:theme_name) theme_class = Theme.find(theme_name) \ or error! "unknown theme: #{theme_name}" @theme = theme_class.new(opts) end def run @theme.render(&method(:puts)) end end class List < CLI def self.desc "list available lexers" end def self.doc return enum_for(:doc) unless block_given? yield %|usage: rouge list| yield %|| yield %|print a list of all available lexers with their descriptions.| end def self.parse(argv) new end def run puts "== Available Lexers ==" Lexer.all.sort_by(&:tag).each do |lexer| desc = String.new("#{lexer.desc}") if lexer.aliases.any? desc << " [aliases: #{lexer.aliases.join(',')}]" end puts "%s: %s" % [lexer.tag, desc] lexer.option_docs.keys.sort.each do |option| puts " ?#{option}= #{lexer.option_docs[option]}" end puts end end end class Guess < CLI def self.desc "guess the languages of file" end def self.parse(args) new(input_file: args.shift) end attr_reader :input_file, :input_source def initialize(opts) @input_file = opts[:input_file] || '-' @input_source = FileReader.new(@input_file).read end def lexers Lexer.guesses( filename: input_file, source: input_source, ) end def run lexers.each do |l| puts "{ tag: #{l.tag.inspect}, title: #{l.title.inspect}, desc: #{l.desc.inspect} }" end end end private_class_method def self.normalize_syntax(argv) out = [] argv.each do |arg| case arg when /^(--\w+)=(.*)$/ out << $1 << $2 when /^(-\w)(.+)$/ out << $1 << $2 else out << arg end end out 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/regex_lexer.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/regex_lexer.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge # @abstract # A stateful lexer that uses sets of regular expressions to # tokenize a string. Most lexers are instances of RegexLexer. class RegexLexer < Lexer # A rule is a tuple of a regular expression to test, and a callback # to perform if the test succeeds. # # @see StateDSL#rule class Rule attr_reader :callback attr_reader :re attr_reader :beginning_of_line def initialize(re, callback) @re = re @callback = callback @beginning_of_line = re.source[0] == ?^ end def inspect "#<Rule #{@re.inspect}>" end end # a State is a named set of rules that can be tested for or # mixed in. # # @see RegexLexer.state class State attr_reader :name, :rules def initialize(name, rules) @name = name @rules = rules end def inspect "#<#{self.class.name} #{@name.inspect}>" end end class StateDSL attr_reader :rules def initialize(name, &defn) @name = name @defn = defn @rules = [] @loaded = false end def to_state(lexer_class) load! rules = @rules.map do |rule| rule.is_a?(String) ? lexer_class.get_state(rule) : rule end State.new(@name, rules) end def prepended(&defn) parent_defn = @defn StateDSL.new(@name) do instance_eval(&defn) instance_eval(&parent_defn) end end def appended(&defn) parent_defn = @defn StateDSL.new(@name) do instance_eval(&parent_defn) instance_eval(&defn) end end protected # Define a new rule for this state. # # @overload rule(re, token, next_state=nil) # @overload rule(re, &callback) # # @param [Regexp] re # a regular expression for this rule to test. # @param [String] tok # the token type to yield if `re` matches. # @param [#to_s] next_state # (optional) a state to push onto the stack if `re` matches. # If `next_state` is `:pop!`, the state stack will be popped # instead. # @param [Proc] callback # a block that will be evaluated in the context of the lexer # if `re` matches. This block has access to a number of lexer # methods, including {RegexLexer#push}, {RegexLexer#pop!}, # {RegexLexer#token}, and {RegexLexer#delegate}. The first # argument can be used to access the match groups. def rule(re, tok=nil, next_state=nil, &callback) if tok.nil? && callback.nil? raise "please pass `rule` a token to yield or a callback" end callback ||= case next_state when :pop! proc do |stream| puts " yielding #{tok.qualname}, #{stream[0].inspect}" if @debug @output_stream.call(tok, stream[0]) puts " popping stack: 1" if @debug @stack.pop or raise 'empty stack!' end when :push proc do |stream| puts " yielding #{tok.qualname}, #{stream[0].inspect}" if @debug @output_stream.call(tok, stream[0]) puts " pushing :#{@stack.last.name}" if @debug @stack.push(@stack.last) end when Symbol proc do |stream| puts " yielding #{tok.qualname}, #{stream[0].inspect}" if @debug @output_stream.call(tok, stream[0]) state = @states[next_state] || self.class.get_state(next_state) puts " pushing :#{state.name}" if @debug @stack.push(state) end when nil proc do |stream| puts " yielding #{tok.qualname}, #{stream[0].inspect}" if @debug @output_stream.call(tok, stream[0]) end else raise "invalid next state: #{next_state.inspect}" end rules << Rule.new(re, callback) end # Mix in the rules from another state into this state. The rules # from the mixed-in state will be tried in order before moving on # to the rest of the rules in this state. def mixin(state) rules << state.to_s end private def load! return if @loaded @loaded = true instance_eval(&@defn) end end # The states hash for this lexer. # @see state def self.states @states ||= {} end def self.state_definitions @state_definitions ||= InheritableHash.new(superclass.state_definitions) end @state_definitions = {} def self.replace_state(name, new_defn) states[name] = nil state_definitions[name] = new_defn end # The routines to run at the beginning of a fresh lex. # @see start def self.start_procs @start_procs ||= InheritableList.new(superclass.start_procs) end @start_procs = [] # Specify an action to be run every fresh lex. # # @example # start { puts "I'm lexing a new string!" } def self.start(&b) start_procs << b end # Define a new state for this lexer with the given name. # The block will be evaluated in the context of a {StateDSL}. def self.state(name, &b) name = name.to_s state_definitions[name] = StateDSL.new(name, &b) end def self.prepend(name, &b) name = name.to_s dsl = state_definitions[name] or raise "no such state #{name.inspect}" replace_state(name, dsl.prepended(&b)) end def self.append(name, &b) name = name.to_s dsl = state_definitions[name] or raise "no such state #{name.inspect}" replace_state(name, dsl.appended(&b)) end # @private def self.get_state(name) return name if name.is_a? State states[name.to_sym] ||= begin defn = state_definitions[name.to_s] or raise "unknown state: #{name.inspect}" defn.to_state(self) end end # @private def get_state(state_name) self.class.get_state(state_name) end # The state stack. This is initially the single state `[:root]`. # It is an error for this stack to be empty. # @see #state def stack @stack ||= [get_state(:root)] end # The current state - i.e. one on top of the state stack. # # NB: if the state stack is empty, this will throw an error rather # than returning nil. def state stack.last or raise 'empty stack!' end # reset this lexer to its initial state. This runs all of the # start_procs. def reset! @stack = nil @current_stream = nil puts "start blocks" if @debug && self.class.start_procs.any? self.class.start_procs.each do |pr| instance_eval(&pr) end end # This implements the lexer protocol, by yielding [token, value] pairs. # # The process for lexing works as follows, until the stream is empty: # # 1. We look at the state on top of the stack (which by default is # `[:root]`). # 2. Each rule in that state is tried until one is successful. If one # is found, that rule's callback is evaluated - which may yield # tokens and manipulate the state stack. Otherwise, one character # is consumed with an `'Error'` token, and we continue at (1.) # # @see #step #step (where (2.) is implemented) def stream_tokens(str, &b) stream = StringScanner.new(str) @current_stream = stream @output_stream = b @states = self.class.states @null_steps = 0 until stream.eos? if @debug puts "lexer: #{self.class.tag}" puts "stack: #{stack.map(&:name).map(&:to_sym).inspect}" puts "stream: #{stream.peek(20).inspect}" end success = step(state, stream) if !success puts " no match, yielding Error" if @debug b.call(Token::Tokens::Error, stream.getch) end end end # The number of successive scans permitted without consuming # the input stream. If this is exceeded, the match fails. MAX_NULL_SCANS = 5 # Runs one step of the lex. Rules in the current state are tried # until one matches, at which point its callback is called. # # @return true if a rule was tried successfully # @return false otherwise. def step(state, stream) state.rules.each do |rule| if rule.is_a?(State) puts " entering mixin #{rule.name}" if @debug return true if step(rule, stream) puts " exiting mixin #{rule.name}" if @debug else puts " trying #{rule.inspect}" if @debug # XXX HACK XXX # StringScanner's implementation of ^ is b0rken. # see http://bugs.ruby-lang.org/issues/7092 # TODO: this doesn't cover cases like /(a|^b)/, but it's # the most common, for now... next if rule.beginning_of_line && !stream.beginning_of_line? if (size = stream.skip(rule.re)) puts " got #{stream[0].inspect}" if @debug instance_exec(stream, &rule.callback) if size.zero? @null_steps += 1 if @null_steps > MAX_NULL_SCANS puts " too many scans without consuming the string!" if @debug return false end else @null_steps = 0 end return true end end end false end # Yield a token. # # @param tok # the token type # @param val # (optional) the string value to yield. If absent, this defaults # to the entire last match. def token(tok, val=@current_stream[0]) yield_token(tok, val) end # @deprecated # # Yield a token with the next matched group. Subsequent calls # to this method will yield subsequent groups. def group(tok) raise "RegexLexer#group is deprecated: use #groups instead" end # Yield tokens corresponding to the matched groups of the current # match. def groups(*tokens) tokens.each_with_index do |tok, i| yield_token(tok, @current_stream[i+1]) end end # Delegate the lex to another lexer. The #lex method will be called # with `:continue` set to true, so that #reset! will not be called. # In this way, a single lexer can be repeatedly delegated to while # maintaining its own internal state stack. # # @param [#lex] lexer # The lexer or lexer class to delegate to # @param [String] text # The text to delegate. This defaults to the last matched string. def delegate(lexer, text=nil) puts " delegating to #{lexer.inspect}" if @debug text ||= @current_stream[0] lexer.lex(text, :continue => true) do |tok, val| puts " delegated token: #{tok.inspect}, #{val.inspect}" if @debug yield_token(tok, val) end end def recurse(text=nil) delegate(self.class, text) end # Push a state onto the stack. If no state name is given and you've # passed a block, a state will be dynamically created using the # {StateDSL}. def push(state_name=nil, &b) push_state = if state_name get_state(state_name) elsif block_given? StateDSL.new(b.inspect, &b).to_state(self.class) else # use the top of the stack by default self.state end puts " pushing :#{push_state.name}" if @debug stack.push(push_state) end # Pop the state stack. If a number is passed in, it will be popped # that number of times. def pop!(times=1) raise 'empty stack!' if stack.empty? puts " popping stack: #{times}" if @debug stack.pop(times) nil end # replace the head of the stack with the given state def goto(state_name) raise 'empty stack!' if stack.empty? puts " going to state :#{state_name} " if @debug stack[-1] = get_state(state_name) end # reset the stack back to `[:root]`. def reset_stack puts ' resetting stack' if @debug stack.clear stack.push get_state(:root) end # Check if `state_name` is in the state stack. def in_state?(state_name) state_name = state_name.to_s stack.any? do |state| state.name == state_name.to_s end end # Check if `state_name` is the state on top of the state stack. def state?(state_name) state_name.to_s == state.name end private def yield_token(tok, val) return if val.nil? || val.empty? puts " yielding #{tok.qualname}, #{val.inspect}" if @debug @output_stream.yield(tok, 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/rouge-3.3.0/lib/rouge/token.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/token.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge class Token class << self attr_reader :name attr_reader :parent attr_reader :shortname def cache @cache ||= {} end def sub_tokens @sub_tokens ||= {} end def [](qualname) return qualname unless qualname.is_a? ::String Token.cache[qualname] end def inspect "<Token #{qualname}>" end def matches?(other) other.token_chain.include? self end def token_chain @token_chain ||= ancestors.take_while { |x| x != Token }.reverse end def qualname @qualname ||= token_chain.map(&:name).join('.') end def register! Token.cache[self.qualname] = self parent.sub_tokens[self.name] = self end def make_token(name, shortname, &b) parent = self Class.new(parent) do @parent = parent @name = name @shortname = shortname register! class_eval(&b) if b end end def token(name, shortname, &b) tok = make_token(name, shortname, &b) const_set(name, tok) end def each_token(&b) Token.cache.each do |(_, t)| b.call(t) end end end module Tokens def self.token(name, shortname, &b) tok = Token.make_token(name, shortname, &b) const_set(name, tok) end # XXX IMPORTANT XXX # For compatibility, this list must be kept in sync with # pygments.token.STANDARD_TYPES # please see https://github.com/jneen/rouge/wiki/List-of-tokens token :Text, '' do token :Whitespace, 'w' end token :Error, 'err' token :Other, 'x' token :Keyword, 'k' do token :Constant, 'kc' token :Declaration, 'kd' token :Namespace, 'kn' token :Pseudo, 'kp' token :Reserved, 'kr' token :Type, 'kt' token :Variable, 'kv' end token :Name, 'n' do token :Attribute, 'na' token :Builtin, 'nb' do token :Pseudo, 'bp' end token :Class, 'nc' token :Constant, 'no' token :Decorator, 'nd' token :Entity, 'ni' token :Exception, 'ne' token :Function, 'nf' token :Property, 'py' token :Label, 'nl' token :Namespace, 'nn' token :Other, 'nx' token :Tag, 'nt' token :Variable, 'nv' do token :Class, 'vc' token :Global, 'vg' token :Instance, 'vi' end end token :Literal, 'l' do token :Date, 'ld' token :String, 's' do token :Backtick, 'sb' token :Char, 'sc' token :Doc, 'sd' token :Double, 's2' token :Escape, 'se' token :Heredoc, 'sh' token :Interpol, 'si' token :Other, 'sx' token :Regex, 'sr' token :Single, 's1' token :Symbol, 'ss' end token :Number, 'm' do token :Float, 'mf' token :Hex, 'mh' token :Integer, 'mi' do token :Long, 'il' end token :Oct, 'mo' token :Bin, 'mb' token :Other, 'mx' end end token :Operator, 'o' do token :Word, 'ow' end token :Punctuation, 'p' do token :Indicator, 'pi' end token :Comment, 'c' do token :Doc, 'cd' token :Multiline, 'cm' token :Preproc, 'cp' token :Single, 'c1' token :Special, 'cs' end token :Generic, 'g' do token :Deleted, 'gd' token :Emph, 'ge' token :Error, 'gr' token :Heading, 'gh' token :Inserted, 'gi' token :Output, 'go' token :Prompt, 'gp' token :Strong, 'gs' token :Subheading, 'gu' token :Traceback, 'gt' token :Lineno, 'gl' end # convenience Num = Literal::Number Str = Literal::String end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/formatter.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/formatter.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge # A Formatter takes a token stream and formats it for human viewing. class Formatter # @private REGISTRY = {} # Specify or get the unique tag for this formatter. This is used # for specifying a formatter in `rougify`. def self.tag(tag=nil) return @tag unless tag REGISTRY[tag] = self @tag = tag end # Find a formatter class given a unique tag. def self.find(tag) REGISTRY[tag] end # Format a token stream. Delegates to {#format}. def self.format(tokens, *a, &b) new(*a).format(tokens, &b) end def initialize(opts={}) # pass end # Format a token stream. def format(tokens, &b) return stream(tokens, &b) if block_given? out = String.new('') stream(tokens) { |piece| out << piece } out end # @deprecated Use {#format} instead. def render(tokens) warn 'Formatter#render is deprecated, use #format instead.' format(tokens) end # @abstract # yield strings that, when concatenated, form the formatted output def stream(tokens, &b) raise 'abstract' end protected def token_lines(tokens, &b) return enum_for(:token_lines, tokens) unless block_given? out = [] tokens.each do |tok, val| val.scan /\n|[^\n]+/ do |s| if s == "\n" yield out out = [] else out << [tok, s] end end end # for inputs not ending in a newline yield out if out.any? 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/text_analyzer.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/text_analyzer.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge class TextAnalyzer < String # Find a shebang. Returns nil if no shebang is present. def shebang return @shebang if instance_variable_defined? :@shebang self =~ /\A\s*#!(.*)$/ @shebang = $1 end # Check if the given shebang is present. # # This normalizes things so that `text.shebang?('bash')` will detect # `#!/bash`, '#!/bin/bash', '#!/usr/bin/env bash', and '#!/bin/bash -x' def shebang?(match) return false unless shebang match = /\b#{match}(\s|$)/ match === shebang end # Return the contents of the doctype tag if present, nil otherwise. def doctype return @doctype if instance_variable_defined? :@doctype self =~ %r(\A\s* (?:<\?.*?\?>\s*)? # possible <?xml...?> tag <!DOCTYPE\s+(.+?)> )xm @doctype = $1 end # Check if the doctype matches a given regexp or string def doctype?(type=//) type === doctype end # Return true if the result of lexing with the given lexer contains no # error tokens. def lexes_cleanly?(lexer) lexer.lex(self) do |(tok, _)| return false if tok.name == 'Error' end true end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/template_lexer.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/template_lexer.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge # @abstract # A TemplateLexer is one that accepts a :parent option, to specify # which language is being templated. The lexer class can specify its # own default for the parent lexer, which is otherwise defaulted to # HTML. class TemplateLexer < RegexLexer # the parent lexer - the one being templated. def parent return @parent if instance_variable_defined? :@parent @parent = lexer_option(:parent) || Lexers::HTML.new(@options) end option :parent, "the parent language (default: html)" start { parent.reset! } 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/util.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/util.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge class InheritableHash < Hash def initialize(parent=nil) @parent = parent end def [](k) value = super return value if own_keys.include?(k) value || parent[k] end def parent @parent ||= {} end def include?(k) super or parent.include?(k) end def each(&b) keys.each do |k| b.call(k, self[k]) end end alias own_keys keys def keys keys = own_keys.concat(parent.keys) keys.uniq! keys end end class InheritableList include Enumerable def initialize(parent=nil) @parent = parent end def parent @parent ||= [] end def each(&b) return enum_for(:each) unless block_given? parent.each(&b) own_entries.each(&b) end def own_entries @own_entries ||= [] end def push(o) own_entries << o end alias << push end # shared methods for some indentation-sensitive lexers module Indentation def reset! super @block_state = @block_indentation = nil end # push a state for the next indented block def starts_block(block_state) @block_state = block_state @block_indentation = @last_indentation || '' puts " starts_block #{block_state.inspect}" if @debug puts " block_indentation: #{@block_indentation.inspect}" if @debug end # handle a single indented line def indentation(indent_str) puts " indentation #{indent_str.inspect}" if @debug puts " block_indentation: #{@block_indentation.inspect}" if @debug @last_indentation = indent_str # if it's an indent and we know where to go next, # push that state. otherwise, push content and # clear the block state. if (@block_state && indent_str.start_with?(@block_indentation) && indent_str != @block_indentation ) push @block_state else @block_state = @block_indentation = nil push :content 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/plugins/redcarpet.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/plugins/redcarpet.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true # this file is not require'd from the root. To use this plugin, run: # # require 'rouge/plugins/redcarpet' module Rouge module Plugins module Redcarpet def block_code(code, language) lexer = Lexer.find_fancy(language, code) || Lexers::PlainText # XXX HACK: Redcarpet strips hard tabs out of code blocks, # so we assume you're not using leading spaces that aren't tabs, # and just replace them here. if lexer.tag == 'make' code.gsub! /^ /, "\t" end formatter = rouge_formatter(lexer) formatter.format(lexer.lex(code)) end # override this method for custom formatting behavior def rouge_formatter(lexer) Formatters::HTMLLegacy.new(:css_class => "highlight #{lexer.tag}") 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/lexers/tcl.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/tcl.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class TCL < RegexLexer title "Tcl" desc "The Tool Command Language (tcl.tk)" tag 'tcl' filenames '*.tcl' mimetypes 'text/x-tcl', 'text/x-script.tcl', 'application/x-tcl' def self.detect?(text) return true if text.shebang? 'tclsh' return true if text.shebang? 'wish' return true if text.shebang? 'jimsh' end KEYWORDS = %w( after apply array break catch continue elseif else error eval expr for foreach global if namespace proc rename return set switch then trace unset update uplevel upvar variable vwait while ) BUILTINS = %w( append bgerror binary cd chan clock close concat dde dict encoding eof exec exit fblocked fconfigure fcopy file fileevent flush format gets glob history http incr info interp join lappend lassign lindex linsert list llength load loadTk lrange lrepeat lreplace lreverse lsearch lset lsort mathfunc mathop memory msgcat open package pid pkg::create pkg_mkIndex platform platform::shell puts pwd re_syntax read refchan regexp registry regsub scan seek socket source split string subst tell time tm unknown unload ) OPEN = %w| \( \[ \{ " | CLOSE = %w| \) \] \} | ALL = OPEN + CLOSE END_LINE = CLOSE + %w(; \n) END_WORD = END_LINE + %w(\s) CHARS = lambda { |list| Regexp.new %/[#{list.join}]/ } NOT_CHARS = lambda { |list| Regexp.new %/[^#{list.join}]/ } state :word do rule /\{\*\}/, Keyword mixin :brace_abort mixin :interp rule /\{/, Punctuation, :brace rule /\(/, Punctuation, :paren rule /"/, Str::Double, :string rule /#{NOT_CHARS[END_WORD]}+?(?=#{CHARS[OPEN+['\\\\']]})/, Text end def self.gen_command_state(name='') state(:"command#{name}") do mixin :word rule /##{NOT_CHARS[END_LINE]}+/, Comment::Single rule /(?=#{CHARS[END_WORD]})/ do push :"params#{name}" end rule /#{NOT_CHARS[END_WORD]}+/ do |m| if KEYWORDS.include? m[0] token Keyword elsif BUILTINS.include? m[0] token Name::Builtin else token Text end end mixin :whitespace end end def self.gen_delimiter_states(name, close, opts={}) gen_command_state("_in_#{name}") state :"params_in_#{name}" do rule close do token Punctuation pop! 2 end # mismatched delimiters. Braced strings with mismatched # closing delimiters should be okay, since this is standard # practice, like {]]]]} if opts[:strict] rule CHARS[CLOSE - [close]], Error else rule CHARS[CLOSE - [close]], Text end mixin :params end state name do rule close, Punctuation, :pop! mixin :"command_in_#{name}" end end # tcl is freaking impossible. If we're in braces and we encounter # a close brace, we have to drop everything and close the brace. # This is so silly things like {abc"def} and {abc]def} don't b0rk # everything after them. # TODO: TCL seems to have this aborting behavior quite a lot. # such things as [ abc" ] are a runtime error, but will still # parse. Currently something like this will muck up the lex. state :brace_abort do rule /}/ do if in_state? :brace pop! until state? :brace pop! token Punctuation else token Error end end end state :params do rule /;/, Punctuation, :pop! rule /\n/, Text, :pop! rule /else|elseif|then/, Keyword mixin :word mixin :whitespace rule /#{NOT_CHARS[END_WORD]}+/, Text end gen_delimiter_states :brace, /\}/, :strict => false gen_delimiter_states :paren, /\)/, :strict => true gen_delimiter_states :bracket, /\]/, :strict => true gen_command_state state :root do mixin :command end state :whitespace do # not a multiline regex because we want to capture \n sometimes rule /\s+/, Text end state :interp do rule /\[/, Punctuation, :bracket rule /\$[a-z0-9.:-]+/, Name::Variable rule /\$\{.*?\}/m, Name::Variable rule /\$/, Text # escape sequences rule /\\[0-7]{3}/, Str::Escape rule /\\x[0-9a-f]{2}/i, Str::Escape rule /\\u[0-9a-f]{4}/i, Str::Escape rule /\\./m, Str::Escape end state :string do rule /"/, Str::Double, :pop! mixin :interp rule /[^\\\[\$"{}]+/m, Str::Double # strings have to keep count of their internal braces, to support # for example { "{ }" }. rule /{/ do @brace_count ||= 0 @brace_count += 1 token Str::Double end rule /}/ do if in_state? :brace and @brace_count.to_i == 0 pop! until state? :brace pop! token Punctuation else @brace_count -= 1 token Str::Double end 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/lexers/erlang.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/erlang.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Erlang < RegexLexer title "Erlang" desc "The Erlang programming language (erlang.org)" tag 'erlang' aliases 'erl' filenames '*.erl', '*.hrl' mimetypes 'text/x-erlang', 'application/x-erlang' keywords = %w( after begin case catch cond end fun if let of query receive try when ) builtins = %w( abs append_element apply atom_to_list binary_to_list bitstring_to_list binary_to_term bit_size bump_reductions byte_size cancel_timer check_process_code delete_module demonitor disconnect_node display element erase exit float float_to_list fun_info fun_to_list function_exported garbage_collect get get_keys group_leader hash hd integer_to_list iolist_to_binary iolist_size is_atom is_binary is_bitstring is_boolean is_builtin is_float is_function is_integer is_list is_number is_pid is_port is_process_alive is_record is_reference is_tuple length link list_to_atom list_to_binary list_to_bitstring list_to_existing_atom list_to_float list_to_integer list_to_pid list_to_tuple load_module localtime_to_universaltime make_tuple md5 md5_final md5_update memory module_loaded monitor monitor_node node nodes open_port phash phash2 pid_to_list port_close port_command port_connect port_control port_call port_info port_to_list process_display process_flag process_info purge_module put read_timer ref_to_list register resume_process round send send_after send_nosuspend set_cookie setelement size spawn spawn_link spawn_monitor spawn_opt split_binary start_timer statistics suspend_process system_flag system_info system_monitor system_profile term_to_binary tl trace trace_delivered trace_info trace_pattern trunc tuple_size tuple_to_list universaltime_to_localtime unlink unregister whereis ) operators = %r{(\+\+?|--?|\*|/|<|>|/=|=:=|=/=|=<|>=|==?|<-|!|\?)} word_operators = %w( and andalso band bnot bor bsl bsr bxor div not or orelse rem xor ) atom_re = %r{(?:[a-z][a-zA-Z0-9_]*|'[^\n']*[^\\]')} variable_re = %r{(?:[A-Z_][a-zA-Z0-9_]*)} escape_re = %r{(?:\\(?:[bdefnrstv\'"\\/]|[0-7][0-7]?[0-7]?|\^[a-zA-Z]))} macro_re = %r{(?:#{variable_re}|#{atom_re})} base_re = %r{(?:[2-9]|[12][0-9]|3[0-6])} state :root do rule(/\s+/, Text) rule(/%.*\n/, Comment) rule(%r{(#{keywords.join('|')})\b}, Keyword) rule(%r{(#{builtins.join('|')})\b}, Name::Builtin) rule(%r{(#{word_operators.join('|')})\b}, Operator::Word) rule(/^-/, Punctuation, :directive) rule(operators, Operator) rule(/"/, Str, :string) rule(/<</, Name::Label) rule(/>>/, Name::Label) rule %r{(#{atom_re})(:)} do groups Name::Namespace, Punctuation end rule %r{(?:^|(?<=:))(#{atom_re})(\s*)(\()} do groups Name::Function, Text, Punctuation end rule(%r{[+-]?#{base_re}#[0-9a-zA-Z]+}, Num::Integer) rule(/[+-]?\d+/, Num::Integer) rule(/[+-]?\d+.\d+/, Num::Float) rule(%r{[\]\[:_@\".{}()|;,]}, Punctuation) rule(variable_re, Name::Variable) rule(atom_re, Name) rule(%r{\?#{macro_re}}, Name::Constant) rule(%r{\$(?:#{escape_re}|\\[ %]|[^\\])}, Str::Char) rule(%r{##{atom_re}(:?\.#{atom_re})?}, Name::Label) end state :string do rule(escape_re, Str::Escape) rule(/"/, Str, :pop!) rule(%r{~[0-9.*]*[~#+bBcdefginpPswWxX]}, Str::Interpol) rule(%r{[^"\\~]+}, Str) rule(/~/, Str) end state :directive do rule %r{(define)(\s*)(\()(#{macro_re})} do groups Name::Entity, Text, Punctuation, Name::Constant pop! end rule %r{(record)(\s*)(\()(#{macro_re})} do groups Name::Entity, Text, Punctuation, Name::Label pop! end rule(atom_re, Name::Entity, :pop!) 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/lexers/literate_coffeescript.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/literate_coffeescript.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class LiterateCoffeescript < RegexLexer tag 'literate_coffeescript' title "Literate CoffeeScript" desc 'Literate coffeescript' aliases 'litcoffee' filenames '*.litcoffee' def markdown @markdown ||= Markdown.new(options) end def coffee @coffee ||= Coffeescript.new(options) end start { markdown.reset!; coffee.reset! } state :root do rule /^( .*?\n)+/m do delegate coffee end rule /^([ ]{0,3}(\S.*?|)\n)*/m do delegate markdown 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/lexers/docker.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/docker.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Docker < RegexLexer title "Docker" desc "Dockerfile syntax" tag 'docker' aliases 'dockerfile' filenames 'Dockerfile', '*.docker' mimetypes 'text/x-dockerfile-config' KEYWORDS = %w( FROM MAINTAINER CMD LABEL EXPOSE ENV ADD COPY ENTRYPOINT VOLUME USER WORKDIR ARG STOPSIGNAL HEALTHCHECK SHELL ).join('|') start { @shell = Shell.new(@options) } state :root do rule /\s+/, Text rule /^(ONBUILD)(\s+)(#{KEYWORDS})(.*)/io do |m| groups Keyword, Text::Whitespace, Keyword, Str end rule /^(#{KEYWORDS})\b(.*)/io do |m| groups Keyword, Str end rule /#.*?$/, Comment rule /^(ONBUILD\s+)?RUN(\s+)/i do token Keyword push :run @shell.reset! end rule /\w+/, Text rule /[^\w]+/, Text rule /./, Text end state :run do rule /\n/, Text, :pop! rule /\\./m, Str::Escape rule(/(\\.|[^\n\\])+/) { delegate @shell } 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/lexers/bsl.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/bsl.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Bsl < RegexLexer title "1C (BSL)" desc "The 1C:Enterprise programming language" tag 'bsl' filenames '*.bsl', '*.os' KEYWORDS = /(?<=[^\wа-яё]|^)(?: КонецПроцедуры | EndProcedure | КонецФункции | EndFunction | Прервать | Break | Продолжить | Continue | Возврат | Return | Если | If | Иначе | Else | ИначеЕсли | ElsIf | Тогда | Then | КонецЕсли | EndIf | Попытка | Try | Исключение | Except | КонецПопытки | EndTry | Raise | ВызватьИсключение | Пока | While | Для | For | Каждого | Each | Из | In | По | To | Цикл | Do | КонецЦикла | EndDo | НЕ | NOT | И | AND | ИЛИ | OR | Новый | New | Процедура | Procedure | Функция | Function | Перем | Var | Экспорт | Export | Знач | Val )(?=[^\wа-яё]|$)/ix BUILTINS = /(?<=[^\wа-яё]|^)(?: СтрДлина|StrLen|СокрЛ|TrimL|СокрП|TrimR|СокрЛП|TrimAll|Лев|Left|Прав|Right|Сред|Mid|СтрНайти|StrFind|ВРег|Upper|НРег|Lower|ТРег|Title|Символ|Char|КодСимвола|CharCode|ПустаяСтрока|IsBlankString|СтрЗаменить|StrReplace|СтрЧислоСтрок|StrLineCount|СтрПолучитьСтроку|StrGetLine|СтрЧислоВхождений|StrOccurrenceCount|СтрСравнить|StrCompare|СтрНачинаетсяС|StrStartWith|СтрЗаканчиваетсяНа|StrEndsWith|СтрРазделить|StrSplit|СтрСоединить|StrConcat | Цел|Int|Окр|Round|ACos|ACos|ASin|ASin|ATan|ATan|Cos|Cos|Exp|Exp|Log|Log|Log10|Log10|Pow|Pow|Sin|Sin|Sqrt|Sqrt|Tan|Tan | Год|Year|Месяц|Month|День|Day|Час|Hour|Минута|Minute|Секунда|Second|НачалоГода|BegOfYear|НачалоДня|BegOfDay|НачалоКвартала|BegOfQuarter|НачалоМесяца|BegOfMonth|НачалоМинуты|BegOfMinute|НачалоНедели|BegOfWeek|НачалоЧаса|BegOfHour|КонецГода|EndOfYear|КонецДня|EndOfDay|КонецКвартала|EndOfQuarter|КонецМесяца|EndOfMonth|КонецМинуты|EndOfMinute|КонецНедели|EndOfWeek|КонецЧаса|EndOfHour|НеделяГода|WeekOfYear|ДеньГода|DayOfYear|ДеньНедели|WeekDay|ТекущаяДата|CurrentDate|ДобавитьМесяц|AddMonth | Тип|Type|ТипЗнч|TypeOf | Булево|Boolean|Число|Number|Строка|String|Дата|Date | ПоказатьВопрос|ShowQueryBox|Вопрос|DoQueryBox|ПоказатьПредупреждение|ShowMessageBox|Предупреждение|DoMessageBox|Сообщить|Message|ОчиститьСообщения|ClearMessages|ОповеститьОбИзменении|NotifyChanged|Состояние|Status|Сигнал|Beep|ПоказатьЗначение|ShowValue|ОткрытьЗначение|OpenValue|Оповестить|Notify|ОбработкаПрерыванияПользователя|UserInterruptProcessing|ОткрытьСодержаниеСправки|OpenHelpContent|ОткрытьИндексСправки|OpenHelpIndex|ОткрытьСправку|OpenHelp|ПоказатьИнформациюОбОшибке|ShowErrorInfo|КраткоеПредставлениеОшибки|BriefErrorDescription|ПодробноеПредставлениеОшибки|DetailErrorDescription|ПолучитьФорму|GetForm|ЗакрытьСправку|CloseHelp|ПоказатьОповещениеПользователя|ShowUserNotification|ОткрытьФорму|OpenForm|ОткрытьФормуМодально|OpenFormModal|АктивноеОкно|ActiveWindow|ВыполнитьОбработкуОповещения|ExecuteNotifyProcessing | ПоказатьВводЗначения|ShowInputValue|ВвестиЗначение|InputValue|ПоказатьВводЧисла|ShowInputNumber|ВвестиЧисло|InputNumber|ПоказатьВводСтроки|ShowInputString|ВвестиСтроку|InputString|ПоказатьВводДаты|ShowInputDate|ВвестиДату|InputDate | Формат|Format|ЧислоПрописью|NumberInWords|НСтр|NStr|ПредставлениеПериода|PeriodPresentation|СтрШаблон|StrTemplate | ПолучитьОбщийМакет|GetCommonTemplate|ПолучитьОбщуюФорму|GetCommonForm|ПредопределенноеЗначение|PredefinedValue|ПолучитьПолноеИмяПредопределенногоЗначения|GetPredefinedValueFullName | ПолучитьЗаголовокСистемы|GetCaption|ПолучитьСкоростьКлиентскогоСоединения|GetClientConnectionSpeed|ПодключитьОбработчикОжидания|AttachIdleHandler|УстановитьЗаголовокСистемы|SetCaption|ОтключитьОбработчикОжидания|DetachIdleHandler|ИмяКомпьютера|ComputerName|ЗавершитьРаботуСистемы|Exit|ИмяПользователя|UserName|ПрекратитьРаботуСистемы|Terminate|ПолноеИмяПользователя|UserFullName|ЗаблокироватьРаботуПользователя|LockApplication|КаталогПрограммы|BinDir|КаталогВременныхФайлов|TempFilesDir|ПравоДоступа|AccessRight|РольДоступна|IsInRole|ТекущийЯзык|CurrentLanguage|ТекущийКодЛокализации|CurrentLocaleCode|СтрокаСоединенияИнформационнойБазы|InfoBaseConnectionString|ПодключитьОбработчикОповещения|AttachNotificationHandler|ОтключитьОбработчикОповещения|DetachNotificationHandler|ПолучитьСообщенияПользователю|GetUserMessages|ПараметрыДоступа|AccessParameters|ПредставлениеПриложения|ApplicationPresentation|ТекущийЯзыкСистемы|CurrentSystemLanguage|ЗапуститьСистему|RunSystem|ТекущийРежимЗапуска|CurrentRunMode|УстановитьЧасовойПоясСеанса|SetSessionTimeZone|ЧасовойПоясСеанса|SessionTimeZone|ТекущаяДатаСеанса|CurrentSessionDate|УстановитьКраткийЗаголовокПриложения|SetShortApplicationCaption|ПолучитьКраткийЗаголовокПриложения|GetShortApplicationCaption|ПредставлениеПрава|RightPresentation|ВыполнитьПроверкуПравДоступа|VerifyAccessRights|РабочийКаталогДанныхПользователя|UserDataWorkDir|КаталогДокументов|DocumentsDir|ПолучитьИнформациюЭкрановКлиента|GetClientDisplaysInformation|ТекущийВариантОсновногоШрифтаКлиентскогоПриложения|ClientApplicationBaseFontCurrentVariant|ТекущийВариантИнтерфейсаКлиентскогоПриложения|ClientApplicationInterfaceCurrentVariant|УстановитьЗаголовокКлиентскогоПриложения|SetClientApplicationCaption|ПолучитьЗаголовокКлиентскогоПриложения|GetClientApplicationCaption|НачатьПолучениеКаталогаВременныхФайлов|BeginGettingTempFilesDir|НачатьПолучениеКаталогаДокументов|BeginGettingDocumentsDir|НачатьПолучениеРабочегоКаталогаДанныхПользователя|BeginGettingUserDataWorkDir|ПодключитьОбработчикЗапросаНастроекКлиентаЛицензирования|AttachLicensingClientParametersRequestHandler|ОтключитьОбработчикЗапросаНастроекКлиентаЛицензирования|DetachLicensingClientParametersRequestHandler | ЗначениеВСтрокуВнутр|ValueToStringInternal|ЗначениеИзСтрокиВнутр|ValueFromStringInternal|ЗначениеВФайл|ValueToFile|ЗначениеИзФайла|ValueFromFile | КомандаСистемы|System|ЗапуститьПриложение|RunApp|ПолучитьCOMОбъект|GetCOMObject|ПользователиОС|OSUsers|НачатьЗапускПриложения|BeginRunningApplication | ПодключитьВнешнююКомпоненту|AttachAddIn|НачатьУстановкуВнешнейКомпоненты|BeginInstallAddIn|УстановитьВнешнююКомпоненту|InstallAddIn|НачатьПодключениеВнешнейКомпоненты|BeginAttachingAddIn | КопироватьФайл|FileCopy|ПереместитьФайл|MoveFile|УдалитьФайлы|DeleteFiles|НайтиФайлы|FindFiles|СоздатьКаталог|CreateDirectory|ПолучитьИмяВременногоФайла|GetTempFileName|РазделитьФайл|SplitFile|ОбъединитьФайлы|MergeFiles|ПолучитьФайл|GetFile|НачатьПомещениеФайла|BeginPutFile|ПоместитьФайл|PutFile|ЭтоАдресВременногоХранилища|IsTempStorageURL|УдалитьИзВременногоХранилища|DeleteFromTempStorage|ПолучитьИзВременногоХранилища|GetFromTempStorage|ПоместитьВоВременноеХранилище|PutToTempStorage|ПодключитьРасширениеРаботыСФайлами|AttachFileSystemExtension|НачатьУстановкуРасширенияРаботыСФайлами|BeginInstallFileSystemExtension|УстановитьРасширениеРаботыСФайлами|InstallFileSystemExtension|ПолучитьФайлы|GetFiles|ПоместитьФайлы|PutFiles|ЗапроситьРазрешениеПользователя|RequestUserPermission|ПолучитьМаскуВсеФайлы|GetAllFilesMask|ПолучитьМаскуВсеФайлыКлиента|GetClientAllFilesMask|ПолучитьМаскуВсеФайлыСервера|GetServerAllFilesMask|ПолучитьРазделительПути|GetPathSeparator|ПолучитьРазделительПутиКлиента|GetClientPathSeparator|ПолучитьРазделительПутиСервера|GetServerPathSeparator|НачатьПодключениеРасширенияРаботыСФайлами|BeginAttachingFileSystemExtension|НачатьЗапросРазрешенияПользователя|BeginRequestingUserPermission|НачатьПоискФайлов|BeginFindingFiles|НачатьСозданиеКаталога|BeginCreatingDirectory|НачатьКопированиеФайла|BeginCopyingFile|НачатьПеремещениеФайла|BeginMovingFile|НачатьУдалениеФайлов|BeginDeletingFiles|НачатьПолучениеФайлов|BeginGettingFiles|НачатьПомещениеФайлов|BeginPuttingFiles | НачатьТранзакцию|BeginTransaction|ЗафиксироватьТранзакцию|CommitTransaction|ОтменитьТранзакцию|RollbackTransaction|УстановитьМонопольныйРежим|SetExclusiveMode|МонопольныйРежим|ExclusiveMode|ПолучитьОперативнуюОтметкуВремени|GetRealTimeTimestamp|ПолучитьСоединенияИнформационнойБазы|GetInfoBaseConnections|НомерСоединенияИнформационнойБазы|InfoBaseConnectionNumber|КонфигурацияИзменена|ConfigurationChanged|КонфигурацияБазыДанныхИзмененаДинамически|DataBaseConfigurationChangedDynamically|УстановитьВремяОжиданияБлокировкиДанных|SetLockWaitTime|ОбновитьНумерациюОбъектов|RefreshObjectsNumbering|ПолучитьВремяОжиданияБлокировкиДанных|GetLockWaitTime|КодЛокализацииИнформационнойБазы|InfoBaseLocaleCode|УстановитьМинимальнуюДлинуПаролейПользователей|SetUserPasswordMinLength|ПолучитьМинимальнуюДлинуПаролейПользователей|GetUserPasswordMinLength|ИнициализироватьПредопределенныеДанные|InitializePredefinedData|УдалитьДанныеИнформационнойБазы|EraseInfoBaseData|УстановитьПроверкуСложностиПаролейПользователей|SetUserPasswordStrengthCheck|ПолучитьПроверкуСложностиПаролейПользователей|GetUserPasswordStrengthCheck|ПолучитьСтруктуруХраненияБазыДанных|GetDBStorageStructureInfo|УстановитьПривилегированныйРежим|SetPrivilegedMode|ПривилегированныйРежим|PrivilegedMode|ТранзакцияАктивна|TransactionActive|НеобходимостьЗавершенияСоединения|ConnectionStopRequest|НомерСеансаИнформационнойБазы|InfoBaseSessionNumber|ПолучитьСеансыИнформационнойБазы|GetInfoBaseSessions|ЗаблокироватьДанныеДляРедактирования|LockDataForEdit|УстановитьСоединениеСВнешнимИсточникомДанных|ConnectExternalDataSource|РазблокироватьДанныеДляРедактирования|UnlockDataForEdit|РазорватьСоединениеСВнешнимИсточникомДанных|DisconnectExternalDataSource|ПолучитьБлокировкуСеансов|GetSessionsLock|УстановитьБлокировкуСеансов|SetSessionsLock|ОбновитьПовторноИспользуемыеЗначения|RefreshReusableValues|УстановитьБезопасныйРежим|SetSafeMode|БезопасныйРежим|SafeMode|ПолучитьДанныеВыбора|GetChoiceData|УстановитьЧасовойПоясИнформационнойБазы|SetInfoBaseTimeZone|ПолучитьЧасовойПоясИнформационнойБазы|GetInfoBaseTimeZone|ПолучитьОбновлениеКонфигурацииБазыДанных|GetDataBaseConfigurationUpdate|УстановитьБезопасныйРежимРазделенияДанных|SetDataSeparationSafeMode|БезопасныйРежимРазделенияДанных|DataSeparationSafeMode|УстановитьВремяЗасыпанияПассивногоСеанса|SetPassiveSessionHibernateTime|ПолучитьВремяЗасыпанияПассивногоСеанса|GetPassiveSessionHibernateTime|УстановитьВремяЗавершенияСпящегоСеанса|SetHibernateSessionTerminateTime|ПолучитьВремяЗавершенияСпящегоСеанса|GetHibernateSessionTerminateTime|ПолучитьТекущийСеансИнформационнойБазы|GetCurrentInfoBaseSession|ПолучитьИдентификаторКонфигурации|GetConfigurationID|УстановитьНастройкиКлиентаЛицензирования|SetLicensingClientParameters|ПолучитьИмяКлиентаЛицензирования|GetLicensingClientName|ПолучитьДополнительныйПараметрКлиентаЛицензирования|GetLicensingClientAdditionalParameter | НайтиПомеченныеНаУдаление|FindMarkedForDeletion|НайтиПоСсылкам|FindByRef|УдалитьОбъекты|DeleteObjects|УстановитьОбновлениеПредопределенныхДанныхИнформационнойБазы|SetInfoBasePredefinedDataUpdate|ПолучитьОбновлениеПредопределенныхДанныхИнформационнойБазы|GetInfoBasePredefinedData | XMLСтрока|XMLString|XMLЗначение|XMLValue|XMLТип|XMLType|XMLТипЗнч|XMLTypeOf|ИзXMLТипа|FromXMLType|ВозможностьЧтенияXML|CanReadXML|ПолучитьXMLТип|GetXMLType|ПрочитатьXML|ReadXML|ЗаписатьXML|WriteXML|НайтиНедопустимыеСимволыXML|FindDisallowedXMLCharacters|ИмпортМоделиXDTO|ImportXDTOModel|СоздатьФабрикуXDTO|CreateXDTOFactory | ЗаписатьJSON|WriteJSON|ПрочитатьJSON|ReadJSON|ПрочитатьДатуJSON|ReadJSONDate|ЗаписатьДатуJSON|WriteJSONDate | ЗаписьЖурналаРегистрации|WriteLogEvent|ПолучитьИспользованиеЖурналаРегистрации|GetEventLogUsing|УстановитьИспользованиеЖурналаРегистрации|SetEventLogUsing|ПредставлениеСобытияЖурналаРегистрации|EventLogEventPresentation|ВыгрузитьЖурналРегистрации|UnloadEventLog|ПолучитьЗначенияОтбораЖурналаРегистрации|GetEventLogFilterValues|УстановитьИспользованиеСобытияЖурналаРегистрации|SetEventLogEventUse|ПолучитьИспользованиеСобытияЖурналаРегистрации|GetEventLogEventUse|СкопироватьЖурналРегистрации|CopyEventLog|ОчиститьЖурналРегистрации|ClearEventLog | ЗначениеВДанныеФормы|ValueToFormData|ДанныеФормыВЗначение|FormDataToValue|КопироватьДанныеФормы|CopyFormData|УстановитьСоответствиеОбъектаИФормы|SetObjectAndFormConformity|ПолучитьСоответствиеОбъектаИФормы|GetObjectAndFormConformity | ПолучитьФункциональнуюОпцию|GetFunctionalOption|ПолучитьФункциональнуюОпциюИнтерфейса|GetInterfaceFunctionalOption|УстановитьПараметрыФункциональныхОпцийИнтерфейса|SetInterfaceFunctionalOptionParameters|ПолучитьПараметрыФункциональныхОпцийИнтерфейса|GetInterfaceFunctionalOptionParameters|ОбновитьИнтерфейс|RefreshInterface | УстановитьРасширениеРаботыСКриптографией|InstallCryptoExtension|НачатьУстановкуРасширенияРаботыСКриптографией|BeginInstallCryptoExtension|ПодключитьРасширениеРаботыСКриптографией|AttachCryptoExtension|НачатьПодключениеРасширенияРаботыСКриптографией|BeginAttachingCryptoExtension | УстановитьСоставСтандартногоИнтерфейсаOData|SetStandardODataInterfaceContent|ПолучитьСоставСтандартногоИнтерфейсаOData|GetStandardODataInterfaceContent | Мин|Min|Макс|Max|ОписаниеОшибки|ErrorDescription|Вычислить|Eval|ИнформацияОбОшибке|ErrorInfo|Base64Значение|Base64Value|Base64Строка|Base64String|ЗаполнитьЗначенияСвойств|FillPropertyValues|ЗначениеЗаполнено|ValueIsFilled|ПолучитьПредставленияНавигационныхСсылок|GetURLsPresentations|НайтиОкноПоНавигационнойСсылке|FindWindowByURL|ПолучитьОкна|GetWindows|ПерейтиПоНавигационнойСсылке|GotoURL|ПолучитьНавигационнуюСсылку|GetURL|ПолучитьДопустимыеКодыЛокализации|GetAvailableLocaleCodes|ПолучитьНавигационнуюСсылкуИнформационнойБазы|GetInfoBaseURL|ПредставлениеКодаЛокализации|LocaleCodePresentation|ПолучитьДопустимыеЧасовыеПояса|GetAvailableTimeZones|ПредставлениеЧасовогоПояса|TimeZonePresentation|ТекущаяУниверсальнаяДата|CurrentUniversalDate|ТекущаяУниверсальнаяДатаВМиллисекундах|CurrentUniversalDateInMilliseconds|МестноеВремя|ToLocalTime|УниверсальноеВремя|ToUniversalTime|ЧасовойПояс|TimeZone|СмещениеЛетнегоВремени|DaylightTimeOffset|СмещениеСтандартногоВремени|StandardTimeOffset|КодироватьСтроку|EncodeString|РаскодироватьСтроку|DecodeString|Найти|Find | ПередНачаломРаботыСистемы|BeforeStart|ПриНачалеРаботыСистемы|OnStart|ПередЗавершениемРаботыСистемы|BeforeExit|ПриЗавершенииРаботыСистемы|OnExit|ОбработкаВнешнегоСобытия|ExternEventProcessing|УстановкаПараметровСеанса|SessionParametersSetting|ПриИзмененииПараметровЭкрана|OnChangeDisplaySettings | WSСсылки|WSReferences|БиблиотекаКартинок|PictureLib|БиблиотекаМакетовОформленияКомпоновкиДанных|DataCompositionAppearanceTemplateLib|БиблиотекаСтилей|StyleLib|БизнесПроцессы|BusinessProcesses|ВнешниеИсточникиДанных|ExternalDataSources|ВнешниеОбработки|ExternalDataProcessors|ВнешниеОтчеты|ExternalReports|Документы|Documents|ДоставляемыеУведомления|DeliverableNotifications|ЖурналыДокументов|DocumentJournals|Задачи|Tasks|ИспользованиеРабочейДаты|WorkingDateUse|ИсторияРаботыПользователя|UserWorkHistory|Константы|Constants|КритерииОтбора|FilterCriteria|Метаданные|Metadata|Обработки|DataProcessors|ОтправкаДоставляемыхУведомлений|DeliverableNotificationSend|Отчеты|Reports|ПараметрыСеанса|SessionParameters|Перечисления|Enums|ПланыВидовРасчета|ChartsOfCalculationTypes|ПланыВидовХарактеристик|ChartsOfCharacteristicTypes|ПланыОбмена|ExchangePlans|ПланыСчетов|ChartsOfAccounts|ПолнотекстовыйПоиск|FullTextSearch|ПользователиИнформационнойБазы|InfoBaseUsers|Последовательности|Sequences|РасширенияКонфигурации|ConfigurationExtensions|РегистрыБухгалтерии|AccountingRegisters|РегистрыНакопления|AccumulationRegisters|РегистрыРасчета|CalculationRegisters|РегистрыСведений|InformationRegisters|РегламентныеЗадания|ScheduledJobs|СериализаторXDTO|XDTOSerializer|Справочники|Catalogs|СредстваГеопозиционирования|LocationTools|СредстваКриптографии|CryptoToolsManager|СредстваМультимедиа|MultimediaTools|СредстваПочты|MailTools|СредстваТелефонии|TelephonyTools|ФабрикаXDTO|XDTOFactory|ФоновыеЗадания|BackgroundJobs|ХранилищаНастроек | ГлавныйИнтерфейс|MainInterface|ГлавныйСтиль|MainStyle|ПараметрЗапуска|LaunchParameter|РабочаяДата|WorkingDate|SettingsStorages|ХранилищеВариантовОтчетов|ReportsVariantsStorage|ХранилищеНастроекДанныхФорм|FormDataSettingsStorage|ХранилищеОбщихНастроек|CommonSettingsStorage|ХранилищеПользовательскихНастроекДинамическихСписков|DynamicListsUserSettingsStorage|ХранилищеПользовательскихНастроекОтчетов|ReportsUserSettingsStorage|ХранилищеСистемныхНастроек|SystemSettingsStorage | Если|If|ИначеЕсли|ElsIf|Иначе|Else|КонецЕсли|EndIf|Тогда|Then | Неопределено|Undefined|Истина|True|Ложь|False|NULL )\s*(?=\()/ix state :root do rule /\n/, Text rule /[^\S\n]+/, Text rule /\/\/.*$/, Comment::Single rule /[\[\]:(),;]/, Punctuation rule /(?<=[^\wа-яё]|^)\&.*$/, Keyword::Declaration rule /[-+\/=<>*%=<>.?&]/, Operator rule /(?<=[^\wа-яё]|^)\#.*$/, Keyword::Declaration rule KEYWORDS, Keyword rule BUILTINS, Name::Builtin rule /[\wа-яё_][\wа-яё0-9_]*/i, Name::Variable #literals rule /\b((\h{8}-(\h{4}-){3}\h{12})|\d+\.?\d*)\b/, Literal::Number rule /\'.*\'/, Literal::Date rule /".*?("|$)/, Literal::String::Single rule /(?<=[^\wа-яё]|^)\|((?!\"\").)*?(\"|$)/, Literal::String 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/lexers/fsharp.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/fsharp.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class FSharp < RegexLexer title "FSharp" desc 'F# (fsharp.net)' tag 'fsharp' filenames '*.fs', '*.fsi', '*.fsx' mimetypes 'application/fsharp-script', 'text/x-fsharp', 'text/x-fsi' def self.keywords @keywords ||= Set.new %w( abstract and as assert base begin class default delegate do done downcast downto elif else end exception extern false finally for fun function global if in inherit inline interface internal lazy let let! match member module mutable namespace new not null of open or override private public rec return return! select static struct then to true try type upcast use use! val void when while with yield yield! sig atomic break checked component const constraint constructor continue eager event external fixed functor include method mixin object parallel process protected pure sealed tailcall trait virtual volatile ) end def self.keyopts @keyopts ||= Set.new %w( != # & && ( ) * \+ , - -. -> . .. : :: := :> ; ;; < <- = > >] >} ? ?? [ [< [> [| ] _ ` { {< | |] } ~ |> <| <> ) end def self.word_operators @word_operators ||= Set.new %w(and asr land lor lsl lxor mod or) end def self.primitives @primitives ||= Set.new %w(unit int float bool string char list array) end operator = %r([\[\];,{}_()!$%&*+./:<=>?@^|~#-]+) id = /([a-z][\w']*)|(``[^`\n\r\t]+``)/i upper_id = /[A-Z][\w']*/ state :root do rule /\s+/m, Text rule /false|true|[(][)]|\[\]/, Name::Builtin::Pseudo rule /#{upper_id}(?=\s*[.])/, Name::Namespace, :dotted rule upper_id, Name::Class rule /[(][*](?![)])/, Comment, :comment rule %r(//.*?$), Comment::Single rule id do |m| match = m[0] if self.class.keywords.include? match token Keyword elsif self.class.word_operators.include? match token Operator::Word elsif self.class.primitives.include? match token Keyword::Type else token Name end end rule operator do |m| match = m[0] if self.class.keyopts.include? match token Punctuation else token Operator end end rule /-?\d[\d_]*(.[\d_]*)?(e[+-]?\d[\d_]*)/i, Num::Float rule /0x\h[\h_]*/i, Num::Hex rule /0o[0-7][0-7_]*/i, Num::Oct rule /0b[01][01_]*/i, Num::Bin rule /\d[\d_]*/, Num::Integer rule /'(?:(\\[\\"'ntbr ])|(\\[0-9]{3})|(\\x\h{2}))'/, Str::Char rule /'[.]'/, Str::Char rule /'/, Keyword rule /"/, Str::Double, :string rule /[~?]#{id}/, Name::Variable end state :comment do rule /[^(*)]+/, Comment rule(/[(][*]/) { token Comment; push } rule /[*][)]/, Comment, :pop! rule /[(*)]/, Comment end state :string do rule /[^\\"]+/, Str::Double mixin :escape_sequence rule /\\\n/, Str::Double rule /"/, Str::Double, :pop! end state :escape_sequence do rule /\\[\\"'ntbr]/, Str::Escape rule /\\\d{3}/, Str::Escape rule /\\x\h{2}/, Str::Escape end state :dotted do rule /\s+/m, Text rule /[.]/, Punctuation rule /#{upper_id}(?=\s*[.])/, Name::Namespace rule upper_id, Name::Class, :pop! rule id, Name, :pop! 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/lexers/sql.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/sql.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class SQL < RegexLexer title "SQL" desc "Structured Query Language, for relational databases" tag 'sql' filenames '*.sql' mimetypes 'text/x-sql' def self.keywords @keywords ||= Set.new %w( ABORT ABS ABSOLUTE ACCESS ADA ADD ADMIN AFTER AGGREGATE ALIAS ALL ALLOCATE ALTER ANALYSE ANALYZE AND ANY ARE AS ASC ASENSITIVE ASSERTION ASSIGNMENT ASYMMETRIC AT ATOMIC AUTHORIZATION AVG BACKWARD BEFORE BEGIN BETWEEN BITVAR BIT_LENGTH BOTH BREADTH BY C CACHE CALL CALLED CARDINALITY CASCADE CASCADED CASE CAST CATALOG CATALOG_NAME CHAIN CHARACTERISTICS CHARACTER_LENGTH CHARACTER_SET_CATALOG CHARACTER_SET_NAME CHARACTER_SET_SCHEMA CHAR_LENGTH CHECK CHECKED CHECKPOINT CLASS CLASS_ORIGIN CLOB CLOSE CLUSTER COALSECE COBOL COLLATE COLLATION COLLATION_CATALOG COLLATION_NAME COLLATION_SCHEMA COLUMN COLUMN_NAME COMMAND_FUNCTION COMMAND_FUNCTION_CODE COMMENT COMMIT COMMITTED COMPLETION CONDITION_NUMBER CONNECT CONNECTION CONNECTION_NAME CONSTRAINT CONSTRAINTS CONSTRAINT_CATALOG CONSTRAINT_NAME CONSTRAINT_SCHEMA CONSTRUCTOR CONTAINS CONTINUE CONVERSION CONVERT COPY CORRESPONTING COUNT CREATE CREATEDB CREATEUSER CROSS CUBE CURRENT CURRENT_DATE CURRENT_PATH CURRENT_ROLE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR CURSOR_NAME CYCLE DATA DATABASE DATETIME_INTERVAL_CODE DATETIME_INTERVAL_PRECISION DAY DEALLOCATE DECLARE DEFAULT DEFAULTS DEFERRABLE DEFERRED DEFINED DEFINER DELETE DELIMITER DELIMITERS DEREF DESC DESCRIBE DESCRIPTOR DESTROY DESTRUCTOR DETERMINISTIC DIAGNOSTICS DICTIONARY DISCONNECT DISPATCH DISTINCT DO DOMAIN DROP DYNAMIC DYNAMIC_FUNCTION DYNAMIC_FUNCTION_CODE EACH ELSE ENCODING ENCRYPTED END END-EXEC EQUALS ESCAPE EVERY EXCEPT ESCEPTION EXCLUDING EXCLUSIVE EXEC EXECUTE EXISTING EXISTS EXPLAIN EXTERNAL EXTRACT FALSE FETCH FINAL FIRST FOR FORCE FOREIGN FORTRAN FORWARD FOUND FREE FREEZE FROM FULL FUNCTION G GENERAL GENERATED GET GLOBAL GO GOTO GRANT GRANTED GROUP GROUPING HANDLER HAVING HIERARCHY HOLD HOST IDENTITY IGNORE ILIKE IMMEDIATE IMMUTABLE IMPLEMENTATION IMPLICIT IN INCLUDING INCREMENT INDEX INDITCATOR INFIX INHERITS INITIALIZE INITIALLY INNER INOUT INPUT INSENSITIVE INSERT INSTANTIABLE INSTEAD INTERSECT INTO INVOKER IS ISNULL ISOLATION ITERATE JOIN KEY KEY_MEMBER KEY_TYPE LANCOMPILER LANGUAGE LARGE LAST LATERAL LEADING LEFT LENGTH LESS LEVEL LIKE LIMIT LISTEN LOAD LOCAL LOCALTIME LOCALTIMESTAMP LOCATION LOCATOR LOCK LOWER MAP MATCH MAX MAXVALUE MESSAGE_LENGTH MESSAGE_OCTET_LENGTH MESSAGE_TEXT METHOD MIN MINUTE MINVALUE MOD MODE MODIFIES MODIFY MONTH MORE MOVE MUMPS NAMES NATIONAL NATURAL NCHAR NCLOB NEW NEXT NO NOCREATEDB NOCREATEUSER NONE NOT NOTHING NOTIFY NOTNULL NULL NULLABLE NULLIF OBJECT OCTET_LENGTH OF OFF OFFSET OIDS OLD ON ONLY OPEN OPERATION OPERATOR OPTION OPTIONS OR ORDER ORDINALITY OUT OUTER OUTPUT OVERLAPS OVERLAY OVERRIDING OWNER PAD PARAMETER PARAMETERS PARAMETER_MODE PARAMATER_NAME PARAMATER_ORDINAL_POSITION PARAMETER_SPECIFIC_CATALOG PARAMETER_SPECIFIC_NAME PARAMATER_SPECIFIC_SCHEMA PARTIAL PASCAL PENDANT PLACING PLI POSITION POSTFIX PRECISION PREFIX PREORDER PREPARE PRESERVE PRIMARY PRIOR PRIVILEGES PROCEDURAL PROCEDURE PUBLIC READ READS RECHECK RECURSIVE REF REFERENCES REFERENCING REINDEX RELATIVE RENAME REPEATABLE REPLACE RESET RESTART RESTRICT RESULT RETURN RETURNED_LENGTH RETURNED_OCTET_LENGTH RETURNED_SQLSTATE RETURNS REVOKE RIGHT ROLE ROLLBACK ROLLUP ROUTINE ROUTINE_CATALOG ROUTINE_NAME ROUTINE_SCHEMA ROW ROWS ROW_COUNT RULE SAVE_POINT SCALE SCHEMA SCHEMA_NAME SCOPE SCROLL SEARCH SECOND SECURITY SELECT SELF SENSITIVE SERIALIZABLE SERVER_NAME SESSION SESSION_USER SET SETOF SETS SHARE SHOW SIMILAR SIMPLE SIZE SOME SOURCE SPACE SPECIFIC SPECIFICTYPE SPECIFIC_NAME SQL SQLCODE SQLERROR SQLEXCEPTION SQLSTATE SQLWARNINIG STABLE START STATE STATEMENT STATIC STATISTICS STDIN STDOUT STORAGE STRICT STRUCTURE STYPE SUBCLASS_ORIGIN SUBLIST SUBSTRING SUM SYMMETRIC SYSID SYSTEM SYSTEM_USER TABLE TABLE_NAME TEMP TEMPLATE TEMPORARY TERMINATE THAN THEN TIMESTAMP TIMEZONE_HOUR TIMEZONE_MINUTE TO TOAST TRAILING TRANSATION TRANSACTIONS_COMMITTED TRANSACTIONS_ROLLED_BACK TRANSATION_ACTIVE TRANSFORM TRANSFORMS TRANSLATE TRANSLATION TREAT TRIGGER TRIGGER_CATALOG TRIGGER_NAME TRIGGER_SCHEMA TRIM TRUE TRUNCATE TRUSTED TYPE UNCOMMITTED UNDER UNENCRYPTED UNION UNIQUE UNKNOWN UNLISTEN UNNAMED UNNEST UNTIL UPDATE UPPER USAGE USER USER_DEFINED_TYPE_CATALOG USER_DEFINED_TYPE_NAME USER_DEFINED_TYPE_SCHEMA USING VACUUM VALID VALIDATOR VALUES VARIABLE VERBOSE VERSION VIEW VOLATILE WHEN WHENEVER WHERE WITH WITHOUT WORK WRITE YEAR ZONE ) end state :root do rule /\s+/m, Text rule /--.*/, Comment::Single rule %r(/\*), Comment::Multiline, :multiline_comments rule /\d+/, Num::Integer rule /'/, Str::Single, :single_string rule /"/, Name::Variable, :double_string rule /`/, Name::Variable, :backtick rule /\w[\w\d]*/ do |m| if self.class.keywords.include? m[0].upcase token Keyword else token Name end end rule %r([+*/<>=~!@#%^&|?^-]), Operator rule /[;:()\[\],.]/, Punctuation end state :multiline_comments do rule %r(/[*]), Comment::Multiline, :multiline_comments rule %r([*]/), Comment::Multiline, :pop! rule %r([^/*]+), Comment::Multiline rule %r([/*]), Comment::Multiline end state :backtick do rule /\\./, Str::Escape rule /``/, Str::Escape rule /`/, Name::Variable, :pop! rule /[^\\`]+/, Name::Variable end state :single_string do rule /\\./, Str::Escape rule /''/, Str::Escape rule /'/, Str::Single, :pop! rule /[^\\']+/, Str::Single end state :double_string do rule /\\./, Str::Escape rule /""/, Str::Escape rule /"/, Name::Variable, :pop! rule /[^\\"]+/, Name::Variable 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/lexers/io.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/io.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class IO < RegexLexer tag 'io' title "Io" desc 'The IO programming language (http://iolanguage.com)' mimetypes 'text/x-iosrc' filenames '*.io' def self.detect?(text) return true if text.shebang? 'io' end def self.constants @constants ||= Set.new %w(nil false true) end def self.builtins @builtins ||= Set.new %w( args call clone do doFile doString else elseif for if list method return super then ) end state :root do rule /\s+/m, Text rule %r(//.*?\n), Comment::Single rule %r(#.*?\n), Comment::Single rule %r(/(\\\n)?[*].*?[*](\\\n)?/)m, Comment::Multiline rule %r(/[+]), Comment::Multiline, :nested_comment rule /"(\\\\|\\"|[^"])*"/, Str rule %r(:?:=), Keyword rule /[()]/, Punctuation rule %r([-=;,*+><!/|^.%&\[\]{}]), Operator rule /[A-Z]\w*/, Name::Class rule /[a-z_]\w*/ do |m| name = m[0] if self.class.constants.include? name token Keyword::Constant elsif self.class.builtins.include? name token Name::Builtin else token Name end end rule %r((\d+[.]?\d*|\d*[.]\d+)(e[+-]?[0-9]+)?)i, Num::Float rule /\d+/, Num::Integer rule /@@?/, Keyword end state :nested_comment do rule %r([^/+]+)m, Comment::Multiline rule %r(/[+]), Comment::Multiline, :nested_comment rule %r([+]/), Comment::Multiline, :pop! 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/lexers/mosel.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/mosel.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Mosel < RegexLexer tag 'mosel' filenames '*.mos' title "Mosel" desc "An optimization language used by Fico's Xpress." # http://www.fico.com/en/products/fico-xpress-optimization-suite filenames '*.mos' mimetypes 'text/x-mosel' def self.detect?(text) return true if text =~ /^\s*(model|package)\s+/ end id = /[a-zA-Z_][a-zA-Z0-9_]*/ ############################################################################################################################ # General language lements ############################################################################################################################ core_keywords = %w( and array as boolean break case count counter declarations div do dynamic elif else end evaluation exit false forall forward from function if imports in include initialisations initializations integer inter is_binary is_continuous is_free is_integer is_partint is_semcont is_semint is_sos1 is_sos2 linctr list max min mod model mpvar next not of options or package parameters procedure public prod range real record repeat requirements set string sum then to true union until uses version while with ) core_functions = %w( abs arctan assert bitflip bitneg bitset bitshift bittest bitval ceil cos create currentdate currenttime cuthead cuttail delcell exists exit exp exportprob fclose fflush finalize findfirst findlast floor fopen fselect fskipline getact getcoeff getcoeffs getdual getfid getfirst gethead getfname getlast getobjval getparam getrcost getreadcnt getreverse getsize getslack getsol gettail gettype getvars iseof ishidden isodd ln log makesos1 makesos2 maxlist minlist publish random read readln reset reverse round setcoeff sethidden setioerr setname setparam setrandseed settype sin splithead splittail sqrt strfmt substr timestamp unpublish write writeln ) ############################################################################################################################ # mmxprs module elements ############################################################################################################################ mmxprs_functions = %w( addmipsol basisstability calcsolinfo clearmipdir clearmodcut command copysoltoinit defdelayedrows defsecurevecs estimatemarginals fixglobal getbstat getdualray getiis getiissense getiistype getinfcause getinfeas getlb getloadedlinctrs getloadedmpvars getname getprimalray getprobstat getrange getsensrng getsize getsol getub getvars implies indicator isiisvalid isintegral loadbasis loadmipsol loadprob maximize minimize postsolve readbasis readdirs readsol refinemipsol rejectintsol repairinfeas resetbasis resetiis resetsol savebasis savemipsol savesol savestate selectsol setbstat setcallback setcbcutoff setgndata setlb setmipdir setmodcut setsol setub setucbdata stopoptimize unloadprob writebasis writedirs writeprob writesol xor ) mmxpres_constants = %w(XPRS_OPT XPRS_UNF XPRS_INF XPRS_UNB XPRS_OTH) mmxprs_parameters = %w(XPRS_colorder XPRS_enumduplpol XPRS_enummaxsol XPRS_enumsols XPRS_fullversion XPRS_loadnames XPRS_problem XPRS_probname XPRS_verbose) ############################################################################################################################ # mmsystem module elements ############################################################################################################################ mmsystem_functions = %w( addmonths copytext cuttext deltext endswith expandpath fcopy fdelete findfiles findtext fmove getasnumber getchar getcwd getdate getday getdaynum getdays getdirsep getendparse setendparse getenv getfsize getfstat getftime gethour getminute getmonth getmsec getpathsep getqtype setqtype getsecond getsepchar setsepchar getsize getstart setstart getsucc setsucc getsysinfo getsysstat gettime gettmpdir gettrim settrim getweekday getyear inserttext isvalid makedir makepath newtar newzip nextfield openpipe parseextn parseint parsereal parsetext pastetext pathmatch pathsplit qsort quote readtextline regmatch regreplace removedir removefiles setchar setdate setday setenv sethour setminute setmonth setmsec setsecond settime setyear sleep startswith system tarlist textfmt tolower toupper trim untar unzip ziplist ) mmsystem_parameters = %w(datefmt datetimefmt monthnames sys_endparse sys_fillchar sys_pid sys_qtype sys_regcache sys_sepchar) ############################################################################################################################ # mmjobs module elements ############################################################################################################################ mmjobs_instance_mgmt_functions = %w( clearaliases connect disconnect findxsrvs getaliases getbanner gethostalias sethostalias ) mmjobs_model_mgmt_functions = %w( compile detach getannidents getannotations getexitcode getgid getid getnode getrmtid getstatus getuid load reset resetmodpar run setcontrol setdefstream setmodpar setworkdir stop unload ) mmjobs_synchornization_functions = %w( dropnextevent getclass getfromgid getfromid getfromuid getnextevent getvalue isqueueempty nullevent peeknextevent send setgid setuid wait waitfor ) mmjobs_functions = mmjobs_instance_mgmt_functions + mmjobs_model_mgmt_functions + mmjobs_synchornization_functions mmjobs_parameters = %w(conntmpl defaultnode fsrvdelay fsrvnbiter fsrvport jobid keepalive nodenumber parentnumber) state :whitespace do # Spaces rule /\s+/m, Text # ! Comments rule %r((!).*$\n?), Comment::Single # (! Comments !) rule %r(\(!.*?!\))m, Comment::Multiline end # From Mosel documentation: # Constant strings of characters must be quoted with single (') or double quote (") and may extend over several lines. Strings enclosed in double quotes may contain C-like escape sequences introduced by the 'backslash' # character (\a \b \f \n \r \t \v \xxx with xxx being the character code as an octal number). # Each sequence is replaced by the corresponding control character (e.g. \n is the `new line' command) or, if no control character exists, by the second character of the sequence itself (e.g. \\ is replaced by '\'). # The escape sequences are not interpreted if they are contained in strings that are enclosed in single quotes. state :single_quotes do rule /'/, Str::Single, :pop! rule /[^']+/, Str::Single end state :double_quotes do rule /"/, Str::Double, :pop! rule /(\\"|\\[0-7]{1,3}\D|\\[abfnrtv]|\\\\)/, Str::Escape rule /[^"]/, Str::Double end state :base do rule %r{"}, Str::Double, :double_quotes rule %r{'}, Str::Single, :single_quotes rule %r{((0(x|X)[0-9a-fA-F]*)|(([0-9]+\.?[0-9]*)|(\.[0-9]+))((e|E)(\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?}, Num rule %r{[~!@#\$%\^&\*\(\)\+`\-={}\[\]:;<>\?,\.\/\|\\]}, Punctuation # rule %r{'([^']|'')*'}, Str # rule /"(\\\\|\\"|[^"])*"/, Str rule /(true|false)\b/i, Name::Builtin rule /\b(#{core_keywords.join('|')})\b/i, Keyword rule /\b(#{core_functions.join('|')})\b/, Name::Builtin rule /\b(#{mmxprs_functions.join('|')})\b/, Name::Function rule /\b(#{mmxpres_constants.join('|')})\b/, Name::Constant rule /\b(#{mmxprs_parameters.join('|')})\b/i, Name::Property rule /\b(#{mmsystem_functions.join('|')})\b/i, Name::Function rule /\b(#{mmsystem_parameters.join('|')})\b/, Name::Property rule /\b(#{mmjobs_functions.join('|')})\b/i, Name::Function rule /\b(#{mmjobs_parameters.join('|')})\b/, Name::Property rule id, Name end state :root do mixin :whitespace mixin :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/rouge-3.3.0/lib/rouge/lexers/common_lisp.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/common_lisp.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class CommonLisp < RegexLexer title "Common Lisp" desc "The Common Lisp variant of Lisp (common-lisp.net)" tag 'common_lisp' aliases 'cl', 'common-lisp', 'elisp', 'emacs-lisp' filenames '*.cl', '*.lisp', '*.asd', '*.el' # used for Elisp too mimetypes 'text/x-common-lisp' # 638 functions BUILTIN_FUNCTIONS = Set.new %w( < <= = > >= - / /= * + 1- 1+ abort abs acons acos acosh add-method adjoin adjustable-array-p adjust-array allocate-instance alpha-char-p alphanumericp append apply apropos apropos-list aref arithmetic-error-operands arithmetic-error-operation array-dimension array-dimensions array-displacement array-element-type array-has-fill-pointer-p array-in-bounds-p arrayp array-rank array-row-major-index array-total-size ash asin asinh assoc assoc-if assoc-if-not atan atanh atom bit bit-and bit-andc1 bit-andc2 bit-eqv bit-ior bit-nand bit-nor bit-not bit-orc1 bit-orc2 bit-vector-p bit-xor boole both-case-p boundp break broadcast-stream-streams butlast byte byte-position byte-size caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar caddar cadddr caddr cadr call-next-method car cdaaar cdaadr cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr cdr ceiling cell-error-name cerror change-class char char< char<= char= char> char>= char/= character characterp char-code char-downcase char-equal char-greaterp char-int char-lessp char-name char-not-equal char-not-greaterp char-not-lessp char-upcase cis class-name class-of clear-input clear-output close clrhash code-char coerce compile compiled-function-p compile-file compile-file-pathname compiler-macro-function complement complex complexp compute-applicable-methods compute-restarts concatenate concatenated-stream-streams conjugate cons consp constantly constantp continue copy-alist copy-list copy-pprint-dispatch copy-readtable copy-seq copy-structure copy-symbol copy-tree cos cosh count count-if count-if-not decode-float decode-universal-time delete delete-duplicates delete-file delete-if delete-if-not delete-package denominator deposit-field describe describe-object digit-char digit-char-p directory directory-namestring disassemble documentation dpb dribble echo-stream-input-stream echo-stream-output-stream ed eighth elt encode-universal-time endp enough-namestring ensure-directories-exist ensure-generic-function eq eql equal equalp error eval evenp every exp export expt fboundp fceiling fdefinition ffloor fifth file-author file-error-pathname file-length file-namestring file-position file-string-length file-write-date fill fill-pointer find find-all-symbols find-class find-if find-if-not find-method find-package find-restart find-symbol finish-output first float float-digits floatp float-precision float-radix float-sign floor fmakunbound force-output format fourth fresh-line fround ftruncate funcall function-keywords function-lambda-expression functionp gcd gensym gentemp get get-decoded-time get-dispatch-macro-character getf gethash get-internal-real-time get-internal-run-time get-macro-character get-output-stream-string get-properties get-setf-expansion get-universal-time graphic-char-p hash-table-count hash-table-p hash-table-rehash-size hash-table-rehash-threshold hash-table-size hash-table-test host-namestring identity imagpart import initialize-instance input-stream-p inspect integer-decode-float integer-length integerp interactive-stream-p intern intersection invalid-method-error invoke-debugger invoke-restart invoke-restart-interactively isqrt keywordp last lcm ldb ldb-test ldiff length lisp-implementation-type lisp-implementation-version list list* list-all-packages listen list-length listp load load-logical-pathname-translations log logand logandc1 logandc2 logbitp logcount logeqv logical-pathname logical-pathname-translations logior lognand lognor lognot logorc1 logorc2 logtest logxor long-site-name lower-case-p machine-instance machine-type machine-version macroexpand macroexpand-1 macro-function make-array make-broadcast-stream make-concatenated-stream make-condition make-dispatch-macro-character make-echo-stream make-hash-table make-instance make-instances-obsolete make-list make-load-form make-load-form-saving-slots make-package make-pathname make-random-state make-sequence make-string make-string-input-stream make-string-output-stream make-symbol make-synonym-stream make-two-way-stream makunbound map mapc mapcan mapcar mapcon maphash map-into mapl maplist mask-field max member member-if member-if-not merge merge-pathnames method-combination-error method-qualifiers min minusp mismatch mod muffle-warning name-char namestring nbutlast nconc next-method-p nintersection ninth no-applicable-method no-next-method not notany notevery nreconc nreverse nset-difference nset-exclusive-or nstring-capitalize nstring-downcase nstring-upcase nsublis nsubst nsubst-if nsubst-if-not nsubstitute nsubstitute-if nsubstitute-if-not nth nthcdr null numberp numerator nunion oddp open open-stream-p output-stream-p package-error-package package-name package-nicknames packagep package-shadowing-symbols package-used-by-list package-use-list pairlis parse-integer parse-namestring pathname pathname-device pathname-directory pathname-host pathname-match-p pathname-name pathnamep pathname-type pathname-version peek-char phase plusp position position-if position-if-not pprint pprint-dispatch pprint-fill pprint-indent pprint-linear pprint-newline pprint-tab pprint-tabular prin1 prin1-to-string princ princ-to-string print print-object probe-file proclaim provide random random-state-p rassoc rassoc-if rassoc-if-not rational rationalize rationalp read read-byte read-char read-char-no-hang read-delimited-list read-from-string read-line read-preserving-whitespace read-sequence readtable-case readtablep realp realpart reduce reinitialize-instance rem remhash remove remove-duplicates remove-if remove-if-not remove-method remprop rename-file rename-package replace require rest restart-name revappend reverse room round row-major-aref rplaca rplacd sbit scale-float schar search second set set-difference set-dispatch-macro-character set-exclusive-or set-macro-character set-pprint-dispatch set-syntax-from-char seventh shadow shadowing-import shared-initialize short-site-name signal signum simple-bit-vector-p simple-condition-format-arguments simple-condition-format-control simple-string-p simple-vector-p sin sinh sixth sleep slot-boundp slot-exists-p slot-makunbound slot-missing slot-unbound slot-value software-type software-version some sort special-operator-p sqrt stable-sort standard-char-p store-value stream-element-type stream-error-stream stream-external-format streamp string string< string<= string= string> string>= string/= string-capitalize string-downcase string-equal string-greaterp string-left-trim string-lessp string-not-equal string-not-greaterp string-not-lessp stringp string-right-trim string-trim string-upcase sublis subseq subsetp subst subst-if subst-if-not substitute substitute-if substitute-if-not subtypepsvref sxhash symbol-function symbol-name symbolp symbol-package symbol-plist symbol-value synonym-stream-symbol syntax: tailp tan tanh tenth terpri third translate-logical-pathname translate-pathname tree-equal truename truncate two-way-stream-input-stream two-way-stream-output-stream type-error-datum type-error-expected-type type-of typep unbound-slot-instance unexport unintern union unread-char unuse-package update-instance-for-different-class update-instance-for-redefined-class upgraded-array-element-type upgraded-complex-part-type upper-case-p use-package user-homedir-pathname use-value values values-list vector vectorp vector-pop vector-push vector-push-extend warn wild-pathname-p write write-byte write-char write-line write-sequence write-string write-to-string yes-or-no-p y-or-n-p zerop ).freeze SPECIAL_FORMS = Set.new %w( block catch declare eval-when flet function go if labels lambda let let* load-time-value locally macrolet multiple-value-call multiple-value-prog1 progn progv quote return-from setq symbol-macrolet tagbody the throw unwind-protect ) MACROS = Set.new %w( and assert call-method case ccase check-type cond ctypecase decf declaim defclass defconstant defgeneric define-compiler-macro define-condition define-method-combination define-modify-macro define-setf-expander define-symbol-macro defmacro defmethod defpackage defparameter defsetf defstruct defsystem deftype defun defvar destructuring-bind do do* do-all-symbols do-external-symbols dolist do-symbols dotimes ecase etypecase formatter handler-bind handler-case ignore-errors incf in-package lambda loop loop-finish make-method multiple-value-bind multiple-value-list multiple-value-setq nth-value or pop pprint-exit-if-list-exhausted pprint-logical-block pprint-pop print-unreadable-object prog prog* prog1 prog2 psetf psetq push pushnew remf restart-bind restart-case return rotatef setf shiftf step time trace typecase unless untrace when with-accessors with-compilation-unit with-condition-restarts with-hash-table-iterator with-input-from-string with-open-file with-open-stream with-output-to-string with-package-iterator with-simple-restart with-slots with-standard-io-syntax ) LAMBDA_LIST_KEYWORDS = Set.new %w( &allow-other-keys &aux &body &environment &key &optional &rest &whole ) DECLARATIONS = Set.new %w( dynamic-extent ignore optimize ftype inline special ignorable notinline type ) BUILTIN_TYPES = Set.new %w( atom boolean base-char base-string bignum bit compiled-function extended-char fixnum keyword nil signed-byte short-float single-float double-float long-float simple-array simple-base-string simple-bit-vector simple-string simple-vector standard-char unsigned-byte arithmetic-error cell-error condition control-error division-by-zero end-of-file error file-error floating-point-inexact floating-point-overflow floating-point-underflow floating-point-invalid-operation parse-error package-error print-not-readable program-error reader-error serious-condition simple-condition simple-error simple-type-error simple-warning stream-error storage-condition style-warning type-error unbound-variable unbound-slot undefined-function warning ) BUILTIN_CLASSES = Set.new %w( array broadcast-stream bit-vector built-in-class character class complex concatenated-stream cons echo-stream file-stream float function generic-function hash-table integer list logical-pathname method-combination method null number package pathname ratio rational readtable real random-state restart sequence standard-class standard-generic-function standard-method standard-object string-stream stream string structure-class structure-object symbol synonym-stream t two-way-stream vector ) nonmacro = /\\.|[a-zA-Z0-9!$%&*+-\/<=>?@\[\]^_{}~]/ constituent = /#{nonmacro}|[#.:]/ terminated = /(?=[ "'()\n,;`])/ # whitespace or terminating macro chars symbol = /(\|[^\|]+\||#{nonmacro}#{constituent}*)/ state :root do rule /\s+/m, Text rule /;.*$/, Comment::Single rule /#\|/, Comment::Multiline, :multiline_comment # encoding comment rule /#\d*Y.*$/, Comment::Special rule /"(\\.|[^"\\])*"/, Str rule /[:']#{symbol}/, Str::Symbol rule /['`]/, Operator # numbers rule /[-+]?\d+\.?#{terminated}/, Num::Integer rule %r([-+]?\d+/\d+#{terminated}), Num::Integer rule %r( [-+]? (\d*\.\d+([defls][-+]?\d+)? |\d+(\.\d*)?[defls][-+]?\d+) #{terminated} )x, Num::Float # sharpsign strings and characters rule /#\\.#{terminated}/, Str::Char rule /#\\#{symbol}/, Str::Char rule /#\(/, Operator, :root # bitstring rule /#\d*\*[01]*/, Other # uninterned symbol rule /#:#{symbol}/, Str::Symbol # read-time and load-time evaluation rule /#[.,]/, Operator # function shorthand rule /#'/, Name::Function # binary rational rule /#b[+-]?[01]+(\/[01]+)?/i, Num # octal rational rule /#o[+-]?[0-7]+(\/[0-7]+)?/i, Num::Oct # hex rational rule /#x[+-]?[0-9a-f]+(\/[0-9a-f]+)?/i, Num # complex rule /(#c)(\()/i do groups Num, Punctuation push :root end # arrays and structures rule /(#(?:\d+a|s))(\()/i do groups Str::Other, Punctuation push :root end # path rule /#p?"(\\.|[^"])*"/i, Str::Symbol # reference rule /#\d+[=#]/, Operator # read-time comment rule /#+nil#{terminated}\s*\(/, Comment, :commented_form # read-time conditional rule /#[+-]/, Operator # special operators that should have been parsed already rule /(,@|,|\.)/, Operator # special constants rule /(t|nil)#{terminated}/, Name::Constant # functions and variables # note that these get filtered through in stream_tokens rule /\*#{symbol}\*/, Name::Variable::Global rule symbol do |m| sym = m[0] if BUILTIN_FUNCTIONS.include? sym token Name::Builtin elsif SPECIAL_FORMS.include? sym token Keyword elsif MACROS.include? sym token Name::Builtin elsif LAMBDA_LIST_KEYWORDS.include? sym token Keyword elsif DECLARATIONS.include? sym token Keyword elsif BUILTIN_TYPES.include? sym token Keyword::Type elsif BUILTIN_CLASSES.include? sym token Name::Class else token Name::Variable end end rule /\(/, Punctuation, :root rule /\)/, Punctuation do if stack.empty? token Error else token Punctuation pop! end end end state :multiline_comment do rule /#\|/, Comment::Multiline, :multiline_comment rule /\|#/, Comment::Multiline, :pop! rule /[^\|#]+/, Comment::Multiline rule /[\|#]/, Comment::Multiline end state :commented_form do rule /\(/, Comment, :commented_form rule /\)/, Comment, :pop! rule /[^()]+/, Comment 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/lexers/typescript.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/typescript.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers load_lexer 'javascript.rb' load_lexer 'typescript/common.rb' class Typescript < Javascript include TypescriptCommon title "TypeScript" desc "TypeScript, a superset of JavaScript" tag 'typescript' aliases 'ts' filenames '*.ts', '*.d.ts' mimetypes 'text/typescript' 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/lexers/c.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/c.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class C < RegexLexer tag 'c' filenames '*.c', '*.h', '*.idc' mimetypes 'text/x-chdr', 'text/x-csrc' title "C" desc "The C programming language" # optional comment or whitespace ws = %r((?:\s|//.*?\n|/[*].*?[*]/)+) id = /[a-zA-Z_][a-zA-Z0-9_]*/ def self.keywords @keywords ||= Set.new %w( auto break case const continue default do else enum extern for goto if register restricted return sizeof static struct switch typedef union volatile virtual while _Alignas _Alignof _Atomic _Generic _Imaginary _Noreturn _Static_assert _Thread_local ) end def self.keywords_type @keywords_type ||= Set.new %w( int long float short double char unsigned signed void jmp_buf FILE DIR div_t ldiv_t mbstate_t sig_atomic_t fpos_t clock_t time_t va_list size_t ssize_t off_t wchar_t ptrdiff_t wctrans_t wint_t wctype_t _Bool _Complex int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t int_least8_t int_least16_t int_least32_t int_least64_t uint_least8_t uint_least16_t uint_least32_t uint_least64_t int_fast8_t int_fast16_t int_fast32_t int_fast64_t uint_fast8_t uint_fast16_t uint_fast32_t uint_fast64_t intptr_t uintptr_t intmax_t uintmax_t char16_t char32_t ) end def self.reserved @reserved ||= Set.new %w( __asm __int8 __based __except __int16 __stdcall __cdecl __fastcall __int32 __declspec __finally __int61 __try __leave inline _inline __inline naked _naked __naked restrict _restrict __restrict thread _thread __thread typename _typename __typename ) end def self.builtins @builtins ||= [] end start { push :bol } state :expr_bol do mixin :inline_whitespace rule /#if\s0/, Comment, :if_0 rule /#/, Comment::Preproc, :macro rule(//) { pop! } end # :expr_bol is the same as :bol but without labels, since # labels can only appear at the beginning of a statement. state :bol do rule /#{id}:(?!:)/, Name::Label mixin :expr_bol end state :inline_whitespace do rule /[ \t\r]+/, Text rule /\\\n/, Text # line continuation rule %r(/(\\\n)?[*].*?[*](\\\n)?/)m, Comment::Multiline end state :whitespace do rule /\n+/m, Text, :bol rule %r(//(\\.|.)*?$), Comment::Single, :bol mixin :inline_whitespace end state :expr_whitespace do rule /\n+/m, Text, :expr_bol mixin :whitespace end state :statements do mixin :whitespace rule /(u8|u|U|L)?"/, Str, :string rule %r((u8|u|U|L)?'(\\.|\\[0-7]{1,3}|\\x[a-f0-9]{1,2}|[^\\'\n])')i, Str::Char rule %r((\d+[.]\d*|[.]?\d+)e[+-]?\d+[lu]*)i, Num::Float rule %r(\d+e[+-]?\d+[lu]*)i, Num::Float rule /0x[0-9a-f]+[lu]*/i, Num::Hex rule /0[0-7]+[lu]*/i, Num::Oct rule /\d+[lu]*/i, Num::Integer rule %r(\*/), Error rule %r([~!%^&*+=\|?:<>/-]), Operator rule /[()\[\],.]/, Punctuation rule /\bcase\b/, Keyword, :case rule /(?:true|false|NULL)\b/, Name::Builtin rule id do |m| name = m[0] if self.class.keywords.include? name token Keyword elsif self.class.keywords_type.include? name token Keyword::Type elsif self.class.reserved.include? name token Keyword::Reserved elsif self.class.builtins.include? name token Name::Builtin else token Name end end end state :case do rule /:/, Punctuation, :pop! mixin :statements end state :root do mixin :expr_whitespace # functions rule %r( ([\w*\s]+?[\s*]) # return arguments (#{id}) # function name (\s*\([^;]*?\)) # signature (#{ws})({) # open brace )mx do |m| # TODO: do this better. recurse m[1] token Name::Function, m[2] recurse m[3] recurse m[4] token Punctuation, m[5] push :function end # function declarations rule %r( ([\w*\s]+?[\s*]) # return arguments (#{id}) # function name (\s*\([^;]*?\)) # signature (#{ws})(;) # semicolon )mx do |m| # TODO: do this better. recurse m[1] token Name::Function, m[2] recurse m[3] recurse m[4] token Punctuation, m[5] push :statement end rule(//) { push :statement } end state :statement do rule /;/, Punctuation, :pop! mixin :expr_whitespace mixin :statements rule /[{}]/, Punctuation end state :function do mixin :whitespace mixin :statements rule /;/, Punctuation rule /{/, Punctuation, :function rule /}/, Punctuation, :pop! end state :string do rule /"/, Str, :pop! rule /\\([\\abfnrtv"']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})/, Str::Escape rule /[^\\"\n]+/, Str rule /\\\n/, Str rule /\\/, Str # stray backslash end state :macro do # NB: pop! goes back to :bol rule /\n/, Comment::Preproc, :pop! rule %r([^/\n\\]+), Comment::Preproc rule /\\./m, Comment::Preproc mixin :inline_whitespace rule %r(/), Comment::Preproc end state :if_0 do # NB: no \b here, to cover #ifdef and #ifndef rule /^\s*#if/, Comment, :if_0 rule /^\s*#\s*el(?:se|if)/, Comment, :pop! rule /^\s*#\s*endif\b.*?(?<!\\)\n/m, Comment, :pop! rule /.*?\n/, Comment 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/lexers/awk.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/awk.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Awk < RegexLexer title "Awk" desc "pattern-directed scanning and processing language" tag 'awk' filenames '*.awk' mimetypes 'application/x-awk' def self.detect?(text) return true if text.shebang?('awk') end id = /[$a-zA-Z_][a-zA-Z0-9_]*/ def self.keywords @keywords ||= Set.new %w( if else while for do break continue return next nextfile delete exit print printf getline ) end def self.declarations @declarations ||= Set.new %w(function) end def self.reserved @reserved ||= Set.new %w(BEGIN END) end def self.constants @constants ||= Set.new %w( CONVFMT FS NF NR FNR FILENAME RS OFS ORS OFMT SUBSEP ARGC ARGV ENVIRON ) end def self.builtins @builtins ||= %w( exp log sqrt sin cos atan2 length rand srand int substr index match split sub gsub sprintf system tolower toupper ) end state :comments_and_whitespace do rule /\s+/, Text rule %r(#.*?$), Comment::Single end state :expr_start do mixin :comments_and_whitespace rule %r(/) do token Str::Regex goto :regex end rule //, Text, :pop! end state :regex do rule %r(/) do token Str::Regex goto :regex_end end rule %r([^/]\n), Error, :pop! rule /\n/, Error, :pop! rule /\[\^/, Str::Escape, :regex_group rule /\[/, Str::Escape, :regex_group rule /\\./, Str::Escape rule %r{[(][?][:=<!]}, Str::Escape rule /[{][\d,]+[}]/, Str::Escape rule /[()?]/, Str::Escape rule /./, Str::Regex end state :regex_end do rule(//) { pop! } end state :regex_group do # specially highlight / in a group to indicate that it doesn't # close the regex rule /\//, Str::Escape rule %r([^/]\n) do token Error pop! 2 end rule /\]/, Str::Escape, :pop! rule /\\./, Str::Escape rule /./, Str::Regex end state :bad_regex do rule /[^\n]+/, Error, :pop! end state :root do mixin :comments_and_whitespace rule %r((?<=\n)(?=\s|/)), Text, :expr_start rule %r([-<>+*/%\^!=]=?|in\b|\+\+|--|\|), Operator, :expr_start rule %r(&&|\|\||~!?), Operator, :expr_start rule /[(\[,]/, Punctuation, :expr_start rule /;/, Punctuation, :statement rule /[)\].]/, Punctuation rule /[?]/ do token Punctuation push :ternary push :expr_start end rule /[{}]/, Punctuation, :statement rule id do |m| if self.class.keywords.include? m[0] token Keyword push :expr_start elsif self.class.declarations.include? m[0] token Keyword::Declaration push :expr_start elsif self.class.reserved.include? m[0] token Keyword::Reserved elsif self.class.constants.include? m[0] token Keyword::Constant elsif self.class.builtins.include? m[0] token Name::Builtin elsif m[0] =~ /^\$/ token Name::Variable else token Name::Other end end rule /[0-9]+\.[0-9]+/, Num::Float rule /[0-9]+/, Num::Integer rule /"(\\[\\"]|[^"])*"/, Str::Double rule /:/, Punctuation end state :statement do rule /[{}]/, Punctuation mixin :expr_start end state :ternary do rule /:/ do token Punctuation goto :expr_start end mixin :root end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/moonscript.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/moonscript.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers load_lexer 'lua.rb' class Moonscript < RegexLexer title "MoonScript" desc "Moonscript (http://www.moonscript.org)" tag 'moonscript' aliases 'moon' filenames '*.moon' mimetypes 'text/x-moonscript', 'application/x-moonscript' option :function_highlighting, 'Whether to highlight builtin functions (default: true)' option :disabled_modules, 'builtin modules to disable' def initialize(*) super @function_highlighting = bool_option(:function_highlighting) { true } @disabled_modules = list_option(:disabled_modules) end def self.detect?(text) return true if text.shebang? 'moon' end def builtins return [] unless @function_highlighting @builtins ||= Set.new.tap do |builtins| Rouge::Lexers::Lua.builtins.each do |mod, fns| next if @disabled_modules.include? mod builtins.merge(fns) end end end state :root do rule %r(#!(.*?)$), Comment::Preproc # shebang rule //, Text, :main end state :base do ident = '(?:[\w_][\w\d_]*)' rule %r((?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?'), Num::Float rule %r((?i)\d+e[+-]?\d+), Num::Float rule %r((?i)0x[0-9a-f]*), Num::Hex rule %r(\d+), Num::Integer rule %r(@#{ident}*), Name::Variable::Instance rule %r([A-Z][\w\d_]*), Name::Class rule %r("?[^"]+":), Literal::String::Symbol rule %r(#{ident}:), Literal::String::Symbol rule %r(:#{ident}), Literal::String::Symbol rule %r(\s+), Text::Whitespace rule %r((==|~=|!=|<=|>=|\.\.\.|\.\.|->|=>|[=+\-*/%^<>#!\\])), Operator rule %r([\[\]\{\}\(\)\.,:;]), Punctuation rule %r((and|or|not)\b), Operator::Word keywords = %w{ break class continue do else elseif end extends for if import in repeat return switch super then unless until using when with while } rule %r((#{keywords.join('|')})\b), Keyword rule %r((local|export)\b), Keyword::Declaration rule %r((true|false|nil)\b), Keyword::Constant rule %r([A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?) do |m| name = m[0] if self.builtins.include?(name) token Name::Builtin elsif name =~ /\./ a, b = name.split('.', 2) token Name, a token Punctuation, '.' token Name, b else token Name end end end state :main do rule %r(--.*$), Comment::Single rule %r(\[(=*)\[.*?\]\1\])m, Str::Heredoc mixin :base rule %r('), Str::Single, :sqs rule %r("), Str::Double, :dqs end state :sqs do rule %r('), Str::Single, :pop! rule %r([^']+), Str::Single end state :interpolation do rule %r(\}), Str::Interpol, :pop! mixin :base end state :dqs do rule %r(#\{), Str::Interpol, :interpolation rule %r("), Str::Double, :pop! rule %r(#[^{]), Str::Double rule %r([^"#]+), Str::Double 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/lexers/jinja.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/jinja.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Jinja < TemplateLexer title "Jinja" desc "Django/Jinja template engine (jinja.pocoo.org)" tag 'jinja' aliases 'django' mimetypes 'application/x-django-templating', 'application/x-jinja', 'text/html+django', 'text/html+jinja' def self.keywords @@keywords ||= %w(as context do else extends from ignore missing import include reversed recursive scoped autoescape endautoescape block endblock call endcall filter endfilter for endfor if endif macro endmacro set endset trans endtrans with endwith without) end def self.tests @@tests ||= %w(callable defined divisibleby equalto escaped even iterable lower mapping none number odd sameas sequence string undefined upper) end def self.pseudo_keywords @@pseudo_keywords ||= %w(true false none True False None) end def self.word_operators @@word_operators ||= %w(is in and or not) end state :root do # Comments rule /{#/, Comment, :comment # Statements rule /\{\%/ do token Comment::Preproc push :statement end # Expressions rule /\{\{/ do token Comment::Preproc push :expression end rule(/(.+?)(?=\\|{{|{%|{#)/m) { delegate parent } rule(/.+/m) { delegate parent } end state :filter do # Filters are called like variable|foo(arg1, ...) rule /(\|)(\w+)/ do groups Operator, Name::Function end end state :function do rule /(\w+)(\()/ do groups Name::Function, Punctuation end end state :text do rule /\s+/m, Text end state :literal do # Strings rule /"(\\.|.)*?"/, Str::Double rule /'(\\.|.)*?'/, Str::Single # Numbers rule /\d+(?=}\s)/, Num # Arithmetic operators (+, -, *, **, //, /) # TODO : implement modulo (%) rule /(\+|\-|\*|\/\/?|\*\*?)/, Operator # Comparisons operators (<=, <, >=, >, ==, ===, !=) rule /(<=?|>=?|===?|!=)/, Operator # Punctuation (the comma, [], ()) rule /,/, Punctuation rule /\[/, Punctuation rule /\]/, Punctuation rule /\(/, Punctuation rule /\)/, Punctuation end state :comment do rule(/[^{#]+/m) { token Comment } rule(/#}/) { token Comment; pop! } end state :expression do rule /\w+\.?/m, Name::Variable mixin :filter mixin :function mixin :literal mixin :text rule /%}|}}/, Comment::Preproc, :pop! end state :statement do rule /(\w+\.?)/ do |m| if self.class.keywords.include?(m[0]) groups Keyword elsif self.class.pseudo_keywords.include?(m[0]) groups Keyword::Pseudo elsif self.class.word_operators.include?(m[0]) groups Operator::Word elsif self.class.tests.include?(m[0]) groups Name::Builtin else groups Name::Variable end end mixin :filter mixin :function mixin :literal mixin :text rule /\%\}/, Comment::Preproc, :pop! 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/lexers/gherkin.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/gherkin.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Gherkin < RegexLexer tag 'gherkin' aliases 'cucumber', 'behat' title "Gherkin" desc 'A business-readable spec DSL ( github.com/cucumber/cucumber/wiki/Gherkin )' filenames '*.feature' mimetypes 'text/x-gherkin' def self.detect?(text) return true if text.shebang? 'cucumber' end # self-modifying method that loads the keywords file def self.keywords load Pathname.new(__FILE__).dirname.join('gherkin/keywords.rb') keywords end def self.step_regex # in Gherkin's config, keywords that end in < don't # need word boundaries at the ends - all others do. @step_regex ||= Regexp.new( keywords[:step].map do |w| if w.end_with? '<' Regexp.escape(w.chop) else "#{Regexp.escape(w)}\\b" end end.join('|') ) end rest_of_line = /.*?(?=[#\n])/ state :basic do rule %r(#.*$), Comment rule /[ \r\t]+/, Text end state :root do mixin :basic rule %r(\n), Text rule %r(""".*?""")m, Str rule %r(@[^\s@]+), Name::Tag mixin :has_table mixin :has_examples end state :has_scenarios do rule %r((.*?)(:)) do |m| reset_stack keyword = m[1] keyword_tok = if self.class.keywords[:element].include? keyword push :description; Keyword::Namespace elsif self.class.keywords[:feature].include? keyword push :feature_description; Keyword::Declaration elsif self.class.keywords[:examples].include? keyword push :example_description; Name::Namespace else Error end groups keyword_tok, Punctuation end end state :has_examples do mixin :has_scenarios rule Gherkin.step_regex, Name::Function do token Name::Function reset_stack; push :step end end state :has_table do rule(/(?=[|])/) { push :table_header } end state :table_header do rule /[^|\s]+/, Name::Variable rule /\n/ do token Text goto :table end mixin :table end state :table do mixin :basic rule /\n/, Text, :table_bol rule /[|]/, Punctuation rule /[^|\s]+/, Name end state :table_bol do rule(/(?=\s*[^\s|])/) { reset_stack } rule(//) { pop! } end state :description do mixin :basic mixin :has_examples rule /\n/, Text rule rest_of_line, Text end state :feature_description do mixin :basic mixin :has_scenarios rule /\n/, Text rule rest_of_line, Text end state :example_description do mixin :basic mixin :has_table rule /\n/, Text rule rest_of_line, Text end state :step do mixin :basic rule /<.*?>/, Name::Variable rule /".*?"/, Str rule /\S+/, Text rule rest_of_line, Text, :pop! 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/lexers/nix.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/nix.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Nix < RegexLexer title 'Nix' desc 'The Nix expression language (https://nixos.org/nix/manual/#ch-expression-language)' tag 'nix' aliases 'nixos' filenames '*.nix' state :whitespaces do rule /^\s*\n\s*$/m, Text rule /\s+/, Text end state :comment do rule /#.*$/, Comment rule /\/\*/, Comment, :multiline_comment end state :multiline_comment do rule /\*\//, Comment, :pop! rule /./, Comment end state :number do rule /[0-9]/, Num::Integer end state :null do rule /(null)/, Keyword::Constant end state :boolean do rule /(true|false)/, Keyword::Constant end state :binding do rule /[a-zA-Z_][a-zA-Z0-9-]*/, Name::Variable end state :path do word = "[a-zA-Z0-9\._-]+" section = "(\/#{word})" prefix = "[a-z\+]+:\/\/" root = /#{section}+/.source tilde = /~#{section}+/.source basic = /#{word}(\/#{word})+/.source url = /#{prefix}(\/?#{basic})/.source rule /(#{root}|#{tilde}|#{basic}|#{url})/, Str::Other end state :string do rule /"/, Str::Double, :double_quoted_string rule /''/, Str::Double, :indented_string end state :string_content do rule /\\./, Str::Escape rule /\$\$/, Str::Escape rule /\${/, Str::Interpol, :string_interpolated_arg end state :indented_string_content do rule /'''/, Str::Escape rule /''\$/, Str::Escape rule /\$\$/, Str::Escape rule /''\\./, Str::Escape rule /\${/, Str::Interpol, :string_interpolated_arg end state :string_interpolated_arg do mixin :expression rule /}/, Str::Interpol, :pop! end state :indented_string do mixin :indented_string_content rule /''/, Str::Double, :pop! rule /./, Str::Double end state :double_quoted_string do mixin :string_content rule /"/, Str::Double, :pop! rule /./, Str::Double end state :operator do rule /(\.|\?|\+\+|\+|!=|!|\/\/|\=\=|&&|\|\||->|\/|\*|-|<|>|<=|=>)/, Operator end state :assignment do rule /(=)/, Operator rule /(@)/, Operator end state :accessor do rule /(\$)/, Punctuation end state :delimiter do rule /(;|,|:)/, Punctuation end state :atom_content do mixin :expression rule /\)/, Punctuation, :pop! end state :atom do rule /\(/, Punctuation, :atom_content end state :list do rule /\[/, Punctuation, :list_content end state :list_content do rule /\]/, Punctuation, :pop! mixin :expression end state :set do rule /{/, Punctuation, :set_content end state :set_content do rule /}/, Punctuation, :pop! mixin :expression end state :expression do mixin :ignore mixin :comment mixin :boolean mixin :null mixin :number mixin :path mixin :string mixin :keywords mixin :operator mixin :accessor mixin :assignment mixin :delimiter mixin :binding mixin :atom mixin :set mixin :list end state :keywords do mixin :keywords_namespace mixin :keywords_declaration mixin :keywords_conditional mixin :keywords_reserved mixin :keywords_builtin end state :keywords_namespace do keywords = %w(with in inherit) rule /(?:#{keywords.join('|')})\b/, Keyword::Namespace end state :keywords_declaration do keywords = %w(let) rule /(?:#{keywords.join('|')})\b/, Keyword::Declaration end state :keywords_conditional do keywords = %w(if then else) rule /(?:#{keywords.join('|')})\b/, Keyword end state :keywords_reserved do keywords = %w(rec assert map) rule /(?:#{keywords.join('|')})\b/, Keyword::Reserved end state :keywords_builtin do keywords = %w( abort baseNameOf builtins derivation fetchTarball import isNull removeAttrs throw toString ) rule /(?:#{keywords.join('|')})\b/, Keyword::Reserved end state :ignore do mixin :whitespaces end state :root do mixin :ignore mixin :expression end start do 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/lexers/perl.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/perl.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Perl < RegexLexer title "Perl" desc "The Perl scripting language (perl.org)" tag 'perl' aliases 'pl' filenames '*.pl', '*.pm', '*.t' mimetypes 'text/x-perl', 'application/x-perl' def self.detect?(text) return true if text.shebang? 'perl' end keywords = %w( case continue do else elsif for foreach if last my next our redo reset then unless until while use print new BEGIN CHECK INIT END return ) builtins = %w( abs accept alarm atan2 bind binmode bless caller chdir chmod chomp chop chown chr chroot close closedir connect continue cos crypt dbmclose dbmopen defined delete die dump each endgrent endhostent endnetent endprotoent endpwent endservent eof eval exec exists exit exp fcntl fileno flock fork format formline getc getgrent getgrgid getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr getnetbyname getnetent getpeername getpgrp getppid getpriority getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid getservbyname getservbyport getservent getsockname getsockopt glob gmtime goto grep hex import index int ioctl join keys kill last lc lcfirst length link listen local localtime log lstat map mkdir msgctl msgget msgrcv msgsnd my next no oct open opendir ord our pack package pipe pop pos printf prototype push quotemeta rand read readdir readline readlink readpipe recv redo ref rename require reverse rewinddir rindex rmdir scalar seek seekdir select semctl semget semop send setgrent sethostent setnetent setpgrp setpriority setprotoent setpwent setservent setsockopt shift shmctl shmget shmread shmwrite shutdown sin sleep socket socketpair sort splice split sprintf sqrt srand stat study substr symlink syscall sysopen sysread sysseek system syswrite tell telldir tie tied time times tr truncate uc ucfirst umask undef unlink unpack unshift untie utime values vec wait waitpid wantarray warn write ) re_tok = Str::Regex state :balanced_regex do rule %r(/(\\[\\/]|[^/])*/[egimosx]*)m, re_tok, :pop! rule %r(!(\\[\\!]|[^!])*![egimosx]*)m, re_tok, :pop! rule %r(\\(\\\\|[^\\])*\\[egimosx]*)m, re_tok, :pop! rule %r({(\\[\\}]|[^}])*}[egimosx]*), re_tok, :pop! rule %r(<(\\[\\>]|[^>])*>[egimosx]*), re_tok, :pop! rule %r(\[(\\[\\\]]|[^\]])*\][egimosx]*), re_tok, :pop! rule %r[\((\\[\\\)]|[^\)])*\)[egimosx]*], re_tok, :pop! rule %r(@(\\[\\@]|[^@])*@[egimosx]*), re_tok, :pop! rule %r(%(\\[\\%]|[^%])*%[egimosx]*), re_tok, :pop! rule %r(\$(\\[\\\$]|[^\$])*\$[egimosx]*), re_tok, :pop! end state :root do rule /#.*?$/, Comment::Single rule /^=[a-zA-Z0-9]+\s+.*?\n=cut/m, Comment::Multiline rule /(?:#{keywords.join('|')})\b/, Keyword rule /(format)(\s+)([a-zA-Z0-9_]+)(\s*)(=)(\s*\n)/ do groups Keyword, Text, Name, Text, Punctuation, Text push :format end rule /(?:eq|lt|gt|le|ge|ne|not|and|or|cmp)\b/, Operator::Word # common delimiters rule %r(s/(\\\\|\\/|[^/])*/(\\\\|\\/|[^/])*/[msixpodualngc]*), re_tok rule %r(s!(\\\\|\\!|[^!])*!(\\\\|\\!|[^!])*![msixpodualngc]*), re_tok rule %r(s\\(\\\\|[^\\])*\\(\\\\|[^\\])*\\[msixpodualngc]*), re_tok rule %r(s@(\\\\|\\@|[^@])*@(\\\\|\\@|[^@])*@[msixpodualngc]*), re_tok rule %r(s%(\\\\|\\%|[^%])*%(\\\\|\\%|[^%])*%[msixpodualngc]*), re_tok # balanced delimiters rule %r(s{(\\\\|\\}|[^}])*}\s*), re_tok, :balanced_regex rule %r(s<(\\\\|\\>|[^>])*>\s*), re_tok, :balanced_regex rule %r(s\[(\\\\|\\\]|[^\]])*\]\s*), re_tok, :balanced_regex rule %r[s\((\\\\|\\\)|[^\)])*\)\s*], re_tok, :balanced_regex rule %r(m?/(\\\\|\\/|[^/\n])*/[msixpodualngc]*), re_tok rule %r(m(?=[/!\\{<\[\(@%\$])), re_tok, :balanced_regex # Perl allows any non-whitespace character to delimit # a regex when `m` is used. rule %r(m(\S).*\1[msixpodualngc]*), re_tok rule %r(((?<==~)|(?<=\())\s*/(\\\\|\\/|[^/])*/[msixpodualngc]*), re_tok, :balanced_regex rule /\s+/, Text rule /(?:#{builtins.join('|')})\b/, Name::Builtin rule /((__(DATA|DIE|WARN)__)|(STD(IN|OUT|ERR)))\b/, Name::Builtin::Pseudo rule /<<([\'"]?)([a-zA-Z_][a-zA-Z0-9_]*)\1;?\n.*?\n\2\n/m, Str rule /__END__\b/, Comment::Preproc, :end_part rule /\$\^[ADEFHILMOPSTWX]/, Name::Variable::Global rule /\$[\\"'\[\]&`+*.,;=%~?@$!<>(^\|\/-](?!\w)/, Name::Variable::Global rule /[-+\/*%=<>&^\|!\\~]=?/, Operator rule /[$@%#]+/, Name::Variable, :varname rule /0_?[0-7]+(_[0-7]+)*/, Num::Oct rule /0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*/, Num::Hex rule /0b[01]+(_[01]+)*/, Num::Bin rule /(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?/i, Num::Float rule /\d+(_\d*)*e[+-]?\d+(_\d*)*/i, Num::Float rule /\d+(_\d+)*/, Num::Integer rule /'(\\\\|\\'|[^'])*'/, Str rule /"(\\\\|\\"|[^"])*"/, Str rule /`(\\\\|\\`|[^`])*`/, Str::Backtick rule /<([^\s>]+)>/, re_tok rule /(q|qq|qw|qr|qx)\{/, Str::Other, :cb_string rule /(q|qq|qw|qr|qx)\(/, Str::Other, :rb_string rule /(q|qq|qw|qr|qx)\[/, Str::Other, :sb_string rule /(q|qq|qw|qr|qx)</, Str::Other, :lt_string rule /(q|qq|qw|qr|qx)([^a-zA-Z0-9])(.|\n)*?\2/, Str::Other rule /package\s+/, Keyword, :modulename rule /sub\s+/, Keyword, :funcname rule /\[\]|\*\*|::|<<|>>|>=|<=|<=>|={3}|!=|=~|!~|&&?|\|\||\.{1,3}/, Operator rule /[()\[\]:;,<>\/?{}]/, Punctuation rule(/(?=\w)/) { push :name } end state :format do rule /\.\n/, Str::Interpol, :pop! rule /.*?\n/, Str::Interpol end state :name_common do rule /\w+::/, Name::Namespace rule /[\w:]+/, Name::Variable, :pop! end state :varname do rule /\s+/, Text rule /\{/, Punctuation, :pop! # hash syntax rule /\)|,/, Punctuation, :pop! # arg specifier mixin :name_common end state :name do mixin :name_common rule /[A-Z_]+(?=[^a-zA-Z0-9_])/, Name::Constant, :pop! rule(/(?=\W)/) { pop! } end state :modulename do rule /[a-z_]\w*/i, Name::Namespace, :pop! end state :funcname do rule /[a-zA-Z_]\w*[!?]?/, Name::Function rule /\s+/, Text # argument declaration rule /(\([$@%]*\))(\s*)/ do groups Punctuation, Text end rule /.*?{/, Punctuation, :pop! rule /;/, Punctuation, :pop! end [[:cb, '\{', '\}'], [:rb, '\(', '\)'], [:sb, '\[', '\]'], [:lt, '<', '>']].each do |name, open, close| tok = Str::Other state :"#{name}_string" do rule /\\[#{open}#{close}\\]/, tok rule /\\/, tok rule(/#{open}/) { token tok; push } rule /#{close}/, tok, :pop! rule /[^#{open}#{close}\\]+/, tok end end state :end_part do # eat the rest of the stream rule /.+/m, Comment::Preproc, :pop! 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/lexers/hylang.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/hylang.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class HyLang < RegexLexer title "HyLang" desc "The HyLang programming language (hylang.org)" tag 'hylang' aliases 'hy' filenames '*.hy' mimetypes 'text/x-hy', 'application/x-hy' def self.keywords @keywords ||= Set.new %w( False None True and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try ) end def self.builtins @builtins ||= Set.new %w( != % %= & &= * ** **= *= *map + += , - -= -> ->> . / // //= /= < << <<= <= = > >= >> >>= @ @= ^ ^= accumulate apply as-> assoc butlast calling-module-name car cdr chain coll? combinations comp complement compress cond cons cons? constantly count cut cycle dec defclass defmacro defmacro! defmacro/g! defmain defn defreader dict-comp disassemble dispatch-reader-macro distinct do doto drop drop-last drop-while empty? eval eval-and-compile eval-when-compile even? every? filter first flatten float? fn for* fraction genexpr gensym get group-by identity if* if-not if-python2 inc input instance? integer integer-char? integer? interleave interpose islice iterable? iterate iterator? juxt keyword keyword? last let lif lif-not list* list-comp macro-error macroexpand macroexpand-1 map merge-with multicombinations name neg? none? not-in not? nth numeric? odd? partition permutations pos? product quasiquote quote range read read-str reduce remove repeat repeatedly require rest second set-comp setv some string string? symbol? take take-nth take-while tee unless unquote unquote-splicing when with* with-decorator with-gensyms xor yield-from zero? zip zip-longest | |= ~ ) end identifier = %r([\w!$%*+,<=>?/.-]+) keyword = %r([\w!\#$%*+,<=>?/.-]+) def name_token(name) return Keyword if self.class.keywords.include?(name) return Name::Builtin if self.class.builtins.include?(name) nil end state :root do rule /;.*?$/, Comment::Single rule /\s+/m, Text::Whitespace rule /-?\d+\.\d+/, Num::Float rule /-?\d+/, Num::Integer rule /0x-?[0-9a-fA-F]+/, Num::Hex rule /"(\\.|[^"])*"/, Str rule /'#{keyword}/, Str::Symbol rule /::?#{keyword}/, Name::Constant rule /\\(.|[a-z]+)/i, Str::Char rule /~@|[`\'#^~&@]/, Operator rule /(\()(\s*)(#{identifier})/m do |m| token Punctuation, m[1] token Text::Whitespace, m[2] token(name_token(m[3]) || Name::Function, m[3]) end rule identifier do |m| token name_token(m[0]) || Name end # vectors rule /[\[\]]/, Punctuation # maps rule /[{}]/, Punctuation # parentheses rule /[()]/, Punctuation 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/lexers/python.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/python.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Python < RegexLexer title "Python" desc "The Python programming language (python.org)" tag 'python' aliases 'py' filenames '*.py', '*.pyw', '*.sc', 'SConstruct', 'SConscript', '*.tac' mimetypes 'text/x-python', 'application/x-python' def self.detect?(text) return true if text.shebang?(/pythonw?(3|2(\.\d)?)?/) end def self.keywords @keywords ||= %w( assert break continue del elif else except exec finally for global if lambda pass print raise return try while yield as with from import yield async await nonlocal ) end def self.builtins @builtins ||= %w( __import__ abs all any apply ascii basestring bin bool buffer bytearray bytes callable chr classmethod cmp coerce compile complex delattr dict dir divmod enumerate eval execfile exit file filter float format frozenset getattr globals hasattr hash hex id input int intern isinstance issubclass iter len list locals long map max memoryview min next object oct open ord pow property range raw_input reduce reload repr reversed round set setattr slice sorted staticmethod str sum super tuple type unichr unicode vars xrange zip ) end def self.builtins_pseudo @builtins_pseudo ||= %w(self None Ellipsis NotImplemented False True) end def self.exceptions @exceptions ||= %w( ArithmeticError AssertionError AttributeError BaseException BlockingIOError BrokenPipeError BufferError BytesWarning ChildProcessError ConnectionAbortedError ConnectionError ConnectionRefusedError ConnectionResetError DeprecationWarning EOFError EnvironmentError Exception FileExistsError FileNotFoundError FloatingPointError FutureWarning GeneratorExit IOError ImportError ImportWarning IndentationError IndexError InterruptedError IsADirectoryError KeyError KeyboardInterrupt LookupError MemoryError ModuleNotFoundError NameError NotADirectoryError NotImplemented NotImplementedError OSError OverflowError OverflowWarning PendingDeprecationWarning ProcessLookupError RecursionError ReferenceError ResourceWarning RuntimeError RuntimeWarning StandardError StopAsyncIteration StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TimeoutError TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError VMSError Warning WindowsError ZeroDivisionError ) end identifier = /[a-z_][a-z0-9_]*/i dotted_identifier = /[a-z_.][a-z0-9_.]*/i state :root do rule /\n+/m, Text rule /^(:)(\s*)([ru]{,2}""".*?""")/mi do groups Punctuation, Text, Str::Doc end rule /[^\S\n]+/, Text rule %r(#(.*)?\n?), Comment::Single rule /[\[\]{}:(),;]/, Punctuation rule /\\\n/, Text rule /\\/, Text rule /(in|is|and|or|not)\b/, Operator::Word rule /(<<|>>|\/\/|\*\*)=?/, Operator rule /[-~+\/*%=<>&^|@]=?|!=/, Operator rule /\.(?![0-9])/, Operator # so it doesn't match float literals rule /(from)((?:\\\s|\s)+)(#{dotted_identifier})((?:\\\s|\s)+)(import)/ do groups Keyword::Namespace, Text, Name::Namespace, Text, Keyword::Namespace end rule /(import)(\s+)(#{dotted_identifier})/ do groups Keyword::Namespace, Text, Name::Namespace end rule /(def)((?:\s|\\\s)+)/ do groups Keyword, Text push :funcname end rule /(class)((?:\s|\\\s)+)/ do groups Keyword, Text push :classname end # TODO: not in python 3 rule /`.*?`/, Str::Backtick rule /(?:r|ur|ru)"""/i, Str, :raw_tdqs rule /(?:r|ur|ru)'''/i, Str, :raw_tsqs rule /(?:r|ur|ru)"/i, Str, :raw_dqs rule /(?:r|ur|ru)'/i, Str, :raw_sqs rule /u?"""/i, Str, :tdqs rule /u?'''/i, Str, :tsqs rule /u?"/i, Str, :dqs rule /u?'/i, Str, :sqs rule /@#{dotted_identifier}/i, Name::Decorator # using negative lookbehind so we don't match property names rule /(?<!\.)#{identifier}/ do |m| if self.class.keywords.include? m[0] token Keyword elsif self.class.exceptions.include? m[0] token Name::Builtin elsif self.class.builtins.include? m[0] token Name::Builtin elsif self.class.builtins_pseudo.include? m[0] token Name::Builtin::Pseudo else token Name end end rule identifier, Name digits = /[0-9](_?[0-9])*/ decimal = /((#{digits})?\.#{digits}|#{digits}\.)/ exponent = /e[+-]?#{digits}/i rule /#{decimal}(#{exponent})?j?/i, Num::Float rule /#{digits}#{exponent}j?/i, Num::Float rule /#{digits}j/i, Num::Float rule /0b(_?[0-1])+/i, Num::Bin rule /0o(_?[0-7])+/i, Num::Oct rule /0x(_?[a-f0-9])+/i, Num::Hex rule /\d+L/, Num::Integer::Long rule /([1-9](_?[0-9])*|0(_?0)*)/, Num::Integer end state :funcname do rule identifier, Name::Function, :pop! end state :classname do rule identifier, Name::Class, :pop! end state :raise do rule /from\b/, Keyword rule /raise\b/, Keyword rule /yield\b/, Keyword rule /\n/, Text, :pop! rule /;/, Punctuation, :pop! mixin :root end state :yield do mixin :raise end state :strings do rule /%(\([a-z0-9_]+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?/i, Str::Interpol end state :strings_double do rule /[^\\"%\n]+/, Str mixin :strings end state :strings_single do rule /[^\\'%\n]+/, Str mixin :strings end state :nl do rule /\n/, Str end state :escape do rule %r(\\ ( [\\abfnrtv"'] | \n | N{[a-zA-z][a-zA-Z ]+[a-zA-Z]} | u[a-fA-F0-9]{4} | U[a-fA-F0-9]{8} | x[a-fA-F0-9]{2} | [0-7]{1,3} ) )x, Str::Escape end state :raw_escape do rule /\\./, Str end state :dqs do rule /"/, Str, :pop! mixin :escape mixin :strings_double end state :sqs do rule /'/, Str, :pop! mixin :escape mixin :strings_single end state :tdqs do rule /"""/, Str, :pop! rule /"/, Str mixin :escape mixin :strings_double mixin :nl end state :tsqs do rule /'''/, Str, :pop! rule /'/, Str mixin :escape mixin :strings_single mixin :nl end %w(tdqs tsqs dqs sqs).each do |qtype| state :"raw_#{qtype}" do mixin :raw_escape mixin :"#{qtype}" 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/lexers/clojure.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/clojure.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Clojure < RegexLexer title "Clojure" desc "The Clojure programming language (clojure.org)" tag 'clojure' aliases 'clj', 'cljs' filenames '*.clj', '*.cljs', '*.cljc', 'build.boot', '*.edn' mimetypes 'text/x-clojure', 'application/x-clojure' def self.keywords @keywords ||= Set.new %w( fn def defn defmacro defmethod defmulti defn- defstruct if cond let for ) end def self.builtins @builtins ||= Set.new %w( . .. * + - -> / < <= = == > >= accessor agent agent-errors aget alength all-ns alter and append-child apply array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc await await-for bean binding bit-and bit-not bit-or bit-shift-left bit-shift-right bit-xor boolean branch? butlast byte cast char children class clear-agent-errors comment commute comp comparator complement concat conj cons constantly construct-proxy contains? count create-ns create-struct cycle dec deref difference disj dissoc distinct doall doc dorun doseq dosync dotimes doto double down drop drop-while edit end? ensure eval every? false? ffirst file-seq filter find find-doc find-ns find-var first float flush fnseq frest gensym get-proxy-class get hash-map hash-set identical? identity if-let import in-ns inc index insert-child insert-left insert-right inspect-table inspect-tree instance? int interleave intersection into into-array iterate join key keys keyword keyword? last lazy-cat lazy-cons left lefts line-seq list* list load load-file locking long loop macroexpand macroexpand-1 make-array make-node map map-invert map? mapcat max max-key memfn merge merge-with meta min min-key name namespace neg? new newline next nil? node not not-any? not-every? not= ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unmap nth nthrest or parse partial path peek pop pos? pr pr-str print print-str println println-str prn prn-str project proxy proxy-mappings quot rand rand-int range re-find re-groups re-matcher re-matches re-pattern re-seq read read-line reduce ref ref-set refer rem remove remove-method remove-ns rename rename-keys repeat replace replicate resolve rest resultset-seq reverse rfirst right rights root rrest rseq second select select-keys send send-off seq seq-zip seq? set short slurp some sort sort-by sorted-map sorted-map-by sorted-set special-symbol? split-at split-with str string? struct struct-map subs subvec symbol symbol? sync take take-nth take-while test time to-array to-array-2d tree-seq true? union up update-proxy val vals var-get var-set var? vector vector-zip vector? when when-first when-let when-not with-local-vars with-meta with-open with-out-str xml-seq xml-zip zero? zipmap zipper' ) end identifier = %r([\w!$%*+,<=>?/.-]+) keyword = %r([\w!\#$%*+,<=>?/.-]+) def name_token(name) return Keyword if self.class.keywords.include?(name) return Name::Builtin if self.class.builtins.include?(name) nil end state :root do rule /;.*?$/, Comment::Single rule /\s+/m, Text::Whitespace rule /-?\d+\.\d+/, Num::Float rule /-?\d+/, Num::Integer rule /0x-?[0-9a-fA-F]+/, Num::Hex rule /"(\\.|[^"])*"/, Str rule /'#{keyword}/, Str::Symbol rule /::?#{keyword}/, Name::Constant rule /\\(.|[a-z]+)/i, Str::Char rule /~@|[`\'#^~&@]/, Operator rule /(\()(\s*)(#{identifier})/m do |m| token Punctuation, m[1] token Text::Whitespace, m[2] token(name_token(m[3]) || Name::Function, m[3]) end rule identifier do |m| token name_token(m[0]) || Name end # vectors rule /[\[\]]/, Punctuation # maps rule /[{}]/, Punctuation # parentheses rule /[()]/, Punctuation 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/lexers/diff.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/diff.rb
# frozen_string_literal: true module Rouge module Lexers class Diff < RegexLexer title 'diff' desc 'Lexes unified diffs or patches' tag 'diff' aliases 'patch', 'udiff' filenames '*.diff', '*.patch' mimetypes 'text/x-diff', 'text/x-patch' def self.detect?(text) return true if text.start_with?('Index: ') return true if text =~ %r(\Adiff[^\n]*?\ba/[^\n]*\bb/) return true if text =~ /(---|[+][+][+]).*?\n(---|[+][+][+])/ end state :root do rule(/^ .*$\n?/, Text) rule(/^---$\n?/, Text) rule(/^\+.*$\n?/, Generic::Inserted) rule(/^-+.*$\n?/, Generic::Deleted) rule(/^!.*$\n?/, Generic::Strong) rule(/^@.*$\n?/, Generic::Subheading) rule(/^([Ii]ndex|diff).*$\n?/, Generic::Heading) rule(/^=.*$\n?/, Generic::Heading) rule(/.*$\n?/, Text) 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/lexers/apiblueprint.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/apiblueprint.rb
# frozen_string_literal: true module Rouge module Lexers load_lexer 'markdown.rb' class APIBlueprint < Markdown title 'API Blueprint' desc 'Markdown based API description language.' tag 'apiblueprint' aliases 'apiblueprint', 'apib' filenames '*.apib' mimetypes 'text/vnd.apiblueprint' prepend :root do # Metadata rule(/(\S+)(:\s*)(.*)$/) do groups Name::Variable, Punctuation, Literal::String end # Resource Group rule(/^(#+)(\s*Group\s+)(.*)$/) do groups Punctuation, Keyword, Generic::Heading end # Resource \ Action rule(/^(#+)(.*)(\[.*\])$/) do groups Punctuation, Generic::Heading, Literal::String end # Relation rule(/^([\+\-\*])(\s*Relation:)(\s*.*)$/) do groups Punctuation, Keyword, Literal::String end # MSON rule(/^(\s+[\+\-\*]\s*)(Attributes|Parameters)(.*)$/) do groups Punctuation, Keyword, Literal::String end # Request/Response rule(/^([\+\-\*]\s*)(Request|Response)(\s+\d\d\d)?(.*)$/) do groups Punctuation, Keyword, Literal::Number, Literal::String 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/lexers/literate_haskell.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/literate_haskell.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class LiterateHaskell < RegexLexer title "Literate Haskell" desc 'Literate haskell' tag 'literate_haskell' aliases 'lithaskell', 'lhaskell', 'lhs' filenames '*.lhs' mimetypes 'text/x-literate-haskell' def haskell @haskell ||= Haskell.new(options) end start { haskell.reset! } # TODO: support TeX versions as well. state :root do rule /\s*?\n(?=>)/, Text, :code rule /.*?\n/, Text rule /.+\z/, Text end state :code do rule /(>)( .*?(\n|\z))/ do |m| token Name::Label, m[1] delegate haskell, m[2] end rule /\s*\n(?=\s*[^>])/, Text, :pop! 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/lexers/css.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/css.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class CSS < RegexLexer title "CSS" desc "Cascading Style Sheets, used to style web pages" tag 'css' filenames '*.css' mimetypes 'text/css' identifier = /[a-zA-Z0-9_-]+/ number = /-?(?:[0-9]+(\.[0-9]+)?|\.[0-9]+)/ def self.attributes @attributes ||= Set.new %w( align-content align-items align-self alignment-adjust alignment-baseline all anchor-point animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function appearance azimuth backface-visibility background background-attachment background-clip background-color background-image background-origin background-position background-repeat background-size baseline-shift binding bleed bookmark-label bookmark-level bookmark-state bookmark-target border border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-spacing border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width bottom box-align box-decoration-break box-direction box-flex box-flex-group box-lines box-ordinal-group box-orient box-pack box-shadow box-sizing break-after break-before break-inside caption-side clear clip clip-path clip-rule color color-profile columns column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width content counter-increment counter-reset crop cue cue-after cue-before cursor direction display dominant-baseline drop-initial-after-adjust drop-initial-after-align drop-initial-before-adjust drop-initial-before-align drop-initial-size drop-initial-value elevation empty-cells filter fit fit-position flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap float float-offset font font-family font-feature-settings font-kerning font-language-override font-size font-size-adjust font-stretch font-style font-synthesis font-variant font-variant-alternates font-variant-caps font-variant-east-asian font-variant-ligatures font-variant-numeric font-variant-position font-weight grid-cell grid-column grid-column-align grid-column-sizing grid-column-span grid-columns grid-flow grid-row grid-row-align grid-row-sizing grid-row-span grid-rows grid-template hanging-punctuation height hyphenate-after hyphenate-before hyphenate-character hyphenate-lines hyphenate-resource hyphens icon image-orientation image-rendering image-resolution ime-mode inline-box-align justify-content left letter-spacing line-break line-height line-stacking line-stacking-ruby line-stacking-shift line-stacking-strategy list-style list-style-image list-style-position list-style-type margin margin-bottom margin-left margin-right margin-top mark marker-offset marks mark-after mark-before marquee-direction marquee-loop marquee-play-count marquee-speed marquee-style mask max-height max-width min-height min-width move-to nav-down nav-index nav-left nav-right nav-up object-fit object-position opacity order orphans outline outline-color outline-offset outline-style outline-width overflow overflow-style overflow-wrap overflow-x overflow-y padding padding-bottom padding-left padding-right padding-top page page-break-after page-break-before page-break-inside page-policy pause pause-after pause-before perspective perspective-origin phonemes pitch pitch-range play-during pointer-events position presentation-level punctuation-trim quotes rendering-intent resize rest rest-after rest-before richness right rotation rotation-point ruby-align ruby-overhang ruby-position ruby-span size speak speak-as speak-header speak-numeral speak-punctuation speech-rate src stress string-set tab-size table-layout target target-name target-new target-position text-align text-align-last text-combine-horizontal text-decoration text-decoration-color text-decoration-line text-decoration-skip text-decoration-style text-emphasis text-emphasis-color text-emphasis-position text-emphasis-style text-height text-indent text-justify text-orientation text-outline text-overflow text-rendering text-shadow text-space-collapse text-transform text-underline-position text-wrap top transform transform-origin transform-style transition transition-delay transition-duration transition-property transition-timing-function unicode-bidi vertical-align visibility voice-balance voice-duration voice-family voice-pitch voice-pitch-range voice-range voice-rate voice-stress voice-volume volume white-space widows width word-break word-spacing word-wrap writing-mode z-index ) end def self.builtins @builtins ||= Set.new %w( above absolute always armenian aural auto avoid left bottom baseline behind below bidi-override blink block bold bolder both bottom capitalize center center-left center-right circle cjk-ideographic close-quote collapse condensed continuous crop cross crosshair cursive dashed decimal decimal-leading-zero default digits disc dotted double e-resize embed expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed georgian groove hebrew help hidden hide high higher hiragana hiragana-iroha icon inherit inline inline-table inset inside invert italic justify katakana katakana-iroha landscape large larger left left-side leftwards level lighter line-through list-item loud low lower lower-alpha lower-greek lower-roman lowercase ltr medium message-box middle mix monospace n-resize narrower ne-resize no-close-quote no-open-quote no-repeat none normal nowrap nw-resize oblique once open-quote outset outside overline pointer portrait px relative repeat repeat-x repeat-y rgb ridge right right-side rightwards s-resize sans-serif scroll se-resize semi-condensed semi-expanded separate serif show silent slow slower small-caps small-caption smaller soft solid spell-out square static status-bar super sw-resize table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group text text-bottom text-top thick thin top transparent ultra-condensed ultra-expanded underline upper-alpha upper-latin upper-roman uppercase url visible w-resize wait wider x-fast x-high x-large x-loud x-low x-small x-soft xx-large xx-small yes ) end def self.constants @constants ||= Set.new %w( indigo gold firebrick indianred yellow darkolivegreen darkseagreen mediumvioletred mediumorchid chartreuse mediumslateblue black springgreen crimson lightsalmon brown turquoise olivedrab cyan silver skyblue gray darkturquoise goldenrod darkgreen darkviolet darkgray lightpink teal darkmagenta lightgoldenrodyellow lavender yellowgreen thistle violet navy orchid blue ghostwhite honeydew cornflowerblue darkblue darkkhaki mediumpurple cornsilk red bisque slategray darkcyan khaki wheat deepskyblue darkred steelblue aliceblue gainsboro mediumturquoise floralwhite coral purple lightgrey lightcyan darksalmon beige azure lightsteelblue oldlace greenyellow royalblue lightseagreen mistyrose sienna lightcoral orangered navajowhite lime palegreen burlywood seashell mediumspringgreen fuchsia papayawhip blanchedalmond peru aquamarine white darkslategray ivory dodgerblue lemonchiffon chocolate orange forestgreen slateblue olive mintcream antiquewhite darkorange cadetblue moccasin limegreen saddlebrown darkslateblue lightskyblue deeppink plum aqua darkgoldenrod maroon sandybrown magenta tan rosybrown pink lightblue palevioletred mediumseagreen dimgray powderblue seagreen snow mediumblue midnightblue paleturquoise palegoldenrod whitesmoke darkorchid salmon lightslategray lawngreen lightgreen tomato hotpink lightyellow lavenderblush linen mediumaquamarine green blueviolet peachpuff ) end # source: http://www.w3.org/TR/CSS21/syndata.html#vendor-keyword-history def self.vendor_prefixes @vendor_prefixes ||= Set.new %w( -ah- -atsc- -hp- -khtml- -moz- -ms- -o- -rim- -ro- -tc- -wap- -webkit- -xv- mso- prince- ) end state :root do mixin :basics rule /{/, Punctuation, :stanza rule /:[:]?#{identifier}/, Name::Decorator rule /\.#{identifier}/, Name::Class rule /##{identifier}/, Name::Function rule /@#{identifier}/, Keyword, :at_rule rule identifier, Name::Tag rule %r([~^*!%&\[\]()<>|+=@:;,./?-]), Operator rule /"(\\\\|\\"|[^"])*"/, Str::Single rule /'(\\\\|\\'|[^'])*'/, Str::Double end state :value do mixin :basics rule /url\(.*?\)/, Str::Other rule /#[0-9a-f]{1,6}/i, Num # colors rule /#{number}(?:%|(?:em|px|pt|pc|in|mm|cm|ex|rem|ch|vw|vh|vmin|vmax|dpi|dpcm|dppx|deg|grad|rad|turn|s|ms|Hz|kHz)\b)?/, Num rule /[\[\]():\/.,]/, Punctuation rule /"(\\\\|\\"|[^"])*"/, Str::Single rule /'(\\\\|\\'|[^'])*'/, Str::Double rule(identifier) do |m| if self.class.constants.include? m[0] token Name::Constant elsif self.class.builtins.include? m[0] token Name::Builtin else token Name end end end state :at_rule do rule /{(?=\s*#{identifier}\s*:)/m, Punctuation, :at_stanza rule /{/, Punctuation, :at_body rule /;/, Punctuation, :pop! mixin :value end state :at_body do mixin :at_content mixin :root end state :at_stanza do mixin :at_content mixin :stanza end state :at_content do rule /}/ do token Punctuation pop! 2 end end state :basics do rule /\s+/m, Text rule %r(/\*(?:.*?)\*/)m, Comment end state :stanza do mixin :basics rule /}/, Punctuation, :pop! rule /(#{identifier})(\s*)(:)/m do |m| name_tok = if self.class.attributes.include? m[1] Name::Label elsif self.class.vendor_prefixes.any? { |p| m[1].start_with?(p) } Name::Label else Name::Property end groups name_tok, Text, Punctuation push :stanza_value end end state :stanza_value do rule /;/, Punctuation, :pop! rule(/(?=})/) { pop! } rule /!\s*important\b/, Comment::Preproc rule /^@.*?$/, Comment::Preproc mixin :value 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/lexers/plist.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/plist.rb
# frozen_string_literal: true module Rouge module Lexers class Plist < RegexLexer desc 'plist' tag 'plist' aliases 'plist' filenames *%w(*.plist *.pbxproj) mimetypes 'text/x-plist', 'application/x-plist' state :whitespace do rule /\s+/, Text::Whitespace end state :root do rule %r{//.*$}, Comment rule %r{/\*.+?\*/}m, Comment mixin :whitespace rule /{/, Punctuation, :dictionary rule /\(/, Punctuation, :array rule /"([^"\\]|\\.)*"/, Literal::String::Double rule /'([^'\\]|\\.)*'/, Literal::String::Single rule /</, Punctuation, :data rule %r{[\w_$/:.-]+}, Literal end state :dictionary do mixin :root rule /[=;]/, Punctuation rule /}/, Punctuation, :pop! end state :array do mixin :root rule /[,]/, Punctuation rule /\)/, Punctuation, :pop! end state :data do rule /[\h\s]+/, Literal::Number::Hex rule />/, Punctuation, :pop! 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/lexers/jsonnet.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/jsonnet.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Jsonnet < RegexLexer title 'Jsonnet' desc 'An elegant, formally-specified config language for JSON' tag 'jsonnet' filenames '*.jsonnet' mimetypes 'text/x-jsonnet' def self.keywords @keywords ||= Set.new %w( self super local for in if then else import importstr error tailstrict assert ) end def self.declarations @declarations ||= Set.new %w( function ) end def self.constants @constants ||= Set.new %w( null true false ) end def self.builtins @builtins ||= Set.new %w( acos asin atan ceil char codepoint cos exp exponent filter floor force length log makeArray mantissa objectFields objectHas pow sin sqrt tan thisFile type abs assertEqual escapeStringBash escapeStringDollars escapeStringJson escapeStringPython filterMap flattenArrays foldl foldr format join lines manifestIni manifestPython manifestPythonVars map max min mod range set setDiff setInter setMember setUnion sort split stringChars substr toString uniq ) end identifier = /[a-zA-Z_][a-zA-Z0-9_]*/ state :root do rule /\s+/, Text rule %r(//.*?$), Comment::Single rule %r(#.*?$), Comment::Single rule %r(/\*.*?\*/)m, Comment::Multiline rule /-?(?:0|[1-9]\d*)\.\d+(?:e[+-]\d+)?/i, Num::Float rule /-?(?:0|[1-9]\d*)(?:e[+-]\d+)?/i, Num::Integer rule /[{}:\.,;+\[\]=%\(\)]/, Punctuation rule /"/, Str, :string_double rule /'/, Str, :string_single rule /\|\|\|/, Str, :string_block rule /\$/, Keyword rule identifier do |m| if self.class.keywords.include? m[0] token Keyword elsif self.class.declarations.include? m[0] token Keyword::Declaration elsif self.class.constants.include? m[0] token Keyword::Constant elsif self.class.builtins.include? m[0] token Name::Builtin else token Name::Other end end end state :string do rule /\\([\\\/bfnrt]|(u[0-9a-fA-F]{4}))/, Str::Escape end state :string_double do mixin :string rule /\\"/, Str::Escape rule /"/, Str, :pop! rule /[^\\"]+/, Str end state :string_single do mixin :string rule /\\'/, Str::Escape rule /'/, Str, :pop! rule /[^\\']+/, Str end state :string_block do mixin :string rule /\|\|\|/, Str, :pop! rule /.*/, Str end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/terraform.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/terraform.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers load_lexer 'hcl.rb' class Terraform < Hcl title "Terraform" desc "Terraform HCL Interpolations" tag 'terraform' aliases 'tf' filenames '*.tf' def self.keywords @keywords ||= Set.new %w( terraform module provider variable resource data provisioner output ) end def self.declarations @declarations ||= Set.new %w( var local ) end def self.reserved @reserved ||= Set.new %w() end def self.constants @constants ||= Set.new %w(true false null) end def self.builtins @builtins ||= %w() end state :strings do rule /\\./, Str::Escape rule /\$\{/ do token Keyword push :interpolation end end state :dq do rule /[^\\"\$]+/, Str::Double mixin :strings rule /"/, Str::Double, :pop! end state :sq do rule /[^\\'\$]+/, Str::Single mixin :strings rule /'/, Str::Single, :pop! end state :heredoc do rule /\n/, Str::Heredoc, :heredoc_nl rule /[^$\n\$]+/, Str::Heredoc rule /[$]/, Str::Heredoc mixin :strings end state :interpolation do rule /\}/ do token Keyword pop! end mixin :expression end id = /[$a-z_\-][a-z0-9_\-]*/io state :expression do mixin :primitives rule /\s+/, Text rule %r(\+\+ | -- | ~ | && | \|\| | \\(?=\n) | << | >>>? | == | != )x, Operator rule %r([-<>+*%&|\^/!=?:]=?), Operator rule /[(\[,]/, Punctuation rule /[)\].]/, Punctuation rule id do |m| if self.class.keywords.include? m[0] token Keyword elsif self.class.declarations.include? m[0] token Keyword::Declaration elsif self.class.reserved.include? m[0] token Keyword::Reserved elsif self.class.constants.include? m[0] token Keyword::Constant elsif self.class.builtins.include? m[0] token Name::Builtin else token Name::Other end 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/lexers/igorpro.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/igorpro.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class IgorPro < RegexLexer tag 'igorpro' filenames '*.ipf' mimetypes 'text/x-igorpro' title "IgorPro" desc "WaveMetrics Igor Pro" def self.keywords @keywords ||= Set.new %w( structure endstructure threadsafe static macro proc window menu function end if else elseif endif switch strswitch endswitch break return continue for endfor do while case default try catch endtry abortonrte ) end def self.preprocessor @preprocessor ||= Set.new %w( pragma include define ifdef ifndef undef if elif else endif ) end def self.igorDeclarations @igorDeclarations ||= Set.new %w( variable string wave strconstant constant nvar svar dfref funcref struct char uchar int16 uint16 int32 uint32 int64 uint64 float double ) end def self.igorConstants @igorConstants ||= Set.new %w( nan inf ) end def self.igorFunction @igorFunction ||= Set.new %w( AddListItem AiryA AiryAD AiryB AiryBD AnnotationInfo AnnotationList AxisInfo AxisList AxisValFromPixel AxonTelegraphAGetDataNum AxonTelegraphAGetDataString AxonTelegraphAGetDataStruct AxonTelegraphGetDataNum AxonTelegraphGetDataString AxonTelegraphGetDataStruct AxonTelegraphGetTimeoutMs AxonTelegraphSetTimeoutMs Base64Decode Base64Encode Besseli Besselj Besselk Bessely BinarySearch BinarySearchInterp CTabList CaptureHistory CaptureHistoryStart CheckName ChildWindowList CleanupName ContourInfo ContourNameList ContourNameToWaveRef ContourZ ControlNameList ConvertTextEncoding CountObjects CountObjectsDFR CreationDate CsrInfo CsrWave CsrWaveRef CsrXWave CsrXWaveRef DataFolderDir DataFolderExists DataFolderRefStatus DataFolderRefsEqual DateToJulian Dawson DimDelta DimOffset DimSize Faddeeva FetchURL FindDimLabel FindListItem FontList FontSizeHeight FontSizeStringWidth FresnelCos FresnelSin FuncRefInfo FunctionInfo FunctionList FunctionPath GISGetAllFileFormats GISSRefsAreEqual Gauss Gauss1D Gauss2D GetBrowserLine GetBrowserSelection GetDataFolder GetDataFolderDFR GetDefaultFont GetDefaultFontSize GetDefaultFontStyle GetDimLabel GetEnvironmentVariable GetErrMessage GetFormula GetIndependentModuleName GetIndexedObjName GetIndexedObjNameDFR GetKeyState GetRTErrMessage GetRTError GetRTLocInfo GetRTLocation GetRTStackInfo GetScrapText GetUserData GetWavesDataFolder GetWavesDataFolderDFR GizmoInfo GizmoScale GrepList GrepString GuideInfo GuideNameList HDF5AttributeInfo HDF5DatasetInfo HDF5LibraryInfo HDF5TypeInfo Hash HyperG0F1 HyperG1F1 HyperG2F1 HyperGNoise HyperGPFQ IgorInfo IgorVersion ImageInfo ImageNameList ImageNameToWaveRef IndependentModuleList IndexToScale IndexedDir IndexedFile Inf Integrate1D Interp2D Interp3D ItemsInList JacobiCn JacobiSn JulianToDate Laguerre LaguerreA LaguerreGauss LambertW LayoutInfo LegendreA ListMatch ListToTextWave ListToWaveRefWave LowerStr MCC_AutoBridgeBal MCC_AutoFastComp MCC_AutoPipetteOffset MCC_AutoSlowComp MCC_AutoWholeCellComp MCC_GetBridgeBalEnable MCC_GetBridgeBalResist MCC_GetFastCompCap MCC_GetFastCompTau MCC_GetHolding MCC_GetHoldingEnable MCC_GetMode MCC_GetNeutralizationCap MCC_GetNeutralizationEnable MCC_GetOscKillerEnable MCC_GetPipetteOffset MCC_GetPrimarySignalGain MCC_GetPrimarySignalHPF MCC_GetPrimarySignalLPF MCC_GetRsCompBandwidth MCC_GetRsCompCorrection MCC_GetRsCompEnable MCC_GetRsCompPrediction MCC_GetSecondarySignalGain MCC_GetSecondarySignalLPF MCC_GetSlowCompCap MCC_GetSlowCompTau MCC_GetSlowCompTauX20Enable MCC_GetSlowCurrentInjEnable MCC_GetSlowCurrentInjLevel MCC_GetSlowCurrentInjSetlTime MCC_GetWholeCellCompCap MCC_GetWholeCellCompEnable MCC_GetWholeCellCompResist MCC_SelectMultiClamp700B MCC_SetBridgeBalEnable MCC_SetBridgeBalResist MCC_SetFastCompCap MCC_SetFastCompTau MCC_SetHolding MCC_SetHoldingEnable MCC_SetMode MCC_SetNeutralizationCap MCC_SetNeutralizationEnable MCC_SetOscKillerEnable MCC_SetPipetteOffset MCC_SetPrimarySignalGain MCC_SetPrimarySignalHPF MCC_SetPrimarySignalLPF MCC_SetRsCompBandwidth MCC_SetRsCompCorrection MCC_SetRsCompEnable MCC_SetRsCompPrediction MCC_SetSecondarySignalGain MCC_SetSecondarySignalLPF MCC_SetSlowCompCap MCC_SetSlowCompTau MCC_SetSlowCompTauX20Enable MCC_SetSlowCurrentInjEnable MCC_SetSlowCurrentInjLevel MCC_SetSlowCurrentInjSetlTime MCC_SetTimeoutMs MCC_SetWholeCellCompCap MCC_SetWholeCellCompEnable MCC_SetWholeCellCompResist MPFXEMGPeak MPFXExpConvExpPeak MPFXGaussPeak MPFXLorenzianPeak MPFXVoigtPeak MacroList MandelbrotPoint MarcumQ MatrixCondition MatrixDet MatrixDot MatrixRank MatrixTrace ModDate NVAR_Exists NaN NameOfWave NewFreeDataFolder NewFreeWave NormalizeUnicode NumVarOrDefault NumberByKey OperationList PICTInfo PICTList PadString PanelResolution ParamIsDefault ParseFilePath PathList Pi PixelFromAxisVal PolygonArea PossiblyQuoteName ProcedureText RemoveByKey RemoveEnding RemoveFromList RemoveListItem ReplaceNumberByKey ReplaceString ReplaceStringByKey SQL2DBinaryWaveToTextWave SQLAllocHandle SQLAllocStmt SQLBinaryWavesToTextWave SQLBindCol SQLBindParameter SQLBrowseConnect SQLBulkOperations SQLCancel SQLCloseCursor SQLColAttributeNum SQLColAttributeStr SQLColumnPrivileges SQLColumns SQLConnect SQLDataSources SQLDescribeCol SQLDescribeParam SQLDisconnect SQLDriverConnect SQLDrivers SQLEndTran SQLError SQLExecDirect SQLExecute SQLFetch SQLFetchScroll SQLForeignKeys SQLFreeConnect SQLFreeEnv SQLFreeHandle SQLFreeStmt SQLGetConnectAttrNum SQLGetConnectAttrStr SQLGetCursorName SQLGetDataNum SQLGetDataStr SQLGetDescFieldNum SQLGetDescFieldStr SQLGetDescRec SQLGetDiagFieldNum SQLGetDiagFieldStr SQLGetDiagRec SQLGetEnvAttrNum SQLGetEnvAttrStr SQLGetFunctions SQLGetInfoNum SQLGetInfoStr SQLGetStmtAttrNum SQLGetStmtAttrStr SQLGetTypeInfo SQLMoreResults SQLNativeSql SQLNumParams SQLNumResultCols SQLNumResultRowsIfKnown SQLNumRowsFetched SQLParamData SQLPrepare SQLPrimaryKeys SQLProcedureColumns SQLProcedures SQLPutData SQLReinitialize SQLRowCount SQLSetConnectAttrNum SQLSetConnectAttrStr SQLSetCursorName SQLSetDescFieldNum SQLSetDescFieldStr SQLSetDescRec SQLSetEnvAttrNum SQLSetEnvAttrStr SQLSetPos SQLSetStmtAttrNum SQLSetStmtAttrStr SQLSpecialColumns SQLStatistics SQLTablePrivileges SQLTables SQLTextWaveTo2DBinaryWave SQLTextWaveToBinaryWaves SQLUpdateBoundValues SQLXOPCheckState SVAR_Exists ScreenResolution Secs2Date Secs2Time SelectNumber SelectString SetEnvironmentVariable SortList SpecialCharacterInfo SpecialCharacterList SpecialDirPath SphericalBessJ SphericalBessJD SphericalBessY SphericalBessYD SphericalHarmonics StartMSTimer StatsBetaCDF StatsBetaPDF StatsBinomialCDF StatsBinomialPDF StatsCMSSDCDF StatsCauchyCDF StatsCauchyPDF StatsChiCDF StatsChiPDF StatsCorrelation StatsDExpCDF StatsDExpPDF StatsEValueCDF StatsEValuePDF StatsErlangCDF StatsErlangPDF StatsErrorPDF StatsExpCDF StatsExpPDF StatsFCDF StatsFPDF StatsFriedmanCDF StatsGEVCDF StatsGEVPDF StatsGammaCDF StatsGammaPDF StatsGeometricCDF StatsGeometricPDF StatsHyperGCDF StatsHyperGPDF StatsInvBetaCDF StatsInvBinomialCDF StatsInvCMSSDCDF StatsInvCauchyCDF StatsInvChiCDF StatsInvDExpCDF StatsInvEValueCDF StatsInvExpCDF StatsInvFCDF StatsInvFriedmanCDF StatsInvGammaCDF StatsInvGeometricCDF StatsInvKuiperCDF StatsInvLogNormalCDF StatsInvLogisticCDF StatsInvMaxwellCDF StatsInvMooreCDF StatsInvNBinomialCDF StatsInvNCChiCDF StatsInvNCFCDF StatsInvNormalCDF StatsInvParetoCDF StatsInvPoissonCDF StatsInvPowerCDF StatsInvQCDF StatsInvQpCDF StatsInvRayleighCDF StatsInvRectangularCDF StatsInvSpearmanCDF StatsInvStudentCDF StatsInvTopDownCDF StatsInvTriangularCDF StatsInvUsquaredCDF StatsInvVonMisesCDF StatsInvWeibullCDF StatsKuiperCDF StatsLogNormalCDF StatsLogNormalPDF StatsLogisticCDF StatsLogisticPDF StatsMaxwellCDF StatsMaxwellPDF StatsMedian StatsMooreCDF StatsNBinomialCDF StatsNBinomialPDF StatsNCChiCDF StatsNCChiPDF StatsNCFCDF StatsNCFPDF StatsNCTCDF StatsNCTPDF StatsNormalCDF StatsNormalPDF StatsParetoCDF StatsParetoPDF StatsPermute StatsPoissonCDF StatsPoissonPDF StatsPowerCDF StatsPowerNoise StatsPowerPDF StatsQCDF StatsQpCDF StatsRayleighCDF StatsRayleighPDF StatsRectangularCDF StatsRectangularPDF StatsRunsCDF StatsSpearmanRhoCDF StatsStudentCDF StatsStudentPDF StatsTopDownCDF StatsTriangularCDF StatsTriangularPDF StatsTrimmedMean StatsUSquaredCDF StatsVonMisesCDF StatsVonMisesNoise StatsVonMisesPDF StatsWaldCDF StatsWaldPDF StatsWeibullCDF StatsWeibullPDF StopMSTimer StrVarOrDefault StringByKey StringFromList StringList StudentA StudentT TDMAddChannel TDMAddGroup TDMAppendDataValues TDMAppendDataValuesTime TDMChannelPropertyExists TDMCloseChannel TDMCloseFile TDMCloseGroup TDMCreateChannelProperty TDMCreateFile TDMCreateFileProperty TDMCreateGroupProperty TDMFilePropertyExists TDMGetChannelPropertyNames TDMGetChannelPropertyNum TDMGetChannelPropertyStr TDMGetChannelPropertyTime TDMGetChannelPropertyType TDMGetChannelStringPropertyLen TDMGetChannels TDMGetDataType TDMGetDataValues TDMGetDataValuesTime TDMGetFilePropertyNames TDMGetFilePropertyNum TDMGetFilePropertyStr TDMGetFilePropertyTime TDMGetFilePropertyType TDMGetFileStringPropertyLen TDMGetGroupPropertyNames TDMGetGroupPropertyNum TDMGetGroupPropertyStr TDMGetGroupPropertyTime TDMGetGroupPropertyType TDMGetGroupStringPropertyLen TDMGetGroups TDMGetLibraryErrorDescription TDMGetNumChannelProperties TDMGetNumChannels TDMGetNumDataValues TDMGetNumFileProperties TDMGetNumGroupProperties TDMGetNumGroups TDMGroupPropertyExists TDMOpenFile TDMOpenFileEx TDMRemoveChannel TDMRemoveGroup TDMReplaceDataValues TDMReplaceDataValuesTime TDMSaveFile TDMSetChannelPropertyNum TDMSetChannelPropertyStr TDMSetChannelPropertyTime TDMSetDataValues TDMSetDataValuesTime TDMSetFilePropertyNum TDMSetFilePropertyStr TDMSetFilePropertyTime TDMSetGroupPropertyNum TDMSetGroupPropertyStr TDMSetGroupPropertyTime TableInfo TagVal TagWaveRef TextEncodingCode TextEncodingName TextFile ThreadGroupCreate ThreadGroupGetDF ThreadGroupGetDFR ThreadGroupRelease ThreadGroupWait ThreadProcessorCount ThreadReturnValue TraceFromPixel TraceInfo TraceNameList TraceNameToWaveRef TrimString URLDecode URLEncode UnPadString UniqueName UnsetEnvironmentVariable UpperStr VariableList Variance VoigtFunc VoigtPeak WaveCRC WaveDims WaveExists WaveHash WaveInfo WaveList WaveMax WaveMin WaveName WaveRefIndexed WaveRefIndexedDFR WaveRefWaveToList WaveRefsEqual WaveTextEncoding WaveType WaveUnits WhichListItem WinList WinName WinRecreation WinType XWaveName XWaveRefFromTrace ZernikeR abs acos acosh alog area areaXY asin asinh atan atan2 atanh beta betai binomial binomialNoise binomialln cabs ceil cequal char2num chebyshev chebyshevU cmplx cmpstr conj cos cosIntegral cosh cot coth cpowi csc csch date date2secs datetime defined deltax digamma dilogarithm ei enoise equalWaves erf erfc erfcw exists exp expInt expIntegralE1 expNoise fDAQmx_AI_GetReader fDAQmx_AO_UpdateOutputs fDAQmx_CTR_Finished fDAQmx_CTR_IsFinished fDAQmx_CTR_IsPulseFinished fDAQmx_CTR_ReadCounter fDAQmx_CTR_ReadWithOptions fDAQmx_CTR_SetPulseFrequency fDAQmx_CTR_Start fDAQmx_ConnectTerminals fDAQmx_DIO_Finished fDAQmx_DIO_PortWidth fDAQmx_DIO_Read fDAQmx_DIO_Write fDAQmx_DeviceNames fDAQmx_DisconnectTerminals fDAQmx_ErrorString fDAQmx_ExternalCalDate fDAQmx_NumAnalogInputs fDAQmx_NumAnalogOutputs fDAQmx_NumCounters fDAQmx_NumDIOPorts fDAQmx_ReadChan fDAQmx_ReadNamedChan fDAQmx_ResetDevice fDAQmx_ScanGetAvailable fDAQmx_ScanGetNextIndex fDAQmx_ScanStart fDAQmx_ScanStop fDAQmx_ScanWait fDAQmx_ScanWaitWithTimeout fDAQmx_SelfCalDate fDAQmx_SelfCalibration fDAQmx_WF_IsFinished fDAQmx_WF_WaitUntilFinished fDAQmx_WaveformStart fDAQmx_WaveformStop fDAQmx_WriteChan factorial fakedata faverage faverageXY floor gamma gammaEuler gammaInc gammaNoise gammln gammp gammq gcd gnoise hcsr hermite hermiteGauss imag interp inverseERF inverseERFC leftx limit ln log logNormalNoise lorentzianNoise magsqr max mean median min mod norm note num2char num2istr num2str numpnts numtype p2rect pcsr pnt2x poissonNoise poly poly2D qcsr r2polar real rightx round sawtooth scaleToIndex sec sech sign sin sinIntegral sinc sinh sqrt str2num stringCRC stringmatch strlen strsearch sum tan tango_close_device tango_command_inout tango_compute_image_proj tango_get_dev_attr_list tango_get_dev_black_box tango_get_dev_cmd_list tango_get_dev_status tango_get_dev_timeout tango_get_error_stack tango_open_device tango_ping_device tango_read_attribute tango_read_attributes tango_reload_dev_interface tango_resume_attr_monitor tango_set_attr_monitor_period tango_set_dev_timeout tango_start_attr_monitor tango_stop_attr_monitor tango_suspend_attr_monitor tango_write_attribute tango_write_attributes tanh ticks time trunc vcsr viAssertIntrSignal viAssertTrigger viAssertUtilSignal viClear viClose viDisableEvent viDiscardEvents viEnableEvent viFindNext viFindRsrc viGetAttribute viGetAttributeString viGpibCommand viGpibControlATN viGpibControlREN viGpibPassControl viGpibSendIFC viIn16 viIn32 viIn8 viLock viMapAddress viMapTrigger viMemAlloc viMemFree viMoveIn16 viMoveIn32 viMoveIn8 viMoveOut16 viMoveOut32 viMoveOut8 viOpen viOpenDefaultRM viOut16 viOut32 viOut8 viPeek16 viPeek32 viPeek8 viPoke16 viPoke32 viPoke8 viRead viReadSTB viSetAttribute viSetAttributeString viStatusDesc viTerminate viUnlock viUnmapAddress viUnmapTrigger viUsbControlIn viUsbControlOut viVxiCommandQuery viWaitOnEvent viWrite wnoise x2pnt xcsr zcsr zeromq_client_connect zeromq_client_connect zeromq_client_recv zeromq_client_recv zeromq_client_send zeromq_client_send zeromq_handler_start zeromq_handler_start zeromq_handler_stop zeromq_handler_stop zeromq_server_bind zeromq_server_bind zeromq_server_recv zeromq_server_recv zeromq_server_send zeromq_server_send zeromq_set zeromq_set zeromq_stop zeromq_stop zeromq_test_callfunction zeromq_test_callfunction zeromq_test_serializeWave zeromq_test_serializeWave zeta ) end def self.igorOperation @igorOperation ||= Set.new %w( APMath Abort AddFIFOData AddFIFOVectData AddMovieAudio AddMovieFrame AddWavesToBoxPlot AddWavesToViolinPlot AdoptFiles Append AppendBoxPlot AppendImage AppendLayoutObject AppendMatrixContour AppendText AppendToGizmo AppendToGraph AppendToLayout AppendToTable AppendViolinPlot AppendXYZContour AutoPositionWindow AxonTelegraphFindServers BackgroundInfo Beep BoundingBall BoxSmooth BrowseURL BuildMenu Button CWT Chart CheckBox CheckDisplayed ChooseColor Close CloseHelp CloseMovie CloseProc ColorScale ColorTab2Wave Concatenate ControlBar ControlInfo ControlUpdate ConvertGlobalStringTextEncoding ConvexHull Convolve CopyDimLabels CopyFile CopyFolder CopyScales Correlate CreateAliasShortcut CreateBrowser Cross CtrlBackground CtrlFIFO CtrlNamedBackground Cursor CurveFit CustomControl DAQmx_AI_SetupReader DAQmx_AO_SetOutputs DAQmx_CTR_CountEdges DAQmx_CTR_OutputPulse DAQmx_CTR_Period DAQmx_CTR_PulseWidth DAQmx_DIO_Config DAQmx_DIO_WriteNewData DAQmx_Scan DAQmx_WaveformGen DPSS DSPDetrend DSPPeriodogram DWT Debugger DebuggerOptions DefaultFont DefaultGuiControls DefaultGuiFont DefaultTextEncoding DefineGuide DelayUpdate DeleteAnnotations DeleteFile DeleteFolder DeletePoints Differentiate Display DisplayHelpTopic DisplayProcedure DoAlert DoIgorMenu DoUpdate DoWindow DoXOPIdle DrawAction DrawArc DrawBezier DrawLine DrawOval DrawPICT DrawPoly DrawRRect DrawRect DrawText DrawUserShape Duplicate DuplicateDataFolder EdgeStats Edit ErrorBars EstimatePeakSizes Execute ExecuteScriptText ExperimentInfo ExperimentModified ExportGizmo Extract FBinRead FBinWrite FFT FGetPos FIFO2Wave FIFOStatus FMaxFlat FPClustering FReadLine FSetPos FStatus FTPCreateDirectory FTPDelete FTPDownload FTPUpload FastGaussTransform FastOp FilterFIR FilterIIR FindAPeak FindContour FindDuplicates FindLevel FindLevels FindPeak FindPointsInPoly FindRoots FindSequence FindValue FuncFit FuncFitMD GBLoadWave GISCreateVectorLayer GISGetRasterInfo GISGetRegisteredFileInfo GISGetVectorLayerInfo GISLoadRasterData GISLoadVectorData GISRasterizeVectorData GISRegisterFile GISTransformCoords GISUnRegisterFile GISWriteFieldData GISWriteGeometryData GISWriteRaster GPIB2 GPIBRead2 GPIBReadBinary2 GPIBReadBinaryWave2 GPIBReadWave2 GPIBWrite2 GPIBWriteBinary2 GPIBWriteBinaryWave2 GPIBWriteWave2 GetAxis GetCamera GetFileFolderInfo GetGizmo GetLastUserMenuInfo GetMarquee GetMouse GetSelection GetWindow GraphNormal GraphWaveDraw GraphWaveEdit Grep GroupBox HDF5CloseFile HDF5CloseGroup HDF5ConvertColors HDF5CreateFile HDF5CreateGroup HDF5CreateLink HDF5Dump HDF5DumpErrors HDF5DumpState HDF5FlushFile HDF5ListAttributes HDF5ListGroup HDF5LoadData HDF5LoadGroup HDF5LoadImage HDF5OpenFile HDF5OpenGroup HDF5SaveData HDF5SaveGroup HDF5SaveImage HDF5TestOperation HDF5UnlinkObject HDFInfo HDFReadImage HDFReadSDS HDFReadVset Hanning HideIgorMenus HideInfo HideProcedures HideTools HilbertTransform Histogram ICA IFFT ITCCloseAll2 ITCCloseDevice2 ITCConfigAllChannels2 ITCConfigChannel2 ITCConfigChannelReset2 ITCConfigChannelUpload2 ITCFIFOAvailable2 ITCFIFOAvailableAll2 ITCGetAllChannelsConfig2 ITCGetChannelConfig2 ITCGetCurrentDevice2 ITCGetDeviceInfo2 ITCGetDevices2 ITCGetErrorString2 ITCGetSerialNumber2 ITCGetState2 ITCGetVersions2 ITCInitialize2 ITCOpenDevice2 ITCReadADC2 ITCReadDigital2 ITCReadTimer2 ITCSelectDevice2 ITCSetDAC2 ITCSetGlobals2 ITCSetModes2 ITCSetState2 ITCStartAcq2 ITCStopAcq2 ITCUpdateFIFOPosition2 ITCUpdateFIFOPositionAll2 ITCWriteDigital2 ImageAnalyzeParticles ImageBlend ImageBoundaryToMask ImageComposite ImageEdgeDetection ImageFileInfo ImageFilter ImageFocus ImageFromXYZ ImageGLCM ImageGenerateROIMask ImageHistModification ImageHistogram ImageInterpolate ImageLineProfile ImageLoad ImageMorphology ImageRegistration ImageRemoveBackground ImageRestore ImageRotate ImageSave ImageSeedFill ImageSkeleton3d ImageSnake ImageStats ImageThreshold ImageTransform ImageUnwrapPhase ImageWindow IndexSort InsertPoints Integrate Integrate2D IntegrateODE Interp3DPath Interpolate2 Interpolate3D JCAMPLoadWave JointHistogram KMeans KillBackground KillControl KillDataFolder KillFIFO KillFreeAxis KillPICTs KillPath KillStrings KillVariables KillWaves KillWindow Label Layout LayoutPageAction LayoutSlideShow Legend LinearFeedbackShiftRegister ListBox LoadData LoadPICT LoadPackagePreferences LoadWave Loess LombPeriodogram MCC_FindServers MFR_CheckForNewBricklets MFR_CloseResultFile MFR_CreateOverviewTable MFR_GetBrickletCount MFR_GetBrickletData MFR_GetBrickletDeployData MFR_GetBrickletMetaData MFR_GetBrickletRawData MFR_GetReportTemplate MFR_GetResultFileMetaData MFR_GetResultFileName MFR_GetVernissageVersion MFR_GetVersion MFR_GetXOPErrorMessage MFR_OpenResultFile MLLoadWave Make MakeIndex MarkPerfTestTime MatrixConvolve MatrixCorr MatrixEigenV MatrixFilter MatrixGLM MatrixGaussJ MatrixInverse MatrixLLS MatrixLUBkSub MatrixLUD MatrixLUDTD MatrixLinearSolve MatrixLinearSolveTD MatrixMultiply MatrixOP MatrixSVBkSub MatrixSVD MatrixSchur MatrixSolve MatrixTranspose MeasureStyledText Modify ModifyBoxPlot ModifyBrowser ModifyCamera ModifyContour ModifyControl ModifyControlList ModifyFreeAxis ModifyGizmo ModifyGraph ModifyImage ModifyLayout ModifyPanel ModifyTable ModifyViolinPlot ModifyWaterfall MoveDataFolder MoveFile MoveFolder MoveString MoveSubwindow MoveVariable MoveWave MoveWindow MultiTaperPSD MultiThreadingControl NC_CloseFile NC_DumpErrors NC_Inquire NC_ListAttributes NC_ListObjects NC_LoadData NC_OpenFile NI4882 NILoadWave NeuralNetworkRun NeuralNetworkTrain NewCamera NewDataFolder NewFIFO NewFIFOChan NewFreeAxis NewGizmo NewImage NewLayout NewMovie NewNotebook NewPanel NewPath NewWaterfall Note Notebook NotebookAction Open OpenHelp OpenNotebook Optimize PCA ParseOperationTemplate PathInfo PauseForUser PauseUpdate PlayMovie PlayMovieAction PlaySound PopupContextualMenu PopupMenu Preferences PrimeFactors Print PrintGraphs PrintLayout PrintNotebook PrintSettings PrintTable Project PulseStats PutScrapText Quit RatioFromNumber Redimension Remez Remove RemoveContour RemoveFromGizmo RemoveFromGraph RemoveFromLayout RemoveFromTable RemoveImage RemoveLayoutObjects RemovePath Rename RenameDataFolder RenamePICT RenamePath RenameWindow ReorderImages ReorderTraces ReplaceText ReplaceWave Resample ResumeUpdate Reverse Rotate SQLHighLevelOp STFT Save SaveData SaveExperiment SaveGizmoCopy SaveGraphCopy SaveNotebook SavePICT SavePackagePreferences SaveTableCopy SetActiveSubwindow SetAxis SetBackground SetDashPattern SetDataFolder SetDimLabel SetDrawEnv SetDrawLayer SetFileFolderInfo SetFormula SetIdlePeriod SetIgorHook SetIgorMenuMode SetIgorOption SetMarquee SetProcessSleep SetRandomSeed SetScale SetVariable SetWaveLock SetWaveTextEncoding SetWindow ShowIgorMenus ShowInfo ShowTools Silent Sleep Slider Smooth SmoothCustom Sort SortColumns SoundInRecord SoundInSet SoundInStartChart SoundInStatus SoundInStopChart SoundLoadWave SoundSaveWave SphericalInterpolate SphericalTriangulate SplitString SplitWave Stack StackWindows StatsANOVA1Test StatsANOVA2NRTest StatsANOVA2RMTest StatsANOVA2Test StatsAngularDistanceTest StatsChiTest StatsCircularCorrelationTest StatsCircularMeans StatsCircularMoments StatsCircularTwoSampleTest StatsCochranTest StatsContingencyTable StatsDIPTest StatsDunnettTest StatsFTest StatsFriedmanTest StatsHodgesAjneTest StatsJBTest StatsKDE StatsKSTest StatsKWTest StatsKendallTauTest StatsLinearCorrelationTest StatsLinearRegression StatsMultiCorrelationTest StatsNPMCTest StatsNPNominalSRTest StatsQuantiles StatsRankCorrelationTest StatsResample StatsSRTest StatsSample StatsScheffeTest StatsShapiroWilkTest StatsSignTest StatsTTest StatsTukeyTest StatsVariancesTest StatsWRCorrelationTest StatsWatsonUSquaredTest StatsWatsonWilliamsTest StatsWheelerWatsonTest StatsWilcoxonRankTest String StructFill StructGet StructPut SumDimension SumSeries TDMLoadData TDMSaveData TabControl Tag TextBox ThreadGroupPutDF ThreadStart TickWavesFromAxis Tile TileWindows TitleBox ToCommandLine ToolsGrid Triangulate3d URLRequest Unwrap VDT2 VDTClosePort2 VDTGetPortList2 VDTGetStatus2 VDTOpenPort2 VDTOperationsPort2 VDTRead2 VDTReadBinary2 VDTReadBinaryWave2 VDTReadHex2 VDTReadHexWave2 VDTReadWave2 VDTTerminalPort2 VDTWrite2 VDTWriteBinary2 VDTWriteBinaryWave2 VDTWriteHex2 VDTWriteHexWave2 VDTWriteWave2 VISAControl VISARead VISAReadBinary VISAReadBinaryWave VISAReadWave VISAWrite VISAWriteBinary VISAWriteBinaryWave VISAWriteWave ValDisplay Variable WaveMeanStdv WaveStats WaveTransform WignerTransform WindowFunction XLLoadWave cd dir fprintf printf pwd sprintf sscanf wfprintf ) end def self.object_name /\b[a-z][a-z0-9_\.]*?\b/i end object = self.object_name noLineBreak = /(?:[ \t]|(?:\\\s*[\r\n]))+/ operator = %r([\#$~!%^&*+=\|?:<>/-]) punctuation = /[{}()\[\],.;]/ number_float= /0x[a-f0-9]+/i number_hex = /\d+\.\d+(e[\+\-]?\d+)?/ number_int = /[\d]+(?:_\d+)*/ state :root do rule %r(//), Comment, :comments rule /#{object}/ do |m| if m[0].downcase =~ /function/ token Keyword::Declaration push :parse_function elsif self.class.igorDeclarations.include? m[0].downcase token Keyword::Declaration push :parse_variables elsif self.class.keywords.include? m[0].downcase token Keyword elsif self.class.igorConstants.include? m[0].downcase token Keyword::Constant elsif self.class.igorFunction.include? m[0].downcase token Name::Builtin elsif self.class.igorOperation.include? m[0].downcase token Keyword::Reserved push :operationFlags elsif m[0].downcase =~ /\b(v|s|w)_[a-z]+[a-z0-9]*/ token Name::Constant else token Name end end mixin :preprocessor mixin :waveFlag mixin :characters mixin :numbers mixin :whitespace end state :preprocessor do rule %r((\#)(#{object})) do |m| if self.class.preprocessor.include? m[2].downcase token Comment::Preproc else token Punctuation, m[1] #i.e. ModuleFunctions token Name, m[2] end end end state :assignment do mixin :whitespace rule /\"/, Literal::String::Double, :string1 #punctuation for string mixin :string2 rule /#{number_float}/, Literal::Number::Float, :pop! rule /#{number_int}/, Literal::Number::Integer, :pop! rule /[\(\[\{][^\)\]\}]+[\)\]\}]/, Generic, :pop! rule /[^\s\/\(]+/, Generic, :pop! rule(//) { pop! } end state :parse_variables do mixin :whitespace rule /[=]/, Punctuation, :assignment rule object, Name::Variable rule /[\[\]]/, Punctuation # optional variables in functions rule /[,]/, Punctuation, :parse_variables rule /\)/, Punctuation, :pop! # end of function rule %r([/][a-z]+)i, Keyword::Pseudo, :parse_variables rule(//) { pop! } end state :parse_function do rule %r([/][a-z]+)i, Keyword::Pseudo # only one flag mixin :whitespace rule object, Name::Function rule /[\(]/, Punctuation, :parse_variables rule(//) { pop! } end state :operationFlags do rule /#{noLineBreak}/, Text rule /[=]/, Punctuation, :assignment rule %r([/][a-z]+)i, Keyword::Pseudo, :operationFlags rule /(as)(\s*)(#{object})/i do groups Keyword::Type, Text, Name::Label end rule(//) { pop! } end # inline variable assignments (i.e. for Make) with strict syntax state :waveFlag do rule %r( (/(?:wave|X|Y)) (\s*)(=)(\s*) (#{object}) )ix do |m| token Keyword::Pseudo, m[1] token Text, m[2] token Punctuation, m[3] token Text, m[4] token Name::Variable, m[5] end end state :characters do rule /\s/, Text rule /#{operator}/, Operator rule /#{punctuation}/, Punctuation rule /\"/, Literal::String::Double, :string1 #punctuation for string mixin :string2 end state :numbers do rule /#{number_float}/, Literal::Number::Float rule /#{number_hex}/, Literal::Number::Hex rule /#{number_int}/, Literal::Number::Integer end state :whitespace do rule /#{noLineBreak}/, Text end state :string1 do rule /%\w\b/, Literal::String::Other rule /\\\\/, Literal::String::Escape rule /\\\"/, Literal::String::Escape rule /\\/, Literal::String::Escape rule /[^"]/, Literal::String rule /\"/, Literal::String::Double, :pop! #punctuation for string end state :string2 do rule /\'[^']*\'/, Literal::String::Single end state :comments do rule %r{([/]\s*)([@]\w+\b)}i do # doxygen comments groups Comment, Comment::Special end rule /[^\r\n]/, Comment rule(//) { pop! } 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/lexers/dart.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/dart.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Dart < RegexLexer title "Dart" desc "The Dart programming language (dartlang.com)" tag 'dart' filenames '*.dart' mimetypes 'text/x-dart' keywords = %w( as assert break case catch continue default do else finally for if in is new rethrow return super switch this throw try while with ) declarations = %w( abstract dynamic const external extends factory final get implements native operator set static typedef var ) types = %w(bool double Dynamic enum int num Object Set String void) imports = %w(import export library part\s*of part source) id = /[a-zA-Z_]\w*/ state :root do rule %r(^ (\s*(?:[a-zA-Z_][a-zA-Z\d_.\[\]]*\s+)+?) # return arguments ([a-zA-Z_][\w]*) # method name (\s*)(\() # signature start )mx do |m| # TODO: do this better, this shouldn't need a delegation delegate Dart, m[1] token Name::Function, m[2] token Text, m[3] token Punctuation, m[4] end rule /\s+/, Text rule %r(//.*?$), Comment::Single rule %r(/\*.*?\*/)m, Comment::Multiline rule /"/, Str, :dqs rule /'/, Str, :sqs rule /r"[^"]*"/, Str::Other rule /r'[^']*'/, Str::Other rule /##{id}*/i, Str::Symbol rule /@#{id}/, Name::Decorator rule /(?:#{keywords.join('|')})\b/, Keyword rule /(?:#{declarations.join('|')})\b/, Keyword::Declaration rule /(?:#{types.join('|')})\b/, Keyword::Type rule /(?:true|false|null)\b/, Keyword::Constant rule /(?:class|interface)\b/, Keyword::Declaration, :class rule /(?:#{imports.join('|')})\b/, Keyword::Namespace, :import rule /(\.)(#{id})/ do groups Operator, Name::Attribute end rule /#{id}:/, Name::Label rule /\$?#{id}/, Name rule /[~^*!%&\[\](){}<>\|+=:;,.\/?-]/, Operator rule /\d*\.\d+([eE]\-?\d+)?/, Num::Float rule /0x[\da-fA-F]+/, Num::Hex rule /\d+L?/, Num::Integer rule /\n/, Text end state :class do rule /\s+/m, Text rule id, Name::Class, :pop! end state :dqs do rule /"/, Str, :pop! rule /[^\\\$"]+/, Str mixin :string end state :sqs do rule /'/, Str, :pop! rule /[^\\\$']+/, Str mixin :string end state :import do rule /;/, Operator, :pop! rule /(?:show|hide)\b/, Keyword::Declaration mixin :root end state :string do mixin :interpolation rule /\\[nrt\"\'\\]/, Str::Escape end state :interpolation do rule /\$#{id}/, Str::Interpol rule /\$\{[^\}]+\}/, Str::Interpol 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/lexers/sass.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/sass.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers load_lexer 'sass/common.rb' class Sass < SassCommon include Indentation title "Sass" desc 'The Sass stylesheet language language (sass-lang.com)' tag 'sass' filenames '*.sass' mimetypes 'text/x-sass' id = /[\w-]+/ state :root do rule /[ \t]*\n/, Text rule(/[ \t]*/) { |m| token Text; indentation(m[0]) } end state :content do # block comments rule %r(//.*?$) do token Comment::Single pop!; starts_block :single_comment end rule %r(/[*].*?\n) do token Comment::Multiline pop!; starts_block :multi_comment end rule /@import\b/, Keyword, :import mixin :content_common rule %r(=#{id}), Name::Function, :value rule %r([+]#{id}), Name::Decorator, :value rule /:/, Name::Attribute, :old_style_attr rule(/(?=[^\[\n]+?:([^a-z]|$))/) { push :attribute } rule(//) { push :selector } end state :single_comment do rule /.*?$/, Comment::Single, :pop! end state :multi_comment do rule /.*?\n/, Comment::Multiline, :pop! end state :import do rule /[ \t]+/, Text rule /\S+/, Str rule /\n/, Text, :pop! end state :old_style_attr do mixin :attr_common rule(//) { pop!; push :value } end state :end_section do rule(/\n/) { token Text; reset_stack } 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/lexers/julia.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/julia.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Julia < RegexLexer title "Julia" desc "The Julia programming language" tag 'julia' aliases 'jl' filenames '*.jl' mimetypes 'text/x-julia', 'application/x-julia' def self.detect?(text) return true if text.shebang? 'julia' end BUILTINS = /\b(?: true | false | missing | nothing | Inf | Inf16 | Inf32 | Inf64 | NaN | NaN16 | NaN32 | NaN64 | stdout | stderr | stdin | devnull | pi | π | ℯ | im )\b/x KEYWORDS = /\b(?: function | return | module | import | export | if | else | elseif | end | for | in | isa | while | try | catch | const | local | global | using | struct | mutable struct | abstract type | finally | begin | do | quote | macro | for outer )\b/x TYPES = /\b(?: Int | UInt | Int8 | UInt8 | Int16 | UInt16 | Int32 | UInt32 | Int64 | UInt64 | Int128 | UInt128 | Float16 | Float32 | Float64 | Bool | BigInt | BigFloat | Complex | ComplexF16 | ComplexF32 | ComplexF64 | Missing | Nothing | Char | String | SubString | Regex | RegexMatch | Any | Type | DataType | UnionAll | (Abstract)?(Array|Vector|Matrix|VecOrMat) )\b/x OPERATORS = / \+ | = | - | \* | \/ | \\ | & | \| | \$ | ~ | \^ | % | ! | >>> | >> | << | && | \|\| | \+= | -= | \*= | \/= | \\= | ÷= | %= | \^= | &= | \|= | \$= | >>>= | >>= | <<= | == | != | ≠ | <= | ≤ | >= | ≥ | \. | :: | <: | -> | \? | \.\* | \.\^ | \.\\ | \.\/ | \\ | < | > | ÷ | >: | : | === | !== /x PUNCTUATION = / [ \[ \] { } \( \) , ; @ ] /x state :root do rule /\n/, Text rule /[^\S\n]+/, Text rule /#=/, Comment::Multiline, :blockcomment rule /#.*$/, Comment rule OPERATORS, Operator rule /\\\n/, Text rule /\\/, Text # functions rule /(function)((?:\s|\\\s)+)/ do groups Keyword, Name::Function push :funcname end # types rule /(type|typealias|abstract)((?:\s|\\\s)+)/ do groups Keyword, Name::Class push :typename end rule TYPES, Keyword::Type # keywords rule /(local|global|const)\b/, Keyword::Declaration rule KEYWORDS, Keyword rule BUILTINS, Name::Builtin # backticks rule /`.*?`/, Literal::String::Backtick # chars rule /'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,3}|\\u[a-fA-F0-9]{1,4}|\\U[a-fA-F0-9]{1,6}|[^\\\'\n])'/, Literal::String::Char # try to match trailing transpose rule /(?<=[.\w)\]])\'+/, Operator # strings rule /(?:[IL])"/, Literal::String, :string rule /[E]?"/, Literal::String, :string # names rule /@[\w.]+/, Name::Decorator rule /(?:[a-zA-Z_\u00A1-\uffff]|[\u1000-\u10ff])(?:[a-zA-Z_0-9\u00A1-\uffff]|[\u1000-\u10ff])*!*/, Name rule PUNCTUATION, Other # numbers rule /(\d+(_\d+)+\.\d*|\d*\.\d+(_\d+)+)([eEf][+-]?[0-9]+)?/, Literal::Number::Float rule /(\d+\.\d*|\d*\.\d+)([eEf][+-]?[0-9]+)?/, Literal::Number::Float rule /\d+(_\d+)+[eEf][+-]?[0-9]+/, Literal::Number::Float rule /\d+[eEf][+-]?[0-9]+/, Literal::Number::Float rule /0b[01]+(_[01]+)+/, Literal::Number::Bin rule /0b[01]+/, Literal::Number::Bin rule /0o[0-7]+(_[0-7]+)+/, Literal::Number::Oct rule /0o[0-7]+/, Literal::Number::Oct rule /0x[a-fA-F0-9]+(_[a-fA-F0-9]+)+/, Literal::Number::Hex rule /0x[a-fA-F0-9]+/, Literal::Number::Hex rule /\d+(_\d+)+/, Literal::Number::Integer rule /\d+/, Literal::Number::Integer end state :funcname do rule /[a-zA-Z_]\w*/, Name::Function, :pop! rule /\([^\s\w{]{1,2}\)/, Operator, :pop! rule /[^\s\w{]{1,2}/, Operator, :pop! end state :typename do rule /[a-zA-Z_]\w*/, Name::Class, :pop! end state :stringescape do rule /\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})/, Literal::String::Escape end state :blockcomment do rule /[^=#]/, Comment::Multiline rule /#=/, Comment::Multiline, :blockcomment rule /\=#/, Comment::Multiline, :pop! rule /[=#]/, Comment::Multiline end state :string do mixin :stringescape rule /"/, Literal::String, :pop! rule /\\\\|\\"|\\\n/, Literal::String::Escape # included here for raw strings rule /\$(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?/, Literal::String::Interpol rule /[^\\"$]+/, Literal::String # quotes, dollar signs, and backslashes must be parsed one at a time rule /["\\]/, Literal::String # unhandled string formatting sign rule /\$/, Literal::String 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/lexers/sqf.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/sqf.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class SQF < RegexLexer tag "sqf" filenames "*.sqf" title "SQF" desc "Status Quo Function, a Real Virtuality engine scripting language" def self.wordoperators @wordoperators ||= Set.new %w( and or not ) end def self.initializers @initializers ||= Set.new %w( private param params ) end def self.controlflow @controlflow ||= Set.new %w( if then else exitwith switch do case default while for from to step foreach ) end def self.constants @constants ||= Set.new %w( true false player confignull controlnull displaynull grpnull locationnull netobjnull objnull scriptnull tasknull teammembernull ) end def self.namespaces @namespaces ||= Set.new %w( currentnamespace missionnamespace parsingnamespace profilenamespace uinamespace ) end def self.diag_commands @diag_commands ||= Set.new %w( diag_activemissionfsms diag_activesqfscripts diag_activesqsscripts diag_activescripts diag_captureframe diag_captureframetofile diag_captureslowframe diag_codeperformance diag_drawmode diag_enable diag_enabled diag_fps diag_fpsmin diag_frameno diag_lightnewload diag_list diag_log diag_logslowframe diag_mergeconfigfile diag_recordturretlimits diag_setlightnew diag_ticktime diag_toggle ) end def self.commands load Pathname.new(__FILE__).dirname.join("sqf/commands.rb") @commands = self.commands end state :root do # Whitespace rule %r"\s+", Text # Preprocessor instructions rule %r"/\*.*?\*/"m, Comment::Multiline rule %r"//.*\n", Comment::Single rule %r"#(define|undef|if(n)?def|else|endif|include)", Comment::Preproc rule %r"\\\r?\n", Comment::Preproc rule %r"__(EVAL|EXEC|LINE__|FILE__)", Name::Builtin # Literals rule %r"\".*?\"", Literal::String rule %r"'.*?'", Literal::String rule %r"(\$|0x)[0-9a-fA-F]+", Literal::Number::Hex rule %r"[0-9]+(\.)?(e[0-9]+)?", Literal::Number::Float # Symbols rule %r"[\!\%\&\*\+\-\/\<\=\>\^\|\#]", Operator rule %r"[\(\)\{\}\[\]\,\:\;]", Punctuation # Identifiers (variables and functions) rule %r"[a-zA-Z0-9_]+" do |m| name = m[0].downcase if self.class.wordoperators.include? name token Operator::Word elsif self.class.initializers.include? name token Keyword::Declaration elsif self.class.controlflow.include? name token Keyword::Reserved elsif self.class.constants.include? name token Keyword::Constant elsif self.class.namespaces.include? name token Keyword::Namespace elsif self.class.diag_commands.include? name token Name::Function elsif self.class.commands.include? name token Name::Function elsif %r"_.+" =~ name token Name::Variable else token Name::Variable::Global end 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/lexers/ocaml.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/ocaml.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class OCaml < RegexLexer title "OCaml" desc 'Objective Caml (ocaml.org)' tag 'ocaml' filenames '*.ml', '*.mli', '*.mll', '*.mly' mimetypes 'text/x-ocaml' def self.keywords @keywords ||= Set.new %w( as assert begin class constraint do done downto else end exception external false for fun function functor if in include inherit initializer lazy let match method module mutable new nonrec object of open private raise rec sig struct then to true try type val virtual when while with ) end def self.word_operators @word_operators ||= Set.new %w(and asr land lor lsl lxor mod or) end def self.primitives @primitives ||= Set.new %w(unit int float bool string char list array) end operator = %r([;,_!$%&*+./:<=>?@^|~#-]+) id = /[a-z_][\w']*/i upper_id = /[A-Z][\w']*/ state :root do rule /\s+/m, Text rule /false|true|[(][)]|\[\]/, Name::Builtin::Pseudo rule /#{upper_id}(?=\s*[.])/, Name::Namespace, :dotted rule /`#{id}/, Name::Tag rule upper_id, Name::Class rule /[(][*](?![)])/, Comment, :comment rule id do |m| match = m[0] if self.class.keywords.include? match token Keyword elsif self.class.word_operators.include? match token Operator::Word elsif self.class.primitives.include? match token Keyword::Type else token Name end end rule /[(){}\[\];]+/, Punctuation rule operator, Operator rule /-?\d[\d_]*(.[\d_]*)?(e[+-]?\d[\d_]*)/i, Num::Float rule /0x\h[\h_]*/i, Num::Hex rule /0o[0-7][0-7_]*/i, Num::Oct rule /0b[01][01_]*/i, Num::Bin rule /\d[\d_]*/, Num::Integer rule /'(?:(\\[\\"'ntbr ])|(\\[0-9]{3})|(\\x\h{2}))'/, Str::Char rule /'[.]'/, Str::Char rule /'/, Keyword rule /"/, Str::Double, :string rule /[~?]#{id}/, Name::Variable end state :comment do rule /[^(*)]+/, Comment rule(/[(][*]/) { token Comment; push } rule /[*][)]/, Comment, :pop! rule /[(*)]/, Comment end state :string do rule /[^\\"]+/, Str::Double mixin :escape_sequence rule /\\\n/, Str::Double rule /"/, Str::Double, :pop! end state :escape_sequence do rule /\\[\\"'ntbr]/, Str::Escape rule /\\\d{3}/, Str::Escape rule /\\x\h{2}/, Str::Escape end state :dotted do rule /\s+/m, Text rule /[.]/, Punctuation rule /#{upper_id}(?=\s*[.])/, Name::Namespace rule upper_id, Name::Class, :pop! rule id, Name, :pop! rule /[({\[]/, Punctuation, :pop! 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/lexers/idlang.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/idlang.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true # vim: set ts=2 sw=2 et: module Rouge module Lexers class IDLang < RegexLexer title "IDL" desc "Interactive Data Language" tag 'idlang' filenames '*.idl' name = /[_A-Z]\w*/i kind_param = /(\d+|#{name})/ exponent = /[dDeE][+-]\d+/ def self.exec_unit @exec_unit ||= Set.new %w( PRO FUNCTION ) end def self.keywords @keywords ||= Set.new %w( STRUCT INHERITS RETURN CONTINUE BEGIN END BREAK GOTO ) end def self.standalone_statements # Must not have a comma afterwards @standalone_statements ||= Set.new %w( COMMON FORWARD_FUNCTION ) end def self.decorators # Must not have a comma afterwards @decorators ||= Set.new %w( COMPILE_OPT ) end def self.operators @operators ||= Set.new %w( AND= EQ= GE= GT= LE= LT= MOD= NE= OR= XOR= NOT= ) end def self.conditionals @conditionals ||= Set.new %w( OF DO ENDIF ENDELSE ENDFOR ENDFOREACH ENDWHILE ENDREP ENDCASE ENDSWITCH IF THEN ELSE FOR FOREACH WHILE REPEAT UNTIL CASE SWITCH AND EQ GE GT LE LT MOD NE OR XOR NOT ) end def self.routines @routines ||= Set.new %w( A_CORRELATE ABS ACOS ADAPT_HIST_EQUAL ALOG ALOG10 AMOEBA ANNOTATE ARG_PRESENT ARRAY_EQUAL ARRAY_INDICES ARROW ASCII_TEMPLATE ASIN ASSOC ATAN AXIS BAR_PLOT BESELI BESELJ BESELK BESELY BETA BILINEAR BIN_DATE BINARY_TEMPLATE BINDGEN BINOMIAL BLAS_AXPY BLK_CON BOX_CURSOR BREAK BREAKPOINT BROYDEN BYTARR BYTE BYTEORDER BYTSCL C_CORRELATE CALDAT CALENDAR CALL_EXTERNAL CALL_FUNCTION CALL_METHOD CALL_PROCEDURE CATCH CD CEIL CHEBYSHEV CHECK_MATH CHISQR_CVF CHISQR_PDF CHOLDC CHOLSOL CINDGEN CIR_3PNT CLOSE CLUST_WTS CLUSTER COLOR_CONVERT COLOR_QUAN COLORMAP_APPLICABLE COMFIT COMPLEX COMPLEXARR COMPLEXROUND COMPUTE_MESH_NORMALS COND CONGRID CONJ CONSTRAINED_MIN CONTOUR CONVERT_COORD CONVOL COORD2TO3 CORRELATE COS COSH CRAMER CREATE_STRUCT CREATE_VIEW CROSSP CRVLENGTH CT_LUMINANCE CTI_TEST CURSOR CURVEFIT CV_COORD CVTTOBM CW_ANIMATE CW_ANIMATE_GETP CW_ANIMATE_LOAD CW_ANIMATE_RUN CW_ARCBALL CW_BGROUP CW_CLR_INDEX CW_COLORSEL CW_DEFROI CW_FIELD CW_FILESEL CW_FORM CW_FSLIDER CW_LIGHT_EDITOR CW_LIGHT_EDITOR_GET CW_LIGHT_EDITOR_SET CW_ORIENT CW_PALETTE_EDITOR CW_PALETTE_EDITOR_GET CW_PALETTE_EDITOR_SET CW_PDMENU CW_RGBSLIDER CW_TMPL CW_ZOOM DBLARR DCINDGEN DCOMPLEX DCOMPLEXARR DEFINE_KEY DEFROI DEFSYSV DELETE_SYMBOL DELLOG DELVAR DERIV DERIVSIG DETERM DEVICE DFPMIN DIALOG_MESSAGE DIALOG_PICKFILE DIALOG_PRINTERSETUP DIALOG_PRINTJOB DIALOG_READ_IMAGE DIALOG_WRITE_IMAGE DICTIONARY DIGITAL_FILTER DILATE DINDGEN DISSOLVE DIST DLM_LOAD DLM_REGISTER DO_APPLE_SCRIPT DOC_LIBRARY DOUBLE DRAW_ROI EFONT EIGENQL EIGENVEC ELMHES EMPTY ENABLE_SYSRTN EOF ERASE ERODE ERRORF ERRPLOT EXECUTE EXIT EXP EXPAND EXPAND_PATH EXPINT EXTRAC EXTRACT_SLICE F_CVF F_PDF FACTORIAL FFT FILE_CHMOD FILE_DELETE FILE_EXPAND_PATH FILE_MKDIR FILE_TEST FILE_WHICH FILE_SEARCH PATH_SEP FILE_DIRNAME FILE_BASENAME FILE_INFO FILE_MOVE FILE_COPY FILE_LINK FILE_POLL_INPUT FILEPATH FINDFILE FINDGEN FINITE FIX FLICK FLOAT FLOOR FLOW3 FLTARR FLUSH FORMAT_AXIS_VALUES FORWARD_FUNCTION FREE_LUN FSTAT FULSTR FUNCT FV_TEST FX_ROOT FZ_ROOTS GAMMA GAMMA_CT GAUSS_CVF GAUSS_PDF GAUSS2DFIT GAUSSFIT GAUSSINT GET_DRIVE_LIST GET_KBRD GET_LUN GET_SCREEN_SIZE GET_SYMBOL GETENV GOTO GREG2JUL GRID_TPS GRID3 GS_ITER H_EQ_CT H_EQ_INT HANNING HASH HEAP_GC HELP HILBERT HIST_2D HIST_EQUAL HISTOGRAM HLS HOUGH HQR HSV IBETA IDENTITY IDL_CONTAINER IDLANROI IDLANROIGROUP IDLFFDICOM IDLFFDXF IDLFFLANGUAGECAT IDLFFSHAPE IDLGRAXIS IDLGRBUFFER IDLGRCLIPBOARD IDLGRCOLORBAR IDLGRCONTOUR IDLGRFONT IDLGRIMAGE IDLGRLEGEND IDLGRLIGHT IDLGRMODEL IDLGRMPEG IDLGRPALETTE IDLGRPATTERN IDLGRPLOT IDLGRPOLYGON IDLGRPOLYLINE IDLGRPRINTER IDLGRROI IDLGRROIGROUP IDLGRSCENE IDLGRSURFACE IDLGRSYMBOL IDLGRTESSELLATOR IDLGRTEXT IDLGRVIEW IDLGRVIEWGROUP IDLGRVOLUME IDLGRVRML IDLGRWINDOW IGAMMA IMAGE_CONT IMAGE_STATISTICS IMAGINARY INDGEN INT_2D INT_3D INT_TABULATED INTARR INTERPOL INTERPOLATE INVERT IOCTL ISA ISHFT ISOCONTOUR ISOSURFACE JOURNAL JUL2GREG JULDAY KEYWORD_SET KRIG2D KURTOSIS KW_TEST L64INDGEN LABEL_DATE LABEL_REGION LADFIT LAGUERRE LEEFILT LEGENDRE LINBCG LINDGEN LINFIT LINKIMAGE LIST LIVE_CONTOUR LIVE_CONTROL LIVE_DESTROY LIVE_EXPORT LIVE_IMAGE LIVE_INFO LIVE_LINE LIVE_LOAD LIVE_OPLOT LIVE_PLOT LIVE_PRINT LIVE_RECT LIVE_STYLE LIVE_SURFACE LIVE_TEXT LJLCT LL_ARC_DISTANCE LMFIT LMGR LNGAMMA LNP_TEST LOADCT LOCALE_GET LON64ARR LONARR LONG LONG64 LSODE LU_COMPLEX LUDC LUMPROVE LUSOL M_CORRELATE MACHAR MAKE_ARRAY MAKE_DLL MAP_2POINTS MAP_CONTINENTS MAP_GRID MAP_IMAGE MAP_PATCH MAP_PROJ_INFO MAP_SET MAX MATRIX_MULTIPLY MD_TEST MEAN MEANABSDEV MEDIAN MEMORY MESH_CLIP MESH_DECIMATE MESH_ISSOLID MESH_MERGE MESH_NUMTRIANGLES MESH_OBJ MESH_SMOOTH MESH_SURFACEAREA MESH_VALIDATE MESH_VOLUME MESSAGE MIN MIN_CURVE_SURF MK_HTML_HELP MODIFYCT MOMENT MORPH_CLOSE MORPH_DISTANCE MORPH_GRADIENT MORPH_HITORMISS MORPH_OPEN MORPH_THIN MORPH_TOPHAT MPEG_CLOSE MPEG_OPEN MPEG_PUT MPEG_SAVE MSG_CAT_CLOSE MSG_CAT_COMPILE MSG_CAT_OPEN MULTI N_ELEMENTS N_PARAMS N_TAGS NEWTON NORM OBJ_CLASS OBJ_DESTROY OBJ_ISA OBJ_NEW OBJ_VALID OBJARR ON_ERROR ON_IOERROR ONLINE_HELP OPEN OPENR OPENW OPENU OPLOT OPLOTERR ORDEREDHASH P_CORRELATE PARTICLE_TRACE PCOMP PLOT PLOT_3DBOX PLOT_FIELD PLOTERR PLOTS PNT_LINE POINT_LUN POLAR_CONTOUR POLAR_SURFACE POLY POLY_2D POLY_AREA POLY_FIT POLYFILL POLYFILLV POLYSHADE POLYWARP POPD POWELL PRIMES PRINT PRINTF PRINTD PRODUCT PROFILE PROFILER PROFILES PROJECT_VOL PS_SHOW_FONTS PSAFM PSEUDO PTR_FREE PTR_NEW PTR_VALID PTRARR PUSHD QROMB QROMO QSIMP QUERY_CSV R_CORRELATE R_TEST RADON RANDOMN RANDOMU RANKS RDPIX READ READF READ_ASCII READ_BINARY READ_BMP READ_CSV READ_DICOM READ_IMAGE READ_INTERFILE READ_JPEG READ_PICT READ_PNG READ_PPM READ_SPR READ_SRF READ_SYLK READ_TIFF READ_WAV READ_WAVE READ_X11_BITMAP READ_XWD READS READU REBIN RECALL_COMMANDS RECON3 REDUCE_COLORS REFORM REGRESS REPLICATE REPLICATE_INPLACE RESOLVE_ALL RESOLVE_ROUTINE RESTORE RETALL REVERSE REWIND RK4 ROBERTS ROT ROTATE ROUND ROUTINE_INFO RS_TEST S_TEST SAVE SAVGOL SCALE3 SCALE3D SCOPE_LEVEL SCOPE_TRACEBACK SCOPE_VARFETCH SCOPE_VARNAME SEARCH2D SEARCH3D SET_PLOT SET_SHADING SET_SYMBOL SETENV SETLOG SETUP_KEYS SFIT SHADE_SURF SHADE_SURF_IRR SHADE_VOLUME SHIFT SHOW3 SHOWFONT SIGNUM SIN SINDGEN SINH SIZE SKEWNESS SKIPF SLICER3 SLIDE_IMAGE SMOOTH SOBEL SOCKET SORT SPAWN SPH_4PNT SPH_SCAT SPHER_HARM SPL_INIT SPL_INTERP SPLINE SPLINE_P SPRSAB SPRSAX SPRSIN SPRSTP SQRT STANDARDIZE STDDEV STOP STRARR STRCMP STRCOMPRESS STREAMLINE STREGEX STRETCH STRING STRJOIN STRLEN STRLOWCASE STRMATCH STRMESSAGE STRMID STRPOS STRPUT STRSPLIT STRTRIM STRUCT_ASSIGN STRUCT_HIDE STRUPCASE SURFACE SURFR SVDC SVDFIT SVSOL SWAP_ENDIAN SWITCH SYSTIME T_CVF T_PDF T3D TAG_NAMES TAN TANH TAPRD TAPWRT TEK_COLOR TEMPORARY TETRA_CLIP TETRA_SURFACE TETRA_VOLUME THIN THREED TIME_TEST2 TIMEGEN TM_TEST TOTAL TRACE TRANSPOSE TRI_SURF TRIANGULATE TRIGRID TRIQL TRIRED TRISOL TRNLOG TS_COEF TS_DIFF TS_FCAST TS_SMOOTH TV TVCRS TVLCT TVRD TVSCL TYPENAME UINDGEN UINT UINTARR UL64INDGEN ULINDGEN ULON64ARR ULONARR ULONG ULONG64 UNIQ USERSYM VALUE_LOCATE VARIANCE VAX_FLOAT VECTOR_FIELD VEL VELOVECT VERT_T3D VOIGT VORONOI VOXEL_PROJ WAIT WARP_TRI WATERSHED WDELETE WEOF WF_DRAW WHERE WIDGET_BASE WIDGET_BUTTON WIDGET_CONTROL WIDGET_DRAW WIDGET_DROPLIST WIDGET_EVENT WIDGET_INFO WIDGET_LABEL WIDGET_LIST WIDGET_SLIDER WIDGET_TABLE WIDGET_TEXT WINDOW WRITE_BMP WRITE_CSV WRITE_IMAGE WRITE_JPEG WRITE_NRIF WRITE_PICT WRITE_PNG WRITE_PPM WRITE_SPR WRITE_SRF WRITE_SYLK WRITE_TIFF WRITE_WAV WRITE_WAVE WRITEU WSET WSHOW WTN WV_APPLET WV_CW_WAVELET WV_CWT WV_DENOISE WV_DWT WV_FN_COIFLET WV_FN_DAUBECHIES WV_FN_GAUSSIAN WV_FN_HAAR WV_FN_MORLET WV_FN_PAUL WV_FN_SYMLET WV_IMPORT_DATA WV_IMPORT_WAVELET WV_PLOT3D_WPS WV_PLOT_MULTIRES WV_PWT WV_TOOL_DENOISE XBM_EDIT XDISPLAYFILE XDXF XFONT XINTERANIMATE XLOADCT XMANAGER XMNG_TMPL XMTOOL XOBJVIEW XPALETTE XPCOLOR XPLOT3D XREGISTERED XROI XSQ_TEST XSURFACE XVAREDIT XVOLUME XVOLUME_ROTATE XVOLUME_WRITE_IMAGE XYOUTS ZOOM ZOOM_24 ) end state :root do rule /[\s\n]+/, Text::Whitespace # Normal comments rule /;.*$/, Comment::Single rule /\,\s*\,/, Error rule /\!#{name}/, Name::Variable::Global rule /[(),:\&\$]/, Punctuation ## Format statements are quite a strange beast. ## Better process them in their own state. #rule /\b(FORMAT)(\s*)(\()/mi do |m| # token Keyword, m[1] # token Text::Whitespace, m[2] # token Punctuation, m[3] # push :format_spec #end rule %r( [+-]? # sign ( (\d+[.]\d*|[.]\d+)(#{exponent})? | \d+#{exponent} # exponent is mandatory ) (_#{kind_param})? # kind parameter )xi, Num::Float rule /\d+(B|S|U|US|LL|L|ULL|UL)?/i, Num::Integer rule /"[0-7]+(B|O|U|ULL|UL|LL|L)?/i, Num::Oct rule /'[0-9A-F]+'X(B|S|US|ULL|UL|U|LL|L)?/i, Num::Hex rule /(#{kind_param}_)?'/, Str::Single, :string_single rule /(#{kind_param}_)?"/, Str::Double, :string_double rule %r{\#\#|\#|\&\&|\|\||/=|<=|>=|->|\@|\?|[-+*/<=~^{}]}, Operator # Structures and the like rule /(#{name})(\.)([^\s,]*)/i do |m| groups Name, Operator, Name #delegate IDLang, m[3] end rule /(function|pro)((?:\s|\$\s)+)/i do groups Keyword, Text::Whitespace push :funcname end rule /#{name}/m do |m| match = m[0].upcase if self.class.keywords.include? match token Keyword elsif self.class.conditionals.include? match token Keyword elsif self.class.decorators.include? match token Name::Decorator elsif self.class.standalone_statements.include? match token Keyword::Reserved elsif self.class.operators.include? match token Operator::Word elsif self.class.routines.include? match token Name::Builtin else token Name end end end state :funcname do rule /#{name}/, Name::Function rule /\s+/, Text::Whitespace rule /(:+|\$)/, Operator rule /;.*/, Comment::Single # Be done with this state if we hit EOL or comma rule /$/, Text::Whitespace, :pop! rule /,/, Operator, :pop! end state :string_single do rule /[^']+/, Str::Single rule /''/, Str::Escape rule /'/, Str::Single, :pop! end state :string_double do rule /[^"]+/, Str::Double rule /"/, Str::Double, :pop! end state :format_spec do rule /'/, Str::Single, :string_single rule /"/, Str::Double, :string_double rule /\(/, Punctuation, :format_spec rule /\)/, Punctuation, :pop! rule /,/, Punctuation rule /[\s\n]+/, Text::Whitespace # Edit descriptors could be seen as a kind of "format literal". rule /[^\s'"(),]+/, Literal 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/lexers/jsx.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/jsx.rb
# frozen_string_literal: true module Rouge module Lexers load_lexer 'javascript.rb' class JSX < Javascript title 'JSX' desc 'React JSX (https://facebook.github.io/react/)' tag 'jsx' aliases 'jsx', 'react' filenames '*.jsx' mimetypes 'text/x-jsx', 'application/x-jsx' id = Javascript.id_regex def start_embed! @embed ||= JSX.new(options) @embed.reset! @embed.push(:expr_start) push :jsx_embed_root end def tag_token(name) name[0] =~ /\p{Lower}/ ? Name::Tag : Name::Class end start { @html = HTML.new(options) } state :jsx_tags do rule /</, Punctuation, :jsx_element end state :jsx_internal do rule %r(</) do token Punctuation goto :jsx_end_tag end rule /{/ do token Str::Interpol start_embed! end rule /[^<>{]+/ do delegate @html end mixin :jsx_tags end prepend :expr_start do mixin :jsx_tags end state :jsx_tag do mixin :comments_and_whitespace rule /#{id}/ do |m| token tag_token(m[0]) end rule /[.]/, Punctuation end state :jsx_end_tag do mixin :jsx_tag rule />/, Punctuation, :pop! end state :jsx_element do rule /#{id}=/, Name::Attribute, :jsx_attribute mixin :jsx_tag rule />/ do token Punctuation; goto :jsx_internal end rule %r(/>), Punctuation, :pop! end state :jsx_attribute do rule /"(\\[\\"]|[^"])*"/, Str::Double, :pop! rule /'(\\[\\']|[^'])*'/, Str::Single, :pop! rule /{/ do token Str::Interpol pop! start_embed! end end state :jsx_embed_root do rule /[.][.][.]/, Punctuation rule /}/, Str::Interpol, :pop! mixin :jsx_embed end state :jsx_embed do rule /{/ do delegate @embed; push :jsx_embed end rule /}/ do delegate @embed; pop! end rule /[^{}]+/ do delegate @embed 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/lexers/elixir.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/elixir.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers # Direct port of pygments Lexer. # See: https://bitbucket.org/birkenfeld/pygments-main/src/7304e4759ae65343d89a51359ca538912519cc31/pygments/lexers/functional.py?at=default#cl-2362 class Elixir < RegexLexer title "Elixir" desc "Elixir language (elixir-lang.org)" tag 'elixir' aliases 'elixir', 'exs' filenames '*.ex', '*.exs' mimetypes 'text/x-elixir', 'application/x-elixir' state :root do rule /\s+/m, Text rule /#.*$/, Comment::Single rule %r{\b(case|cond|end|bc|lc|if|unless|try|loop|receive|fn|defmodule| defp?|defprotocol|defimpl|defrecord|defmacrop?|defdelegate| defexception|defguardp?|defstruct|exit|raise|throw|after|rescue|catch|else)\b(?![?!])| (?<!\.)\b(do|\-\>)\b}x, Keyword rule /\b(import|require|use|recur|quote|unquote|super|refer)\b(?![?!])/, Keyword::Namespace rule /(?<!\.)\b(and|not|or|when|xor|in)\b/, Operator::Word rule %r{%=|\*=|\*\*=|\+=|\-=|\^=|\|\|=| <=>|<(?!<|=)|>(?!<|=|>)|<=|>=|===|==|=~|!=|!~|(?=[\s\t])\?| (?<=[\s\t])!+|&(&&?|(?!\d))|\|\||\^|\*|\+|\-|/| \||\+\+|\-\-|\*\*|\/\/|\<\-|\<\>|<<|>>|=|\.|~~~}x, Operator rule %r{(?<!:)(:)([a-zA-Z_]\w*([?!]|=(?![>=]))?|\<\>|===?|>=?|<=?| <=>|&&?|%\(\)|%\[\]|%\{\}|\+\+?|\-\-?|\|\|?|\!|//|[%&`/\|]| \*\*?|=?~|<\-)|([a-zA-Z_]\w*([?!])?)(:)(?!:)}, Str::Symbol rule /:"/, Str::Symbol, :interpoling_symbol rule /\b(nil|true|false)\b(?![?!])|\b[A-Z]\w*\b/, Name::Constant rule /\b(__(FILE|LINE|MODULE|MAIN|FUNCTION)__)\b(?![?!])/, Name::Builtin::Pseudo rule /[a-zA-Z_!][\w_]*[!\?]?/, Name rule %r{::|[%(){};,/\|:\\\[\]]}, Punctuation rule /@[a-zA-Z_]\w*|&\d/, Name::Variable rule %r{\b(0[xX][0-9A-Fa-f]+|\d(_?\d)*(\.(?![^\d\s]) (_?\d)*)?([eE][-+]?\d(_?\d)*)?|0[bB][01]+)\b}x, Num mixin :strings mixin :sigil_strings end state :strings do rule /(%[A-Ba-z])?"""(?:.|\n)*?"""/, Str::Doc rule /'''(?:.|\n)*?'''/, Str::Doc rule /"/, Str::Doc, :dqs rule /'.*?'/, Str::Single rule %r{(?<!\w)\?(\\(x\d{1,2}|\h{1,2}(?!\h)\b|0[0-7]{0,2}(?![0-7])\b[^x0MC])|(\\[MC]-)+\w|[^\s\\])}, Str::Other end state :dqs do rule /"/, Str::Double, :pop! mixin :enddoublestr end state :interpoling do rule /#\{/, Str::Interpol, :interpoling_string end state :interpoling_string do rule /\}/, Str::Interpol, :pop! mixin :root end state :interpoling_symbol do rule /"/, Str::Symbol, :pop! mixin :interpoling rule /[^#"]+/, Str::Symbol end state :enddoublestr do mixin :interpoling rule /[^#"]+/, Str::Double end state :sigil_strings do # ~-sigiled strings # ~(abc), ~[abc], ~<abc>, ~|abc|, ~r/abc/, etc # Cribbed and adjusted from Ruby lexer delimiter_map = { '{' => '}', '[' => ']', '(' => ')', '<' => '>' } # Match a-z for custom sigils too sigil_opens = Regexp.union(delimiter_map.keys + %w(| / ' ")) rule /~([A-Za-z])?(#{sigil_opens})/ do |m| open = Regexp.escape(m[2]) close = Regexp.escape(delimiter_map[m[2]] || m[2]) interp = /[SRCW]/ === m[1] toktype = Str::Other puts " open: #{open.inspect}" if @debug puts " close: #{close.inspect}" if @debug # regexes if 'Rr'.include? m[1] toktype = Str::Regex push :regex_flags end if 'Ww'.include? m[1] push :list_flags end token toktype push do rule /#{close}/, toktype, :pop! if interp mixin :interpoling rule /#/, toktype else rule /[\\#]/, toktype end rule /[^##{open}#{close}\\]+/m, toktype end end end state :regex_flags do rule /[fgimrsux]*/, Str::Regex, :pop! end state :list_flags do rule /[csa]?/, Str::Other, :pop! 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/lexers/mxml.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/mxml.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class MXML < RegexLexer title "MXML" desc "MXML" tag 'mxml' filenames '*.mxml' mimetypes 'application/xv+xml' state :root do rule /[^<&]+/, Text rule /&\S*?;/, Name::Entity rule /<!\[CDATA\[/m do token Comment::Preproc push :actionscript_content end rule /<!--/, Comment, :comment rule /<\?.*?\?>/, Comment::Preproc rule /<![^>]*>/, Comment::Preproc rule %r(<\s*[\w:.-]+)m, Name::Tag, :tag # opening tags rule %r(<\s*/\s*[\w:.-]+\s*>)m, Name::Tag # closing tags end state :comment do rule /[^-]+/m, Comment rule /-->/, Comment, :pop! rule /-/, Comment end state :tag do rule /\s+/m, Text rule /[\w.:-]+\s*=/m, Name::Attribute, :attribute rule %r(/?\s*>), Name::Tag, :root end state :attribute do rule /\s+/m, Text rule /(")({|@{)/m do groups Str, Punctuation push :actionscript_attribute end rule /".*?"|'.*?'|[^\s>]+/, Str, :tag end state :actionscript_content do rule /\]\]\>/m, Comment::Preproc, :pop! rule /.*?(?=\]\]\>)/m do delegate Actionscript end end state :actionscript_attribute do rule /(})(")/m do groups Punctuation, Str push :tag end rule /.*?(?=}")/m do delegate Actionscript 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/lexers/biml.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/biml.rb
# frozen_string_literal: true module Rouge module Lexers load_lexer 'xml.rb' class BIML < XML title "BIML" desc "BIML, Business Intelligence Markup Language" tag 'biml' filenames '*.biml' def self.detect?(text) return true if text =~ /<\s*Biml\b/ end prepend :root do rule %r(<#\@\s*)m, Name::Tag, :directive_tag rule %r(<#[=]?\s*)m, Name::Tag, :directive_as_csharp end prepend :attr do #TODO: how to deal with embedded <# tags inside a attribute string #rule %r("<#[=]?\s*)m, Name::Tag, :directive_as_csharp end state :directive_as_csharp do rule /\s*#>\s*/m, Name::Tag, :pop! rule %r(.*?(?=\s*#>\s*))m do delegate CSharp end end state :directive_tag do rule /\s+/m, Text rule /[\w.:-]+\s*=/m, Name::Attribute, :attr rule /[\w]+\s*/m, Name::Attribute rule %r(/?\s*#>), Name::Tag, :pop! 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/lexers/racket.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/racket.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Racket < RegexLexer title "Racket" desc "Racket is a Lisp descended from Scheme (racket-lang.org)" tag 'racket' filenames '*.rkt', '*.rktd', '*.rktl' mimetypes 'text/x-racket', 'application/x-racket' def self.detect?(text) text =~ /\A#lang\s*(.*?)$/ lang_attr = $1 return false unless lang_attr return true if lang_attr =~ /racket|scribble/ end def self.keywords @keywords ||= Set.new %w( ... and begin begin-for-syntax begin0 case case-lambda cond datum->syntax-object define define-for-syntax define-logger define-struct define-syntax define-syntax-rule define-syntaxes define-values define-values-for-syntax delay do expand-path fluid-let force hash-table-copy hash-table-count hash-table-for-each hash-table-get hash-table-iterate-first hash-table-iterate-key hash-table-iterate-next hash-table-iterate-value hash-table-map hash-table-put! hash-table-remove! hash-table? if lambda let let* let*-values let-struct let-syntax let-syntaxes let-values let/cc let/ec letrec letrec-syntax letrec-syntaxes letrec-syntaxes+values letrec-values list-immutable make-hash-table make-immutable-hash-table make-namespace module module* module-identifier=? module-label-identifier=? module-template-identifier=? module-transformer-identifier=? namespace-transformer-require or parameterize parameterize* parameterize-break promise? prop:method-arity-error provide provide-for-label provide-for-syntax quasiquote quasisyntax quasisyntax/loc quote quote-syntax quote-syntax/prune require require-for-label require-for-syntax require-for-template set! set!-values syntax syntax-case syntax-case* syntax-id-rules syntax-object->datum syntax-rules syntax/loc tcp-abandon-port tcp-accept tcp-accept-evt tcp-accept-ready? tcp-accept/enable-break tcp-addresses tcp-close tcp-connect tcp-connect/enable-break tcp-listen tcp-listener? tcp-port? time transcript-off transcript-on udp-addresses udp-bind! udp-bound? udp-close udp-connect! udp-connected? udp-multicast-interface udp-multicast-join-group! udp-multicast-leave-group! udp-multicast-loopback? udp-multicast-set-interface! udp-multicast-set-loopback! udp-multicast-set-ttl! udp-multicast-ttl udp-open-socket udp-receive! udp-receive!* udp-receive!-evt udp-receive!/enable-break udp-receive-ready-evt udp-send udp-send* udp-send-evt udp-send-ready-evt udp-send-to udp-send-to* udp-send-to-evt udp-send-to/enable-break udp-send/enable-break udp? unless unquote unquote-splicing unsyntax unsyntax-splicing when with-continuation-mark with-handlers with-handlers* with-syntax λ) end def self.builtins @builtins ||= Set.new %w( * + - / < <= = > >= abort-current-continuation abs absolute-path? acos add1 alarm-evt always-evt andmap angle append apply arithmetic-shift arity-at-least arity-at-least-value arity-at-least? asin assoc assq assv atan banner bitwise-and bitwise-bit-field bitwise-bit-set? bitwise-ior bitwise-not bitwise-xor boolean? bound-identifier=? box box-cas! box-immutable box? break-enabled break-thread build-path build-path/convention-type byte-pregexp byte-pregexp? byte-ready? byte-regexp byte-regexp? byte? bytes bytes->immutable-bytes bytes->list bytes->path bytes->path-element bytes->string/latin-1 bytes->string/locale bytes->string/utf-8 bytes-append bytes-close-converter bytes-convert bytes-convert-end bytes-converter? bytes-copy bytes-copy! bytes-environment-variable-name? bytes-fill! bytes-length bytes-open-converter bytes-ref bytes-set! bytes-utf-8-index bytes-utf-8-length bytes-utf-8-ref bytes<? bytes=? bytes>? bytes? caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar caddar cadddr caddr cadr call-in-nested-thread call-with-break-parameterization call-with-composable-continuation call-with-continuation-barrier call-with-continuation-prompt call-with-current-continuation call-with-default-reading-parameterization call-with-escape-continuation call-with-exception-handler call-with-immediate-continuation-mark call-with-input-file call-with-output-file call-with-parameterization call-with-semaphore call-with-semaphore/enable-break call-with-values call/cc call/ec car cdaaar cdaadr cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr cdr ceiling channel-get channel-put channel-put-evt channel-put-evt? channel-try-get channel? chaperone-box chaperone-continuation-mark-key chaperone-evt chaperone-hash chaperone-of? chaperone-procedure chaperone-prompt-tag chaperone-struct chaperone-struct-type chaperone-vector chaperone? char->integer char-alphabetic? char-blank? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-foldcase char-general-category char-graphic? char-iso-control? char-lower-case? char-numeric? char-punctuation? char-ready? char-symbolic? char-title-case? char-titlecase char-upcase char-upper-case? char-utf-8-length char-whitespace? char<=? char<? char=? char>=? char>? char? check-duplicate-identifier checked-procedure-check-and-extract choice-evt cleanse-path close-input-port close-output-port collect-garbage collection-file-path collection-path compile compile-allow-set!-undefined compile-context-preservation-enabled compile-enforce-module-constants compile-syntax compiled-expression? compiled-module-expression? complete-path? complex? cons continuation-mark-key? continuation-mark-set->context continuation-mark-set->list continuation-mark-set->list* continuation-mark-set-first continuation-mark-set? continuation-marks continuation-prompt-available? continuation-prompt-tag? continuation? copy-file cos current-break-parameterization current-code-inspector current-command-line-arguments current-compile current-compiled-file-roots current-continuation-marks current-custodian current-directory current-directory-for-user current-drive current-environment-variables current-error-port current-eval current-evt-pseudo-random-generator current-gc-milliseconds current-get-interaction-input-port current-inexact-milliseconds current-input-port current-inspector current-library-collection-paths current-load current-load-extension current-load-relative-directory current-load/use-compiled current-locale current-memory-use current-milliseconds current-module-declare-name current-module-declare-source current-module-name-resolver current-module-path-for-load current-namespace current-output-port current-parameterization current-preserved-thread-cell-values current-print current-process-milliseconds current-prompt-read current-pseudo-random-generator current-read-interaction current-reader-guard current-readtable current-seconds current-security-guard current-subprocess-custodian-mode current-thread current-thread-group current-thread-initial-stack-size current-write-relative-directory custodian-box-value custodian-box? custodian-limit-memory custodian-managed-list custodian-memory-accounting-available? custodian-require-memory custodian-shutdown-all custodian? custom-print-quotable-accessor custom-print-quotable? custom-write-accessor custom-write? date date* date*-nanosecond date*-time-zone-name date*? date-day date-dst? date-hour date-minute date-month date-second date-time-zone-offset date-week-day date-year date-year-day date? datum-intern-literal default-continuation-prompt-tag delete-directory delete-file denominator directory-exists? directory-list display displayln dump-memory-stats dynamic-require dynamic-require-for-syntax dynamic-wind environment-variables-copy environment-variables-names environment-variables-ref environment-variables-set! environment-variables? eof eof-object? ephemeron-value ephemeron? eprintf eq-hash-code eq? equal-hash-code equal-secondary-hash-code equal? equal?/recur eqv-hash-code eqv? error error-display-handler error-escape-handler error-print-context-length error-print-source-location error-print-width error-value->string-handler eval eval-jit-enabled eval-syntax even? evt? exact->inexact exact-integer? exact-nonnegative-integer? exact-positive-integer? exact? executable-yield-handler exit exit-handler exn exn-continuation-marks exn-message exn:break exn:break-continuation exn:break:hang-up exn:break:hang-up? exn:break:terminate exn:break:terminate? exn:break? exn:fail exn:fail:contract exn:fail:contract:arity exn:fail:contract:arity? exn:fail:contract:continuation exn:fail:contract:continuation? exn:fail:contract:divide-by-zero exn:fail:contract:divide-by-zero? exn:fail:contract:non-fixnum-result exn:fail:contract:non-fixnum-result? exn:fail:contract:variable exn:fail:contract:variable-id exn:fail:contract:variable? exn:fail:contract? exn:fail:filesystem exn:fail:filesystem:errno exn:fail:filesystem:errno-errno exn:fail:filesystem:errno? exn:fail:filesystem:exists exn:fail:filesystem:exists? exn:fail:filesystem:missing-module exn:fail:filesystem:missing-module-path exn:fail:filesystem:missing-module? exn:fail:filesystem:version exn:fail:filesystem:version? exn:fail:filesystem? exn:fail:network exn:fail:network:errno exn:fail:network:errno-errno exn:fail:network:errno? exn:fail:network? exn:fail:out-of-memory exn:fail:out-of-memory? exn:fail:read exn:fail:read-srclocs exn:fail:read:eof exn:fail:read:eof? exn:fail:read:non-char exn:fail:read:non-char? exn:fail:read? exn:fail:syntax exn:fail:syntax-exprs exn:fail:syntax:missing-module exn:fail:syntax:missing-module-path exn:fail:syntax:missing-module? exn:fail:syntax:unbound exn:fail:syntax:unbound? exn:fail:syntax? exn:fail:unsupported exn:fail:unsupported? exn:fail:user exn:fail:user? exn:fail? exn:missing-module-accessor exn:missing-module? exn:srclocs-accessor exn:srclocs? exn? exp expand expand-once expand-syntax expand-syntax-once expand-syntax-to-top-form expand-to-top-form expand-user-path explode-path expt file-exists? file-or-directory-identity file-or-directory-modify-seconds file-or-directory-permissions file-position file-position* file-size file-stream-buffer-mode file-stream-port? file-truncate filesystem-change-evt filesystem-change-evt-cancel filesystem-change-evt? filesystem-root-list find-executable-path find-library-collection-paths find-system-path fixnum? floating-point-bytes->real flonum? floor flush-output for-each format fprintf free-identifier=? gcd generate-temporaries gensym get-output-bytes get-output-string getenv global-port-print-handler guard-evt handle-evt handle-evt? hash hash-equal? hash-eqv? hash-has-key? hash-placeholder? hash-ref! hasheq hasheqv identifier-binding identifier-binding-symbol identifier-label-binding identifier-prune-lexical-context identifier-prune-to-source-module identifier-remove-from-definition-context identifier-template-binding identifier-transformer-binding identifier? imag-part immutable? impersonate-box impersonate-continuation-mark-key impersonate-hash impersonate-procedure impersonate-prompt-tag impersonate-struct impersonate-vector impersonator-ephemeron impersonator-of? impersonator-prop:application-mark impersonator-property-accessor-procedure? impersonator-property? impersonator? inexact->exact inexact-real? inexact? input-port? inspector? integer->char integer->integer-bytes integer-bytes->integer integer-length integer-sqrt integer-sqrt/remainder integer? internal-definition-context-seal internal-definition-context? keyword->string keyword<? keyword? kill-thread lcm length liberal-define-context? link-exists? list list* list->bytes list->string list->vector list-ref list-tail list? load load-extension load-on-demand-enabled load-relative load-relative-extension load/cd load/use-compiled local-expand local-expand/capture-lifts local-transformer-expand local-transformer-expand/capture-lifts locale-string-encoding log log-max-level magnitude make-arity-at-least make-bytes make-channel make-continuation-mark-key make-continuation-prompt-tag make-custodian make-custodian-box make-date make-date* make-derived-parameter make-directory make-environment-variables make-ephemeron make-exn make-exn:break make-exn:break:hang-up make-exn:break:terminate make-exn:fail make-exn:fail:contract make-exn:fail:contract:arity make-exn:fail:contract:continuation make-exn:fail:contract:divide-by-zero make-exn:fail:contract:non-fixnum-result make-exn:fail:contract:variable make-exn:fail:filesystem make-exn:fail:filesystem:errno make-exn:fail:filesystem:exists make-exn:fail:filesystem:missing-module make-exn:fail:filesystem:version make-exn:fail:network make-exn:fail:network:errno make-exn:fail:out-of-memory make-exn:fail:read make-exn:fail:read:eof make-exn:fail:read:non-char make-exn:fail:syntax make-exn:fail:syntax:missing-module make-exn:fail:syntax:unbound make-exn:fail:unsupported make-exn:fail:user make-file-or-directory-link make-hash-placeholder make-hasheq-placeholder make-hasheqv make-hasheqv-placeholder make-immutable-hasheqv make-impersonator-property make-input-port make-inspector make-known-char-range-list make-output-port make-parameter make-phantom-bytes make-pipe make-placeholder make-polar make-prefab-struct make-pseudo-random-generator make-reader-graph make-readtable make-rectangular make-rename-transformer make-resolved-module-path make-security-guard make-semaphore make-set!-transformer make-shared-bytes make-sibling-inspector make-special-comment make-srcloc make-string make-struct-field-accessor make-struct-field-mutator make-struct-type make-struct-type-property make-syntax-delta-introducer make-syntax-introducer make-thread-cell make-thread-group make-vector make-weak-box make-weak-hasheqv make-will-executor map max mcar mcdr mcons member memq memv min module->exports module->imports module->language-info module->namespace module-compiled-cross-phase-persistent? module-compiled-exports module-compiled-imports module-compiled-language-info module-compiled-name module-compiled-submodules module-declared? module-path-index-join module-path-index-resolve module-path-index-split module-path-index-submodule module-path-index? module-path? module-predefined? module-provide-protected? modulo mpair? nack-guard-evt namespace-attach-module namespace-attach-module-declaration namespace-base-phase namespace-mapped-symbols namespace-module-identifier namespace-module-registry namespace-require namespace-require/constant namespace-require/copy namespace-require/expansion-time namespace-set-variable-value! namespace-symbol->identifier namespace-syntax-introduce namespace-undefine-variable! namespace-unprotect-module namespace-variable-value namespace? negative? never-evt newline normal-case-path not null null? number->string number? numerator object-name odd? open-input-bytes open-input-file open-input-output-file open-input-string open-output-bytes open-output-file open-output-string ormap output-port? pair? parameter-procedure=? parameter? parameterization? path->bytes path->complete-path path->directory-path path->string path-add-suffix path-convention-type path-element->bytes path-element->string path-for-some-system? path-list-string->path-list path-replace-suffix path-string? path? peek-byte peek-byte-or-special peek-bytes peek-bytes! peek-bytes-avail! peek-bytes-avail!* peek-bytes-avail!/enable-break peek-char peek-char-or-special peek-string peek-string! phantom-bytes? pipe-content-length placeholder-get placeholder-set! placeholder? poll-guard-evt port-closed-evt port-closed? port-commit-peeked port-count-lines! port-count-lines-enabled port-counts-lines? port-display-handler port-file-identity port-file-unlock port-next-location port-print-handler port-progress-evt port-provides-progress-evts? port-read-handler port-try-file-lock? port-write-handler port-writes-atomic? port-writes-special? port? positive? prefab-key->struct-type prefab-key? prefab-struct-key pregexp pregexp? primitive-closure? primitive-result-arity primitive? print print-as-expression print-boolean-long-form print-box print-graph print-hash-table print-mpair-curly-braces print-pair-curly-braces print-reader-abbreviations print-struct print-syntax-width print-unreadable print-vector-length printf procedure->method procedure-arity procedure-arity-includes? procedure-arity? procedure-closure-contents-eq? procedure-extract-target procedure-reduce-arity procedure-rename procedure-struct-type? procedure? progress-evt? prop:arity-string prop:checked-procedure prop:custom-print-quotable prop:custom-write prop:equal+hash prop:evt prop:exn:missing-module prop:exn:srclocs prop:impersonator-of prop:input-port prop:liberal-define-context prop:output-port prop:procedure prop:rename-transformer prop:set!-transformer pseudo-random-generator->vector pseudo-random-generator-vector? pseudo-random-generator? putenv quotient quotient/remainder raise raise-argument-error raise-arguments-error raise-arity-error raise-mismatch-error raise-range-error raise-result-error raise-syntax-error raise-type-error raise-user-error random random-seed rational? rationalize read read-accept-bar-quote read-accept-box read-accept-compiled read-accept-dot read-accept-graph read-accept-infix-dot read-accept-lang read-accept-quasiquote read-accept-reader read-byte read-byte-or-special read-bytes read-bytes! read-bytes-avail! read-bytes-avail!* read-bytes-avail!/enable-break read-bytes-line read-case-sensitive read-char read-char-or-special read-curly-brace-as-paren read-decimal-as-inexact read-eval-print-loop read-language read-line read-on-demand-source read-square-bracket-as-paren read-string read-string! read-syntax read-syntax/recursive read/recursive readtable-mapping readtable? real->double-flonum real->floating-point-bytes real->single-flonum real-part real? regexp regexp-match regexp-match-peek regexp-match-peek-immediate regexp-match-peek-positions regexp-match-peek-positions-immediate regexp-match-peek-positions-immediate/end regexp-match-peek-positions/end regexp-match-positions regexp-match-positions/end regexp-match/end regexp-match? regexp-max-lookbehind regexp-replace regexp-replace* regexp? relative-path? remainder rename-file-or-directory rename-transformer-target rename-transformer? reroot-path resolve-path resolved-module-path-name resolved-module-path? reverse round seconds->date security-guard? semaphore-peek-evt semaphore-peek-evt? semaphore-post semaphore-try-wait? semaphore-wait semaphore-wait/enable-break semaphore? set!-transformer-procedure set!-transformer? set-box! set-mcar! set-mcdr! set-phantom-bytes! set-port-next-location! shared-bytes shell-execute simplify-path sin single-flonum? sleep special-comment-value special-comment? split-path sqrt srcloc srcloc->string srcloc-column srcloc-line srcloc-position srcloc-source srcloc-span srcloc? string string->bytes/latin-1 string->bytes/locale string->bytes/utf-8 string->immutable-string string->keyword string->list string->number string->path string->path-element string->symbol string->uninterned-symbol string->unreadable-symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-copy! string-downcase string-environment-variable-name? string-fill! string-foldcase string-length string-locale-ci<? string-locale-ci=? string-locale-ci>? string-locale-downcase string-locale-upcase string-locale<? string-locale=? string-locale>? string-normalize-nfc string-normalize-nfd string-normalize-nfkc string-normalize-nfkd string-ref string-set! string-titlecase string-upcase string-utf-8-length string<=? string<? string=? string>=? string>? string? struct->vector struct-accessor-procedure? struct-constructor-procedure? struct-info struct-mutator-procedure? struct-predicate-procedure? struct-type-info struct-type-make-constructor struct-type-make-predicate struct-type-property-accessor-procedure? struct-type-property? struct-type? struct:arity-at-least struct:date struct:date* struct:exn struct:exn:break struct:exn:break:hang-up struct:exn:break:terminate struct:exn:fail struct:exn:fail:contract struct:exn:fail:contract:arity struct:exn:fail:contract:continuation struct:exn:fail:contract:divide-by-zero struct:exn:fail:contract:non-fixnum-result struct:exn:fail:contract:variable struct:exn:fail:filesystem struct:exn:fail:filesystem:errno struct:exn:fail:filesystem:exists struct:exn:fail:filesystem:missing-module struct:exn:fail:filesystem:version struct:exn:fail:network struct:exn:fail:network:errno struct:exn:fail:out-of-memory struct:exn:fail:read struct:exn:fail:read:eof struct:exn:fail:read:non-char struct:exn:fail:syntax struct:exn:fail:syntax:missing-module struct:exn:fail:syntax:unbound struct:exn:fail:unsupported struct:exn:fail:user struct:srcloc struct? sub1 subbytes subprocess subprocess-group-enabled subprocess-kill subprocess-pid subprocess-status subprocess-wait subprocess? substring symbol->string symbol-interned? symbol-unreadable? symbol? sync sync/enable-break sync/timeout sync/timeout/enable-break syntax->list syntax-arm syntax-column syntax-disarm syntax-e syntax-line syntax-local-bind-syntaxes syntax-local-certifier syntax-local-context syntax-local-expand-expression syntax-local-get-shadower syntax-local-introduce syntax-local-lift-context syntax-local-lift-expression syntax-local-lift-module-end-declaration syntax-local-lift-provide syntax-local-lift-require syntax-local-lift-values-expression syntax-local-make-definition-context syntax-local-make-delta-introducer syntax-local-module-defined-identifiers syntax-local-module-exports syntax-local-module-required-identifiers syntax-local-name syntax-local-phase-level syntax-local-submodules syntax-local-transforming-module-provides? syntax-local-value syntax-local-value/immediate syntax-original? syntax-position syntax-property syntax-property-symbol-keys syntax-protect syntax-rearm syntax-recertify syntax-shift-phase-level syntax-source syntax-source-module syntax-span syntax-taint syntax-tainted? syntax-track-origin syntax-transforming-module-expression? syntax-transforming? syntax? system-big-endian? system-idle-evt system-language+country system-library-subpath system-path-convention-type system-type tan terminal-port? thread thread-cell-ref thread-cell-set! thread-cell-values? thread-cell? thread-dead-evt thread-dead? thread-group? thread-resume thread-resume-evt thread-rewind-receive thread-running? thread-suspend thread-suspend-evt thread-wait thread/suspend-to-kill thread? time-apply truncate unbox uncaught-exception-handler use-collection-link-paths use-compiled-file-paths use-user-specific-search-paths values variable-reference->empty-namespace variable-reference->module-base-phase variable-reference->module-declaration-inspector variable-reference->module-path-index variable-reference->module-source variable-reference->namespace variable-reference->phase variable-reference->resolved-module-path variable-reference-constant? variable-reference? vector vector->immutable-vector vector->list vector->pseudo-random-generator vector->pseudo-random-generator! vector->values vector-fill! vector-immutable vector-length vector-ref vector-set! vector-set-performance-stats! vector? version void void? weak-box-value weak-box? will-execute will-executor? will-register will-try-execute with-input-from-file with-output-to-file wrap-evt write write-byte write-bytes write-bytes-avail write-bytes-avail* write-bytes-avail-evt write-bytes-avail/enable-break write-char write-special write-special-avail* write-special-evt write-string zero? ) end # Since Racket allows identifiers to consist of nearly anything, # it's simpler to describe what an ID is _not_. id = /[^\s\(\)\[\]\{\}'`,.]+/i state :root do # comments rule /;.*$/, Comment::Single rule /\s+/m, Text rule /[+-]inf[.][f0]/, Num::Float rule /[+-]nan[.]0/, Num::Float rule /[-]min[.]0/, Num::Float rule /[+]max[.]0/, Num::Float rule /-?\d+\.\d+/, Num::Float rule /-?\d+/, Num::Integer rule /#:#{id}+/, Name::Tag # keyword rule /#b[01]+/, Num::Bin rule /#o[0-7]+/, Num::Oct rule /#d[0-9]+/, Num::Integer rule /#x[0-9a-f]+/i, Num::Hex rule /#[ei][\d.]+/, Num::Other rule /"(\\\\|\\"|[^"])*"/, Str rule /['`]#{id}/i, Str::Symbol rule /#\\([()\/'"._!\$%& ?=+-]{1}|[a-z0-9]+)/i, Str::Char rule /#t|#f/, Name::Constant rule /(?:'|#|`|,@|,|\.)/, Operator rule /(['#])(\s*)(\()/m do groups Str::Symbol, Text, Punctuation end # () [] {} are all permitted as like pairs rule /\(|\[|\{/, Punctuation, :command rule /\)|\]|\}/, Punctuation rule id, Name::Variable end state :command do rule id, Name::Function do |m| if self.class.keywords.include? m[0] token Keyword elsif self.class.builtins.include? m[0] token Name::Builtin else token Name::Function end pop! end rule(//) { pop! } 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/lexers/hack.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/hack.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers load_lexer 'php.rb' class Hack < PHP title 'Hack' desc 'The Hack programming language (hacklang.org)' tag 'hack' aliases 'hack', 'hh' filenames '*.php', '*.hh' def self.detect?(text) return true if /<\?hh/ =~ text return true if text.shebang?('hhvm') return true if /async function [a-zA-Z]/ =~ text return true if /\): Awaitable</ =~ text return false end def self.keywords @hh_keywords ||= super.merge Set.new %w( type newtype enum as super async await Awaitable vec dict keyset void int string bool float double arraykey num Stringish ) end prepend :template do rule /<\?hh(\s*\/\/\s*(strict|decl|partial))?$/, Comment::Preproc, :php end prepend :php do rule %r((/\*\s*)(HH_(?:IGNORE_ERROR|FIXME)\[\d+\])([^*]*)(\*/)) do groups Comment::Preproc, Comment::Preproc, Comment::Multiline, Comment::Preproc end rule %r(// UNSAFE(?:_EXPR|_BLOCK)?), Comment::Preproc rule %r(/\*\s*UNSAFE_EXPR\s*\*/), Comment::Preproc 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/lexers/cfscript.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/cfscript.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Cfscript < RegexLexer title "CFScript" desc 'CFScript, the CFML scripting language' tag 'cfscript' aliases 'cfc' filenames '*.cfc' def self.keywords @keywords ||= %w( if else var xml default break switch do try catch throw in continue for return while required ) end def self.declarations @declarations ||= %w( component property function remote public package private ) end def self.types @types ||= %w( any array binary boolean component date guid numeric query string struct uuid void xml ) end constants = %w(application session client cookie super this variables arguments cgi) operators = %w(\+\+ -- && \|\| <= >= < > == != mod eq lt gt lte gte not is and or xor eqv imp equal contains \? ) dotted_id = /[$a-zA-Z_][a-zA-Z0-9_.]*/ state :root do mixin :comments_and_whitespace rule /(?:#{operators.join('|')}|does not contain|greater than(?: or equal to)?|less than(?: or equal to)?)\b/i, Operator, :expr_start rule %r([-<>+*%&|\^/!=]=?), Operator, :expr_start rule /[(\[,]/, Punctuation, :expr_start rule /;/, Punctuation, :statement rule /[)\].]/, Punctuation rule /[?]/ do token Punctuation push :ternary push :expr_start end rule /[{}]/, Punctuation, :statement rule /(?:#{constants.join('|')})\b/, Name::Constant rule /(?:true|false|null)\b/, Keyword::Constant rule /import\b/, Keyword::Namespace, :import rule /(#{dotted_id})(\s*)(:)(\s*)/ do groups Name, Text, Punctuation, Text push :expr_start end rule /([A-Za-z_$][\w.]*)(\s*)(\()/ do |m| if self.class.keywords.include? m[1] token Keyword, m[1] token Text, m[2] token Punctuation, m[3] else token Name::Function, m[1] token Text, m[2] token Punctuation, m[3] end end rule dotted_id do |m| if self.class.declarations.include? m[0] token Keyword::Declaration push :expr_start elsif self.class.keywords.include? m[0] token Keyword push :expr_start elsif self.class.types.include? m[0] token Keyword::Type push :expr_start else token Name::Other end end rule /[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?/, Num::Float rule /0x[0-9a-fA-F]+/, Num::Hex rule /[0-9]+/, Num::Integer rule /"(\\\\|\\"|[^"])*"/, Str::Double rule /'(\\\\|\\'|[^'])*'/, Str::Single end # same as java, broken out state :comments_and_whitespace do rule /\s+/, Text rule %r(//.*?$), Comment::Single rule %r(/\*.*?\*/)m, Comment::Multiline end state :expr_start do mixin :comments_and_whitespace rule /[{]/, Punctuation, :object rule //, Text, :pop! end state :statement do rule /[{}]/, Punctuation mixin :expr_start end # object literals state :object do mixin :comments_and_whitespace rule /[}]/ do token Punctuation push :expr_start end rule /(#{dotted_id})(\s*)(:)/ do groups Name::Other, Text, Punctuation push :expr_start end rule /:/, Punctuation mixin :root end # ternary expressions, where <dotted_id>: is not a label! state :ternary do rule /:/ do token Punctuation goto :expr_start end mixin :root end state :import do rule /\s+/m, Text rule /[a-z0-9_.]+\*?/i, Name::Namespace, :pop! 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/lexers/lasso.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/lasso.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true require 'yaml' module Rouge module Lexers class Lasso < TemplateLexer title "Lasso" desc "The Lasso programming language (lassosoft.com)" tag 'lasso' aliases 'lassoscript' filenames '*.lasso', '*.lasso[89]' mimetypes 'text/x-lasso', 'text/html+lasso', 'application/x-httpd-lasso' option :start_inline, 'Whether to start inline instead of requiring <?lasso or [' def self.detect?(text) return true if text.shebang?('lasso9') return true if text =~ /\A.*?<\?(lasso(script)?|=)/ end def initialize(*) super @start_inline = bool_option(:start_inline) end def start_inline? @start_inline end start do push :lasso if start_inline? end class << self attr_reader :keywords end # Load Lasso keywords from separate YML file @keywords = ::YAML.load_file(Pathname.new(__FILE__).dirname.join('lasso/keywords.yml')).tap do |h| h.each do |k,v| h[k] = Set.new v end end id = /[a-z_][\w.]*/i state :root do rule /^#![ \S]+lasso9\b/, Comment::Preproc, :lasso rule(/(?=\[|<)/) { push :delimiters } rule /\s+/, Text::Whitespace rule(//) { push :delimiters; push :lassofile } end state :delimiters do rule /\[no_square_brackets\]/, Comment::Preproc, :nosquarebrackets rule /\[noprocess\]/, Comment::Preproc, :noprocess rule /\[/, Comment::Preproc, :squarebrackets rule /<\?(lasso(script)?|=)/i, Comment::Preproc, :anglebrackets rule(/([^\[<]|<!--.*?-->|<(script|style).*?\2>|<(?!\?(lasso(script)?|=)))+/im) { delegate parent } end state :nosquarebrackets do rule /\[noprocess\]/, Comment::Preproc, :noprocess rule /<\?(lasso(script)?|=)/i, Comment::Preproc, :anglebrackets rule(/([^\[<]|<!--.*?-->|<(script|style).*?\2>|<(?!\?(lasso(script)?|=))|\[(?!noprocess))+/im) { delegate parent } end state :noprocess do rule %r(\[/noprocess\]), Comment::Preproc, :pop! rule(%r(([^\[]|\[(?!/noprocess))+)i) { delegate parent } end state :squarebrackets do rule /\]/, Comment::Preproc, :pop! mixin :lasso end state :anglebrackets do rule /\?>/, Comment::Preproc, :pop! mixin :lasso end state :lassofile do rule /\]|\?>/, Comment::Preproc, :pop! mixin :lasso end state :whitespacecomments do rule /\s+/, Text rule %r(//.*?\n), Comment::Single rule %r(/\*\*!.*?\*/)m, Comment::Doc rule %r(/\*.*?\*/)m, Comment::Multiline end state :lasso do mixin :whitespacecomments # literals rule /\d*\.\d+(e[+-]?\d+)?/i, Num::Float rule /0x[\da-f]+/i, Num::Hex rule /\d+/, Num::Integer rule /(infinity|NaN)\b/i, Num rule /'[^'\\]*(\\.[^'\\]*)*'/m, Str::Single rule /"[^"\\]*(\\.[^"\\]*)*"/m, Str::Double rule /`[^`]*`/m, Str::Backtick # names rule /\$#{id}/, Name::Variable rule /#(#{id}|\d+\b)/, Name::Variable::Instance rule /(\.\s*)('#{id}')/ do groups Name::Builtin::Pseudo, Name::Variable::Class end rule /(self)(\s*->\s*)('#{id}')/i do groups Name::Builtin::Pseudo, Operator, Name::Variable::Class end rule /(\.\.?\s*)(#{id}(=(?!=))?)/ do groups Name::Builtin::Pseudo, Name::Other end rule /(->\\?\s*|&\s*)(#{id}(=(?!=))?)/ do groups Operator, Name::Other end rule /(?<!->)(self|inherited|currentcapture|givenblock)\b/i, Name::Builtin::Pseudo rule /-(?!infinity)#{id}/i, Name::Attribute rule /::\s*#{id}/, Name::Label rule /error_((code|msg)_\w+|adderror|columnrestriction|databaseconnectionunavailable|databasetimeout|deleteerror|fieldrestriction|filenotfound|invaliddatabase|invalidpassword|invalidusername|modulenotfound|noerror|nopermission|outofmemory|reqcolumnmissing|reqfieldmissing|requiredcolumnmissing|requiredfieldmissing|updateerror)/i, Name::Exception # definitions rule /(define)(\s+)(#{id})(\s*=>\s*)(type|trait|thread)\b/i do groups Keyword::Declaration, Text, Name::Class, Operator, Keyword end rule %r((define)(\s+)(#{id})(\s*->\s*)(#{id}=?|[-+*/%]))i do groups Keyword::Declaration, Text, Name::Class, Operator, Name::Function push :signature end rule /(define)(\s+)(#{id})/i do groups Keyword::Declaration, Text, Name::Function push :signature end rule %r((public|protected|private|provide)(\s+)((#{id}=?|[-+*/%])(?=\s*\()))i do groups Keyword, Text, Name::Function push :signature end rule /(public|protected|private|provide)(\s+)(#{id})/i do groups Keyword, Text, Name::Function end # keywords rule /(true|false|none|minimal|full|all|void)\b/i, Keyword::Constant rule /(local|var|variable|global|data(?=\s))\b/i, Keyword::Declaration rule /(array|date|decimal|duration|integer|map|pair|string|tag|xml|null|boolean|bytes|keyword|list|locale|queue|set|stack|staticarray)\b/i, Keyword::Type rule /(#{id})(\s+)(in)\b/i do groups Name, Text, Keyword end rule /(let|into)(\s+)(#{id})/i do groups Keyword, Text, Name end # other rule /,/, Punctuation, :commamember rule /(and|or|not)\b/i, Operator::Word rule /(#{id})(\s*::\s*#{id})?(\s*=(?!=|>))/ do groups Name, Name::Label, Operator end rule %r((/?)([\w.]+)) do |m| name = m[2].downcase if m[1] != '' token Punctuation, m[1] end if name == 'namespace_using' token Keyword::Namespace, m[2] elsif self.class.keywords[:keywords].include? name token Keyword, m[2] elsif self.class.keywords[:types_traits].include? name token Name::Builtin, m[2] else token Name::Other, m[2] end end rule /(=)(n?bw|n?ew|n?cn|lte?|gte?|n?eq|n?rx|ft)\b/i do groups Operator, Operator::Word end rule %r(:=|[-+*/%=<>&|!?\\]+), Operator rule /[{}():;,@^]/, Punctuation end state :signature do rule /\=>/, Operator, :pop! rule /\)/, Punctuation, :pop! rule /[(,]/, Punctuation, :parameter mixin :lasso end state :parameter do rule /\)/, Punctuation, :pop! rule /-?#{id}/, Name::Attribute, :pop! rule /\.\.\./, Name::Builtin::Pseudo mixin :lasso end state :commamember do rule %r((#{id}=?|[-+*/%])(?=\s*(\(([^()]*\([^()]*\))*[^\)]*\)\s*)?(::[\w.\s]+)?=>)), Name::Function, :signature mixin :whitespacecomments rule //, Text, :pop! 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/lexers/factor.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/factor.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Factor < RegexLexer title "Factor" desc "Factor, the practical stack language (factorcode.org)" tag 'factor' filenames '*.factor' mimetypes 'text/x-factor' def self.detect?(text) return true if text.shebang? 'factor' end def self.builtins @builtins ||= {}.tap do |builtins| builtins[:kernel] = Set.new %w( or 2bi 2tri while wrapper nip 4dip wrapper? bi* callstack>array both? hashcode die dupd callstack callstack? 3dup tri@ pick curry build ?execute 3bi prepose >boolean if clone eq? tri* ? = swapd 2over 2keep 3keep clear 2dup when not tuple? dup 2bi* 2tri* call tri-curry object bi@ do unless* if* loop bi-curry* drop when* assert= retainstack assert? -rot execute 2bi@ 2tri@ boa with either? 3drop bi curry? datastack until 3dip over 3curry tri-curry* tri-curry@ swap and 2nip throw bi-curry (clone) hashcode* compose 2dip if 3tri unless compose? tuple keep 2curry equal? assert tri 2drop most <wrapper> boolean? identity-hashcode identity-tuple? null new dip bi-curry@ rot xor identity-tuple boolean ) builtins[:assocs] = Set.new %w( ?at assoc? assoc-clone-like assoc= delete-at* assoc-partition extract-keys new-assoc value? assoc-size map>assoc push-at assoc-like key? assoc-intersect assoc-refine update assoc-union assoc-combine at* assoc-empty? at+ set-at assoc-all? assoc-subset? assoc-hashcode change-at assoc-each assoc-diff zip values value-at rename-at inc-at enum? at cache assoc>map <enum> assoc assoc-map enum value-at* assoc-map-as >alist assoc-filter-as clear-assoc assoc-stack maybe-set-at substitute assoc-filter 2cache delete-at assoc-find keys assoc-any? unzip ) builtins[:combinators] = Set.new %w( case execute-effect no-cond no-case? 3cleave>quot 2cleave cond>quot wrong-values? no-cond? cleave>quot no-case case>quot 3cleave wrong-values to-fixed-point alist>quot case-find cond cleave call-effect 2cleave>quot recursive-hashcode linear-case-quot spread spread>quot ) builtins[:math] = Set.new %w( number= if-zero next-power-of-2 each-integer ?1+ fp-special? imaginary-part unless-zero float>bits number? fp-infinity? bignum? fp-snan? denominator fp-bitwise= * + power-of-2? - u>= / >= bitand log2-expects-positive < log2 > integer? number bits>double 2/ zero? (find-integer) bits>float float? shift ratio? even? ratio fp-sign bitnot >fixnum complex? /i /f byte-array>bignum when-zero sgn >bignum next-float u< u> mod recip rational find-last-integer >float (all-integers?) 2^ times integer fixnum? neg fixnum sq bignum (each-integer) bit? fp-qnan? find-integer complex <fp-nan> real double>bits bitor rem fp-nan-payload all-integers? real-part log2-expects-positive? prev-float align unordered? float fp-nan? abs bitxor u<= odd? <= /mod rational? >integer real? numerator ) builtins[:sequences] = Set.new %w( member-eq? append assert-sequence= find-last-from trim-head-slice clone-like 3sequence assert-sequence? map-as last-index-from reversed index-from cut* pad-tail remove-eq! concat-as but-last snip trim-tail nths nth 2selector sequence slice? <slice> partition remove-nth tail-slice empty? tail* if-empty find-from virtual-sequence? member? set-length drop-prefix unclip unclip-last-slice iota map-sum bounds-error? sequence-hashcode-step selector-for accumulate-as map start midpoint@ (accumulate) rest-slice prepend fourth sift accumulate! new-sequence follow map! like first4 1sequence reverse slice unless-empty padding virtual@ repetition? set-last index 4sequence max-length set-second immutable-sequence first2 first3 replicate-as reduce-index unclip-slice supremum suffix! insert-nth trim-tail-slice tail 3append short count suffix concat flip filter sum immutable? reverse! 2sequence map-integers delete-all start* indices snip-slice check-slice sequence? head map-find filter! append-as reduce sequence= halves collapse-slice interleave 2map filter-as binary-reduce slice-error? product bounds-check? bounds-check harvest immutable virtual-exemplar find produce remove pad-head last replicate set-fourth remove-eq shorten reversed? map-find-last 3map-as 2unclip-slice shorter? 3map find-last head-slice pop* 2map-as tail-slice* but-last-slice 2map-reduce iota? collector-for accumulate each selector append! new-resizable cut-slice each-index head-slice* 2reverse-each sequence-hashcode pop set-nth ?nth <flat-slice> second join when-empty collector immutable-sequence? <reversed> all? 3append-as virtual-sequence subseq? remove-nth! push-either new-like length last-index push-if 2all? lengthen assert-sequence copy map-reduce move third first 3each tail? set-first prefix bounds-error any? <repetition> trim-slice exchange surround 2reduce cut change-nth min-length set-third produce-as push-all head? delete-slice rest sum-lengths 2each head* infimum remove! glue slice-error subseq trim replace-slice push repetition map-index trim-head unclip-last mismatch ) builtins[:namespaces] = Set.new %w( global +@ change set-namestack change-global init-namespaces on off set-global namespace set with-scope bind with-variable inc dec counter initialize namestack get get-global make-assoc ) builtins[:arrays] = Set.new %w( <array> 2array 3array pair >array 1array 4array pair? array resize-array array? ) builtins[:io] = Set.new %w( +character+ bad-seek-type? readln each-morsel stream-seek read print with-output-stream contents write1 stream-write1 stream-copy stream-element-type with-input-stream stream-print stream-read stream-contents stream-tell tell-output bl seek-output bad-seek-type nl stream-nl write flush stream-lines +byte+ stream-flush read1 seek-absolute? stream-read1 lines stream-readln stream-read-until each-line seek-end with-output-stream* seek-absolute with-streams seek-input seek-relative? input-stream stream-write read-partial seek-end? seek-relative error-stream read-until with-input-stream* with-streams* tell-input each-block output-stream stream-read-partial each-stream-block each-stream-line ) builtins[:strings] = Set.new %w( resize-string >string <string> 1string string string? ) builtins[:vectors] = Set.new %w( with-return restarts return-continuation with-datastack recover rethrow-restarts <restart> ifcc set-catchstack >continuation< cleanup ignore-errors restart? compute-restarts attempt-all-error error-thread continue <continuation> attempt-all-error? condition? <condition> throw-restarts error catchstack continue-with thread-error-hook continuation rethrow callcc1 error-continuation callcc0 attempt-all condition continuation? restart return ) builtins[:continuations] = Set.new %w( with-return restarts return-continuation with-datastack recover rethrow-restarts <restart> ifcc set-catchstack >continuation< cleanup ignore-errors restart? compute-restarts attempt-all-error error-thread continue <continuation> attempt-all-error? condition? <condition> throw-restarts error catchstack continue-with thread-error-hook continuation rethrow callcc1 error-continuation callcc0 attempt-all condition continuation? restart return ) end end state :root do rule /\s+/m, Text rule /(:|::|MACRO:|MEMO:|GENERIC:|HELP:)(\s+)(\S+)/m do groups Keyword, Text, Name::Function end rule /(M:|HOOK:|GENERIC#)(\s+)(\S+)(\s+)(\S+)/m do groups Keyword, Text, Name::Class, Text, Name::Function end rule /\((?=\s)/, Name::Function, :stack_effect rule /;(?=\s)/, Keyword rule /(USING:)((?:\s|\\\s)+)/m do groups Keyword::Namespace, Text push :import end rule /(IN:|USE:|UNUSE:|QUALIFIED:|QUALIFIED-WITH:)(\s+)(\S+)/m do groups Keyword::Namespace, Text, Name::Namespace end rule /(FROM:|EXCLUDE:)(\s+)(\S+)(\s+)(=>)/m do groups Keyword::Namespace, Text, Name::Namespace, Text, Punctuation end rule /(?:ALIAS|DEFER|FORGET|POSTPONE):/, Keyword::Namespace rule /(TUPLE:)(\s+)(\S+)(\s+)(<)(\s+)(\S+)/m do groups( Keyword, Text, Name::Class, Text, Punctuation, Text, Name::Class ) push :slots end rule /(TUPLE:)(\s+)(\S+)/m do groups Keyword, Text, Name::Class push :slots end rule /(UNION:|INTERSECTION:)(\s+)(\S+)/m do groups Keyword, Text, Name::Class end rule /(PREDICATE:)(\s+)(\S+)(\s+)(<)(\s+)(\S+)/m do groups( Keyword, Text, Name::Class, Text, Punctuation, Text, Name::Class ) end rule /(C:)(\s+)(\S+)(\s+)(\S+)/m do groups( Keyword, Text, Name::Function, Text, Name::Class ) end rule %r( (INSTANCE|SLOT|MIXIN|SINGLETONS?|CONSTANT|SYMBOLS?|ERROR|SYNTAX |ALIEN|TYPEDEF|FUNCTION|STRUCT): )x, Keyword rule /(?:<PRIVATE|PRIVATE>)/, Keyword::Namespace rule /(MAIN:)(\s+)(\S+)/ do groups Keyword::Namespace, Text, Name::Function end # strings rule /"""\s+.*?\s+"""/, Str rule /"(\\.|[^\\])*?"/, Str rule /(CHAR:)(\s+)(\\[\\abfnrstv]*|\S)(?=\s)/, Str::Char # comments rule /!\s+.*$/, Comment rule /#!\s+.*$/, Comment # booleans rule /[tf](?=\s)/, Name::Constant # numbers rule /-?\d+\.\d+(?=\s)/, Num::Float rule /-?\d+(?=\s)/, Num::Integer rule /HEX:\s+[a-fA-F\d]+(?=\s)/m, Num::Hex rule /BIN:\s+[01]+(?=\s)/, Num::Bin rule /OCT:\s+[0-7]+(?=\s)/, Num::Oct rule %r([-+/*=<>^](?=\s)), Operator rule /(?:deprecated|final|foldable|flushable|inline|recursive)(?=\s)/, Keyword rule /\S+/ do |m| name = m[0] if self.class.builtins.values.any? { |b| b.include? name } token Name::Builtin else token Name end end end state :stack_effect do rule /\s+/, Text rule /\(/, Name::Function, :stack_effect rule /\)/, Name::Function, :pop! rule /--/, Name::Function rule /\S+/, Name::Variable end state :slots do rule /\s+/, Text rule /;(?=\s)/, Keyword, :pop! rule /\S+/, Name::Variable end state :import do rule /;(?=\s)/, Keyword, :pop! rule /\s+/, Text rule /\S+/, Name::Namespace 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/lexers/d.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/d.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class D < RegexLexer tag 'd' aliases 'dlang' filenames '*.d', '*.di' mimetypes 'application/x-dsrc', 'text/x-dsrc' title "D" desc 'The D programming language(dlang.org)' keywords = %w( abstract alias align asm assert auto body break case cast catch class const continue debug default delegate delete deprecated do else enum export extern finally final foreach_reverse foreach for function goto if immutable import interface invariant inout in is lazy mixin module new nothrow out override package pragma private protected public pure ref return scope shared static struct super switch synchronized template this throw try typedef typeid typeof union unittest version volatile while with __gshared __traits __vector __parameters ) keywords_type = %w( bool byte cdouble cent cfloat char creal dchar double float idouble ifloat int ireal long real short ubyte ucent uint ulong ushort void wchar ) keywords_pseudo = %w( __FILE__ __MODULE__ __LINE__ __FUNCTION__ __PRETTY_FUNCTION__ __DATE__ __EOF__ __TIME__ __TIMESTAMP__ __VENDOR__ __VERSION__ ) state :whitespace do rule /\n/m, Text rule /\s+/m, Text end state :root do mixin :whitespace # Comments rule %r(//(.*?)\n), Comment::Single rule %r(/(\\\n)?[*](.|\n)*?[*](\\\n)?/), Comment::Multiline rule %r(/\+), Comment::Multiline, :nested_comment # Keywords rule /(#{keywords.join('|')})\b/, Keyword rule /(#{keywords_type.join('|')})\b/, Keyword::Type rule /(false|true|null)\b/, Keyword::Constant rule /(#{keywords_pseudo.join('|')})\b/, Keyword::Pseudo rule /macro\b/, Keyword::Reserved rule /(string|wstring|dstring|size_t|ptrdiff_t)\b/, Name::Builtin # Literals # HexFloat rule /0[xX]([0-9a-fA-F_]*\.[0-9a-fA-F_]+|[0-9a-fA-F_]+)[pP][+\-]?[0-9_]+[fFL]?[i]?/, Num::Float # DecimalFloat rule /[0-9_]+(\.[0-9_]+[eE][+\-]?[0-9_]+|\.[0-9_]*|[eE][+\-]?[0-9_]+)[fFL]?[i]?/, Num::Float rule /\.(0|[1-9][0-9_]*)([eE][+\-]?[0-9_]+)?[fFL]?[i]?/, Num::Float # IntegerLiteral # Binary rule /0[Bb][01_]+/, Num::Bin # Octal # TODO: 0[0-7] isn't supported use octal![0-7] instead rule /0[0-7_]+/, Num::Oct # Hexadecimal rule /0[xX][0-9a-fA-F_]+/, Num::Hex # Decimal rule /(0|[1-9][0-9_]*)([LUu]|Lu|LU|uL|UL)?/, Num::Integer # CharacterLiteral rule /'(\\['"?\\abfnrtv]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\&\w+;|.)'/, Str::Char # StringLiteral # WysiwygString rule /r"[^"]*"[cwd]?/, Str # Alternate WysiwygString rule /`[^`]*`[cwd]?/, Str # DoubleQuotedString rule /"(\\\\|\\"|[^"])*"[cwd]?/, Str # EscapeSequence rule /\\(['\"?\\abfnrtv]|x[0-9a-fA-F]{2}|[0-7]{1,3}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|&\w+;)/, Str # HexString rule /x"[0-9a-fA-F_\s]*"[cwd]?/, Str # DelimitedString rule /q"\[/, Str, :delimited_bracket rule /q"\(/, Str, :delimited_parenthesis rule /q"</, Str, :delimited_angle rule /q"\{/, Str, :delimited_curly rule /q"([a-zA-Z_]\w*)\n.*?\n\1"/, Str rule /q"(.).*?\1"/, Str # TokenString rule /q\{/, Str, :token_string # Attributes rule /@([a-zA-Z_]\w*)?/, Name::Decorator # Tokens rule %r`(~=|\^=|%=|\*=|==|!>=|!<=|!<>=|!<>|!<|!>|!=|>>>=|>>>|>>=|>>|>=|<>=|<>|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.\.|\.\.|/=)|[/.&|\-+<>!()\[\]{}?,;:$=*%^~]`, Punctuation # Identifier rule /[a-zA-Z_]\w*/, Name # Line rule /#line\s.*\n/, Comment::Special end state :nested_comment do rule %r([^+/]+), Comment::Multiline rule %r(/\+), Comment::Multiline, :push rule %r(\+/), Comment::Multiline, :pop! rule %r([+/]), Comment::Multiline end state :token_string do rule /\{/, Punctuation, :token_string_nest rule /\}/, Str, :pop! mixin :root end state :token_string_nest do rule /\{/, Punctuation, :push rule /\}/, Punctuation, :pop! mixin :root end state :delimited_bracket do rule /[^\[\]]+/, Str rule /\[/, Str, :delimited_inside_bracket rule /\]"/, Str, :pop! end state :delimited_inside_bracket do rule /[^\[\]]+/, Str rule /\[/, Str, :push rule /\]/, Str, :pop! end state :delimited_parenthesis do rule /[^()]+/, Str rule /\(/, Str, :delimited_inside_parenthesis rule /\)"/, Str, :pop! end state :delimited_inside_parenthesis do rule /[^()]+/, Str rule /\(/, Str, :push rule /\)/, Str, :pop! end state :delimited_angle do rule /[^<>]+/, Str rule /</, Str, :delimited_inside_angle rule />"/, Str, :pop! end state :delimited_inside_angle do rule /[^<>]+/, Str rule /</, Str, :push rule />/, Str, :pop! end state :delimited_curly do rule /[^{}]+/, Str rule /\{/, Str, :delimited_inside_curly rule /\}"/, Str, :pop! end state :delimited_inside_curly do rule /[^{}]+/, Str rule /\{/, Str, :push rule /\}/, Str, :pop! 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/lexers/toml.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/toml.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class TOML < RegexLexer title "TOML" desc 'the TOML configuration format (https://github.com/mojombo/toml)' tag 'toml' filenames '*.toml' mimetypes 'text/x-toml' identifier = /[\w.\S]+/ state :basic do rule /\s+/, Text rule /#.*?$/, Comment rule /(true|false)/, Keyword::Constant rule /(?<!=)\s*\[[\w\d\S]+\]/, Name::Namespace rule /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/, Literal::Date rule /(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?/, Num::Float rule /\d+[eE][+-]?[0-9]+j?/, Num::Float rule /\-?\d+/, Num::Integer end state :root do mixin :basic rule /(#{identifier})(\s*)(=)/ do groups Name::Property, Text, Punctuation push :value end end state :value do rule /\n/, Text, :pop! mixin :content end state :content do mixin :basic rule /"/, Str, :dq mixin :esc_str rule /\,/, Punctuation rule /\[/, Punctuation, :array end state :dq do rule /"/, Str, :pop! mixin :esc_str rule /[^\\"]+/, Str end state :esc_str do rule /\\[0t\tn\n "\\ r]/, Str::Escape end state :array do mixin :content rule /\]/, Punctuation, :pop! 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/lexers/xml.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/xml.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class XML < RegexLexer title "XML" desc %q(<desc for="this-lexer">XML</desc>) tag 'xml' filenames *%w(*.xml *.xsl *.rss *.xslt *.xsd *.wsdl *.svg) mimetypes *%w( text/xml application/xml image/svg+xml application/rss+xml application/atom+xml ) def self.detect?(text) return false if text.doctype?(/html/) return true if text =~ /\A<\?xml\b/ return true if text.doctype? end state :root do rule /[^<&]+/, Text rule /&\S*?;/, Name::Entity rule /<!\[CDATA\[.*?\]\]\>/, Comment::Preproc rule /<!--/, Comment, :comment rule /<\?.*?\?>/, Comment::Preproc rule /<![^>]*>/, Comment::Preproc # open tags rule %r(<\s*[\w:.-]+)m, Name::Tag, :tag # self-closing tags rule %r(<\s*/\s*[\w:.-]+\s*>)m, Name::Tag end state :comment do rule /[^-]+/m, Comment rule /-->/, Comment, :pop! rule /-/, Comment end state :tag do rule /\s+/m, Text rule /[\w.:-]+\s*=/m, Name::Attribute, :attr rule %r(/?\s*>), Name::Tag, :pop! end state :attr do rule /\s+/m, Text rule /".*?"|'.*?'|[^\s>]+/m, Str, :pop! 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/lexers/vb.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/vb.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class VisualBasic < RegexLexer title "Visual Basic" desc "Visual Basic" tag 'vb' aliases 'visualbasic' filenames '*.vbs', '*.vb' mimetypes 'text/x-visualbasic', 'application/x-visualbasic' def self.keywords @keywords ||= Set.new %w( AddHandler Alias ByRef ByVal CBool CByte CChar CDate CDbl CDec CInt CLng CObj CSByte CShort CSng CStr CType CUInt CULng CUShort Call Case Catch Class Const Continue Declare Default Delegate Dim DirectCast Do Each Else ElseIf End EndIf Enum Erase Error Event Exit False Finally For Friend Function Get Global GoSub GoTo Handles If Implements Imports Inherits Interface Let Lib Loop Me Module MustInherit MustOverride MyBase MyClass Namespace Narrowing New Next Not NotInheritable NotOverridable Nothing Of On Operator Option Optional Overloads Overridable Overrides ParamArray Partial Private Property Protected Public RaiseEvent ReDim ReadOnly RemoveHandler Resume Return Select Set Shadows Shared Single Static Step Stop Structure Sub SyncLock Then Throw To True Try TryCast Using Wend When While Widening With WithEvents WriteOnly ) end def self.keywords_type @keywords_type ||= Set.new %w( Boolean Byte Char Date Decimal Double Integer Long Object SByte Short Single String Variant UInteger ULong UShort ) end def self.operator_words @operator_words ||= Set.new %w( AddressOf And AndAlso As GetType In Is IsNot Like Mod Or OrElse TypeOf Xor ) end def self.builtins @builtins ||= Set.new %w( Console ConsoleColor ) end id = /[a-z_]\w*/i upper_id = /[A-Z]\w*/ state :whitespace do rule /\s+/, Text rule /\n/, Text, :bol rule /rem\b.*?$/i, Comment::Single rule %r(%\{.*?%\})m, Comment::Multiline rule /'.*$/, Comment::Single end state :bol do rule /\s+/, Text rule /<.*?>/, Name::Attribute rule(//) { :pop! } end state :root do mixin :whitespace rule %r( [#]If\b .*? \bThen | [#]ElseIf\b .*? \bThen | [#]End \s+ If | [#]Const | [#]ExternalSource .*? \n | [#]End \s+ ExternalSource | [#]Region .*? \n | [#]End \s+ Region | [#]ExternalChecksum )x, Comment::Preproc rule /[.]/, Punctuation, :dotted rule /[(){}!#,:]/, Punctuation rule /Option\s+(Strict|Explicit|Compare)\s+(On|Off|Binary|Text)/, Keyword::Declaration rule /End\b/, Keyword, :end rule /(Dim|Const)\b/, Keyword, :dim rule /(Function|Sub|Property)\b/, Keyword, :funcname rule /(Class|Structure|Enum)\b/, Keyword, :classname rule /(Module|Namespace|Imports)\b/, Keyword, :namespace rule upper_id do |m| match = m[0] if self.class.keywords.include? match token Keyword elsif self.class.keywords_type.include? match token Keyword::Type elsif self.class.operator_words.include? match token Operator::Word elsif self.class.builtins.include? match token Name::Builtin else token Name end end rule( %r(&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|<=|>=|<>|[-&*/\\^+=<>.]), Operator ) rule /"/, Str, :string rule /#{id}[%&@!#\$]?/, Name rule /#.*?#/, Literal::Date rule /(\d+\.\d*|\d*\.\d+)(f[+-]?\d+)?/i, Num::Float rule /\d+([SILDFR]|US|UI|UL)?/, Num::Integer rule /&H[0-9a-f]+([SILDFR]|US|UI|UL)?/, Num::Integer rule /&O[0-7]+([SILDFR]|US|UI|UL)?/, Num::Integer rule /_\n/, Keyword end state :dotted do mixin :whitespace rule id, Name, :pop! end state :string do rule /""/, Str::Escape rule /"C?/, Str, :pop! rule /[^"]+/, Str end state :dim do mixin :whitespace rule id, Name::Variable, :pop! rule(//) { pop! } end state :funcname do mixin :whitespace rule id, Name::Function, :pop! end state :classname do mixin :whitespace rule id, Name::Class, :pop! end state :namespace do mixin :whitespace rule /#{id}([.]#{id})*/, Name::Namespace, :pop! end state :end do mixin :whitespace rule /(Function|Sub|Property|Class|Structure|Enum|Module|Namespace)\b/, Keyword, :pop! rule(//) { pop! } 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/lexers/viml.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/viml.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class VimL < RegexLexer title "VimL" desc "VimL, the scripting language for the Vim editor (vim.org)" tag 'viml' aliases 'vim', 'vimscript', 'ex' filenames '*.vim', '*.vba', '.vimrc', '.exrc', '.gvimrc', '_vimrc', '_exrc', '_gvimrc' # _ names for windows mimetypes 'text/x-vim' def self.keywords load Pathname.new(__FILE__).dirname.join('viml/keywords.rb') self.keywords end state :root do rule /^(\s*)(".*?)$/ do groups Text, Comment end rule /^\s*\\/, Str::Escape rule /[ \t]+/, Text # TODO: regexes can have other delimiters rule %r(/(\\\\|\\/|[^\n/])*/), Str::Regex rule %r("(\\\\|\\"|[^\n"])*"), Str::Double rule %r('(\\\\|\\'|[^\n'])*'), Str::Single # if it's not a string, it's a comment. rule /(?<=\s)"[^-:.%#=*].*?$/, Comment rule /-?\d+/, Num rule /#[0-9a-f]{6}/i, Num::Hex rule /^:/, Punctuation rule /[():<>+=!\[\]{}\|,~.-]/, Punctuation rule /\b(let|if|else|endif|elseif|fun|function|endfunction)\b/, Keyword rule /\b(NONE|bold|italic|underline|dark|light)\b/, Name::Builtin rule /[absg]:\w+\b/, Name::Variable rule /\b\w+\b/ do |m| name = m[0] keywords = self.class.keywords if mapping_contains?(keywords[:command], name) token Keyword elsif mapping_contains?(keywords[:option], name) token Name::Builtin elsif mapping_contains?(keywords[:auto], name) token Name::Builtin else token Text end end # no errors in VimL! rule /./m, Text end def mapping_contains?(mapping, word) shortest, longest = find_likely_mapping(mapping, word) shortest and word.start_with?(shortest) and longest and longest.start_with?(word) end # binary search through the mappings to find the one that's likely # to actually work. def find_likely_mapping(mapping, word) min = 0 max = mapping.size until max == min mid = (max + min) / 2 cmp, _ = mapping[mid] case word <=> cmp when 1 # too low min = mid + 1 when -1 # too high max = mid when 0 # just right, abort! return mapping[mid] end end mapping[max - 1] end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/ini.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/ini.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class INI < RegexLexer title "INI" desc 'the INI configuration format' tag 'ini' # TODO add more here filenames '*.ini', '*.INI', '*.gitconfig' mimetypes 'text/x-ini' identifier = /[\w\-.]+/ state :basic do rule /[;#].*?\n/, Comment rule /\s+/, Text rule /\\\n/, Str::Escape end state :root do mixin :basic rule /(#{identifier})(\s*)(=)/ do groups Name::Property, Text, Punctuation push :value end rule /\[.*?\]/, Name::Namespace end state :value do rule /\n/, Text, :pop! mixin :basic rule /"/, Str, :dq rule /'.*?'/, Str mixin :esc_str rule /[^\\\n]+/, Str end state :dq do rule /"/, Str, :pop! mixin :esc_str rule /[^\\"]+/m, Str end state :esc_str do rule /\\./m, Str::Escape 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/lexers/yaml.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/yaml.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class YAML < RegexLexer title "YAML" desc "Yaml Ain't Markup Language (yaml.org)" mimetypes 'text/x-yaml' tag 'yaml' aliases 'yml' filenames '*.yaml', '*.yml' def self.detect?(text) # look for the %YAML directive return true if text =~ /\A\s*%YAML/m end SPECIAL_VALUES = Regexp.union(%w(true false null)) # NB: Tabs are forbidden in YAML, which is why you see things # like /[ ]+/. # reset the indentation levels def reset_indent puts " yaml: reset_indent" if @debug @indent_stack = [0] @next_indent = 0 @block_scalar_indent = nil end def indent raise 'empty indent stack!' if @indent_stack.empty? @indent_stack.last end def dedent?(level) level < self.indent end def indent?(level) level > self.indent end # Save a possible indentation level def save_indent(match) @next_indent = match.size puts " yaml: indent: #{self.indent}/#@next_indent" if @debug puts " yaml: popping indent stack - before: #@indent_stack" if @debug if dedent?(@next_indent) @indent_stack.pop while dedent?(@next_indent) puts " yaml: popping indent stack - after: #@indent_stack" if @debug puts " yaml: indent: #{self.indent}/#@next_indent" if @debug # dedenting to a state not previously indented to is an error [match[0...self.indent], match[self.indent..-1]] else [match, ''] end end def continue_indent(match) puts " yaml: continue_indent" if @debug @next_indent += match.size end def set_indent(match, opts={}) if indent < @next_indent puts " yaml: indenting #{indent}/#{@next_indent}" if @debug @indent_stack << @next_indent end @next_indent += match.size unless opts[:implicit] end plain_scalar_start = /[^ \t\n\r\f\v?:,\[\]{}#&*!\|>'"%@`]/ start { reset_indent } state :basic do rule /#.*$/, Comment::Single end state :root do mixin :basic rule /\n+/, Text # trailing or pre-comment whitespace rule /[ ]+(?=#|$)/, Text rule /^%YAML\b/ do token Name::Tag reset_indent push :yaml_directive end rule /^%TAG\b/ do token Name::Tag reset_indent push :tag_directive end # doc-start and doc-end indicators rule /^(?:---|\.\.\.)(?= |$)/ do token Name::Namespace reset_indent push :block_line end # indentation spaces rule /[ ]*(?!\s|$)/ do |m| text, err = save_indent(m[0]) token Text, text token Error, err push :block_line; push :indentation end end state :indentation do rule(/\s*?\n/) { token Text; pop! 2 } # whitespace preceding block collection indicators rule /[ ]+(?=[-:?](?:[ ]|$))/ do |m| token Text continue_indent(m[0]) end # block collection indicators rule(/[?:-](?=[ ]|$)/) do |m| set_indent m[0] token Punctuation::Indicator end # the beginning of a block line rule(/[ ]*/) { |m| token Text; continue_indent(m[0]); pop! } end # indented line in the block context state :block_line do # line end rule /[ ]*(?=#|$)/, Text, :pop! rule /[ ]+/, Text # tags, anchors, and aliases mixin :descriptors # block collections and scalars mixin :block_nodes # flow collections and quoed scalars mixin :flow_nodes # a plain scalar rule /(?=#{plain_scalar_start}|[?:-][^ \t\n\r\f\v])/ do token Name::Variable push :plain_scalar_in_block_context end end state :descriptors do # a full-form tag rule /!<[0-9A-Za-z;\/?:@&=+$,_.!~*'()\[\]%-]+>/, Keyword::Type # a tag in the form '!', '!suffix' or '!handle!suffix' rule %r( (?:![\w-]+)? # handle !(?:[\w;/?:@&=+$,.!~*\'()\[\]%-]*) # suffix )x, Keyword::Type # an anchor rule /&[\w-]+/, Name::Label # an alias rule /\*[\w-]+/, Name::Variable end state :block_nodes do # implicit key rule /((?:\w[\w -]*)?)(:)(?=\s|$)/ do |m| groups Name::Attribute, Punctuation::Indicator set_indent m[0], :implicit => true end # literal and folded scalars rule /[\|>]/ do token Punctuation::Indicator push :block_scalar_content push :block_scalar_header end end state :flow_nodes do rule /\[/, Punctuation::Indicator, :flow_sequence rule /\{/, Punctuation::Indicator, :flow_mapping rule /'/, Str::Single, :single_quoted_scalar rule /"/, Str::Double, :double_quoted_scalar end state :flow_collection do rule /\s+/m, Text mixin :basic rule /[?:,]/, Punctuation::Indicator mixin :descriptors mixin :flow_nodes rule /(?=#{plain_scalar_start})/ do push :plain_scalar_in_flow_context end end state :flow_sequence do rule /\]/, Punctuation::Indicator, :pop! mixin :flow_collection end state :flow_mapping do rule /\}/, Punctuation::Indicator, :pop! mixin :flow_collection end state :block_scalar_content do rule /\n+/, Text # empty lines never dedent, but they might be part of the scalar. rule /^[ ]+$/ do |m| text = m[0] indent_size = text.size indent_mark = @block_scalar_indent || indent_size token Text, text[0...indent_mark] token Name::Constant, text[indent_mark..-1] end # TODO: ^ doesn't actually seem to affect the match at all. # Find a way to work around this limitation. rule /^[ ]*/ do |m| token Text indent_size = m[0].size dedent_level = @block_scalar_indent || self.indent @block_scalar_indent ||= indent_size if indent_size < dedent_level save_indent m[0] pop! push :indentation end end rule /[^\n\r\f\v]+/, Name::Constant end state :block_scalar_header do # optional indentation indicator and chomping flag, in either order rule %r( ( ([1-9])[+-]? | [+-]?([1-9])? )(?=[ ]|$) )x do |m| @block_scalar_indent = nil goto :ignored_line next if m[0].empty? increment = m[1] || m[2] if increment @block_scalar_indent = indent + increment.to_i end token Punctuation::Indicator end end state :ignored_line do mixin :basic rule /[ ]+/, Text rule /\n/, Text, :pop! end state :quoted_scalar_whitespaces do # leading and trailing whitespace is ignored rule /^[ ]+/, Text rule /[ ]+$/, Text rule /\n+/m, Text rule /[ ]+/, Name::Variable end state :single_quoted_scalar do mixin :quoted_scalar_whitespaces rule /\\'/, Str::Escape rule /'/, Str, :pop! rule /[^\s']+/, Str end state :double_quoted_scalar do rule /"/, Str, :pop! mixin :quoted_scalar_whitespaces # escapes rule /\\[0abt\tn\nvfre "\\N_LP]/, Str::Escape rule /\\(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/, Str::Escape rule /[^ \t\n\r\f\v"\\]+/, Str end state :plain_scalar_in_block_context_new_line do rule /^[ ]+\n/, Text rule /\n+/m, Text rule /^(?=---|\.\.\.)/ do pop! 3 end # dedent detection rule /^[ ]*/ do |m| token Text pop! indent_size = m[0].size # dedent = end of scalar if indent_size <= self.indent pop! save_indent(m[0]) push :indentation end end end state :plain_scalar_in_block_context do # the : indicator ends a scalar rule /[ ]*(?=:[ \n]|:$)/, Text, :pop! rule /[ ]*:/, Str rule /[ ]+(?=#)/, Text, :pop! rule /[ ]+$/, Text # check for new documents or dedents at the new line rule /\n+/ do token Text push :plain_scalar_in_block_context_new_line end rule /[ ]+/, Str rule SPECIAL_VALUES, Name::Constant # regular non-whitespace characters rule /[^\s:]+/, Str end state :plain_scalar_in_flow_context do rule /[ ]*(?=[,:?\[\]{}])/, Text, :pop! rule /[ ]+(?=#)/, Text, :pop! rule /^[ ]+/, Text rule /[ ]+$/, Text rule /\n+/, Text rule /[ ]+/, Name::Variable rule /[^\s,:?\[\]{}]+/, Name::Variable end state :yaml_directive do rule /([ ]+)(\d+\.\d+)/ do groups Text, Num goto :ignored_line end end state :tag_directive do rule %r( ([ ]+)(!|![\w-]*!) # prefix ([ ]+)(!|!?[\w;/?:@&=+$,.!~*'()\[\]%-]+) # tag handle )x do groups Text, Keyword::Type, Text, Keyword::Type goto :ignored_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/rouge-3.3.0/lib/rouge/lexers/qml.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/qml.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers load_lexer 'javascript.rb' class Qml < Javascript title "QML" desc 'QML, a UI markup language' tag 'qml' aliases 'qml' filenames '*.qml' mimetypes 'application/x-qml', 'text/x-qml' id_with_dots = /[$a-zA-Z_][a-zA-Z0-9_.]*/ prepend :root do rule /(#{id_with_dots})(\s*)({)/ do groups Keyword::Type, Text, Punctuation push :type_block end rule /(#{id_with_dots})(\s+)(on)(\s+)(#{id_with_dots})(\s*)({)/ do groups Keyword::Type, Text, Keyword, Text, Name::Label, Text, Punctuation push :type_block end rule /[{]/, Punctuation, :push end state :type_block do rule /(id)(\s*)(:)(\s*)(#{id_with_dots})/ do groups Name::Label, Text, Punctuation, Text, Keyword::Declaration end rule /(#{id_with_dots})(\s*)(:)/ do groups Name::Label, Text, Punctuation push :expr_start end rule /(signal)(\s+)(#{id_with_dots})/ do groups Keyword::Declaration, Text, Name::Label push :signal end rule /(property)(\s+)(#{id_with_dots})(\s+)(#{id_with_dots})(\s*)(:?)/ do groups Keyword::Declaration, Text, Keyword::Type, Text, Name::Label, Text, Punctuation push :expr_start end rule /[}]/, Punctuation, :pop! mixin :root end state :signal do mixin :comments_and_whitespace rule /\(/ do token Punctuation goto :signal_args end rule //, Text, :pop! end state :signal_args do mixin :comments_and_whitespace rule /(#{id_with_dots})(\s+)(#{id_with_dots})(\s*)(,?)/ do groups Keyword::Type, Text, Name, Text, Punctuation end rule /\)/ , Punctuation, :pop! 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/lexers/wollok.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/wollok.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Wollok < RegexLexer title 'Wollok' desc 'Wollok lang' tag 'wollok' filenames *%w(*.wlk *.wtest *.wpgm) keywords = %w(new super return if else var const override constructor) entity_name = /[a-zA-Z][a-zA-Z0-9]*/ variable_naming = /_?#{entity_name}/ entities = [] state :whitespaces_and_comments do rule /\s+/m, Text::Whitespace rule /$+/m, Text::Whitespace rule %r(//.*$), Comment::Single rule %r(/\*(.|\s)*?\*/)m, Comment::Multiline end state :root do mixin :whitespaces_and_comments rule /(import)(.+$)/ do groups Keyword::Reserved, Text end rule /(class|object|mixin)/, Keyword::Reserved, :foo rule /test|program/, Keyword::Reserved #, :chunk_naming rule /(package)(\s+)(#{entity_name})/ do groups Keyword::Reserved, Text::Whitespace, Name::Class end rule /{|}/, Text mixin :keywords mixin :symbols mixin :objects end state :foo do mixin :whitespaces_and_comments rule /inherits|mixed|with|and/, Keyword::Reserved rule /#{entity_name}(?=\s*{)/ do |m| token Name::Class entities << m[0] pop! end rule /#{entity_name}/ do |m| token Name::Class entities << m[0] end end state :keywords do def any(expressions) /#{expressions.map { |keyword| "#{keyword}\\b" }.join('|')}/ end rule /self\b/, Name::Builtin::Pseudo rule any(keywords), Keyword::Reserved rule /(method)(\s+)(#{variable_naming})/ do groups Keyword::Reserved, Text::Whitespace, Text end end state :objects do rule variable_naming do |m| variable = m[0] if entities.include?(variable) || ('A'..'Z').cover?(variable[0]) token Name::Class else token Keyword::Variable end end rule /\.#{entity_name}/, Text mixin :literals end state :literals do mixin :whitespaces_and_comments rule /[0-9]+\.?[0-9]*/, Literal::Number rule /"[^"]*"/m, Literal::String rule /\[|\#{/, Punctuation, :lists end state :lists do rule /,/, Punctuation rule /]|}/, Punctuation, :pop! mixin :objects end state :symbols do rule /\+\+|--|\+=|-=|\*\*|!/, Operator rule /\+|-|\*|\/|%/, Operator rule /<=|=>|===|==|<|>/, Operator rule /and\b|or\b|not\b/, Operator rule /\(|\)|=/, Text rule /,/, Punctuation 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/lexers/console.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/console.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class ConsoleLexer < Lexer tag 'console' aliases 'terminal', 'shell_session', 'shell-session' filenames '*.cap' desc 'A generic lexer for shell sessions. Accepts ?lang and ?output lexer options, a ?prompt option, and ?comments to enable # comments.' option :lang, 'the shell language to lex (default: shell)' option :output, 'the output language (default: plaintext?token=Generic.Output)' option :prompt, 'comma-separated list of strings that indicate the end of a prompt. (default: $,#,>,;)' option :comments, 'enable hash-comments at the start of a line - otherwise interpreted as a prompt. (default: false, implied by ?prompt not containing `#`)' def initialize(*) super @prompt = list_option(:prompt) { nil } @lang = lexer_option(:lang) { 'shell' } @output = lexer_option(:output) { PlainText.new(token: Generic::Output) } @comments = bool_option(:comments) { :guess } end def prompt_regex @prompt_regex ||= begin /^#{prompt_prefix_regex}(?:#{end_chars.map(&Regexp.method(:escape)).join('|')})/ end end def end_chars @end_chars ||= if @prompt.any? @prompt.reject { |c| c.empty? } else %w($ # > ;) end end # whether to allow comments. if manually specifying a prompt that isn't # simply "#", we flag this to on def allow_comments? case @comments when :guess @prompt && !@prompt.empty? && !end_chars.include?('#') else @comments end end def prompt_prefix_regex if allow_comments? /[^<#]*?/m else /.*?/m end end def lang_lexer @lang_lexer ||= case @lang when Lexer @lang when nil Shell.new(options) when Class @lang.new(options) when String Lexer.find(@lang).new(options) end end def output_lexer @output_lexer ||= case @output when nil PlainText.new(token: Generic::Output) when Lexer @output when Class @output.new(options) when String Lexer.find(@output).new(options) end end def line_regex /(\\.|[^\\])*?(\n|$)/m end def comment_regex /\A\s*?#/ end def stream_tokens(input, &output) input = StringScanner.new(input) lang_lexer.reset! output_lexer.reset! process_line(input, &output) while !input.eos? end def process_line(input, &output) input.scan(line_regex) if input[0] =~ /\A\s*(?:<[.]+>|[.]+)\s*\z/ puts "console: matched snip #{input[0].inspect}" if @debug output_lexer.reset! lang_lexer.reset! yield Comment, input[0] elsif prompt_regex =~ input[0] puts "console: matched prompt #{input[0].inspect}" if @debug output_lexer.reset! yield Generic::Prompt, $& # make sure to take care of initial whitespace # before we pass to the lang lexer so it can determine where # the "real" beginning of the line is $' =~ /\A\s*/ yield Text, $& unless $&.empty? lang_lexer.lex($', continue: true, &output) elsif comment_regex =~ input[0].strip puts "console: matched comment #{input[0].inspect}" if @debug output_lexer.reset! lang_lexer.reset! yield Comment, input[0] else puts "console: matched output #{input[0].inspect}" if @debug lang_lexer.reset! output_lexer.lex(input[0], continue: true, &output) 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/lexers/swift.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/swift.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Swift < RegexLexer tag 'swift' filenames '*.swift' title "Swift" desc 'Multi paradigm, compiled programming language developed by Apple for iOS and OS X development. (developer.apple.com/swift)' id_head = /_|(?!\p{Mc})\p{Alpha}|[^\u0000-\uFFFF]/ id_rest = /[\p{Alnum}_]|[^\u0000-\uFFFF]/ id = /#{id_head}#{id_rest}*/ keywords = Set.new %w( break case continue default do else fallthrough if in for return switch where while try catch throw guard defer repeat as dynamicType is new super self Self Type __COLUMN__ __FILE__ __FUNCTION__ __LINE__ associativity didSet get infix inout mutating none nonmutating operator override postfix precedence prefix set unowned weak willSet throws rethrows precedencegroup ) declarations = Set.new %w( class deinit enum convenience extension final func import init internal lazy let optional private protocol public required static struct subscript typealias var dynamic indirect associatedtype open fileprivate ) constants = Set.new %w( true false nil ) start { push :bol } # beginning of line state :bol do rule /#.*/, Comment::Preproc mixin :inline_whitespace rule(//) { pop! } end state :inline_whitespace do rule /\s+/m, Text mixin :has_comments end state :whitespace do rule /\n+/m, Text, :bol rule %r(\/\/.*?$), Comment::Single, :bol mixin :inline_whitespace end state :has_comments do rule %r(/[*]), Comment::Multiline, :nested_comment end state :nested_comment do mixin :has_comments rule %r([*]/), Comment::Multiline, :pop! rule %r([^*/]+)m, Comment::Multiline rule /./, Comment::Multiline end state :root do mixin :whitespace rule /\$(([1-9]\d*)?\d)/, Name::Variable rule %r{[()\[\]{}:;,?\\]}, Punctuation rule %r([-/=+*%<>!&|^.~]+), Operator rule /@?"/, Str, :dq rule /'(\\.|.)'/, Str::Char rule /(\d+\*|\d*\.\d+)(e[+-]?[0-9]+)?/i, Num::Float rule /\d+e[+-]?[0-9]+/i, Num::Float rule /0_?[0-7]+(?:_[0-7]+)*/, Num::Oct rule /0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*/, Num::Hex rule /0b[01]+(?:_[01]+)*/, Num::Bin rule %r{[\d]+(?:_\d+)*}, Num::Integer rule /@#{id}(\([^)]+\))?/, Keyword::Declaration rule /(private|internal)(\([ ]*)(\w+)([ ]*\))/ do |m| if m[3] == 'set' token Keyword::Declaration else groups Keyword::Declaration, Keyword::Declaration, Error, Keyword::Declaration end end rule /(unowned\([ ]*)(\w+)([ ]*\))/ do |m| if m[2] == 'safe' || m[2] == 'unsafe' token Keyword::Declaration else groups Keyword::Declaration, Error, Keyword::Declaration end end rule /#available\([^)]+\)/, Keyword::Declaration rule /(#(?:selector|keyPath)\()([^)]+?(?:[(].*?[)])?)(\))/ do groups Keyword::Declaration, Name::Function, Keyword::Declaration end rule /#(line|file|column|function|dsohandle)/, Keyword::Declaration rule /(let|var)\b(\s*)(#{id})/ do groups Keyword, Text, Name::Variable end rule /(let|var)\b(\s*)([(])/ do groups Keyword, Text, Punctuation push :tuple end rule /(?!\b(if|while|for|private|internal|unowned|switch|case)\b)\b#{id}(?=(\?|!)?\s*[(])/ do |m| if m[0] =~ /^[[:upper:]]/ token Keyword::Type else token Name::Function end end rule /as[?!]?(?=\s)/, Keyword rule /try[!]?(?=\s)/, Keyword rule /(#?(?!default)(?![[:upper:]])#{id})(\s*)(:)/ do groups Name::Variable, Text, Punctuation end rule id do |m| if keywords.include? m[0] token Keyword elsif declarations.include? m[0] token Keyword::Declaration elsif constants.include? m[0] token Keyword::Constant elsif m[0] =~ /^[[:upper:]]/ token Keyword::Type else token Name end end rule /(`)(#{id})(`)/ do groups Punctuation, Name::Variable, Punctuation end end state :tuple do rule /(#{id})/, Name::Variable rule /(`)(#{id})(`)/ do groups Punctuation, Name::Variable, Punctuation end rule /,/, Punctuation rule /[(]/, Punctuation, :push rule /[)]/, Punctuation, :pop! mixin :inline_whitespace end state :dq do rule /\\[\\0tnr'"]/, Str::Escape rule /\\[(]/, Str::Escape, :interp rule /\\u\{\h{1,8}\}/, Str::Escape rule /[^\\"]+/, Str rule /"/, Str, :pop! end state :interp do rule /[(]/, Punctuation, :interp_inner rule /[)]/, Str::Escape, :pop! mixin :root end state :interp_inner do rule /[(]/, Punctuation, :push rule /[)]/, Punctuation, :pop! mixin :root end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/crystal.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/crystal.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Crystal < RegexLexer title "Crystal" desc "Crystal The Programming Language (crystal-lang.org)" tag 'crystal' aliases 'cr' filenames '*.cr' mimetypes 'text/x-crystal', 'application/x-crystal' def self.detect?(text) return true if text.shebang? 'crystal' end state :symbols do # symbols rule %r( : # initial : @{0,2} # optional ivar, for :@foo and :@@foo [a-z_]\w*[!?]? # the symbol )xi, Str::Symbol # special symbols rule %r(:(?:\*\*|[-+]@|[/\%&\|^`~]|\[\]=?|<<|>>|<=?>|<=?|===?)), Str::Symbol rule /:'(\\\\|\\'|[^'])*'/, Str::Symbol rule /:"/, Str::Symbol, :simple_sym end state :sigil_strings do # %-sigiled strings # %(abc), %[abc], %<abc>, %.abc., %r.abc., etc delimiter_map = { '{' => '}', '[' => ']', '(' => ')', '<' => '>' } rule /%([rqswQWxiI])?([^\w\s])/ do |m| open = Regexp.escape(m[2]) close = Regexp.escape(delimiter_map[m[2]] || m[2]) interp = /[rQWxI]/ === m[1] toktype = Str::Other puts " open: #{open.inspect}" if @debug puts " close: #{close.inspect}" if @debug # regexes if m[1] == 'r' toktype = Str::Regex push :regex_flags end token toktype push do rule /\\[##{open}#{close}\\]/, Str::Escape # nesting rules only with asymmetric delimiters if open != close rule /#{open}/ do token toktype push end end rule /#{close}/, toktype, :pop! if interp mixin :string_intp_escaped rule /#/, toktype else rule /[\\#]/, toktype end rule /[^##{open}#{close}\\]+/m, toktype end end end state :strings do mixin :symbols rule /\b[a-z_]\w*?[?!]?:\s+/, Str::Symbol, :expr_start rule /'(\\\\|\\'|[^'])*'/, Str::Single rule /"/, Str::Double, :simple_string rule /(?<!\.)`/, Str::Backtick, :simple_backtick end state :regex_flags do rule /[mixounse]*/, Str::Regex, :pop! end # double-quoted string and symbol [[:string, Str::Double, '"'], [:sym, Str::Symbol, '"'], [:backtick, Str::Backtick, '`']].each do |name, tok, fin| state :"simple_#{name}" do mixin :string_intp_escaped rule /[^\\#{fin}#]+/m, tok rule /[\\#]/, tok rule /#{fin}/, tok, :pop! end end keywords = %w( BEGIN END alias begin break case defined\? do else elsif end ensure for if ifdef in next redo rescue raise retry return super then undef unless until when while yield lib fun type of as ) keywords_pseudo = %w( initialize new loop include extend raise attr_reader attr_writer attr_accessor alias_method attr catch throw private module_function public protected true false nil __FILE__ __LINE__ getter getter? getter! property property? property! struct record ) builtins_g = %w( abort ancestors at_exit caller catch chomp chop clone constants display dup eval exec exit extend fail fork format freeze getc gets global_variables gsub hash id included_modules inspect instance_eval instance_method instance_methods lambda loop method method_missing methods module_eval name object_id open p print printf proc putc puts raise rand readline readlines require scan select self send sleep split sprintf srand sub syscall system test throw to_a to_s trap warn ) builtins_q = %w( eql equal include is_a iterator kind_of nil ) builtins_b = %w(chomp chop exit gsub sub) start do push :expr_start @heredoc_queue = [] end state :whitespace do mixin :inline_whitespace rule /\n\s*/m, Text, :expr_start rule /#.*$/, Comment::Single rule %r(=begin\b.*?\n=end\b)m, Comment::Multiline end state :inline_whitespace do rule /[ \t\r]+/, Text end state :root do mixin :whitespace rule /__END__/, Comment::Preproc, :end_part rule /0_?[0-7]+(?:_[0-7]+)*/, Num::Oct rule /0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*/, Num::Hex rule /0b[01]+(?:_[01]+)*/, Num::Bin rule /\d+\.\d+(e[\+\-]?\d+)?/, Num::Float rule /[\d]+(?:_\d+)*/, Num::Integer rule /@\[([^\]]+)\]/, Name::Decorator # names rule /@@[a-z_]\w*/i, Name::Variable::Class rule /@[a-z_]\w*/i, Name::Variable::Instance rule /\$\w+/, Name::Variable::Global rule %r(\$[!@&`'+~=/\\,;.<>_*\$?:"]), Name::Variable::Global rule /\$-[0adFiIlpvw]/, Name::Variable::Global rule /::/, Operator mixin :strings rule /(?:#{keywords.join('|')})\b/, Keyword, :expr_start rule /(?:#{keywords_pseudo.join('|')})\b/, Keyword::Pseudo, :expr_start rule %r( (module) (\s+) ([a-zA-Z_][a-zA-Z0-9_]*(::[a-zA-Z_][a-zA-Z0-9_]*)*) )x do groups Keyword, Text, Name::Namespace end rule /(def\b)(\s*)/ do groups Keyword, Text push :funcname end rule /(class\b)(\s*)/ do groups Keyword, Text push :classname end rule /(?:#{builtins_q.join('|')})[?]/, Name::Builtin, :expr_start rule /(?:#{builtins_b.join('|')})!/, Name::Builtin, :expr_start rule /(?<!\.)(?:#{builtins_g.join('|')})\b/, Name::Builtin, :method_call mixin :has_heredocs # `..` and `...` for ranges must have higher priority than `.` # Otherwise, they will be parsed as :method_call rule /\.{2,3}/, Operator, :expr_start rule /[A-Z][a-zA-Z0-9_]*/, Name::Constant, :method_call rule /(\.|::)(\s*)([a-z_]\w*[!?]?|[*%&^`~+-\/\[<>=])/ do groups Punctuation, Text, Name::Function push :method_call end rule /[a-zA-Z_]\w*[?!]/, Name, :expr_start rule /[a-zA-Z_]\w*/, Name, :method_call rule /\*\*|<<?|>>?|>=|<=|<=>|=~|={3}|!~|&&?|\|\||\./, Operator, :expr_start rule /[-+\/*%=<>&!^|~]=?/, Operator, :expr_start rule(/[?]/) { token Punctuation; push :ternary; push :expr_start } rule %r<[\[({,:\\;/]>, Punctuation, :expr_start rule %r<[\])}]>, Punctuation end state :has_heredocs do rule /(?<!\w)(<<[-~]?)(["`']?)([a-zA-Z_]\w*)(\2)/ do |m| token Operator, m[1] token Name::Constant, "#{m[2]}#{m[3]}#{m[4]}" @heredoc_queue << [['<<-', '<<~'].include?(m[1]), m[3]] push :heredoc_queue unless state? :heredoc_queue end rule /(<<[-~]?)(["'])(\2)/ do |m| token Operator, m[1] token Name::Constant, "#{m[2]}#{m[3]}#{m[4]}" @heredoc_queue << [['<<-', '<<~'].include?(m[1]), ''] push :heredoc_queue unless state? :heredoc_queue end end state :heredoc_queue do rule /(?=\n)/ do goto :resolve_heredocs end mixin :root end state :resolve_heredocs do mixin :string_intp_escaped rule /\n/, Str::Heredoc, :test_heredoc rule /[#\\\n]/, Str::Heredoc rule /[^#\\\n]+/, Str::Heredoc end state :test_heredoc do rule /[^#\\\n]*$/ do |m| tolerant, heredoc_name = @heredoc_queue.first check = tolerant ? m[0].strip : m[0].rstrip # check if we found the end of the heredoc puts " end heredoc check #{check.inspect} = #{heredoc_name.inspect}" if @debug if check == heredoc_name @heredoc_queue.shift # if there's no more, we're done looking. pop! if @heredoc_queue.empty? token Name::Constant else token Str::Heredoc end pop! end rule(//) { pop! } end state :funcname do rule /\s+/, Text rule /\(/, Punctuation, :defexpr rule %r( (?:([a-zA-Z_][\w_]*)(\.))? ( [a-zA-Z_][\w_]*[!?]? | \*\*? | [-+]@? | [/%&\|^`~] | \[\]=? | <<? | >>? | <=>? | >= | ===? ) )x do |m| puts "matches: #{[m[0], m[1], m[2], m[3]].inspect}" if @debug groups Name::Class, Operator, Name::Function pop! end rule(//) { pop! } end state :classname do rule /\s+/, Text rule /\(/ do token Punctuation push :defexpr push :expr_start end # class << expr rule /<</ do token Operator goto :expr_start end rule /[A-Z_]\w*/, Name::Class, :pop! rule(//) { pop! } end state :ternary do rule(/:(?!:)/) { token Punctuation; goto :expr_start } mixin :root end state :defexpr do rule /(\))(\.|::)?/ do groups Punctuation, Operator pop! end rule /\(/ do token Punctuation push :defexpr push :expr_start end mixin :root end state :in_interp do rule /}/, Str::Interpol, :pop! mixin :root end state :string_intp do rule /[#][{]/, Str::Interpol, :in_interp rule /#(@@?|\$)[a-z_]\w*/i, Str::Interpol end state :string_intp_escaped do mixin :string_intp rule /\\([\\abefnrstv#"']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})/, Str::Escape rule /\\./, Str::Escape end state :method_call do rule %r(/) do token Operator goto :expr_start end rule(/(?=\n)/) { pop! } rule(//) { goto :method_call_spaced } end state :method_call_spaced do mixin :whitespace rule %r([%/]=) do token Operator goto :expr_start end rule %r((/)(?=\S|\s*/)) do token Str::Regex goto :slash_regex end mixin :sigil_strings rule(%r((?=\s*/))) { pop! } rule(/\s+/) { token Text; goto :expr_start } rule(//) { pop! } end state :expr_start do mixin :inline_whitespace rule %r(/) do token Str::Regex goto :slash_regex end # char operator. ?x evaulates to "x", unless there's a digit # beforehand like x>=0?n[x]:"" rule %r( [?](\\[MC]-)* # modifiers (\\([\\abefnrstv\#"']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})|\S) (?!\w) )x, Str::Char, :pop! # special case for using a single space. Ruby demands that # these be in a single line, otherwise it would make no sense. rule /(\s*)(%[rqswQWxiI]? \S* )/ do groups Text, Str::Other pop! end mixin :sigil_strings rule(//) { pop! } end state :slash_regex do mixin :string_intp rule %r(\\\\), Str::Regex rule %r(\\/), Str::Regex rule %r([\\#]), Str::Regex rule %r([^\\/#]+)m, Str::Regex rule %r(/) do token Str::Regex goto :regex_flags end end state :end_part do # eat up the rest of the stream as Comment::Preproc rule /.+/m, Comment::Preproc, :pop! 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/lexers/fortran.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/fortran.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true # vim: set ts=2 sw=2 et: # TODO: Implement format list support. module Rouge module Lexers class Fortran < RegexLexer title "Fortran" desc "Fortran 2008 (free-form)" tag 'fortran' filenames '*.f', '*.f90', '*.f95', '*.f03', '*.f08', '*.F', '*.F90', '*.F95', '*.F03', '*.F08' mimetypes 'text/x-fortran' name = /[A-Z][_A-Z0-9]*/i kind_param = /(\d+|#{name})/ exponent = /[ED][+-]?\d+/i def self.keywords # Special rules for two-word keywords are defined further down. # Note: Fortran allows to omit whitespace between certain keywords. @keywords ||= Set.new %w( abstract allocatable allocate assign assignment associate asynchronous backspace bind block blockdata call case class close codimension common concurrent contains contiguous continue critical cycle data deallocate deferred dimension do elemental else elseif elsewhere end endassociate endblock endblockdata enddo endenum endfile endforall endfunction endif endinterface endmodule endprogram endselect endsubmodule endsubroutine endtype endwhere endwhile entry enum enumerator equivalence exit extends external final flush forall format function generic goto if implicit import in include inout inquire intent interface intrinsic is lock module namelist non_overridable none nopass nullify only open operator optional out parameter pass pause pointer print private procedure program protected public pure read recursive result return rewind save select selectcase sequence stop submodule subroutine target then type unlock use value volatile wait where while write ) end def self.types # A special rule for the two-word version "double precision" is # defined further down. @types ||= Set.new %w( character complex doubleprecision integer logical real ) end def self.intrinsics @intrinsics ||= Set.new %w( abs achar acos acosh adjustl adjustr aimag aint all allocated anint any asin asinh associated atan atan2 atanh atomic_define atomic_ref bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn bge bgt bit_size ble blt btest c_associated c_f_pointer c_f_procpointer c_funloc c_loc c_sizeof ceiling char cmplx command_argument_count compiler_options compiler_version conjg cos cosh count cpu_time cshift date_and_time dble digits dim dot_product dprod dshiftl dshiftr eoshift epsilon erf erfc_scaled erfc execute_command_line exp exponent extends_type_of findloc floor fraction gamma get_command_argument get_command get_environment_variable huge hypot iachar iall iand iany ibclr ibits ibset ichar ieee_class ieee_copy_sign ieee_get_flag ieee_get_halting_mode ieee_get_rounding_mode ieee_get_status ieee_get_underflow_mode ieee_is_finite ieee_is_nan ieee_is_normal ieee_logb ieee_next_after ieee_rem ieee_rint ieee_scalb ieee_selected_real_kind ieee_set_flag ieee_set_halting_mode ieee_set_rounding_mode ieee_set_status ieee_set_underflow_mode ieee_support_datatype ieee_support_denormal ieee_support_divide ieee_support_flag ieee_support_halting ieee_support_inf ieee_support_io ieee_support_nan ieee_support_rounding ieee_support_sqrt ieee_support_standard ieee_support_underflow_control ieee_unordered ieee_value ieor image_index index int ior iparity is_contiguous is_iostat_end is_iostat_eor ishft ishftc kind lbound lcobound leadz len_trim len lge lgt lle llt log_gamma log log10 logical maskl maskr matmul max maxexponent maxloc maxval merge_bits merge min minexponent minloc minval mod modulo move_alloc mvbits nearest new_line nint norm2 not null num_images pack parity popcnt poppar present product radix random_number random_seed range real repeat reshape rrspacing same_type_as scale scan selected_char_kind selected_int_kind selected_real_kind set_exponent shape shifta shiftl shiftr sign sin sinh size spacing spread sqrt storage_size sum system_clock tan tanh this_image tiny trailz transfer transpose trim ubound ucobound unpack verify ) end state :root do rule /[\s\n]+/, Text::Whitespace rule /!.*$/, Comment::Single rule /^#.*$/, Comment::Preproc rule /::|[()\/;,:&\[\]]/, Punctuation # TODO: This does not take into account line continuation. rule /^(\s*)([0-9]+)\b/m do |m| token Text::Whitespace, m[1] token Name::Label, m[2] end # Format statements are quite a strange beast. # Better process them in their own state. rule /\b(FORMAT)(\s*)(\()/mi do |m| token Keyword, m[1] token Text::Whitespace, m[2] token Punctuation, m[3] push :format_spec end rule %r( [+-]? # sign ( (\d+[.]\d*|[.]\d+)(#{exponent})? | \d+#{exponent} # exponent is mandatory ) (_#{kind_param})? # kind parameter )xi, Num::Float rule /[+-]?\d+(_#{kind_param})?/i, Num::Integer rule /B'[01]+'|B"[01]+"/i, Num::Bin rule /O'[0-7]+'|O"[0-7]+"/i, Num::Oct rule /Z'[0-9A-F]+'|Z"[0-9A-F]+"/i, Num::Hex rule /(#{kind_param}_)?'/, Str::Single, :string_single rule /(#{kind_param}_)?"/, Str::Double, :string_double rule /[.](TRUE|FALSE)[.](_#{kind_param})?/i, Keyword::Constant rule %r{\*\*|//|==|/=|<=|>=|=>|[-+*/<>=%]}, Operator rule /\.(?:EQ|NE|LT|LE|GT|GE|NOT|AND|OR|EQV|NEQV|[A-Z]+)\./i, Operator::Word # Special rules for two-word keywords and types. # Note: "doubleprecision" is covered by the normal keyword rule. rule /double\s+precision\b/i, Keyword::Type rule /go\s+to\b/i, Keyword rule /sync\s+(all|images|memory)\b/i, Keyword rule /error\s+stop\b/i, Keyword rule /#{name}/m do |m| match = m[0].downcase if self.class.keywords.include? match token Keyword elsif self.class.types.include? match token Keyword::Type elsif self.class.intrinsics.include? match token Name::Builtin else token Name end end end state :string_single do rule /[^']+/, Str::Single rule /''/, Str::Escape rule /'/, Str::Single, :pop! end state :string_double do rule /[^"]+/, Str::Double rule /""/, Str::Escape rule /"/, Str::Double, :pop! end state :format_spec do rule /'/, Str::Single, :string_single rule /"/, Str::Double, :string_double rule /\(/, Punctuation, :format_spec rule /\)/, Punctuation, :pop! rule /,/, Punctuation rule /[\s\n]+/, Text::Whitespace # Edit descriptors could be seen as a kind of "format literal". rule /[^\s'"(),]+/, Literal 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/lexers/m68k.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/m68k.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class M68k < RegexLexer tag 'm68k' title "M68k" desc "Motorola 68k Assembler" ws = %r((?:\s|;.*?\n/)+) id = /[a-zA-Z_][a-zA-Z0-9_]*/ def self.keywords @keywords ||= Set.new %w( abcd add adda addi addq addx and andi asl asr bcc bcs beq bge bgt bhi ble bls blt bmi bne bpl bvc bvs bhs blo bchg bclr bfchg bfclr bfests bfextu bfffo bfins bfset bftst bkpt bra bse bsr btst callm cas cas2 chk chk2 clr cmp cmpa cmpi cmpm cmp2 dbcc dbcs dbeq dbge dbgt dbhi dble dbls dblt dbmi dbne dbpl dbvc dbvs dbhs dblo dbra dbf dbt divs divsl divu divul eor eori exg ext extb illegal jmp jsr lea link lsl lsr move movea move16 movem movep moveq muls mulu nbcd neg negx nop not or ori pack pea rol ror roxl roxr rtd rtm rtr rts sbcd seq sne spl smi svc svs st sf sge sgt sle slt scc shi sls scs shs slo sub suba subi subq subx swap tas trap trapcc TODO trapv tst unlk unpk eori ) end def self.keywords_type @keywords_type ||= Set.new %w( dc ds dcb ) end def self.reserved @reserved ||= Set.new %w( include incdir incbin end endf endfunc endmain endproc fpu func machine main mmu opword proc set opt section rept endr ifeq ifne ifgt ifge iflt ifle iif ifd ifnd ifc ifnc elseif else endc even cnop fail machine output radix __G2 __LK list nolist plen llen ttl subttl spc page listchar format equ equenv equr set reg rsreset rsset offset cargs fequ.s fequ.d fequ.x fequ.p fequ.w fequ.l fopt macro endm mexit narg ) end def self.builtins @builtins ||=Set.new %w( d0 d1 d2 d3 d4 d5 d6 d7 a0 a1 a2 a3 a4 a5 a6 a7 a7' pc usp ssp ccr ) end start { push :expr_bol } state :expr_bol do mixin :inline_whitespace rule(//) { pop! } end state :inline_whitespace do rule /[\s\t\r]+/, Text end state :whitespace do rule /\n+/m, Text, :expr_bol rule %r(^\*(\\.|.)*?\n), Comment::Single, :expr_bol rule %r(;(\\.|.)*?\n), Comment::Single, :expr_bol mixin :inline_whitespace end state :root do rule(//) { push :statements } end state :statements do mixin :whitespace rule /"/, Str, :string rule /#/, Name::Decorator rule /^\.?[a-zA-Z0-9_]+:?/, Name::Label rule /\.[bswl]\s/i, Name::Decorator rule %r('(\\.|\\[0-7]{1,3}|\\x[a-f0-9]{1,2}|[^\\'\n])')i, Str::Char rule /\$[0-9a-f]+/i, Num::Hex rule /@[0-8]+/i, Num::Oct rule /%[01]+/i, Num::Bin rule /\d+/i, Num::Integer rule %r([*~&+=\|?:<>/-]), Operator rule /\\./, Comment::Preproc rule /[(),.]/, Punctuation rule /\[[a-zA-Z0-9]*\]/, Punctuation rule id do |m| name = m[0] if self.class.keywords.include? name.downcase token Keyword elsif self.class.keywords_type.include? name.downcase token Keyword::Type elsif self.class.reserved.include? name.downcase token Keyword::Reserved elsif self.class.builtins.include? name.downcase token Name::Builtin elsif name =~ /[a-zA-Z0-9]+/ token Name::Variable else token Name end end end state :string do rule /"/, Str, :pop! rule /\\([\\abfnrtv"']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})/, Str::Escape rule /[^\\"\n]+/, Str rule /\\\n/, Str rule /\\/, Str # stray backslash 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/lexers/json.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/json.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class JSON < RegexLexer title 'JSON' desc "JavaScript Object Notation (json.org)" tag 'json' filenames '*.json' mimetypes 'application/json', 'application/vnd.api+json', 'application/hal+json' state :root do rule /\s+/m, Text::Whitespace rule /"/, Str::Double, :string rule /(?:true|false|null)\b/, Keyword::Constant rule /[{},:\[\]]/, Punctuation rule /-?(?:0|[1-9]\d*)\.\d+(?:e[+-]?\d+)?/i, Num::Float rule /-?(?:0|[1-9]\d*)(?:e[+-]?\d+)?/i, Num::Integer end state :string do rule /[^\\"]+/, Str::Double rule /\\./, Str::Escape rule /"/, Str::Double, :pop! 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/lexers/irb.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/irb.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers load_lexer 'console.rb' class IRBLexer < ConsoleLexer tag 'irb' aliases 'pry' desc 'Shell sessions in IRB or Pry' # unlike the superclass, we do not accept any options @option_docs = {} def output_lexer @output_lexer ||= IRBOutputLexer.new(@options) end def lang_lexer @lang_lexer ||= Ruby.new(@options) end def prompt_regex /^.*?(irb|pry).*?[>"*]/ end def allow_comments? true end end load_lexer 'ruby.rb' class IRBOutputLexer < Ruby tag 'irb_output' start do push :stdout end state :has_irb_output do rule %r(=>), Punctuation, :pop! rule /.+?(\n|$)/, Generic::Output end state :irb_error do rule /.+?(\n|$)/, Generic::Error mixin :has_irb_output end state :stdout do rule /\w+?(Error|Exception):.+?(\n|$)/, Generic::Error, :irb_error mixin :has_irb_output end prepend :root do rule /#</, Keyword::Type, :irb_object end state :irb_object do rule />/, Keyword::Type, :pop! mixin :root end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/coffeescript.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/coffeescript.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Coffeescript < RegexLexer tag 'coffeescript' aliases 'coffee', 'coffee-script' filenames '*.coffee', 'Cakefile' mimetypes 'text/coffeescript' title "CoffeeScript" desc 'The Coffeescript programming language (coffeescript.org)' def self.detect?(text) return true if text.shebang? 'coffee' end def self.keywords @keywords ||= Set.new %w( for in of while break return continue switch when then if else throw try catch finally new delete typeof instanceof super extends this class by ) end def self.constants @constants ||= Set.new %w( true false yes no on off null NaN Infinity undefined ) end def self.builtins @builtins ||= Set.new %w( Array Boolean Date Error Function Math netscape Number Object Packages RegExp String sun decodeURI decodeURIComponent encodeURI encodeURIComponent eval isFinite isNaN parseFloat parseInt document window ) end id = /[$a-zA-Z_][a-zA-Z0-9_]*/ state :comments_and_whitespace do rule /\s+/m, Text rule /###\s*\n.*?###/m, Comment::Multiline rule /#.*$/, Comment::Single end state :multiline_regex do # this order is important, so that #{ isn't interpreted # as a comment mixin :has_interpolation mixin :comments_and_whitespace rule %r(///([gim]+\b|\B)), Str::Regex, :pop! rule %r(/), Str::Regex rule %r([^/#]+), Str::Regex end state :slash_starts_regex do mixin :comments_and_whitespace rule %r(///) do token Str::Regex goto :multiline_regex end rule %r( /(\\.|[^\[/\\\n]|\[(\\.|[^\]\\\n])*\])+/ # a regex ([gim]+\b|\B) )x, Str::Regex, :pop! rule(//) { pop! } end state :root do rule(%r(^(?=\s|/|<!--))) { push :slash_starts_regex } mixin :comments_and_whitespace rule %r( [+][+]|--|~|&&|\band\b|\bor\b|\bis\b|\bisnt\b|\bnot\b|[?]|:|=| [|][|]|\\(?=\n)|(<<|>>>?|==?|!=?|[-<>+*`%&|^/])=? )x, Operator, :slash_starts_regex rule /[-=]>/, Name::Function rule /(@)([ \t]*)(#{id})/ do groups Name::Variable::Instance, Text, Name::Attribute push :slash_starts_regex end rule /([.])([ \t]*)(#{id})/ do groups Punctuation, Text, Name::Attribute push :slash_starts_regex end rule /#{id}(?=\s*:)/, Name::Attribute, :slash_starts_regex rule /#{id}/ do |m| if self.class.keywords.include? m[0] token Keyword elsif self.class.constants.include? m[0] token Name::Constant elsif self.class.builtins.include? m[0] token Name::Builtin else token Name::Other end push :slash_starts_regex end rule /[{(\[;,]/, Punctuation, :slash_starts_regex rule /[})\].]/, Punctuation rule /\d+[.]\d+([eE]\d+)?[fd]?/, Num::Float rule /0x[0-9a-fA-F]+/, Num::Hex rule /\d+/, Num::Integer rule /"""/, Str, :tdqs rule /'''/, Str, :tsqs rule /"/, Str, :dqs rule /'/, Str, :sqs end state :strings do # all coffeescript strings are multi-line rule /[^#\\'"]+/m, Str rule /\\./, Str::Escape rule /#/, Str end state :double_strings do rule /'/, Str mixin :has_interpolation mixin :strings end state :single_strings do rule /"/, Str mixin :strings end state :interpolation do rule /}/, Str::Interpol, :pop! mixin :root end state :has_interpolation do rule /[#][{]/, Str::Interpol, :interpolation end state :dqs do rule /"/, Str, :pop! mixin :double_strings end state :tdqs do rule /"""/, Str, :pop! rule /"/, Str mixin :double_strings end state :sqs do rule /'/, Str, :pop! mixin :single_strings end state :tsqs do rule /'''/, Str, :pop! rule /'/, Str mixin :single_strings 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/lexers/apache.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/apache.rb
# frozen_string_literal: true require 'yaml' module Rouge module Lexers class Apache < RegexLexer title "Apache" desc 'configuration files for Apache web server' tag 'apache' mimetypes 'text/x-httpd-conf', 'text/x-apache-conf' filenames '.htaccess', 'httpd.conf' class << self attr_reader :keywords end # Load Apache keywords from separate YML file @keywords = ::YAML.load_file(Pathname.new(__FILE__).dirname.join('apache/keywords.yml')).tap do |h| h.each do |k,v| h[k] = Set.new v end end def name_for_token(token, kwtype, tktype) if self.class.keywords[kwtype].include? token tktype else Text end end state :whitespace do rule /\#.*/, Comment rule /\s+/m, Text end state :root do mixin :whitespace rule /(<\/?)(\w+)/ do |m| groups Punctuation, name_for_token(m[2].downcase, :sections, Name::Label) push :section end rule /\w+/ do |m| token name_for_token(m[0].downcase, :directives, Name::Class) push :directive end end state :section do # Match section arguments rule /([^>]+)?(>(?:\r\n?|\n)?)/ do |m| groups Literal::String::Regex, Punctuation pop! end mixin :whitespace end state :directive do # Match value literals and other directive arguments rule /\r\n?|\n/, Text, :pop! mixin :whitespace rule /\S+/ do |m| token name_for_token(m[0], :values, Literal::String::Symbol) 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/lexers/hcl.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/hcl.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class Hcl < RegexLexer tag 'hcl' title 'Hashicorp Configuration Language' desc 'Hashicorp Configuration Language, used by Terraform and other Hashicorp tools' state :multiline_comment do rule %r([*]/), Comment::Multiline, :pop! rule %r([^*/]+), Comment::Multiline rule %r([*/]), Comment::Multiline end state :comments_and_whitespace do rule /\s+/, Text rule %r(//.*?$), Comment::Single rule %r(#.*?$), Comment::Single rule %r(/[*]), Comment::Multiline, :multiline_comment end state :primitives do rule /[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?([kKmMgG]b?)?/, Num::Float rule /[0-9]+([kKmMgG]b?)?/, Num::Integer rule /"/, Str::Double, :dq rule /'/, Str::Single, :sq rule /(<<-?)(\s*)(\'?)(\\?)(\w+)(\3)/ do |m| groups Operator, Text, Str::Heredoc, Str::Heredoc, Name::Constant, Str::Heredoc @heredocstr = Regexp.escape(m[5]) push :heredoc end end def self.keywords @keywords ||= Set.new %w() end def self.declarations @declarations ||= Set.new %w() end def self.reserved @reserved ||= Set.new %w() end def self.constants @constants ||= Set.new %w(true false null) end def self.builtins @builtins ||= %w() end id = /[$a-z_][a-z0-9_]*/io state :root do mixin :comments_and_whitespace mixin :primitives rule /\{/ do token Punctuation push :hash end rule /\[/ do token Punctuation push :array end rule id do |m| if self.class.keywords.include? m[0] token Keyword push :composite elsif self.class.declarations.include? m[0] token Keyword::Declaration push :composite elsif self.class.reserved.include? m[0] token Keyword::Reserved elsif self.class.constants.include? m[0] token Keyword::Constant elsif self.class.builtins.include? m[0] token Name::Builtin else token Name::Other push :composite end end end state :composite do mixin :comments_and_whitespace rule /[{]/ do token Punctuation pop! push :hash end rule /[\[]/ do token Punctuation pop! push :array end mixin :root rule //, Text, :pop! end state :hash do mixin :comments_and_whitespace rule /\=/, Punctuation rule /\}/, Punctuation, :pop! mixin :root end state :array do mixin :comments_and_whitespace rule /,/, Punctuation rule /\]/, Punctuation, :pop! mixin :root end state :dq do rule /[^\\"]+/, Str::Double rule /\\"/, Str::Escape rule /"/, Str::Double, :pop! end state :sq do rule /[^\\']+/, Str::Single rule /\\'/, Str::Escape rule /'/, Str::Single, :pop! end state :heredoc do rule /\n/, Str::Heredoc, :heredoc_nl rule /[^$\n]+/, Str::Heredoc rule /[$]/, Str::Heredoc end state :heredoc_nl do rule /\s*(\w+)\s*\n/ do |m| if m[1] == @heredocstr token Name::Constant pop! 2 else token Str::Heredoc end end rule(//) { pop! } 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/lexers/php.rb
_vendor/ruby/2.6.0/gems/rouge-3.3.0/lib/rouge/lexers/php.rb
# -*- coding: utf-8 -*- # # frozen_string_literal: true module Rouge module Lexers class PHP < TemplateLexer title "PHP" desc "The PHP scripting language (php.net)" tag 'php' aliases 'php', 'php3', 'php4', 'php5' filenames '*.php', '*.php[345t]','*.phtml', # Support Drupal file extensions, see: # https://github.com/gitlabhq/gitlabhq/issues/8900 '*.module', '*.inc', '*.profile', '*.install', '*.test' mimetypes 'text/x-php' option :start_inline, 'Whether to start with inline php or require <?php ... ?>. (default: best guess)' option :funcnamehighlighting, 'Whether to highlight builtin functions (default: true)' option :disabledmodules, 'Disable certain modules from being highlighted as builtins (default: empty)' def initialize(*) super # if truthy, the lexer starts highlighting with php code # (no <?php required) @start_inline = bool_option(:start_inline) { :guess } @funcnamehighlighting = bool_option(:funcnamehighlighting) { true } @disabledmodules = list_option(:disabledmodules) end def self.builtins load Pathname.new(__FILE__).dirname.join('php/builtins.rb') self.builtins end def builtins return [] unless @funcnamehighlighting @builtins ||= Set.new.tap do |builtins| self.class.builtins.each do |mod, fns| next if @disabledmodules.include? mod builtins.merge(fns) end end end # source: http://php.net/manual/en/language.variables.basics.php # the given regex is invalid utf8, so... we're using the unicode # "Letter" property instead. id = /[\p{L}_][\p{L}\p{N}_]*/ nsid = /#{id}(?:\\#{id})*/ start do case @start_inline when true push :template push :php when false push :template when :guess # pass end end def self.keywords @keywords ||= Set.new %w( and E_PARSE old_function E_ERROR or as E_WARNING parent eval PHP_OS break exit case extends PHP_VERSION cfunction FALSE print for require continue foreach require_once declare return default static do switch die stdClass echo else TRUE elseif var empty if xor enddeclare include virtual endfor include_once while endforeach global __FILE__ endif list __LINE__ endswitch new __sleep endwhile not array __wakeup E_ALL NULL final php_user_filter interface implements public private protected abstract clone try catch throw this use namespace yield ) end def self.detect?(text) return true if text.shebang?('php') return false if /^<\?hh/ =~ text return true if /^<\?php/ =~ text end state :root do # some extremely rough heuristics to decide whether to start inline or not rule(/\s*(?=<)/m) { delegate parent; push :template } rule(/[^$]+(?=<\?(php|=))/) { delegate parent; push :template } rule(//) { push :template; push :php } end state :template do rule /<\?(php|=)?/, Comment::Preproc, :php rule(/.*?(?=<\?)|.*/m) { delegate parent } end state :php do rule /\?>/, Comment::Preproc, :pop! # heredocs rule /<<<('?)(#{id})\1\n.*?\n\2;?\n/im, Str::Heredoc rule /\s+/, Text rule /#.*?$/, Comment::Single rule %r(//.*?$), Comment::Single # empty comment, otherwise seen as the start of a docstring rule %r(/\*\*/), Comment::Multiline rule %r(/\*\*.*?\*/)m, Str::Doc rule %r(/\*.*?\*/)m, Comment::Multiline rule /(->|::)(\s*)(#{id})/ do groups Operator, Text, Name::Attribute end rule /[~!%^&*+=\|:.<>\/?@-]+/, Operator rule /[\[\]{}();,]/, Punctuation rule /class\b/, Keyword, :classname # anonymous functions rule /(function)(\s*)(?=\()/ do groups Keyword, Text end # named functions rule /(function)(\s+)(&?)(\s*)/ do groups Keyword, Text, Operator, Text push :funcname end rule /(const)(\s+)(#{id})/i do groups Keyword, Text, Name::Constant end rule /(true|false|null)\b/, Keyword::Constant rule /\$\{\$+#{id}\}/i, Name::Variable rule /\$+#{id}/i, Name::Variable # may be intercepted for builtin highlighting rule /\\?#{nsid}/i do |m| name = m[0] if self.class.keywords.include? name token Keyword elsif self.builtins.include? name token Name::Builtin else token Name::Other end end rule /(\d+\.\d*|\d*\.\d+)(e[+-]?\d+)?/i, Num::Float rule /\d+e[+-]?\d+/i, Num::Float rule /0[0-7]+/, Num::Oct rule /0x[a-f0-9]+/i, Num::Hex rule /\d+/, Num::Integer rule /'([^'\\]*(?:\\.[^'\\]*)*)'/, Str::Single rule /`([^`\\]*(?:\\.[^`\\]*)*)`/, Str::Backtick rule /"/, Str::Double, :string end state :classname do rule /\s+/, Text rule /#{nsid}/, Name::Class, :pop! end state :funcname do rule /#{id}/, Name::Function, :pop! end state :string do rule /"/, Str::Double, :pop! rule /[^\\{$"]+/, Str::Double rule /\\([nrt\"$\\]|[0-7]{1,3}|x[0-9A-Fa-f]{1,2})/, Str::Escape rule /\$#{id}(\[\S+\]|->#{id})?/, Name::Variable rule /\{\$\{/, Str::Interpol, :interp_double rule /\{(?=\$)/, Str::Interpol, :interp_single rule /(\{)(\S+)(\})/ do groups Str::Interpol, Name::Variable, Str::Interpol end rule /[${\\]+/, Str::Double end state :interp_double do rule /\}\}/, Str::Interpol, :pop! mixin :php end state :interp_single do rule /\}/, Str::Interpol, :pop! mixin :php end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false