Class: Crass::Tokenizer
- Inherits:
-
Object
- Object
- Crass::Tokenizer
- Defined in:
- lib/crass/tokenizer.rb
Overview
Tokenizes a CSS string.
Constant Summary collapse
- RE_COMMENT_CLOSE =
/\*\//- RE_DIGIT =
/[0-9]+/- RE_ESCAPE =
/\\[^\n]/- RE_HEX =
/[0-9A-Fa-f]{1,6}/- RE_NAME =
/[0-9A-Za-z_\u0080-\u{10ffff}-]+/- RE_NAME_START =
/[A-Za-z_\u0080-\u{10ffff}]+/- RE_NON_PRINTABLE =
/[\u0000-\u0008\u000b\u000e-\u001f\u007f]+/- RE_NUMBER_DECIMAL =
/\.[0-9]+/- RE_NUMBER_EXPONENT =
/[Ee][+-]?[0-9]+/- RE_NUMBER_SIGN =
/[+-]/- RE_NUMBER_STR =
/\A (?<sign> [+-]?) (?<integer> [0-9]*) (?:\. (?<fractional> [0-9]*) )? (?:[Ee] (?<exponent_sign> [+-]?) (?<exponent> [0-9]*) )? \z/x- RE_QUOTED_URL_START =
/\A[\n\u0009\u0020]?["']/- RE_UNICODE_RANGE_START =
/\+(?:[0-9A-Fa-f]|\?)/- RE_UNICODE_RANGE_END =
/-[0-9A-Fa-f]/- RE_WHITESPACE =
/[\n\u0009\u0020]+/- RE_WHITESPACE_ANCHORED =
/\A[\n\u0009\u0020]+\z/
Class Method Summary collapse
-
.tokenize(input, options = {}) ⇒ Object
Tokenizes the given input as a CSS string and returns an array of tokens.
Instance Method Summary collapse
-
#consume ⇒ Object
Consumes a token and returns the token that was consumed.
-
#consume_bad_url ⇒ Object
Consumes the remnants of a bad URL and returns the consumed text.
-
#consume_comments ⇒ Object
Consumes comments and returns them, or
nilif no comments were consumed. -
#consume_escaped ⇒ Object
Consumes an escaped code point and returns its unescaped value.
-
#consume_ident ⇒ Object
Consumes an ident-like token and returns it.
-
#consume_name ⇒ Object
Consumes a name and returns it.
-
#consume_number ⇒ Object
Consumes a number and returns a 3-element array containing the number's original representation, its numeric value, and its type (either
:integeror:number). -
#consume_numeric ⇒ Object
Consumes a numeric token and returns it.
-
#consume_string(ending = nil) ⇒ Object
Consumes a string token that ends at the given character, and returns the token.
-
#consume_unicode_range ⇒ Object
Consumes a Unicode range token and returns it.
-
#consume_url ⇒ Object
Consumes a URL token and returns it.
-
#convert_string_to_number(str) ⇒ Object
Converts a valid CSS number string into a number and returns the number.
-
#create_token(type, properties = {}) ⇒ Object
Creates and returns a new token with the given properties.
-
#initialize(input, options = {}) ⇒ Tokenizer
constructor
Initializes a new Tokenizer.
-
#preprocess(input) ⇒ Object
Preprocesses input to prepare it for the tokenizer.
-
#start_identifier?(text = nil) ⇒ Boolean
Returns
trueif the given three-character text would start an identifier. -
#start_number?(text = nil) ⇒ Boolean
Returns
trueif the given three-character text would start a number. -
#tokenize ⇒ Object
Tokenizes the input stream and returns an array of tokens.
-
#valid_escape?(text = nil) ⇒ Boolean
Returns
trueif the given two-character text is the beginning of a valid escape sequence.
Constructor Details
#initialize(input, options = {}) ⇒ Tokenizer
Initializes a new Tokenizer.
Options:
:preserve_comments - If
true, comments will be preserved as:commenttokens.:preserve_hacks - If
true, certain non-standard browser hacks such as the IE "*" hack will be preserved even though they violate CSS 3 syntax rules.
62 63 64 65 |
# File 'lib/crass/tokenizer.rb', line 62 def initialize(input, = {}) @s = Scanner.new(preprocess(input)) @options = end |
Class Method Details
.tokenize(input, options = {}) ⇒ Object
Tokenizes the given input as a CSS string and returns an array of tokens.
See #initialize for options.
45 46 47 |
# File 'lib/crass/tokenizer.rb', line 45 def self.tokenize(input, = {}) Tokenizer.new(input, ).tokenize end |
Instance Method Details
#consume ⇒ Object
Consumes a token and returns the token that was consumed.
4.3.1. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-a-token
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 |
# File 'lib/crass/tokenizer.rb', line 70 def consume # Skip over any comments. When comments aren't being preserved this is # done iteratively rather than recursively so that a long run of adjacent # comments can't exhaust the Ruby stack and raise a `SystemStackError`. loop do return nil if @s.eos? @s.mark comment_token = consume_comments break unless comment_token return comment_token if @options[:preserve_comments] end # Consume whitespace. return create_token(:whitespace) if @s.scan(RE_WHITESPACE) char = @s.consume case char.to_sym when :'"' consume_string when :'#' if @s.peek =~ RE_NAME || valid_escape?(@s.peek(2)) create_token(:hash, :type => start_identifier?(@s.peek(3)) ? :id : :unrestricted, :value => consume_name) else create_token(:delim, :value => char) end when :'$' if @s.peek == '=' @s.consume create_token(:suffix_match) else create_token(:delim, :value => char) end when :"'" consume_string when :'(' create_token(:'(') when :')' create_token(:')') when :* if @s.peek == '=' @s.consume create_token(:substring_match) # Non-standard: Preserve the IE * hack. elsif @options[:preserve_hacks] && @s.peek =~ RE_NAME_START @s.reconsume consume_ident else create_token(:delim, :value => char) end when :+ if start_number? @s.reconsume consume_numeric else create_token(:delim, :value => char) end when :',' create_token(:comma) when :- nextTwoChars = @s.peek(2) nextThreeChars = char + nextTwoChars if start_number?(nextThreeChars) @s.reconsume consume_numeric elsif nextTwoChars == '->' @s.consume @s.consume create_token(:cdc) elsif start_identifier?(nextThreeChars) @s.reconsume consume_ident else create_token(:delim, :value => char) end when :'.' if start_number? @s.reconsume consume_numeric else create_token(:delim, :value => char) end when :':' create_token(:colon) when :';' create_token(:semicolon) when :< if @s.peek(3) == '!--' @s.consume @s.consume @s.consume create_token(:cdo) else create_token(:delim, :value => char) end when :'@' if start_identifier?(@s.peek(3)) create_token(:at_keyword, :value => consume_name) else create_token(:delim, :value => char) end when :'[' create_token(:'[') when :'\\' if valid_escape? @s.reconsume consume_ident else # Parse error. create_token(:delim, :error => true, :value => char) end when :']' create_token(:']') when :'^' if @s.peek == '=' @s.consume create_token(:prefix_match) else create_token(:delim, :value => char) end when :'{' create_token(:'{') when :'}' create_token(:'}') when :U, :u if @s.peek(2) =~ RE_UNICODE_RANGE_START @s.consume consume_unicode_range else @s.reconsume consume_ident end when :| case @s.peek when '=' @s.consume create_token(:dash_match) when '|' @s.consume create_token(:column) else create_token(:delim, :value => char) end when :~ if @s.peek == '=' @s.consume create_token(:include_match) else create_token(:delim, :value => char) end else case char when RE_DIGIT @s.reconsume consume_numeric when RE_NAME_START @s.reconsume consume_ident else create_token(:delim, :value => char) end end end |
#consume_bad_url ⇒ Object
Consumes the remnants of a bad URL and returns the consumed text.
4.3.15. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-the-remnants-of-a-bad-url
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
# File 'lib/crass/tokenizer.rb', line 276 def consume_bad_url text = String.new until @s.eos? if valid_escape? text << consume_escaped elsif valid_escape?(@s.peek(2)) @s.consume text << consume_escaped else char = @s.consume if char == ')' break else text << char end end end text end |
#consume_comments ⇒ Object
Consumes comments and returns them, or nil if no comments were consumed.
4.3.2. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-comments
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
# File 'lib/crass/tokenizer.rb', line 302 def consume_comments if @s.peek(2) == '/*' @s.consume @s.consume if text = @s.scan_until(RE_COMMENT_CLOSE) text.slice!(-2, 2) else # Parse error. text = @s.consume_rest end return create_token(:comment, :value => text) end nil end |
#consume_escaped ⇒ Object
Consumes an escaped code point and returns its unescaped value.
This method assumes that the \ has already been consumed, and that the
next character in the input has already been verified not to be a newline
or EOF.
4.3.8. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-an-escaped-code-point
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/crass/tokenizer.rb', line 327 def consume_escaped return "\ufffd" if @s.eos? if hex_str = @s.scan(RE_HEX) @s.consume if @s.peek =~ RE_WHITESPACE codepoint = hex_str.hex if codepoint == 0 || codepoint.between?(0xD800, 0xDFFF) || codepoint > 0x10FFFF return "\ufffd" else return codepoint.chr(Encoding::UTF_8) end end @s.consume end |
#consume_ident ⇒ Object
Consumes an ident-like token and returns it.
4.3.4. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-an-ident-like-token
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
# File 'lib/crass/tokenizer.rb', line 351 def consume_ident value = consume_name if @s.peek == '(' @s.consume if value.downcase == 'url' @s.consume while @s.peek(2) =~ RE_WHITESPACE_ANCHORED if @s.peek(2) =~ RE_QUOTED_URL_START create_token(:function, :value => value) else consume_url end else create_token(:function, :value => value) end else create_token(:ident, :value => value) end end |
#consume_name ⇒ Object
Consumes a name and returns it.
4.3.12. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-a-name
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
# File 'lib/crass/tokenizer.rb', line 376 def consume_name result = String.new until @s.eos? if match = @s.scan(RE_NAME) result << match next end char = @s.consume if valid_escape? result << consume_escaped # Non-standard: IE * hack elsif char == '*' && @options[:preserve_hacks] result << @s.consume else @s.reconsume return result end end result end |
#consume_number ⇒ Object
Consumes a number and returns a 3-element array containing the number's
original representation, its numeric value, and its type (either
:integer or :number).
4.3.13. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-a-number
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 |
# File 'lib/crass/tokenizer.rb', line 408 def consume_number repr = String.new type = :integer repr << @s.consume if @s.peek =~ RE_NUMBER_SIGN repr << (@s.scan(RE_DIGIT) || '') if match = @s.scan(RE_NUMBER_DECIMAL) repr << match type = :number end if match = @s.scan(RE_NUMBER_EXPONENT) repr << match type = :number end [repr, convert_string_to_number(repr), type] end |
#consume_numeric ⇒ Object
Consumes a numeric token and returns it.
4.3.3. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-a-numeric-token
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
# File 'lib/crass/tokenizer.rb', line 431 def consume_numeric number = consume_number repr = number[0] value = number[1] type = number[2] if type == :integer value = value.to_i else value = value.to_f end if start_identifier?(@s.peek(3)) create_token(:dimension, :repr => repr, :type => type, :unit => consume_name, :value => value) elsif @s.peek == '%' @s.consume create_token(:percentage, :repr => repr, :type => type, :value => value) else create_token(:number, :repr => repr, :type => type, :value => value) end end |
#consume_string(ending = nil) ⇒ Object
Consumes a string token that ends at the given character, and returns the token.
4.3.5. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-a-string-token
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 |
# File 'lib/crass/tokenizer.rb', line 470 def consume_string(ending = nil) ending = @s.current if ending.nil? value = String.new until @s.eos? case char = @s.consume when ending break when "\n" # Parse error. @s.reconsume return create_token(:bad_string, :error => true, :value => value) when '\\' case @s.peek when '' # End of the input, so do nothing. next when "\n" @s.consume else value << consume_escaped end else value << char end end create_token(:string, :value => value) end |
#consume_unicode_range ⇒ Object
Consumes a Unicode range token and returns it. Assumes the initial "u+" or "U+" has already been consumed.
4.3.7. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-a-unicode-range-token
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
# File 'lib/crass/tokenizer.rb', line 511 def consume_unicode_range value = @s.scan(RE_HEX) || String.new while value.length < 6 break unless @s.peek == '?' value << @s.consume end range = {} if value.include?('?') range[:start] = value.gsub('?', '0').hex range[:end] = value.gsub('?', 'F').hex return create_token(:unicode_range, range) end range[:start] = value.hex if @s.peek(2) =~ RE_UNICODE_RANGE_END @s.consume range[:end] = (@s.scan(RE_HEX) || '').hex else range[:end] = range[:start] end create_token(:unicode_range, range) end |
#consume_url ⇒ Object
Consumes a URL token and returns it. Assumes the original "url(" has already been consumed.
4.3.6. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#consume-a-url-token
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 |
# File 'lib/crass/tokenizer.rb', line 543 def consume_url value = String.new @s.scan(RE_WHITESPACE) until @s.eos? case char = @s.consume when ')' break when RE_WHITESPACE @s.scan(RE_WHITESPACE) if @s.eos? || @s.peek == ')' @s.consume break else return create_token(:bad_url, :value => value + consume_bad_url) end when '"', "'", '(', RE_NON_PRINTABLE # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url) when '\\' if valid_escape? value << consume_escaped else # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url ) end else value << char end end create_token(:url, :value => value) end |
#convert_string_to_number(str) ⇒ Object
Converts a valid CSS number string into a number and returns the number.
4.3.14. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#convert-a-string-to-a-number
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 |
# File 'lib/crass/tokenizer.rb', line 591 def convert_string_to_number(str) matches = RE_NUMBER_STR.match(str) s = matches[:sign] == '-' ? -1 : 1 i = matches[:integer].to_i f = matches[:fractional].to_i d = matches[:fractional] ? matches[:fractional].length : 0 t = matches[:exponent_sign] == '-' ? -1 : 1 e = matches[:exponent].to_i exponent = t * e # Guard against denial of service via attacker-controlled exponentiation. # A tiny input like "1e5000000" would otherwise force Ruby to compute # `10**exponent` (an enormous integer) before the value is clamped below, # consuming disproportionate CPU and memory. When the exponent's magnitude # is far outside the range a finite double can represent, we saturate or # underflow without performing the exponentiation. if i == 0 && f == 0 # The mantissa is zero, so the value is zero regardless of the exponent. value = s * 0.0 elsif exponent - d > Float::MAX_10_EXP + 1 # The value is larger than `Float::MAX` and would be clamped anyway. value = s * Float::MAX elsif exponent + matches[:integer].length < -325 # The value is smaller than the smallest representable double and would # round to zero. (-325 is one less than the smallest subnormal base-10 # exponent of roughly -324; `matches[:integer].length` is an upper bound # on the mantissa's magnitude, ensuring we never zero a representable # value.) value = s * 0.0 else # I know this formula looks nutty, but it's exactly what's defined in # the spec, and it works. value = s * (i + f * 10**-d) * 10**exponent # Maximum and minimum values aren't defined in the spec, but are # enforced here for sanity. if value > Float::MAX value = Float::MAX elsif value < -Float::MAX value = -Float::MAX end end value end |
#create_token(type, properties = {}) ⇒ Object
Creates and returns a new token with the given properties.
643 644 645 646 647 648 649 |
# File 'lib/crass/tokenizer.rb', line 643 def create_token(type, properties = {}) { :node => type, :pos => @s.marker, :raw => @s.marked }.merge!(properties) end |
#preprocess(input) ⇒ Object
Preprocesses input to prepare it for the tokenizer.
3.3. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#input-preprocessing
654 655 656 657 658 659 660 661 662 |
# File 'lib/crass/tokenizer.rb', line 654 def preprocess(input) input = input.to_s.encode('UTF-8', :invalid => :replace, :undef => :replace) input.gsub!(/(?:\r\n|[\r\f])/, "\n") input.gsub!("\u0000", "\ufffd") input end |
#start_identifier?(text = nil) ⇒ Boolean
Returns true if the given three-character text would start an
identifier. If text is nil, the current and next two characters in the
input stream will be checked, but will not be consumed.
4.3.10. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#would-start-an-identifier
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 |
# File 'lib/crass/tokenizer.rb', line 669 def start_identifier?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '-' nextChar = text[1] !!(nextChar == '-' || nextChar =~ RE_NAME_START || valid_escape?(text[1, 2])) when RE_NAME_START true when '\\' valid_escape?(text[0, 2]) else false end end |
#start_number?(text = nil) ⇒ Boolean
Returns true if the given three-character text would start a number.
If text is nil, the current and next two characters in the input
stream will be checked, but will not be consumed.
4.3.11. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#starts-with-a-number
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 |
# File 'lib/crass/tokenizer.rb', line 693 def start_number?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '+', '-' !!(text[1] =~ RE_DIGIT || (text[1] == '.' && text[2] =~ RE_DIGIT)) when '.' !!(text[1] =~ RE_DIGIT) when RE_DIGIT true else false end end |
#tokenize ⇒ Object
Tokenizes the input stream and returns an array of tokens.
712 713 714 715 716 717 718 719 720 721 722 |
# File 'lib/crass/tokenizer.rb', line 712 def tokenize @s.reset tokens = [] while token = consume tokens << token end tokens end |
#valid_escape?(text = nil) ⇒ Boolean
Returns true if the given two-character text is the beginning of a
valid escape sequence. If text is nil, the current and next character
in the input stream will be checked, but will not be consumed.
4.3.9. https://www.w3.org/TR/2013/WD-css-syntax-3-20130919/#starts-with-a-valid-escape
729 730 731 732 |
# File 'lib/crass/tokenizer.rb', line 729 def valid_escape?(text = nil) text = @s.current + @s.peek if text.nil? !!(text[0] == '\\' && text[1] != "\n") end |