node_modules

This commit is contained in:
saeid
2019-07-15 13:07:31 +04:30
parent d3735c6d30
commit ce1a3ebf9c
35713 changed files with 3639219 additions and 1 deletions
+422
View File
@@ -0,0 +1,422 @@
## 1.0.0-alpha.28 (February 19, 2018)
- Renamed `lexer.grammar.translate()` method into `generate()`
- Fixed `<'-webkit-font-smoothing'>` and `<'-moz-osx-font-smoothing'>` syntaxes (#75)
- Added vendor keywords for `<'overflow'>` property syntax (#76)
- Pined `mdn-data` to `~1.1.0` and fixed issues with some updated property syntaxes
## 1.0.0-alpha.27 (January 14, 2018)
- Generator
- Changed node's `generate()` methods invocation, methods now take a node as a single argument and context (i.e. `this`) that have methods: `chunk()`, `node()` and `children()`
- Renamed `translate()` to `generate()` and changed to take `options` argument
- Removed `translateMarkup(ast, enter, leave)` method, use `generate(ast, { decorator: (handlers) => { ... }})` instead
- Removed `translateWithSourceMap(ast)`, use `generate(ast, { sourceMap: true })` instead
- Changed to support for children as an array
- Walker
- Changed `walk()` to take an `options` argument instead of handler, with `enter`, `leave`, `visit` and `reverse` options (`walk(ast, fn)` is still works and equivalent to `walk(ast, { enter: fn })`)
- Removed `walkUp(ast, fn)`, use `walk(ast, { leave: fn })`
- Removed `walkRules(ast, fn)`, use `walk(ast, { visit: 'Rule', enter: fn })` instead
- Removed `walkRulesRight(ast, fn)`, use `walk(ast, { visit: 'Rule', reverse: true, enter: fn })` instead
- Removed `walkDeclarations(ast, fn)`, use `walk(ast, { visit: 'Declaration', enter: fn })` instead
- Changed to support for children as array in most cases (`reverse: true` will fail on arrays since they have no `forEachRight()` method)
- Misc
- List
- Added `List#forEach()` method
- Added `List#forEachRight()` method
- Added `List#filter()` method
- Changed `List#map()` method to return a `List` instance instead of `Array`
- Added `List#push()` method, similar to `List#appendData()` but returns nothing
- Added `List#pop()` method
- Added `List#unshift()` method, similar to `List#prependData()` but returns nothing
- Added `List#shift()` method
- Added `List#prependList()` method
- Changed `List#insert()`, `List#insertData()`, `List#appendList()` and `List#insertList()` methods to return a list that performed an operation
- Changed `keyword()` method
- Changed `name` field to include a vendor prefix
- Added `basename` field to contain a name without a vendor prefix
- Added `custom` field that contain a `true` when keyword is a custom property reference
- Changed `property()` method
- Changed `name` field to include a vendor prefix
- Added `basename` field to contain a name without any prefixes, i.e. a hack and a vendor prefix
- Added `vendorPrefix()` method
- Added `isCustomProperty()` method
## 1.0.0-alpha.26 (November 9, 2017)
- Tokenizer
- Added `Tokenizer#isBalanceEdge()` method
- Removed `Tokenizer.endsWith()` method
- Parser
- Made the parser tolerant to errors by default
- Removed `tolerant` parser option (no parsing modes anymore)
- Removed `property` parser option (a value parsing does not depend on property name anymore)
- Canceled error for a handing semicolon in a block
- Canceled error for unclosed `Brackets`, `Function` and `Parentheses` when EOF is reached
- Fixed error when prelude ends with a comment for at-rules with custom prelude consumer
- Relaxed at-rule parsing:
- Canceled error when EOF is reached after a prelude
- Canceled error for an at-rule with custom block consumer when at-rule has no block (just don't apply consumer in that case)
- Canceled error on at-rule parsing when it occurs outside prelude or block (at-rule is converting to `Raw` node)
- Allowed for any at-rule to have a prelude and a block, even if it's invalid per at-rule syntax (the responsibility for this check is moved to lexer, since it's possible to construct a AST with such errors)
- Made a declaration value a safe parsing point (i.e. error on value parsing lead to a value is turning into `Raw` node, not a declaration as before)
- Excluded surrounding white spaces and comments from a `Raw` node that represents a declaration value
- Changed `Value` parse handler to return a node only with type `Value` (previously it returned a `Raw` node in some cases)
- Fixed issue with `onParseError()` is not invoked for errors occured on selector or declaration value parsing in some cases
- Changed using of `onParseError()` to stop parsing if handler throws an exception
- Lexer
- Changed `grammar.walk()` to invoke passed handler on entering to node rather than on leaving the node
- Improved `grammar.walk()` to take a walk handler pair as an object, i.e. `walk(node, { enter: fn, leave: fn })`
- Changed `Lexer#match*()` methods to take a node of any type, but with a `children` field
- Added `Lexer#match(syntax, node)` method
- Fixed `Lexer#matchType()` method to stop return a positive result for the CSS wide keywords
## 1.0.0-alpha25 (October 9, 2017)
- Parser
- Added fallback node as argument to `onParseError()` handler
- Fixed raw consuming in tolerant mode when selector is invalid (greedy consuming and redundant warnings)
- Fixed exception in tolerant mode caused by unknown at-rule with unclosed block
- Changed handling of semicolons:
- Hanging semicolon inside declaration blocks raise an error or turns into a `Raw` node in tolerant mode instead of being ignored
- Semicolon outside of declaration blocks opens a `Rule` node as part of selector instead of being ignored
- Aligned `parseAtrulePrelude` behaviour to `parseRulePrelude`
- Removed `Raw` node wraping into `AtrulePrelude` when `parseAtrulePrelude` is disabled
- Removed error emitting when at-rule has a custom prelude customer but no prelude is found (it should be validated by a lexer later)
- Generator
- Fixed performance issue with `translateWithSourceMap()`, flattening the string (because of mixing building string and indexing into it) turned it into a quadratic algorithm (approximate numbers can be found in [the quiz created by this case](https://gist.github.com/lahmatiy/ea25d0e623d88ca9848384b5707d52d9))
- Added support for a single solidus hack for `property()`
- Minor fixes for custom errors
## 1.0.0-alpha24 (September 14, 2017)
- Improved CSSTree to be stable for standart build-in objects extension (#58)
- Parser
- Renamed rule's `selector` to `prelude`. The reasons: [spec names this part so](https://www.w3.org/TR/css-syntax-3/#qualified-rule), and this branch can contain not only a selector (`SelectorList`) but also a raw payload (`Raw`). What's changed:
- Renamed `Rule.selector` to `Rule.prelude`
- Renamed `parseSelector` parser option to `parseRulePrelude`
- Removed option for selector parse in `SelectorList`
- Lexer
- Fixed undefined positions in a error when match a syntax to empty or white space only value
- Improved `Lexer#checkStructure()`
- Return a warning as an object with node reference and message
- No exception on unknown node type, return a warning instead
## 1.0.0-alpha23 (September 10, 2017)
- Fixed `Tokenizer#getRawLength()`'s false positive balance match to the end of input in some cases (#56)
- Rename walker's entry point methods to be the same as CSSTree exposed methods (i.e. `walk()`, `walkUp()` etc)
- Rename at-rule's `expression` to `prelude` (since [spec names it so](https://www.w3.org/TR/css-syntax-3/#at-rule))
- `AtruleExpression` node type → `AtrulePrelude`
- `Atrule.expression` field → `Atrule.prelude`
- `parseAtruleExpression` parser's option → `parseAtrulePrelude`
- `atruleExpression` parse context → `atrulePrelude`
- `atruleExpression` walk context reference → `atrulePrelude`
## 1.0.0-alpha22 (September 8, 2017)
- Parser
- Fixed exception on parsing of unclosed `{}-block` in tolerant mode
- Added tolerant mode support for `DeclarationList`
- Added standalone entry point, i.e. default parser can be used via `require('css-tree/lib/parser')` (#47)
- Generator
- Changed generator to produce `+n` when `AnPlusB.a` is `+1` to be "round-trip" with parser
- Added standalone entry point, i.e. default generators can be used via `require('css-tree/lib/generator')`
- Walker
- Added standalone entry point, i.e. default walkers can be used via `require('css-tree/lib/walker')` (#47)
- Lexer
- Added `default` keyword to the list of invalid values for `<custom-ident>` (since it reversed per [spec](https://www.w3.org/TR/css-values/#custom-idents))
- Convertors (`toPlainObject()` and `fromPlainObject()`) moved to `lib/convertor` (entry point is `require('css-tree/lib/convertor')`)
## 1.0.0-alpha21 (September 5, 2017)
- Tokenizer
- Added `Raw` token type
- Improved tokenization of `url()` with raw as url to be more spec complient
- Added `Tokenizer#balance` array computation on token layout
- Added `Tokenizer#getRawLength()` to compute a raw length with respect of block balance
- Added `Tokenizer#getTokenStart(offset)` method to get token start offset by token index
- Added `idx` and `balance` fields to each token of `Tokenizer#dump()` method result
- Parser
- Added `onParseError` option
- Reworked node parsers that consume a `Raw` node to use a new approach. Since now a `Raw` node builds in `parser#Raw()` function only
- Changed semantic of `parser#Raw()`, it takes 5 parameters now (it might to be changed in future)
- Changed `parser#tolerantParse()` to pass a start token index to fallback function instead of source offset
- Fixed `AtruleExpression` consuming in tolerant mode
- Atrule handler to convert an empty `AtruleExpression` node into `null`
- Changed `AtruleExpression` handler to always return a node (before it could return a `null` in some cases)
- Lexer
- Fixed comma match node for `#` multiplier
- Added reference name to `SyntaxReferenceError`
- Additional fixes on custom errors
- Reduced possible corruption of base config by `syntax.fork()`
## 1.0.0-alpha20 (August 28, 2017)
- Tokenizer
- Added `Atrule` token type (`<at-rule-token>` per spec)
- Added `Function` token type (`<function-token>` per spec)
- Added `Url` token type
- Replaced `Tokenizer#getTypes()` method with `Tokenizer#dump()` to get all tokens as an array
- Renamed `Tokenizer.TYPE.Whitespace` to `Tokenizer.TYPE.WhiteSpace`
- Renamed `Tokenizer.findWhitespaceEnd()` to `Tokenizer.findWhiteSpaceEnd()`
- Parser
- Added initial implementation of tollerant mode (turn on by passing `tolerant: true` option). In this mode parse errors are never occour and any invalid part of CSS turns into a `Raw` node. Current safe points: `Atrule`, `AtruleExpression`, `Rule`, `Selector` and `Declaration`. Feature is experimental and further improvements are planned.
- Changed `Atrule.expression` to contain a `AtruleExpression` node or `null` only (other node types is wrapping into a `AtruleExpression` node)
- Renamed `AttributeSelector.operator` to `AttributeSelector.matcher`
- Generator
- `translate()` method is now can take a function as second argument, that recieves every generated chunk. When no function is passed, default handler is used, it concats all the chunks and method returns a string.
- Lexer
- Used [mdn/data](https://github.com/mdn/data) package as source of lexer's grammar instead of local dictionaries
- Added `x` unit to `<resolution>` generic type
- Improved match tree:
- Omited Group (sequences) match nodes
- Omited empty match nodes (for terms with `zero or more` multipliers)
- Added `ASTNode` node type to contain a reference to AST node
- Fixed node duplication (uncompleted match were added to tree)
- Added AST node reference in match nodes
- Added comma match node by `#` multiplier
- Grammar
- Changed `translate()` function to get a handler as third argument (optional). That handler recieves result of node traslation and can be used for decoration purposes. See [example](https://github.com/csstree/docs/blob/04c65af44477b5ea05feb373482898122b2a4528/docs/syntax.html#L619-L627)
- Added `SyntaxParseError` to grammar export
- Reworked group and multipliers representation in syntax tree:
- Replaced `Sequence` for `Group` node type (`Sequence` node type removed)
- Added `explicit` boolean property for `Group`
- Only groups can have a multiplier now (other node types is wrapping into a single term implicit group when multiplier is applied)
- Renamed `nonEmpty` Group's property to `disallowEmpty`
- Added optimisation for syntax tree by dropping redundant root `Group` when it contains a single `Group` term (return this `Group` as a result)
- Changed lexer's match functionality
- Changed `Lexer#matchProperty()` and `Lexer#matchType()` to return an object instead of match tree. A match tree stores in `matched` field when AST is matched to grammar successfully, otherwise an error in `error` field. The result object also has some methods to test AST node against a match tree: `getTrace()`, `isType()`, `isProperty()` and `isKeyword()`
- Added `Lexer#matchDeclaration()` method
- Removed `Lexer#lastMatchError` (error stores in match result object in `error` field)
- Added initial implementation of search for AST segments (new lexer methods: `Lexer#findValueSegments()`, `Lexer#findDeclarationValueSegments()` and `Lexer#findAllSegments`)
- Implemented `SyntaxReferenceError` for unknown property and type references
- Renamed field in resulting object of `property()` function: `variable` → `custom`
- Fixed issue with readonly properties (e.g. `line` and `column`) of `Error` and exception on attempt to write in iOS Safari
## 1.0.0-alpha19 (April 24, 2017)
- Extended `List` class with new methods:
- `List#prepend(item)`
- `List#prependData(data)`
- `List#insertData(data)`
- `List#insertList(list)`
- `List#replace(item, itemOrList)`
## 1.0.0-alpha18 (April 3, 2017)
- Added `atrule` walk context (#39)
- Changed a result of generate method for `AnPlusB`, `AttributeSelector`, `Function`, `MediaFeature` and `Ratio` ([1e95877](https://github.com/csstree/csstree/commit/1e9587710efa8e9338bcf0bc794b4b45f286231d))
- Fixed typo in `List` exception messages (@strarsis, #42)
- Improved tokenizer to convert an input to a string
## 1.0.0-alpha17 (March 13, 2017)
- Implemented new concept of `syntax`
- Changed main `exports` to expose a default syntax
- Defined initial [CSS syntax](lib/syntax/default.js)
- Implemented `createSyntax()` method to create a new syntax from scratch
- Implemented `fork()` method to create a new syntax based on given via extension
- Parser
- Implemented `mediaQueryList` and `mediaQuery` parsing contexts
- Implemented `CDO` and `CDC` node types
- Implemented additional declaration property prefix hacks (`#` and `+`)
- Added support for UTF-16LE BOM
- Added support for `@font-face` at-rule
- Added `chroma()` to legacy IE filter functions
- Improved `HexColor` to consume hex only
- Improved support for `\0` and `\9` hacks (#2)
- Relaxed number check for `Ratio` terms
- Allowed fractal values as a `Ratio` term
- Disallowed zero number as a `Ratio` term
- Changed important clause parsing
- Allowed any identifier for important (to support hacks like `!ie`)
- Store `true` for `important` field in case identifier equals to `important` and string otherwise
- Fixed parse error formatted message rendering to take into account tabs
- Removed exposing of `Parser` class
- Removed `readSelectorSequence()`, `readSequenceFallback()` and `readSelectorSequenceFallback` methods
- Used single universal sequence consumer for `AtruleExpression`, `Selector` and `Value`
- Generator
- Reworked generator to use auto-generated functions based on syntax definition (additional work to be done in next releases)
- Implemented `translateMarkup(ast, before, after)` method for complex cases
- Reworked `translateWithSourceMap` to be more flexible (based on `translateMarkup`, additional work to be done in next releases)
- Walker
- Reworked walker to use auto-generated function based on syntax definition (additional work to be done in next releases)
- Lexer
- Prepared for better extensibility (additional work to be done in next releases)
- Implemented `checkStructure(ast)` method to check AST structure based on syntax definition
- Update syntax dictionaries to latest `mdn/data`
- Add missing `<'offset-position'>` syntax
- Extended `<position>` property with `-webkit-sticky` (@sergejmueller, #37)
- Improved mismatch error position
- Implemented script (`gen:syntax`) to generate AST format reference page (`docs/ast.md`) using syntax definition
## 1.0.0-alpha16 (February 12, 2017)
- Exposed `Parser` class
- Added `startOffset` option to `Tokenizer` (constructor and `setSource()` method)
- Added fallback functions for default (`readSequenceFallback`) and selector (`readSelectorSequenceFallback`) sequence readers
- Fixed edge cases for `AnPlusB`
- Fixed wrong whitespace ignoring in `Selector` consumer
## 1.0.0-alpha15 (February 8, 2017)
- Fixed broken `atruleExpression` context
- Fixed vendor prefix detection in `keyword()` and `property()`
- Fixed `property()` to not lowercase custom property names
- Added `variable` boolean flag in `property()` result
- Renamed `scanner` into `tokenizer`
- Ranamed `syntax` into `lexer`
- Moved `docs/*.html` files to [csstree/docs](https://github.com/csstree/docs) repo
- Added `element()` function for `Value` context (`-moz-element()` supported as well)
- Merged `Universal` node type into `Type`
- Renamed node types:
- `Id` -> `IdSelector`
- `Class` -> `ClassSelector`
- `Type` -> `TypeSelector`
- `Attribute` -> `AttributeSelector`
- `PseudoClass` -> `PseudoClassSelector`
- `PseudoElement` -> `PseudoElementSelector`
- `Hash` -> `HexColor`
- `Space` -> `WhiteSpace`
- `An+B` -> `AnPlusB`
- Removed `Progid` node type
- Relaxed `MediaQuery` consumer to not validate syntax on parse and to include whitespaces in children sequence as is
- Added `WhiteSpace.value` property to store whitespace sequence
- Implemented parser options to specify what should be parsed in details (when option is `false` some part of CSS represents as balanced `Raw`):
- `parseAtruleExpression` – to parse at-rule expressions (`true` by default)
- `parseSelector` – to parse rule's selector (`true` by default)
- `parseValue` - to parse declaration's value (`true` by default)
- `parseCustomProperty` – to parse value and fallback of custom property (`false` by default)
- Changed tokenization to stick leading hyphen minus to identifier token
- Changed selector parsing:
- Don't convert spaces into descendant combinator
- Don't validate selector structure on parsing (selectors may be checked by lexer later)
- Initial refactoring of [docs](https://github.com/csstree/csstree/blob/master/docs)
- Various improvements and fixes
## 1.0.0-alpha14 (February 3, 2017)
- Implemented `DeclarationList`, `MediaQueryList`, `MediaQuery`, `MediaFeature` and `Ratio` node types
- Implemented `declarationList` context (useful to parse HTML `style` attribute content)
- Implemented custom consumers for `@import`, `@media`, `@page` and `@supports` at-rules
- Implemented `atrule` option for `parse()` config, is used for `atruleExpession` context to specify custom consumer for at-rule if any
- Added `Scanner#skipWS()`, `Scanner#eatNonWS()`, `Scanner#consume()` and `Scanner#consumeNonWS()` helper methods
- Added custom consumers for known functional-pseudos, consume unknown functional-pseudo content as balanced `Raw`
- Allowed any `PseudoElement` to be a functional-pseudo (#33)
- Improved walker implementations to reduce GC thrashing by reusing cursors
- Changed `Atrule.block` to contain a `Block` node type only if any
- Changed `Block.loc` positions to include curly brackets
- Changed `Atrule.expression` to store a `null` if no expression
- Changed parser to use `StyleSheet` node type only for top level node (when context is `stylesheet`, that's by default)
- Changed `Parentheses`, `Brackets` and `Function` consumers to use passed sequence reader instead of its own
- Changed `Value` and `AtruleExpression` consumers to use common sequence reader (that reader was used by `Value` consumer before)
- Changed default sequence reader to exclude storage of spaces around `Comma`
- Changed processing of custom properties:
- Consume declaration value as balanced `Raw`
- Consume `var()` fallback value as balanced `Raw`
- Validate first argument of `var()` starts with double dash
- Custom property's value and fallback includes spaces around
- Fixed `Nth` to have a `loc` property
- Fixed `SelectorList.loc` and `Selector.loc` positions to exclude spaces
- Fixed issue Browserify build fail with `default-syntax.json` is not found error (#32, @philschatz)
- Disallowed `Type` selector starting with dash (parser throws an error in this case now)
- Disallowed empty selectors for `Rule` (not sure if it's correct but looks reasonable)
- Removed `>>` combinator support until any browser support (no signals about that yet)
- Removed `PseudoElement.legacy` property
- Removed special case for `:before`, `:after`, `:first-letter` and `:first-line` to represent them as `PseudoElement`, now those pseudos are represented as `PseudoClass` nodes
- Removed deprecated `Syntax#match()` method
- Parser was splitted into modules and related changes, one step closer to an extensible parser
- Various fixes and improvements, all changes have negligible impact on performance
## 1.0.0-alpha13 (January 19, 2017)
- Changed location storing in `SyntaxMatchError`
- Changed property to store mismatch offset to `mismatchOffset`
- Changed `offset` property to store bad node offset in source CSS if any
- Added `loc` property that stores bad node `loc` if any
## 1.0.0-alpha12 (January 19, 2017)
- Fixed `Syntax#matchProperty()` method to always return a positive result for custom properties since syntax is never defined for them (#31)
- Implemented `fromPlainObject()` and `toPlainObject()` to convert plain object to AST or AST to plain object (currently converts `List` <-> `Array`)
## 1.0.0-alpha11 (January 18, 2017)
- Added support for `:matches(<selector-list>)` (#28)
- Added support for `:has(<relative-selector-list>)`
- Added support for `::slotted(<compound-selector>)`
- Implemented `Brackets` node type
- Implemented basic support for at-rule inside rule block (#24)
- Renamed `Selector` node type to `SelectorList`
- Renamed `SimpleSelector` node type to `Selector`
- Renamed `UnicodeRange.name` property to `UnicodeRange.value`
- Replaced `Negation` node type for regular `PseudoClass`
- Unified name of node property to store nested nodes, it always `children` now:
- `StyleSheet.rules` -> `StyleSheet.children`
- `SelectorList.selectors` -> `SelectorList.children`
- `Block.declarations` -> `Block.children`
- `*.sequence` -> `*.children`
- Fixed edge cases in parsing `Hex` and `UnicodeRange` when number not an integer
- Changed `nth-` pseudos parsing
- Implemented `An+B` node type to represent expressions like `2n + 1` or `-3n`
- Fixed edge cases when `a` or `b` is not an integer
- Changed `odd` and `even` keywords processing, keywords are storing as `Identifier` node type now
- Changed `Nth` node type format to store a `nth`-query and an optional `selector`
- Implemented `of` clause for `nth-` pseudos (a.e. `:nth-child(2n + 1 of li, img)`)
- Limited `Nth` parsing rules to `:nth-child()`, `:nth-last-child()`, `:nth-of-type()` and `:nth-last-of-type()` pseudos
- Changed the way to store locations
- Renamed `info` node property to `loc`
- Changed format of `loc` to store `start` and `end` positions
## 1.0.0-alpha10 (January 11, 2017)
- Reworked `Scanner` to be a single point to its functionality
- Exposed `Scanner` class to be useful for external projects
- Changed `walk()` function behaviour to traverse AST nodes in natural order
- Implemented `walkUp()` function to traverse AST nodes from deepest to parent (behaves as `walk()` before)
## 1.0.0-alpha9 (December 21, 2016)
- Fixed `<angle>` generic according to specs that allow a `<number>` equals to zero to be used as valid value (#30)
## 1.0.0-alpha8 (November 11, 2016)
- Fixed `Scanner#skip()` issue method when cursor is moving to the end of source
- Simplified `Progid` node
- Changed behaviour for bad selector processing, now parsing fails instead of selector ignoring
- Fixed `<id-selector>` generic syntax
- Added `q` unit for `<length>` generic syntax
- Refactored syntax parser (performance)
- Reduced startup time by implementing lazy syntax parsing (default syntax doesn't parse on module load)
- Updated syntax dictionaries and used [`mdn/data`](https://github.com/mdn/data) instead of `Template:CSSData`
- Renamed `syntax.stringify()` method to `syntax.translate()`
- Simplified generic syntax functions, those functions receive a single AST node for checking and should return `true` or `false`
- Added exception for values that contains `var()`, those values are always valid for now
- Added more tests and increase code coverage to `98.5%`
## 1.0.0-alpha7 (October 7, 2016)
- Added support for explicit descendant combinator (`>>`)
- Implemented `Type` and `Universal` type nodes
- Improved `Number` parsing by including sign and exponent (#26)
- Parse `before`, `after`, `first-letter` and `first-line` pseudos with single colon as `PseudoElement`
- Changed `FunctionalPseudo` node type to `PseudoClass`
- Fixed attribute selector name parsing (namespace edge cases)
- Fixed location calculation for specified offset when `eof` is reached
- Added more non-standard colors (#25)
- Removed obsolete `Syntax#getAll()` method
- Fixed various edge cases, code clean up and performance improvements
## 1.0.0-alpha6 (September 23, 2016)
- More accurate positions for syntax mismatch errors
- Added [`apple`](https://webkit.org/blog/3709/using-the-system-font-in-web-content/) specific font keywords (#20)
- Changed `Property` node stucture from object to string
- Renamed `Ruleset` node type to `Rule`
- Removed `Argument` node type
- Fixed `Dimension` and `Percentage` position computation
- Fixed bad selector parsing (temporary solution)
- Fixed location computation for CSS with very long lines that may lead to really long parsing with `positions:true` (even freeze)
- Fixed `line` and `column` computation for `SyntaxMatch` error
- Improved performance of parsing and translation. Now CSSTree is under 10ms in [PostCSS benchmark](https://github.com/postcss/benchmark).
+19
View File
@@ -0,0 +1,19 @@
Copyright (C) 2016 by Roman Dvornov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+90
View File
@@ -0,0 +1,90 @@
<img align="right" width="111" height="111"
alt="CSSTree logo"
src="https://cloud.githubusercontent.com/assets/270491/19243723/6f9136c6-8f21-11e6-82ac-eeeee4c6c452.png"/>
# CSSTree
[![NPM version](https://img.shields.io/npm/v/css-tree.svg)](https://www.npmjs.com/package/css-tree)
[![Build Status](https://travis-ci.org/csstree/csstree.svg?branch=master)](https://travis-ci.org/csstree/csstree)
[![Coverage Status](https://coveralls.io/repos/github/csstree/csstree/badge.svg?branch=master)](https://coveralls.io/github/csstree/csstree?branch=master)
[![Join the CSSTree chat at https://gitter.im/csstree/csstree](https://badges.gitter.im/csstree/csstree.svg)](https://gitter.im/csstree/csstree)
[![Twitter](https://img.shields.io/badge/Twitter-@csstree-blue.svg)](https://twitter.com/csstree)
CSSTree is a tool set to work with CSS, including [fast](https://github.com/postcss/benchmark) detailed parser (string->AST), walker (AST traversal), generator (AST->string) and lexer (validation and matching) based on knowledge of spec and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks.
> NOTE: The project is in alpha stage since some parts need further improvements, AST format and API are subjects to change. However it's stable enough and used by packages like [CSSO](https://github.com/css/csso) (CSS minifier) and [SVGO](https://github.com/svg/svgo) (SVG optimizer) in production.
## Features
- **Detailed parsing with an adjustable level of detail**
By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see [AST format](docs/ast.md) for all possible node types). The parsing detail level can be changed through [parser options](docs/parsing.md#parsesource-options), for example, you can disable parsing of selectors or declarations for component parts.
- **Tolerant to errors by design**
Parser behaves as [spec says](https://www.w3.org/TR/css-syntax-3/#error-handling): "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in the special nodes, which allows processing it later.
- **Fast and efficient**
CSSTree is created with focus on performance and effective memory consumption. Therefore it's [one of the fastest CSS parsers](https://github.com/postcss/benchmark) at the moment.
- **Syntax validation**
The build-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses [mdn/data](https://github.com/mdn/data/) as a basis for lexer's dictionaries and extends them with vendor specific and legacy syntaxes. Lexer can only check the declaration values currently, but this feature will be extended to other parts of the CSS in the future.
## Docs
- [Parsing CSS into AST](docs/parsing.md)
- [AST format](docs/ast.md)
- [Generate CSS from AST](docs/generate.md)
- [AST traversal](docs/traversal.md)
- [Utils to work with AST](docs/utils.md)
## Tools
* [AST Explorer](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8) – explore CSSTree AST format with zero setup
* [CSS syntax reference](https://csstree.github.io/docs/syntax.html)
* [CSS syntax validator](https://csstree.github.io/docs/validator.html)
## Related projects
* [csstree-validator](https://github.com/csstree/validator) – NPM package to validate CSS
* [stylelint-csstree-validator](https://github.com/csstree/stylelint-validator) – plugin for stylelint to validate CSS
* [Grunt plugin](https://github.com/sergejmueller/grunt-csstree-validator)
* [Gulp plugin](https://github.com/csstree/gulp-csstree)
* [Sublime plugin](https://github.com/csstree/SublimeLinter-contrib-csstree)
* [VS Code plugin](https://github.com/csstree/vscode-plugin)
* [Atom plugin](https://github.com/csstree/atom-plugin)
## Usage
Install with npm:
```
> npm install css-tree
```
Use in your code:
```js
var csstree = require('css-tree');
var ast = csstree.parse('.example { world: "!" }');
csstree.walk(ast, function(node) {
if (node.type === 'ClassSelector' && node.name === 'example') {
node.name = 'hello';
}
});
console.log(csstree.generate(ast));
// .hello{world:"!"}
```
## Top level API
![API map](https://cdn.rawgit.com/csstree/csstree/master/docs/api-map.svg)
## License
MIT
+46
View File
@@ -0,0 +1,46 @@
var mdnProperties = require('mdn-data/css/properties.json');
var mdnSyntaxes = require('mdn-data/css/syntaxes.json');
var patch = require('./patch.json');
var data = {
properties: {},
types: {}
};
function normalizeSyntax(syntax) {
return syntax
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&nbsp;/g, ' ')
.replace(/&amp;/g, '&');
}
function patchDict(dict, patchDict) {
for (var key in patchDict) {
if (key in dict) {
if (patchDict[key].syntax) {
dict[key].syntax = patchDict[key].syntax;
} else {
delete dict[key];
}
} else {
if (patchDict[key].syntax) {
dict[key] = patchDict[key];
}
}
}
}
// apply patch
patchDict(mdnProperties, patch.properties);
patchDict(mdnSyntaxes, patch.syntaxes);
// normalize source mdnProperties syntaxes, since it uses html token
for (var key in mdnProperties) {
data.properties[key] = normalizeSyntax(mdnProperties[key].syntax);
}
for (var key in mdnSyntaxes) {
data.types[key] = normalizeSyntax(mdnSyntaxes[key].syntax);
}
module.exports = data;
+829
View File
@@ -0,0 +1,829 @@
{
"properties": {
"--*": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"-moz-background-clip": {
"comment": "deprecated syntax in old Firefox, https://developer.mozilla.org/en/docs/Web/CSS/background-clip",
"syntax": "padding | border"
},
"-moz-border-radius-bottomleft": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-left-radius",
"syntax": "<'border-bottom-left-radius'>"
},
"-moz-border-radius-bottomright": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-right-radius",
"syntax": "<'border-bottom-right-radius'>"
},
"-moz-border-radius-topleft": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-left-radius",
"syntax": "<'border-top-left-radius'>"
},
"-moz-border-radius-topright": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-right-radius",
"syntax": "<'border-bottom-right-radius'>"
},
"-moz-osx-font-smoothing": {
"comment": "misssed old syntax https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth",
"syntax": "auto | grayscale"
},
"-moz-user-select": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/user-select",
"syntax": "none | text | all | -moz-none"
},
"-ms-filter": {
"comment": "added missed syntax https://blogs.msdn.microsoft.com/ie/2009/02/19/the-css-corner-using-filters-in-ie8/",
"syntax": "<string>"
},
"-ms-flex-align": {
"comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-align",
"syntax": "start | end | center | baseline | stretch"
},
"-ms-flex-item-align": {
"comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-align",
"syntax": "auto | start | end | center | baseline | stretch"
},
"-ms-flex-line-pack": {
"comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-line-pack",
"syntax": "start | end | center | justify | distribute | stretch"
},
"-ms-flex-negative": {
"comment": "misssed old syntax implemented in IE; TODO: find references for comfirmation",
"syntax": "<'flex-shrink'>"
},
"-ms-flex-pack": {
"comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-pack",
"syntax": "start | end | center | justify | distribute"
},
"-ms-flex-order": {
"comment": "misssed old syntax implemented in IE; https://msdn.microsoft.com/en-us/library/jj127303(v=vs.85).aspx",
"syntax": "<integer>"
},
"-ms-flex-positive": {
"comment": "misssed old syntax implemented in IE; TODO: find references for comfirmation",
"syntax": "<'flex-grow'>"
},
"-ms-flex-preferred-size": {
"comment": "misssed old syntax implemented in IE; TODO: find references for comfirmation",
"syntax": "<'flex-basis'>"
},
"-ms-interpolation-mode": {
"comment": "https://msdn.microsoft.com/en-us/library/ff521095(v=vs.85).aspx",
"syntax": "nearest-neighbor | bicubic"
},
"-ms-grid-column-align": {
"comment": "add this property first since it uses as fallback for flexbox, https://msdn.microsoft.com/en-us/library/windows/apps/hh466338.aspx",
"syntax": "start | end | center | stretch"
},
"-ms-grid-row-align": {
"comment": "add this property first since it uses as fallback for flexbox, https://msdn.microsoft.com/en-us/library/windows/apps/hh466348.aspx",
"syntax": "start | end | center | stretch"
},
"-ms-high-contrast-adjust": {
"comment": "https://msdn.microsoft.com/en-us/library/hh771863(v=vs.85).aspx",
"syntax": "auto | none"
},
"-ms-user-select": {
"comment": "https://msdn.microsoft.com/en-us/library/hh781492(v=vs.85).aspx",
"syntax": "none | element | text"
},
"-webkit-appearance": {
"comment": "webkit specific keywords",
"references": [
"http://css-infos.net/property/-webkit-appearance"
],
"syntax": "none | button | button-bevel | caps-lock-indicator | caret | checkbox | default-button | listbox | listitem | media-fullscreen-button | media-mute-button | media-play-button | media-seek-back-button | media-seek-forward-button | media-slider | media-sliderthumb | menulist | menulist-button | menulist-text | menulist-textfield | push-button | radio | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbargripper-horizontal | scrollbargripper-vertical | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | searchfield-cancel-button | searchfield-decoration | searchfield-results-button | searchfield-results-decoration | slider-horizontal | slider-vertical | sliderthumb-horizontal | sliderthumb-vertical | square-button | textarea | textfield"
},
"-webkit-background-clip": {
"comment": "https://developer.mozilla.org/en/docs/Web/CSS/background-clip",
"syntax": "[ <box> | border | padding | content | text ]#"
},
"-webkit-column-break-after": {
"comment": "added, http://help.dottoro.com/lcrthhhv.php",
"syntax": "always | auto | avoid"
},
"-webkit-column-break-before": {
"comment": "added, http://help.dottoro.com/lcxquvkf.php",
"syntax": "always | auto | avoid"
},
"-webkit-column-break-inside": {
"comment": "added, http://help.dottoro.com/lclhnthl.php",
"syntax": "always | auto | avoid"
},
"-webkit-font-smoothing": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth",
"syntax": "auto | none | antialiased | subpixel-antialiased"
},
"-webkit-line-clamp": {
"comment": "non-standard and deprecated but may still using by some sites",
"syntax": "<positive-integer>"
},
"-webkit-mask-box-image": {
"comment": "missed; https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-mask-box-image",
"syntax": "[ <url> | <gradient> | none ] [ <length-percentage>{4} <-webkit-mask-box-repeat>{2} ]?"
},
"-webkit-mask-clip": {
"comment": "change type to <-webkit-mask-clip-style> since it differ from <mask-clip>, extra space between [ and ,",
"syntax": "<-webkit-mask-clip-style> [, <-webkit-mask-clip-style> ]*"
},
"-webkit-overflow-scrolling": {
"comment": "missed; https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-overflow-scrolling",
"syntax": "auto | touch"
},
"-webkit-print-color-adjust": {
"comment": "missed",
"references": [
"https://developer.mozilla.org/en/docs/Web/CSS/-webkit-print-color-adjust"
],
"syntax": "economy | exact"
},
"-webkit-text-security": {
"comment": "missed; http://help.dottoro.com/lcbkewgt.php",
"syntax": "none | circle | disc | square"
},
"-webkit-user-drag": {
"comment": "missed; http://help.dottoro.com/lcbixvwm.php",
"syntax": "none | element | auto"
},
"-webkit-user-select": {
"comment": "auto is supported by old webkit, https://developer.mozilla.org/en-US/docs/Web/CSS/user-select",
"syntax": "auto | none | text | all"
},
"alignment-baseline": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#AlignmentBaselineProperty"
],
"syntax": "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical"
},
"baseline-shift": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#BaselineShiftProperty"
],
"syntax": "baseline | sub | super | <svg-length>"
},
"behavior": {
"comment": "added old IE property https://msdn.microsoft.com/en-us/library/ms530723(v=vs.85).aspx",
"syntax": "<url>+"
},
"clip-rule": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/masking.html#ClipRuleProperty"
],
"syntax": "nonzero | evenodd"
},
"cue": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<'cue-before'> <'cue-after'>?"
},
"cue-after": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<url> <decibel>? | none"
},
"cue-before": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<url> <decibel>? | none"
},
"cursor": {
"comment": "added legacy keywords: hand, -webkit-grab. -webkit-grabbing, -webkit-zoom-in, -webkit-zoom-out, -moz-grab, -moz-grabbing, -moz-zoom-in, -moz-zoom-out",
"refenrences": ["https://www.sitepoint.com/css3-cursor-styles/"],
"syntax": "[ [ <url> [ <x> <y> ]? , ]* [ auto | default | none | context-menu | help | pointer | progress | wait | cell | crosshair | text | vertical-text | alias | copy | move | no-drop | not-allowed | e-resize | n-resize | ne-resize | nw-resize | s-resize | se-resize | sw-resize | w-resize | ew-resize | ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | all-scroll | zoom-in | zoom-out | grab | grabbing | hand | -webkit-grab | -webkit-grabbing | -webkit-zoom-in | -webkit-zoom-out | -moz-grab | -moz-grabbing | -moz-zoom-in | -moz-zoom-out ] ]"
},
"display": {
"comment": "extended with -ms-flexbox",
"syntax": "none | inline | block | list-item | inline-list-item | inline-block | inline-table | table | table-cell | table-column | table-column-group | table-footer-group | table-header-group | table-row | table-row-group | flex | inline-flex | grid | inline-grid | run-in | ruby | ruby-base | ruby-text | ruby-base-container | ruby-text-container | contents | -ms-flexbox | -ms-inline-flexbox | -ms-grid | -ms-inline-grid | -webkit-flex | -webkit-inline-flex | -webkit-box | -webkit-inline-box | -moz-inline-stack | -moz-box | -moz-inline-box"
},
"position": {
"comment": "extended with -webkit-sticky",
"syntax": "static | relative | absolute | sticky | fixed | -webkit-sticky"
},
"dominant-baseline": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#DominantBaselineProperty"
],
"syntax": "auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge"
},
"image-rendering": {
"comment": "extended with <-non-standard-image-rendering>, added SVG keywords optimizeSpeed and optimizeQuality",
"references": [
"https://developer.mozilla.org/en/docs/Web/CSS/image-rendering",
"https://www.w3.org/TR/SVG/painting.html#ImageRenderingProperty"
],
"syntax": "auto | crisp-edges | pixelated | optimizeSpeed | optimizeQuality | <-non-standard-image-rendering>"
},
"fill": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#FillProperty"
],
"syntax": "<paint>"
},
"fill-opacity": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#FillProperty"
],
"syntax": "<number-zero-one>"
},
"fill-rule": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#FillProperty"
],
"syntax": "nonzero | evenodd"
},
"filter": {
"comment": "extend with IE legacy syntaxes",
"syntax": "none | <filter-function-list> | <-ms-filter>"
},
"font": {
"comment": "extend with non-standard fonts",
"syntax": "[ [ <'font-style'> || <font-variant-css21> || <'font-weight'> || <'font-stretch'> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'> ] | caption | icon | menu | message-box | small-caption | status-bar | <-non-standard-font>"
},
"glyph-orientation-horizontal": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#GlyphOrientationHorizontalProperty"
],
"syntax": "<angle>"
},
"glyph-orientation-vertical": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#GlyphOrientationVerticalProperty"
],
"syntax": "<angle>"
},
"kerning": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#KerningProperty"
],
"syntax": "auto | <svg-length>"
},
"letter-spacing": {
"comment": "fix syntax <length> -> <length-percentage>",
"references": [
"https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/letter-spacing"
],
"syntax": "normal | <length-percentage>"
},
"line-height-step": {
"comment": "fix extra spaces around",
"syntax": "none | <length>"
},
"marker": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#MarkerProperties"
],
"syntax": "none | <url>"
},
"marker-end": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#MarkerProperties"
],
"syntax": "none | <url>"
},
"marker-mid": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#MarkerProperties"
],
"syntax": "none | <url>"
},
"marker-start": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#MarkerProperties"
],
"syntax": "none | <url>"
},
"max-width": {
"comment": "extend by non-standard width keywords https://developer.mozilla.org/en-US/docs/Web/CSS/max-width",
"syntax": "<length> | <percentage> | none | max-content | min-content | fit-content | fill-available | <-non-standard-width>"
},
"min-width": {
"comment": "extend by non-standard width keywords https://developer.mozilla.org/en-US/docs/Web/CSS/width",
"syntax": "<length> | <percentage> | auto | max-content | min-content | fit-content | fill-available | <-non-standard-width>"
},
"opacity": {
"comment": "strict to 0..1 <number> -> <number-zero-one>",
"syntax": "<number-zero-one>"
},
"overflow": {
"comment": "extend by vendor keywords https://developer.mozilla.org/en-US/docs/Web/CSS/overflow",
"syntax": "visible | hidden | scroll | auto | <-non-standard-overflow>"
},
"pause": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<'pause-before'> <'pause-after'>?"
},
"pause-after": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<time> | none | x-weak | weak | medium | strong | x-strong"
},
"pause-before": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<time> | none | x-weak | weak | medium | strong | x-strong"
},
"rest": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<'rest-before'> <'rest-after'>?"
},
"rest-after": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<time> | none | x-weak | weak | medium | strong | x-strong"
},
"rest-before": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<time> | none | x-weak | weak | medium | strong | x-strong"
},
"shape-rendering": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#ShapeRenderingPropert"
],
"syntax": "auto | optimizeSpeed | crispEdges | geometricPrecision"
},
"src": {
"comment": "added @font-face's src property https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src",
"syntax": "[ <url> format( <string># )? | local( <family-name> ) ]#"
},
"speak": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "auto | none | normal"
},
"speak-as": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "normal | spell-out || digits || [ literal-punctuation | no-punctuation ]"
},
"stroke": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<paint>"
},
"stroke-dasharray": {
"comment": "added SVG property; a list of comma and/or white space separated <length>s and <percentage>s",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "none | [ <svg-length>+ ]#"
},
"stroke-dashoffset": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<svg-length>"
},
"stroke-linecap": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "butt | round | square"
},
"stroke-linejoin": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "miter | round | bevel"
},
"stroke-miterlimit": {
"comment": "added SVG property (<miterlimit> = <number-one-or-greater>) ",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<number-one-or-greater>"
},
"stroke-opacity": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<number-zero-one>"
},
"stroke-width": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<svg-length>"
},
"text-anchor": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#TextAlignmentProperties"
],
"syntax": "start | middle | end"
},
"transform-origin": {
"comment": "move first group to the end since less collecting",
"syntax": "[ [ <length-percentage> | left | center | right ] && [ <length-percentage> | top | center | bottom ] ] <length>? | [ <length-percentage> | left | center | right | top | bottom ]"
},
"unicode-bidi": {
"comment": "added prefixed keywords https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-bidi",
"syntax": "normal | embed | isolate | bidi-override | isolate-override | plaintext | -moz-isolate | -moz-isolate-override | -moz-plaintext | -webkit-isolate"
},
"unicode-range": {
"comment": "added missed property https://developer.mozilla.org/en-US/docs/Web/CSS/%40font-face/unicode-range",
"syntax": "<unicode-range>#"
},
"voice-balance": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<number> | left | center | right | leftwards | rightwards"
},
"voice-duration": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "auto | <time>"
},
"voice-family": {
"comment": "<name> -> <family-name>, https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "[ [ <family-name> | <generic-voice> ] , ]* [ <family-name> | <generic-voice> ] | preserve"
},
"voice-pitch": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<frequency> && absolute | [ [ x-low | low | medium | high | x-high ] || [ <frequency> | <semitones> | <percentage> ] ]"
},
"voice-range": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<frequency> && absolute | [ [ x-low | low | medium | high | x-high ] || [ <frequency> | <semitones> | <percentage> ] ]"
},
"voice-rate": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "[ normal | x-slow | slow | medium | fast | x-fast ] || <percentage>"
},
"voice-stress": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "normal | strong | moderate | none | reduced"
},
"voice-volume": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "silent | [ [ x-soft | soft | medium | loud | x-loud ] || <decibel> ]"
},
"word-break": {
"comment": "extend with non-standard keywords",
"syntax": "normal | break-all | keep-all | <-non-standard-word-break>"
},
"writing-mode": {
"comment": "extend with SVG keywords",
"syntax": "horizontal-tb | vertical-rl | vertical-lr | sideways-rl | sideways-lr | <svg-writing-mode>"
},
"zoom": {
"comment": "missed, not in DB, https://developer.mozilla.org/en-US/docs/Web/CSS/zoom",
"syntax": "normal | reset | <number> | <percentage>"
}
},
"syntaxes": {
"-legacy-gradient()": {
"comment": "added collection of legacy gradient syntaxes",
"syntax": "<-webkit-gradient()> | <-legacy-linear-gradient()> | <-legacy-repeating-linear-gradient()> | <-legacy-radial-gradient()> | <-legacy-repeating-radial-gradient()>"
},
"-legacy-linear-gradient()": {
"comment": "like standard syntax but w/o `to` keyword https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient",
"syntax": "-moz-linear-gradient( <-legacy-linear-gradient-arguments> ) | -ms-linear-gradient( <-legacy-linear-gradient-arguments> ) | -webkit-linear-gradient( <-legacy-linear-gradient-arguments> ) | -o-linear-gradient( <-legacy-linear-gradient-arguments> )"
},
"-legacy-repeating-linear-gradient()": {
"comment": "like standard syntax but w/o `to` keyword https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient",
"syntax": "-moz-repeating-linear-gradient( <-legacy-linear-gradient-arguments> ) | -ms-repeating-linear-gradient( <-legacy-linear-gradient-arguments> ) | -webkit-repeating-linear-gradient( <-legacy-linear-gradient-arguments> ) | -o-repeating-linear-gradient( <-legacy-linear-gradient-arguments> )"
},
"-legacy-linear-gradient-arguments": {
"comment": "like standard syntax but w/o `to` keyword https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient",
"syntax": "[ <angle> | <side-or-corner> ]? , <color-stop-list>"
},
"-legacy-radial-gradient()": {
"comment": "deprecated syntax that implemented by some browsers https://www.w3.org/TR/2011/WD-css3-images-20110908/#radial-gradients",
"syntax": "-moz-radial-gradient( <-legacy-radial-gradient-arguments> ) | -ms-radial-gradient( <-legacy-radial-gradient-arguments> ) | -webkit-radial-gradient( <-legacy-radial-gradient-arguments> ) | -o-radial-gradient( <-legacy-radial-gradient-arguments> )"
},
"-legacy-repeating-radial-gradient()": {
"comment": "deprecated syntax that implemented by some browsers https://www.w3.org/TR/2011/WD-css3-images-20110908/#radial-gradients",
"syntax": "-moz-repeating-radial-gradient( <-legacy-radial-gradient-arguments> ) | -ms-repeating-radial-gradient( <-legacy-radial-gradient-arguments> ) | -webkit-repeating-radial-gradient( <-legacy-radial-gradient-arguments> ) | -o-repeating-radial-gradient( <-legacy-radial-gradient-arguments> )"
},
"-legacy-radial-gradient-arguments": {
"comment": "deprecated syntax that implemented by some browsers https://www.w3.org/TR/2011/WD-css3-images-20110908/#radial-gradients",
"syntax": "[ <position> , ]? [ [ [ <-legacy-radial-gradient-shape> || <-legacy-radial-gradient-size> ] | [ <length> | <percentage> ]{2} ] , ]? <color-stop-list>"
},
"-legacy-radial-gradient-size": {
"comment": "before a standard it contains 2 extra keywords (`contain` and `cover`) https://www.w3.org/TR/2011/WD-css3-images-20110908/#ltsize",
"syntax": "closest-side | closest-corner | farthest-side | farthest-corner | contain | cover"
},
"-legacy-radial-gradient-shape": {
"comment": "define to duoble sure it doesn't extends in future https://www.w3.org/TR/2011/WD-css3-images-20110908/#ltshape",
"syntax": "circle | ellipse"
},
"-non-standard-font": {
"comment": "non standard fonts",
"preferences": [
"https://webkit.org/blog/3709/using-the-system-font-in-web-content/"
],
"syntax": "-apple-system-body | -apple-system-headline | -apple-system-subheadline | -apple-system-caption1 | -apple-system-caption2 | -apple-system-footnote | -apple-system-short-body | -apple-system-short-headline | -apple-system-short-subheadline | -apple-system-short-caption1 | -apple-system-short-footnote | -apple-system-tall-body"
},
"-non-standard-color": {
"comment": "non standard colors",
"references": [
"http://cssdot.ru/%D0%A1%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D1%87%D0%BD%D0%B8%D0%BA_CSS/color-i305.html",
"https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#Mozilla_Color_Preference_Extensions"
],
"syntax": "-moz-ButtonDefault | -moz-ButtonHoverFace | -moz-ButtonHoverText | -moz-CellHighlight | -moz-CellHighlightText | -moz-Combobox | -moz-ComboboxText | -moz-Dialog | -moz-DialogText | -moz-dragtargetzone | -moz-EvenTreeRow | -moz-Field | -moz-FieldText | -moz-html-CellHighlight | -moz-html-CellHighlightText | -moz-mac-accentdarkestshadow | -moz-mac-accentdarkshadow | -moz-mac-accentface | -moz-mac-accentlightesthighlight | -moz-mac-accentlightshadow | -moz-mac-accentregularhighlight | -moz-mac-accentregularshadow | -moz-mac-chrome-active | -moz-mac-chrome-inactive | -moz-mac-focusring | -moz-mac-menuselect | -moz-mac-menushadow | -moz-mac-menutextselect | -moz-MenuHover | -moz-MenuHoverText | -moz-MenuBarText | -moz-MenuBarHoverText | -moz-nativehyperlinktext | -moz-OddTreeRow | -moz-win-communicationstext | -moz-win-mediatext | -moz-activehyperlinktext | -moz-default-background-color | -moz-default-color | -moz-hyperlinktext | -moz-visitedhyperlinktext | -webkit-activelink | -webkit-focus-ring-color | -webkit-link | -webkit-text"
},
"-non-standard-image-rendering": {
"comment": "non-standard keywords http://phrogz.net/tmp/canvas_image_zoom.html",
"syntax": "optimize-contrast | -moz-crisp-edges | -o-crisp-edges | -webkit-optimize-contrast"
},
"-non-standard-overflow": {
"comment": "non-standard keywords https://developer.mozilla.org/en-US/docs/Web/CSS/overflow",
"syntax": "-moz-scrollbars-none | -moz-scrollbars-horizontal | -moz-scrollbars-vertical | -moz-hidden-unscrollable"
},
"-non-standard-width": {
"comment": "non-standard keywords https://developer.mozilla.org/en-US/docs/Web/CSS/width",
"syntax": "min-intrinsic | intrinsic | -moz-min-content | -moz-max-content | -webkit-min-content | -webkit-max-content"
},
"-non-standard-word-break": {
"comment": "non-standard keywords https://css-tricks.com/almanac/properties/w/word-break/",
"syntax": "break-word"
},
"-webkit-image-set()": {
"comment": "added alias",
"syntax": "<image-set()>"
},
"-webkit-gradient()": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/ - TODO: simplify when after match algorithm improvement ( [, point, radius | , point] -> [, radius]? , point )",
"syntax": "-webkit-gradient( <-webkit-gradient-type>, <-webkit-gradient-point> [, <-webkit-gradient-point> | , <-webkit-gradient-radius>, <-webkit-gradient-point> ] [, <-webkit-gradient-radius>]? [, <-webkit-gradient-color-stop()>]* )"
},
"-webkit-gradient-color-stop()": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/",
"syntax": "from( <color> ) | color-stop( [ <number-zero-one> | <percentage> ] , <color> ) | to( <color> )"
},
"-webkit-gradient-point": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/",
"syntax": " [ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ]"
},
"-webkit-gradient-radius": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/",
"syntax": "<length> | <percentage>"
},
"-webkit-gradient-type": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/",
"syntax": "linear | radial"
},
"-webkit-mask-box-repeat": {
"comment": "missed; https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-mask-box-image",
"syntax": "repeat | stretch | round"
},
"-webkit-mask-clip-style": {
"comment": "missed; there is no enough information about `-webkit-mask-clip` property, but looks like all those keywords are working",
"syntax": "border | border-box | padding | padding-box | content | content-box | text"
},
"-ms-filter": {
"syntax": "[ <progid> | FlipH | FlipV ]+"
},
"age": {
"comment": "https://www.w3.org/TR/css3-speech/#voice-family",
"syntax": "child | young | old"
},
"attr()": {
"comment": "drop it since it's a generic",
"syntax": null
},
"border-radius": {
"comment": "missed, https://drafts.csswg.org/css-backgrounds-3/#the-border-radius",
"syntax": "<length-percentage>{1,2}"
},
"bottom": {
"comment": "missed; not sure we should add it, but no others except `shape` is using it so it's ok for now; https://drafts.fxtf.org/css-masking-1/#funcdef-clip-rect",
"syntax": "<length> | auto"
},
"content-list": {
"comment": "missed -> https://drafts.csswg.org/css-content/#typedef-content-list (document-url, <target> and leader() is omitted util stabilization)",
"syntax": "[ <string> | contents | <url> | <quote> | <attr()> | counter( <ident>, <'list-style-type'>? ) ]+"
},
"inset()": {
"comment": "changed <border-radius> to <'border-radius'>",
"syntax": "inset( <length-percentage>{1,4} [ round <'border-radius'> ]? )"
},
"generic-voice": {
"comment": "https://www.w3.org/TR/css3-speech/#voice-family",
"syntax": "[ <age>? <gender> <integer>? ]"
},
"gender": {
"comment": "https://www.w3.org/TR/css3-speech/#voice-family",
"syntax": "male | female | neutral"
},
"generic-family": {
"comment": "added -apple-system",
"references": [
"https://webkit.org/blog/3709/using-the-system-font-in-web-content/"
],
"syntax": "serif | sans-serif | cursive | fantasy | monospace | -apple-system"
},
"gradient": {
"comment": "added -webkit-gradient() since may to be used for legacy support",
"syntax": "<-legacy-gradient()> | <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()>"
},
"left": {
"comment": "missed; not sure we should add it, but no others except `shape` is using it so it's ok for now; https://drafts.fxtf.org/css-masking-1/#funcdef-clip-rect",
"syntax": "<length> | auto"
},
"mask-image": {
"comment": "missed; https://drafts.fxtf.org/css-masking-1/#the-mask-image",
"syntax": "<mask-reference>#"
},
"matrix()": {
"comment": "redundant max",
"syntax": "matrix( <number> [, <number> ]{5} )"
},
"matrix3d()": {
"comment": "redundant max",
"syntax": "matrix3d( <number> [, <number> ]{15} )"
},
"name-repeat": {
"comment": "missed, and looks like obsolete, keep it as is since other property syntaxes should be changed too; https://www.w3.org/TR/2015/WD-css-grid-1-20150917/#typedef-name-repeat",
"syntax": "repeat( [ <positive-integer> | auto-fill ], <line-names>+)"
},
"named-color": {
"comment": "replaced <ident> to list of colors according to https://www.w3.org/TR/css-color-4/#named-colors",
"syntax": "transparent | aliceblue | antiquewhite | aqua | aquamarine | azure | beige | bisque | black | blanchedalmond | blue | blueviolet | brown | burlywood | cadetblue | chartreuse | chocolate | coral | cornflowerblue | cornsilk | crimson | cyan | darkblue | darkcyan | darkgoldenrod | darkgray | darkgreen | darkgrey | darkkhaki | darkmagenta | darkolivegreen | darkorange | darkorchid | darkred | darksalmon | darkseagreen | darkslateblue | darkslategray | darkslategrey | darkturquoise | darkviolet | deeppink | deepskyblue | dimgray | dimgrey | dodgerblue | firebrick | floralwhite | forestgreen | fuchsia | gainsboro | ghostwhite | gold | goldenrod | gray | green | greenyellow | grey | honeydew | hotpink | indianred | indigo | ivory | khaki | lavender | lavenderblush | lawngreen | lemonchiffon | lightblue | lightcoral | lightcyan | lightgoldenrodyellow | lightgray | lightgreen | lightgrey | lightpink | lightsalmon | lightseagreen | lightskyblue | lightslategray | lightslategrey | lightsteelblue | lightyellow | lime | limegreen | linen | magenta | maroon | mediumaquamarine | mediumblue | mediumorchid | mediumpurple | mediumseagreen | mediumslateblue | mediumspringgreen | mediumturquoise | mediumvioletred | midnightblue | mintcream | mistyrose | moccasin | navajowhite | navy | oldlace | olive | olivedrab | orange | orangered | orchid | palegoldenrod | palegreen | paleturquoise | palevioletred | papayawhip | peachpuff | peru | pink | plum | powderblue | purple | rebeccapurple | red | rosybrown | royalblue | saddlebrown | salmon | sandybrown | seagreen | seashell | sienna | silver | skyblue | slateblue | slategray | slategrey | snow | springgreen | steelblue | tan | teal | thistle | tomato | turquoise | violet | wheat | white | whitesmoke | yellow | yellowgreen | <-non-standard-color>"
},
"outline-radius": {
"comment": "missed, looks like it's a similar to <border-radius> https://developer.mozilla.org/en/docs/Web/CSS/-moz-outline-radius",
"syntax": "<border-radius>"
},
"paint": {
"comment": "simplified SVG syntax (omit <icccolor>, replace <funciri> for <url>) https://www.w3.org/TR/SVG/painting.html#SpecifyingPaint",
"syntax": "none | currentColor | <color> | <url> [ none | currentColor | <color> ]?"
},
"path()": {
"comment": "missed, `motion` property was renamed, but left it as is for now; path() syntax was get from last draft https://drafts.fxtf.org/motion-1/#funcdef-offset-path-path",
"syntax": "path( <string> )"
},
"bg-position": {
"comment": "rewrite syntax (TODO: make match work with original syntax)",
"syntax": "[ center && [ left | right | top | bottom ] <length-percentage>? ] | [ [ left | right ] <length-percentage>? ] && [ [ top | bottom ] <length-percentage>? ] | [ [ left | center | right | <length-percentage> ] || [ top | center | bottom | <length-percentage> ] ]"
},
"right": {
"comment": "missed; not sure we should add it, but no others except `shape` is using it so it's ok for now; https://drafts.fxtf.org/css-masking-1/#funcdef-clip-rect",
"syntax": "<length> | auto"
},
"shape": {
"comment": "missed spaces in function body and add backwards compatible syntax",
"syntax": "rect( [ [ <top>, <right>, <bottom>, <left> ] | [ <top> <right> <bottom> <left> ] ] )"
},
"single-transition": {
"comment": "moved <single-transition-timing-function> in the beginning to avoid wrong match to <single-transition-property>",
"syntax": "<single-transition-timing-function> || [ none | <single-transition-property> ] || <time> || <time>"
},
"svg-length": {
"comment": "All coordinates and lengths in SVG can be specified with or without a unit identifier",
"references": [
"https://www.w3.org/TR/SVG11/coords.html#Units"
],
"syntax": "<percentage> | <length> | <number>"
},
"svg-writing-mode": {
"comment": "SVG specific keywords (deprecated for CSS)",
"references": [
"https://developer.mozilla.org/en/docs/Web/CSS/writing-mode",
"https://www.w3.org/TR/SVG/text.html#WritingModeProperty"
],
"syntax": "lr-tb | rl-tb | tb-rl | lr | rl | tb"
},
"top": {
"comment": "missed; not sure we should add it, but no others except `shape` is using it so it's ok for now; https://drafts.fxtf.org/css-masking-1/#funcdef-clip-rect",
"syntax": "<length> | auto"
},
"x": {
"comment": "missed; not sure we should add it, but no others except `cursor` is using it so it's ok for now; https://drafts.csswg.org/css-ui-3/#cursor",
"syntax": "<number>"
},
"y": {
"comment": "missed; not sure we should add it, but no others except `cursor` is using so it's ok for now; https://drafts.csswg.org/css-ui-3/#cursor",
"syntax": "<number>"
},
"var()": {
"comment": "drop it since it's a generic (also syntax is incorrect and can't be parsed)",
"syntax": null
},
"an-plus-b": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"feature-type": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"feature-value-block": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"feature-value-declaration": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"feature-value-block-list": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"feature-value-declaration-list": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"general-enclosed": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"keyframe-block": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"keyframe-block-list": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"mf-plain": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"mf-range": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"mf-value": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"media-and": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"media-condition": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"media-not": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"media-or": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"media-in-parens": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"media-feature": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"media-condition-without-or": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"media-query": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"media-query-list": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"nth": {
"comment": "syntax has <an-plus-b> that doesn't support currently, drop for now",
"syntax": null
},
"page-selector": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"page-selector-list": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"page-body": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"page-margin-box": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"page-margin-box-type": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
},
"pseudo-page": {
"comment": "syntax is incorrect and can't be parsed, drop for now",
"syntax": null
}
}
}
+6
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
BIN
View File
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
# Lexer
> To be done
+132
View File
@@ -0,0 +1,132 @@
# List
<!-- MarkdownTOC -->
- [Static methods](#static-methods)
- [List.createItem](#listcreateitem)
- [Properties](#properties)
- [List#head](#listhead)
- [List#tail](#listtail)
- [List#cursor](#listcursor)
- [Methods](#methods)
- [List#createItem\(\)](#listcreateitem-1)
- [List#updateCursors\(\)](#listupdatecursors)
- [List#getSize\(\)](#listgetsize)
- [List#fromArray\(\)](#listfromarray)
- [List#toArray\(\)](#listtoarray)
- [List#toJSON\(\)](#listtojson)
- [List#isEmpty\(\)](#listisempty)
- [List#first\(\)](#listfirst)
- [List#last\(\)](#listlast)
- [List#each\(\)](#listeach)
- [List#forEach\(\)](#listforeach)
- [List#eachRight\(\)](#listeachright)
- [List#forEachRight\(\)](#listforeachright)
- [List#nextUntil\(\)](#listnextuntil)
- [List#prevUntil\(\)](#listprevuntil)
- [List#some\(\)](#listsome)
- [List#map\(\)](#listmap)
- [List#filter\(\)](#listfilter)
- [List#clear\(\)](#listclear)
- [List#copy\(\)](#listcopy)
- [List#prepend\(\)](#listprepend)
- [List#prependData\(\)](#listprependdata)
- [List#append\(\)](#listappend)
- [List#appendData\(\)](#listappenddata)
- [List#insert\(\)](#listinsert)
- [List#insertData\(\)](#listinsertdata)
- [List#remove\(\)](#listremove)
- [List#push\(\)](#listpush)
- [List#pop\(\)](#listpop)
- [List#unshift\(\)](#listunshift)
- [List#shift\(\)](#listshift)
- [List#prependList\(\)](#listprependlist)
- [List#appendList\(\)](#listappendlist)
- [List#insertList\(\)](#listinsertlist)
- [List#replace\(\)](#listreplace)
<!-- /MarkdownTOC -->
## Static methods
### List.createItem
## Properties
### List#head
### List#tail
### List#cursor
## Methods
### List#createItem()
### List#updateCursors()
### List#getSize()
### List#fromArray()
### List#toArray()
### List#toJSON()
### List#isEmpty()
### List#first()
### List#last()
### List#each()
### List#forEach()
### List#eachRight()
### List#forEachRight()
### List#nextUntil()
### List#prevUntil()
### List#some()
### List#map()
### List#filter()
### List#clear()
### List#copy()
### List#prepend()
### List#prependData()
### List#append()
### List#appendData()
### List#insert()
### List#insertData()
### List#remove()
### List#push()
### List#pop()
### List#unshift()
### List#shift()
### List#prependList()
### List#appendList()
### List#insertList()
### List#replace()
+131
View File
@@ -0,0 +1,131 @@
# Tokenizer
<!-- MarkdownTOC -->
- [Static properties](#static-properties)
- [CssSyntaxError](#csssyntaxerror)
- [TYPE](#type)
- [NAME](#name)
- [SYMBOL_TYPE](#symboltype)
- [PUNCTUATION](#punctuation)
- [Static methods](#static-methods)
- [firstCharOffset\(source\)](#firstcharoffsetsource)
- [isHex\(code\)](#ishexcode)
- [isNumber\(code\)](#isnumbercode)
- [isNewline\(source, offset, code\)](#isnewlinesource-offset-code)
- [cmpChar\(testStr, offset, referenceCode\)](#cmpcharteststr-offset-referencecode)
- [cmpStr\(testStr, start, end, referenceStr\)](#cmpstrteststr-start-end-referencestr)
- [endsWith\(testStr, referenceStr\)](#endswithteststr-referencestr)
- [findLastNonSpaceLocation\(scanner\)](#findlastnonspacelocationscanner)
- [findWhitespaceEnd\(source, offset\)](#findwhitespaceendsource-offset)
- [findCommentEnd\(source, offset\)](#findcommentendsource-offset)
- [findStringEnd\(source, offset, quote\)](#findstringendsource-offset-quote)
- [findDecimalNumberEnd\(source, offset\)](#finddecimalnumberendsource-offset)
- [findNumberEnd\(source, offset, allowFraction\)](#findnumberendsource-offset-allowfraction)
- [findEscaseEnd\(source, offset\)](#findescaseendsource-offset)
- [findIdentifierEnd\(source, offset\)](#findidentifierendsource-offset)
- [Methods](#methods)
- [setSource\(source, startOffset, startLine, startColumn\)](#setsourcesource-startoffset-startline-startcolumn)
- [lookupType\(offset\)](#lookuptypeoffset)
- [lookupNonWSType\(offset\)](#lookupnonwstypeoffset)
- [lookupValue\(offset, referenceStr\)](#lookupvalueoffset-referencestr)
- [getTokenValue\(\)](#gettokenvalue)
- [substrToCursor\(start\)](#substrtocursorstart)
- [skipWS\(\)](#skipws)
- [skip\(tokenCount\)](#skiptokencount)
- [next\(\)](#next)
- [eat\(tokenType\)](#eattokentype)
- [eatNonWS\(tokenType\)](#eatnonwstokentype)
- [consume\(tokenType\)](#consumetokentype)
- [consumeNonWS\(tokenType\)](#consumenonwstokentype)
- [expectIdentifier\(name\)](#expectidentifiername)
- [getLocation\(offset, filename\)](#getlocationoffset-filename)
- [getLocationRange\(start, end, filename\)](#getlocationrangestart-end-filename)
- [error\(message, offset\)](#errormessage-offset)
- [getTypes\(\)](#gettypes)
<!-- /MarkdownTOC -->
## Static properties
### CssSyntaxError
### TYPE
### NAME
### SYMBOL_TYPE
### PUNCTUATION
## Static methods
### firstCharOffset(source)
### isHex(code)
### isNumber(code)
### isNewline(source, offset, code)
### cmpChar(testStr, offset, referenceCode)
### cmpStr(testStr, start, end, referenceStr)
### endsWith(testStr, referenceStr)
### findLastNonSpaceLocation(scanner)
### findWhitespaceEnd(source, offset)
### findCommentEnd(source, offset)
### findStringEnd(source, offset, quote)
### findDecimalNumberEnd(source, offset)
### findNumberEnd(source, offset, allowFraction)
### findEscaseEnd(source, offset)
### findIdentifierEnd(source, offset)
## Methods
### setSource(source, startOffset, startLine, startColumn)
### lookupType(offset)
### lookupNonWSType(offset)
### lookupValue(offset, referenceStr)
### getTokenValue()
### substrToCursor(start)
### skipWS()
### skip(tokenCount)
### next()
### eat(tokenType)
### eatNonWS(tokenType)
### consume(tokenType)
### consumeNonWS(tokenType)
### expectIdentifier(name)
### getLocation(offset, filename)
### getLocationRange(start, end, filename)
### error(message, offset)
### getTypes()
+3
View File
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 42 KiB

+567
View File
@@ -0,0 +1,567 @@
# AST format
CSSTree's AST consists of nodes (leafs). Each node is an object with a set of properties that depends on node's type. Nodes can refers to other nodes and contain a list of nested nodes.
Interactively explore the AST with [AST Explorer](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8).
<!-- MarkdownTOC -->
- [Example](#example)
- [Common node's properties](#common-nodes-properties)
- [type](#type)
- [loc](#loc)
- [children](#children)
- [Node types](#node-types)
- [AnPlusB](#anplusb)
- [Atrule](#atrule)
- [AtrulePrelude](#atruleprelude)
- [AttributeSelector](#attributeselector)
- [Block](#block)
- [Brackets](#brackets)
- [CDC](#cdc)
- [CDO](#cdo)
- [ClassSelector](#classselector)
- [Combinator](#combinator)
- [Comment](#comment)
- [Declaration](#declaration)
- [DeclarationList](#declarationlist)
- [Dimension](#dimension)
- [Function](#function)
- [HexColor](#hexcolor)
- [IdSelector](#idselector)
- [Identifier](#identifier)
- [MediaFeature](#mediafeature)
- [MediaQuery](#mediaquery)
- [MediaQueryList](#mediaquerylist)
- [Nth](#nth)
- [Number](#number)
- [Operator](#operator)
- [Parentheses](#parentheses)
- [Percentage](#percentage)
- [PseudoClassSelector](#pseudoclassselector)
- [PseudoElementSelector](#pseudoelementselector)
- [Ratio](#ratio)
- [Raw](#raw)
- [Rule](#rule)
- [Selector](#selector)
- [SelectorList](#selectorlist)
- [String](#string)
- [StyleSheet](#stylesheet)
- [TypeSelector](#typeselector)
- [UnicodeRange](#unicoderange)
- [Url](#url)
- [Value](#value)
- [WhiteSpace](#whitespace)
<!-- /MarkdownTOC -->
## Example
Assume we have a CSS:
```css
body {
color: red;
}
```
An AST for this CSS might look like:
```js
{
type: 'StyleSheet',
loc: null,
children: [
{
type: 'Rule',
loc: null,
prelude: {
type: 'SelectorList',
loc: null,
children: [
{
type: 'Selector',
loc: null,
children: [
{
type: 'TypeSelector',
loc: null,
name: 'body'
}
]
}
]
},
block: {
type: 'Block',
loc: null,
children: [
{
type: 'Declaration',
loc: null,
important: false,
property: 'color',
value: {
type: 'Value',
loc: null,
children: [
{
type: 'Identifier',
loc: null,
name: 'red'
}
]
}
}
]
}
}
]
}
```
> NOTE: The example uses arrays for the values of the property `children`. In fact, the values of this property are instances of the [`List`](List.md) class.
An AST structure (i.e. details level, include positions or not) is depend on options passed to parser. See [Parsing CSS into AST](parsing.md) for details.
## Common node's properties
All nodes have the following properties.
### type
Type: `String`
Indicates the type of a node. The possible values are the ones listed in the [Node types](#node-types) below.
### loc
Type: `Object` or `null`
Information about the position in the source string that corresponds to the node. It has the following structure:
```js
{
source: String,
start: {
offset: Number,
line: Number,
column: Number
},
end: {
offset: Number,
line: Number,
column: Number
}
}
```
The `source` property contains value of `options.filename` if passed to `csstree.parse()`, otherwise `"<unknown>"`.
The `offset` number is zero-based, indicates the index in a source string passed to the parser.
The `line` and `column` numbers are 1-based: the first line is `1` and the first column of a line is `1`.
The `loc` property lets you know from which source file the node comes from (if available) and what part of that file was parsed into the node. By default parser doesn't include `loc` data into the AST (sets `null` for this property), you should pass `options.positions` equal to `true` to make `loc` filled.
### children
Type: `List` or `null`
Only certain types of nodes can contain this property, such as [`StyleSheet`](#stylesheet) or [`Block`](#block). However, this is the only property that can store a list of nested nodes.
Most node types always store an instance of the `List` in this property, even if there is no nested nodes (the list is empty). Only some node types, such as `PseudoClassSelector` and `PseudoElementSelector`, can store a `null` instead of a list. This is due to the fact that in the absence of a list such node types is represent a pseudo-selector, and in the presence of a list, a functional pseudo-selector. See definition of each node type for details.
## Node types
> NOTE: Despite every node has a `loc` property, this property is excluded from definitions to reduce a noise.
<!-- node types -->
### AnPlusB
Used for [the An+B microsyntax](https://drafts.csswg.org/css-syntax/#anb-microsyntax).
```js
{
type: "AnPlusB",
a: String | null,
b: String | null
}
```
`a` or `b` fields may have no value (equals to `null`) but not both at the same time. Parser normalizes `a` value to store a valid integer, i.e. parser will store `-1` for `-n` and `1` for `n`.
### Atrule
```js
{
type: "Atrule",
name: String,
prelude: <AtrulePrelude> | <Raw> | null,
block: <Block> | null
}
```
### AtrulePrelude
```js
{
type: "AtrulePrelude",
children: List
}
```
### AttributeSelector
```js
{
type: "AttributeSelector",
name: <Identifier>,
matcher: String | null,
value: <String> | <Identifier> | null,
flags: String | null
}
```
### Block
```js
{
type: "Block",
children: List
}
```
### Brackets
```js
{
type: "Brackets",
children: List
}
```
### CDC
```js
{
type: "CDC"
}
```
### CDO
```js
{
type: "CDO"
}
```
### ClassSelector
```js
{
type: "ClassSelector",
name: String
}
```
### Combinator
```js
{
type: "Combinator",
name: String
}
```
### Comment
```js
{
type: "Comment",
value: String
}
```
### Declaration
```js
{
type: "Declaration",
important: Boolean | String,
property: String,
value: <Value> | <Raw>
}
```
### DeclarationList
```js
{
type: "DeclarationList",
children: List
}
```
### Dimension
```js
{
type: "Dimension",
value: String,
unit: String
}
```
### Function
```js
{
type: "Function",
name: String,
children: List
}
```
### HexColor
```js
{
type: "HexColor",
value: String
}
```
### IdSelector
```js
{
type: "IdSelector",
name: String
}
```
### Identifier
```js
{
type: "Identifier",
name: String
}
```
### MediaFeature
```js
{
type: "MediaFeature",
name: String,
value: <Identifier> | <Number> | <Dimension> | <Ratio> | null
}
```
### MediaQuery
```js
{
type: "MediaQuery",
children: List
}
```
### MediaQueryList
```js
{
type: "MediaQueryList",
children: List
}
```
### Nth
```js
{
type: "Nth",
nth: <AnPlusB> | <Identifier>,
selector: <SelectorList> | null
}
```
### Number
```js
{
type: "Number",
value: String
}
```
### Operator
```js
{
type: "Operator",
value: String
}
```
### Parentheses
```js
{
type: "Parentheses",
children: List
}
```
### Percentage
```js
{
type: "Percentage",
value: String
}
```
### PseudoClassSelector
```js
{
type: "PseudoClassSelector",
name: String,
children: List | null
}
```
### PseudoElementSelector
```js
{
type: "PseudoElementSelector",
name: String,
children: List | null
}
```
### Ratio
```js
{
type: "Ratio",
left: String,
right: String
}
```
### Raw
A sequence of any characters. This node type is used for unparsed fragments of CSS, e.g. due to parse error or parser settings, and for quirk parts like content of some functions, such as `url()` or `expression()`.
```js
{
type: "Raw",
value: String
}
```
### Rule
```js
{
type: "Rule",
prelude: <SelectorList> | <Raw>,
block: <Block>
}
```
### Selector
```js
{
type: "Selector",
children: List
}
```
### SelectorList
```js
{
type: "SelectorList",
children: List
}
```
### String
A sequence of characters enclosed in double quotes or single quotes.
```js
{
type: "String",
value: String
}
```
### StyleSheet
```js
{
type: "StyleSheet",
children: List
}
```
### TypeSelector
```js
{
type: "TypeSelector",
name: String
}
```
### UnicodeRange
Used for [the Unicode-Range microsyntax](https://drafts.csswg.org/css-syntax/#urange).
```js
{
type: "UnicodeRange",
value: String
}
```
### Url
```js
{
type: "Url",
value: <String> | <Raw>
}
```
### Value
```js
{
type: "Value",
children: List
}
```
### WhiteSpace
A sequence of one or more white spaces, i.e. ` ` (space), `\t`, `\r`, `\n` and `\f`.
```js
{
type: "WhiteSpace",
value: String
}
```
<!-- /node types -->
+48
View File
@@ -0,0 +1,48 @@
# Translate AST to string
## generate(ast[, options])
Generates a CSS string for given AST.
```js
// generate with default settings
csstree.generate(ast);
// generate with options
csstree.generate(ast, {
sourceMap: true
});
```
Options (optional):
<!-- MarkdownTOC -->
- [sourceMap](#sourcemap)
- [decorator](#decorator)
<!-- /MarkdownTOC -->
### sourceMap
Type: `boolean`
Default: `false`
Generates a source map (nodes should contain positions in `loc` property). Note, that an object instead of string is returned in that case.
```js
var ast = csstree.parse('.test { color: red }', {
filename: 'my.css',
positions: true
});
var result = csstree.generate(ast, { sourceMap: true });
// { css: '.test{color:red}', map: SourceMapGenerator {} }
```
### decorator
Type: `function`
Default: none
A function that a handlers used by a generator. TBD
+285
View File
@@ -0,0 +1,285 @@
# Parsing CSS into AST
> NOTE: Currenly parser omits redundant separators, spaces and comments (except exclamation comments, i.e. `/*! comment */`) on AST build.
## parse(source[, options])
Parses CSS into AST.
```js
// simple parsing with no options
var ast = csstree.parse('.example { color: red }');
// parse with options
var ast = csstree.parse('.foo.bar', {
context: 'selector',
positions: true
});
```
Options (optional):
<!-- MarkdownTOC -->
- [context](#context)
- [atrule](#atrule)
- [positions](#positions)
- [onParseError](#onparseerror)
- [filename](#filename)
- [offset](#offset)
- [line](#line)
- [column](#column)
- [parseAtrulePrelude](#parseatruleprelude)
- [parseRulePrelude](#parseruleprelude)
- [parseValue](#parsevalue)
- [parseCustomProperty](#parsecustomproperty)
<!-- /MarkdownTOC -->
### context
Type: `string`
Default: `'stylesheet'`
Defines what part of CSS is parsing.
Contexts:
- `stylesheet` (default) – regular stylesheet, should be suitable in most cases
- `atrule` – at-rule (e.g. `@media screen, print { ... }`)
- `atrulePrelude` – at-rule prelude (`screen, print` for example above)
- `mediaQueryList` – used to parse comma separated media query list
- `mediaQuery` – used to parse media query
- `rule` – rule (e.g. `.foo, .bar:hover { color: red; border: 1px solid black; }`)
- `selectorList` – selector group (`.foo, .bar:hover` for rule example)
- `selector` – selector (`.foo` or `.bar:hover` for rule example)
- `block` – block with curly braces (`{ color: red; border: 1px solid black; }` for rule example)
- `declarationList` – block content w/o curly braces (`color: red; border: 1px solid black;` for rule example), useful for parsing HTML `style` attribute value
- `declaration` – declaration (`color: red` or `border: 1px solid black` for rule example)
- `value` – declaration value (`red` or `1px solid black` for rule example)
### atrule
Type: `string` or `null`
Default: `null`
Using for `atrulePrelude` context to apply atrule specific parse rules.
### positions
Type: `boolean`
Default: `false`
Specify to store locations of node content in original source. Location is storing as `loc` field of nodes. `loc` property is always `null` when option is `false`. The structure of `loc`:
```
loc: {
source: 'value of `filename` option or `<unknown>`',
start: {
offset: <number>,
line: <number>,
column: <number>
},
end: {
offset: <number>,
line: <number>,
column: <number>
}
}
```
### onParseError
Type: `function(error, fallbackNode)` or `null`
Default: `null`
Parsing is tolerant by default, i.e. any text may to be parsed with no an raised exception. However, mistakes in CSS may make it imposible to parse some part, e.g. a selector or declaration. In that case bad content is wrapping into a `Raw` node and `onParseError` is invoking.
```js
csstree.parse('example { foo; bar: 1! }', {
onParseError: function(error) {
console.log(error.formattedMessage);
}
});
// Parse error: Colon is expected
// 1 |example { foo; bar: 1! }
// --------------------^
// Parse error: Identifier is expected
// 1 |example { foo; bar: 1! }
// ------------------------------^
```
### filename
Type: `string`
Default: `'<unknown>'`
Filename of source. This value adds to `loc` as `source` property when `positions` option is `true`. Using for source map generation.
### offset
Type: `number`
Default: `0`
Start offset. Useful when parsing a fragment of CSS to store a correct positions for node's `loc` property.
### line
Type: `number`
Default: `1`
Start line number. Useful when parsing fragment of CSS to store correct positions in node's `loc` property.
### column
Type: `number`
Default: `1`
Start column number. Useful when parsing fragment of CSS to store correct positions in node's `loc` property.
### parseAtrulePrelude
Type: `boolean`
Default: `true`
Defines to parse a at-rule prelude in details (represents as `AtruleExpresion`, `MediaQueryList` or `SelectorList` if any). Otherwise represents prelude as `Raw` node.
```js
csstree.parse('@example 1 2;');
// {
// "type": "Atrule",
// "prelude": {
// "type": "AtrulePrelude",
// "children": [
// { "type": "Number", "value": "1" },
// { "type": "WhiteSpace", "value": " " },
// { "type": "Number", "value": "2" }
// ]
// },
// "block": null
// }
csstree.parse('@example 1 2;', { parseAtrulePrelude: false });
// {
// "type": "Atrule",
// "prelude": {
// "type": "Raw",
// "value": "1 2"
// },
// "block": null
// }
```
### parseRulePrelude
Type: `boolean`
Default: `true`
Defines to parse a rule prelude in details or left unparsed (represents as `Raw` node).
```js
csstree.parse('.foo {}');
// {
// "type": "Rule",
// "prelude": {
// "type": "SelectorList",
// "children": [
// {
// "type": "Selector",
// "children": [
// { "type": "ClassSelector", "name": "foo" }
// ]
// }
// ]
// },
// "block": {
// "type": "Block",
// "children": []
// }
// }
csstree.parse('.foo {}', { parseRulePrelude: false });
// {
// "type": "Rule",
// "prelude": {
// "type": "Raw",
// "value": ".foo"
// },
// "block": {
// "type": "Block",
// "children": []
// }
// }
```
### parseValue
Type: `boolean`
Default: `true`
Defines to parse a declaration value in details (represents as `Value`). Otherwise represents value as `Raw` node.
```js
csstree.parse('color: #aabbcc', { context: 'declaration' });
// {
// "type": "Declaration",
// "important": false,
// "property": "color",
// "value": {
// "type": "Value",
// "children": [
// {
// "type": "HexColor",
// "value": "aabbcc"
// }
// ]
// }
// }
csstree.parse('color: #aabbcc', { context: 'declaration', parseValue: false });
// {
// "type": "Declaration",
// "important": false,
// "property": "color",
// "value": {
// "type": "Raw",
// "value": " #aabbcc"
// }
// }
```
### parseCustomProperty
Type: `boolean`
Default: `false`
Defines to parse a custom property value and a `var()` fallback in details (represents as `Value`). Otherwise represents value as `Raw` node.
```js
csstree.parse('--custom: #aabbcc', { context: 'declaration' });
// {
// "type": "Declaration",
// "important": false,
// "property": "--custom",
// "value": {
// "type": "Raw",
// "value": " #aabbcc"
// }
// }
csstree.parse('--custom: #aabbcc', { context: 'declaration', parseCustomProperty: true });
// {
// "type": "Declaration",
// "important": false,
// "property": "--custom",
// "value": {
// "type": "Value",
// "children": [
// {
// "type": "HexColor",
// "value": "aabbcc"
// }
// ]
// }
// }
```
+15
View File
@@ -0,0 +1,15 @@
# API
## General
- [Parsing CSS into AST](parsing.md)
- [AST format](ast.md)
- [Generate CSS from AST](generate.md)
- [AST traversal](traversal.md)
- [Utils to work with AST](utils.md)
## Classes
- [Tokenizer](Tokenizer.md)
- [Lexer](Lexer.md)
- [List](List.md)
+512
View File
@@ -0,0 +1,512 @@
# Supported syntaxes
> ⚠️ This is a basic implementation of support reference. Further improvements are pending. See comments on each section for details.
> ⚠️ This page is auto-generated. Please, don't update any content between special comments.
<!-- MarkdownTOC -->
- [Atrules](#atrules)
- [Functional pseudos](#functional-pseudos)
- [Properties](#properties)
<!-- /MarkdownTOC -->
## Atrules
At-rules with a custom parsing rules. In fact, any at-rule is supported but prelude and block are parsing with default rules. Validation support isn't supported for at-rules at the moment.
<!-- gen:atrule -->
- `@font-face`
- `@import`
- `@media`
- `@page`
- `@supports`
<!-- /gen:atrule -->
## Functional pseudos
Functional pseudos with a custom parsing rule. Non-listed functional pseudos don't parse a content inside parentheses and represent it as a `Raw` node if any. There is no difference between pseudo class and pseudo element on parsing, like no validation for functional pseudos is supported at the moment.
<!-- gen:pseudo -->
- `:dir()`
- `:has()`
- `:lang()`
- `:matches()`
- `:not()`
- `:nth-child()`
- `:nth-last-child()`
- `:nth-last-of-type()`
- `:nth-of-type()`
- `:slotted()`
<!-- /gen:pseudo -->
## Properties
Support for a property means CSSTree has a grammar for such property, so its value can be checked (validated) for complience to spec or browser inplementations (for non-standart properties). The validation doesn't perform on parsing stage and should be done as a separate step using Lexer API. In other words any property value can be parsed with default parsing rules, but validation is possible for listed properties only.
<!-- gen:properties -->
- `-moz-appearance`
- `-moz-background-clip`
- `-moz-binding`
- `-moz-border-bottom-colors`
- `-moz-border-left-colors`
- `-moz-border-radius-bottomleft`
- `-moz-border-radius-bottomright`
- `-moz-border-radius-topleft`
- `-moz-border-radius-topright`
- `-moz-border-right-colors`
- `-moz-border-top-colors`
- `-moz-context-properties`
- `-moz-float-edge`
- `-moz-force-broken-image-icon`
- `-moz-image-region`
- `-moz-orient`
- `-moz-osx-font-smoothing`
- `-moz-outline-radius`
- `-moz-outline-radius-bottomleft`
- `-moz-outline-radius-bottomright`
- `-moz-outline-radius-topleft`
- `-moz-outline-radius-topright`
- `-moz-stack-sizing`
- `-moz-text-blink`
- `-moz-user-focus`
- `-moz-user-input`
- `-moz-user-modify`
- `-moz-user-select`
- `-moz-window-dragging`
- `-moz-window-shadow`
- `-ms-filter`
- `-ms-flex-align`
- `-ms-flex-item-align`
- `-ms-flex-line-pack`
- `-ms-flex-negative`
- `-ms-flex-order`
- `-ms-flex-pack`
- `-ms-flex-positive`
- `-ms-flex-preferred-size`
- `-ms-grid-column-align`
- `-ms-grid-row-align`
- `-ms-high-contrast-adjust`
- `-ms-interpolation-mode`
- `-ms-overflow-style`
- `-ms-user-select`
- `-webkit-appearance`
- `-webkit-background-clip`
- `-webkit-border-before`
- `-webkit-border-before-color`
- `-webkit-border-before-style`
- `-webkit-border-before-width`
- `-webkit-box-reflect`
- `-webkit-column-break-after`
- `-webkit-column-break-before`
- `-webkit-column-break-inside`
- `-webkit-font-smoothing`
- `-webkit-line-clamp`
- `-webkit-mask`
- `-webkit-mask-attachment`
- `-webkit-mask-box-image`
- `-webkit-mask-clip`
- `-webkit-mask-composite`
- `-webkit-mask-image`
- `-webkit-mask-origin`
- `-webkit-mask-position`
- `-webkit-mask-position-x`
- `-webkit-mask-position-y`
- `-webkit-mask-repeat`
- `-webkit-mask-repeat-x`
- `-webkit-mask-repeat-y`
- `-webkit-overflow-scrolling`
- `-webkit-print-color-adjust`
- `-webkit-tap-highlight-color`
- `-webkit-text-fill-color`
- `-webkit-text-security`
- `-webkit-text-stroke`
- `-webkit-text-stroke-color`
- `-webkit-text-stroke-width`
- `-webkit-touch-callout`
- `-webkit-user-drag`
- `-webkit-user-select`
- `align-content`
- `align-items`
- `align-self`
- `alignment-baseline`
- `all`
- `animation`
- `animation-delay`
- `animation-direction`
- `animation-duration`
- `animation-fill-mode`
- `animation-iteration-count`
- `animation-name`
- `animation-play-state`
- `animation-timing-function`
- `appearance`
- `azimuth`
- `backdrop-filter`
- `backface-visibility`
- `background`
- `background-attachment`
- `background-blend-mode`
- `background-clip`
- `background-color`
- `background-image`
- `background-origin`
- `background-position`
- `background-position-x`
- `background-position-y`
- `background-repeat`
- `background-size`
- `baseline-shift`
- `behavior`
- `block-size`
- `border`
- `border-block-end`
- `border-block-end-color`
- `border-block-end-style`
- `border-block-end-width`
- `border-block-start`
- `border-block-start-color`
- `border-block-start-style`
- `border-block-start-width`
- `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-inline-end`
- `border-inline-end-color`
- `border-inline-end-style`
- `border-inline-end-width`
- `border-inline-start`
- `border-inline-start-color`
- `border-inline-start-style`
- `border-inline-start-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`
- `caret-color`
- `clear`
- `clip`
- `clip-path`
- `clip-rule`
- `color`
- `column-count`
- `column-fill`
- `column-gap`
- `column-rule`
- `column-rule-color`
- `column-rule-style`
- `column-rule-width`
- `column-span`
- `column-width`
- `columns`
- `contain`
- `content`
- `counter-increment`
- `counter-reset`
- `cue`
- `cue-after`
- `cue-before`
- `cursor`
- `direction`
- `display`
- `display-inside`
- `display-list`
- `display-outside`
- `dominant-baseline`
- `empty-cells`
- `fill`
- `fill-opacity`
- `fill-rule`
- `filter`
- `flex`
- `flex-basis`
- `flex-direction`
- `flex-flow`
- `flex-grow`
- `flex-shrink`
- `flex-wrap`
- `float`
- `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-variation-settings`
- `font-weight`
- `glyph-orientation-horizontal`
- `glyph-orientation-vertical`
- `grid`
- `grid-area`
- `grid-auto-columns`
- `grid-auto-flow`
- `grid-auto-rows`
- `grid-column`
- `grid-column-end`
- `grid-column-gap`
- `grid-column-start`
- `grid-gap`
- `grid-row`
- `grid-row-end`
- `grid-row-gap`
- `grid-row-start`
- `grid-template`
- `grid-template-areas`
- `grid-template-columns`
- `grid-template-rows`
- `hanging-punctuation`
- `height`
- `hyphens`
- `image-orientation`
- `image-rendering`
- `image-resolution`
- `ime-mode`
- `initial-letter`
- `initial-letter-align`
- `inline-size`
- `isolation`
- `justify-content`
- `kerning`
- `left`
- `letter-spacing`
- `line-break`
- `line-height`
- `line-height-step`
- `list-style`
- `list-style-image`
- `list-style-position`
- `list-style-type`
- `margin`
- `margin-block-end`
- `margin-block-start`
- `margin-bottom`
- `margin-inline-end`
- `margin-inline-start`
- `margin-left`
- `margin-right`
- `margin-top`
- `marker`
- `marker-end`
- `marker-mid`
- `marker-start`
- `mask`
- `mask-border`
- `mask-border-mode`
- `mask-border-outset`
- `mask-border-repeat`
- `mask-border-slice`
- `mask-border-source`
- `mask-border-width`
- `mask-clip`
- `mask-composite`
- `mask-image`
- `mask-mode`
- `mask-origin`
- `mask-position`
- `mask-repeat`
- `mask-size`
- `mask-type`
- `max-block-size`
- `max-height`
- `max-inline-size`
- `max-width`
- `min-block-size`
- `min-height`
- `min-inline-size`
- `min-width`
- `mix-blend-mode`
- `object-fit`
- `object-position`
- `offset`
- `offset-anchor`
- `offset-block-end`
- `offset-block-start`
- `offset-distance`
- `offset-inline-end`
- `offset-inline-start`
- `offset-path`
- `offset-position`
- `offset-rotate`
- `opacity`
- `order`
- `orphans`
- `outline`
- `outline-color`
- `outline-offset`
- `outline-style`
- `outline-width`
- `overflow`
- `overflow-clip-box`
- `overflow-wrap`
- `overflow-x`
- `overflow-y`
- `padding`
- `padding-block-end`
- `padding-block-start`
- `padding-bottom`
- `padding-inline-end`
- `padding-inline-start`
- `padding-left`
- `padding-right`
- `padding-top`
- `page-break-after`
- `page-break-before`
- `page-break-inside`
- `pause`
- `pause-after`
- `pause-before`
- `perspective`
- `perspective-origin`
- `pointer-events`
- `position`
- `quotes`
- `resize`
- `rest`
- `rest-after`
- `rest-before`
- `right`
- `ruby-align`
- `ruby-merge`
- `ruby-position`
- `scroll-behavior`
- `scroll-snap-coordinate`
- `scroll-snap-destination`
- `scroll-snap-points-x`
- `scroll-snap-points-y`
- `scroll-snap-type`
- `scroll-snap-type-x`
- `scroll-snap-type-y`
- `shape-image-threshold`
- `shape-margin`
- `shape-outside`
- `shape-rendering`
- `speak`
- `speak-as`
- `src`
- `stroke`
- `stroke-dasharray`
- `stroke-dashoffset`
- `stroke-linecap`
- `stroke-linejoin`
- `stroke-miterlimit`
- `stroke-opacity`
- `stroke-width`
- `tab-size`
- `table-layout`
- `text-align`
- `text-align-last`
- `text-anchor`
- `text-combine-upright`
- `text-decoration`
- `text-decoration-color`
- `text-decoration-line`
- `text-decoration-skip`
- `text-decoration-skip-ink`
- `text-decoration-style`
- `text-emphasis`
- `text-emphasis-color`
- `text-emphasis-position`
- `text-emphasis-style`
- `text-indent`
- `text-justify`
- `text-orientation`
- `text-overflow`
- `text-rendering`
- `text-shadow`
- `text-size-adjust`
- `text-transform`
- `text-underline-position`
- `top`
- `touch-action`
- `transform`
- `transform-box`
- `transform-origin`
- `transform-style`
- `transition`
- `transition-delay`
- `transition-duration`
- `transition-property`
- `transition-timing-function`
- `unicode-bidi`
- `unicode-range`
- `user-select`
- `vertical-align`
- `visibility`
- `voice-balance`
- `voice-duration`
- `voice-family`
- `voice-pitch`
- `voice-range`
- `voice-rate`
- `voice-stress`
- `voice-volume`
- `white-space`
- `widows`
- `width`
- `will-change`
- `word-break`
- `word-spacing`
- `word-wrap`
- `writing-mode`
- `z-index`
- `zoom`
<!-- /gen:properties -->
+3
View File
@@ -0,0 +1,3 @@
# Working with syntax
> To be done...
+249
View File
@@ -0,0 +1,249 @@
# AST traversal
AST traversal API is provided by `walk()` method.
```js
var csstree = require('css-tree');
var ast = csstree.parse('.a { color: red; }');
csstree.walk(ast, function(node) {
console.log(node.type);
});
// StyleSheet
// Rule
// SelectorList
// Selector
// ClassSelector
// Block
// Declaration
// Value
// Identifier
```
The facts you should know about `walk()` internals:
- Method uses `structure` field value of every node type to define the way how to iterate the nodes:
- A function-iterator is generating for every node type.
- Node's properties iterates in the order it defined in `structure` ([reverse](#reverse) option can invert an order).
- Properties that are not defined in `structure` are ignoring (doesn't interate).
- An exception is possible when a tree is not following to expected structure (it may happen if AST was built outside the CSSTree parser or transformed in a wrong way). In case you are not sure about correctness of a tree structure, you can use `try/catch` or check the tree with `csstree.lexer.validateStructure(ast)` before iterate it.
- Only `children` fields can contain a list of nodes. A list of nodes should be represented as a `List` instances. But for certain cases, `children` can be an array. Since `List` provides a similar to `Array` API, traversal can work in most cases, but without any guarantee. Therefore usings arrays in AST is not recomended, use them on your own risk.
## walk(ast, options)
Method visits each node of passed tree in a natural way and calls a handler for each one. It takes two arguments: a root node (`ast`) and an object (`options`). In simple case, it can take a function (handler) instead of `options` (`walk(ast, fn)` is equivalent to `walk(ast, { enter: fn })`).
Options:
<!-- MarkdownTOC -->
- [enter](#enter)
- [leave](#leave)
- [visit](#visit)
- [reverse](#reverse)
<!-- /MarkdownTOC -->
### enter
Type: `function` or `undefined`
Default: `undefined`
Handler on node entrance, i.e. before any nested node is processed.
```js
var csstree = require('css-tree');
var ast = csstree.parse('.a { color: red; }');
csstree.walk(ast, {
enter: function(node) {
console.log(node.type);
}
});
// StyleSheet
// Rule
// SelectorList
// Selector
// ClassSelector
// Block
// Declaration
// Value
// Identifier
```
In case `options` has a single `enter` field, it can replaced for the handler passed as a value for `enter`, i.e. `walk(ast, { enter: fn })` → `walk(ast, fn)`.
Handler receives a three arguments:
- `node` – the AST node a walker entering to
- `item` – node wrapper, that contains references to `prev` and `next` nodes in a list, and `data` reference for the node
- `list` – is a reference for the list; it's useful for list operations like `remove()` or `insert()`
> NOTE: If `children` is an array, the last two arguments are `index` and `array`, like for `Array#forEach()` or `Array#map()` methods.
```js
const csstree = require('css-tree');
const ast = csstree.parse(`
.a { foo: 1; bar: 2; }
.b { bar: 3; baz: 4; }
`);
// remove declarations with `bar` property from the tree
csstree.walk(ast, function(node, item, list) {
if (node.type === 'Declaration' && node.property === 'bar' && list) {
// remove a declaration from a list it
list.remove(item);
}
});
console.log(csstree.generate(ast));
// .a{foo:1}.b{baz:4}
```
> NOTE:
> - `item` and `list` are not defined for nodes that are not in a list. Even `Declaration` can be outside of any list in case it is a root of tree or a part of `@supports` prelude, e.g. `@supports (bar: 123) { ... }`. Therefore, it's recomended to check `item` or `list` are defined before using of it (those values both are defined or both are undefined, so it's enough to test one of them)
> - Only `List` instances are safe for tree transformations such as node removal. In case you perform such operations, you can ensure that all `children` in a tree is a `List` instances by calling `csstree.fromPlainObject(ast)` before traversal.
> - It's better to use `visit` option when possible to reach better performance
Context (`this`) for a handler is an object with a references to the closest ancestor nodes:
- `root` – refers to AST root node (actually it's a node passed to `walk()` method)
- `stylesheet` – refers to `StyleSheet` node, usually it's a root node
- `atrule` – refers to closest `Atrule` node if any
- `atrulePrelude` – refers to `AtrulePrelude` node if any
- `rule` – refers to closest `Rule` node if any
- `selector` – refers to `SelectorList` node if any
- `block` - refers to closest `Block` node if any
- `declaration` – refers to `Declaration` node if any
- `function` – refers to closest `Function`, `PseudoClassSelector` or `PseudoElementSelector` node if current node inside one of them
```js
const csstree = require('css-tree');
const ast = csstree.parse(`
@import url(import.css);
.foo { background: url('foo.jpg'); }
.bar { background-image: url(bar.png); }
`);
// collect all urls in declarations
const urls = [];
csstree.walk(ast, function(node) {
if (this.declaration !== null && node.type === 'Url') {
const value = node.value;
if (value.type === 'Raw') {
urls.push(value.value);
} else {
urls.push(value.value.substr(1, value.value.length - 2));
}
}
});
console.log(urls);
// [ 'foo.jpg', 'bar.png' ]
```
### leave
Type: `function` or `undefined`
Default: `undefined`
The same as `enter` handler but invokes on node exit, i.e. after all nested nodes are processed.
```js
var csstree = require('css-tree');
var ast = csstree.parse('.a { color: red; }');
csstree.walk(ast, {
leave: function(node) {
console.log(node.type);
}
});
// ClassSelector
// Selector
// SelectorList
// Identifier
// Value
// Declaration
// Block
// Rule
// StyleSheet
```
### visit
Type: `string` or `null`
Default: `null`
Invokes a handler for a specified node type only.
```js
var csstree = require('css-tree');
var ast = csstree.parse('.a { color: red; } .b { color: green; }');
csstree.walk(ast, {
visit: 'ClassSelector',
enter: function(node) {
console.log(node.name);
}
});
// example above is equal to
csstree.walk(ast, {
enter: function(node) {
if (node.type === 'ClassSelector') {
console.log(node.name);
}
}
});
```
The traveral for some node types can performs faster (10-15 times depending on the CSS structure), because some subtrees may to be skipped since they can't contain a node of specified type (e.g. `Rule` can't be used inside of `Declaration`, so declaration's subtree can be exclude from traversal path). Fast traversal is supported for node types:
- `Atrule`
- `Rule`
- `Declaration`
> NOTE: When fast traversal is applied, some nodes may not be reached in case of an incorrect location in the tree. That's may happen if AST was built outside the CSSTree parser or transformed in a wrong way. If you need to be 100% sure that every node of type will be visited (even in wrong position), don't use `visit` option and test node type by your own.
### reverse
Type: `boolean`
Default: `false`
Inverts a natural order of traversal of nodes. To achieve this, the following actions are performed:
- children nodes are iterated in reverse order (from last to first)
- properties are iterated in reverse order (according to `structure` definition of node)
- `enter` and `leave` handlers are swapped
```js
var assert = require('assert');
var csstree = require('css-tree');
var ast = csstree.parse('.a { color: red; }');
var natural = [];
csstree.walk(ast, {
enter: function(node) {
natural.push('enter ' + node.type);
},
leave: function(node) {
natural.push('leave ' + node.type);
}
});
var reverse = [];
csstree.walk(ast, {
reverse: true,
enter: function(node) {
reverse.push('enter ' + node.type);
},
leave: function(node) {
reverse.push('leave ' + node.type);
}
});
// will be truthy
assert.deepEqual(
reverse,
natural.reverse()
);
```
+151
View File
@@ -0,0 +1,151 @@
# Utils to work with AST
<!-- MarkdownTOC -->
- [property\(name\)](#propertyname)
- [keyword\(name\)](#keywordname)
- [clone\(ast\)](#cloneast)
- [fromPlainObject\(object\)](#fromplainobjectobject)
- [toPlainObject\(ast\)](#toplainobjectast)
<!-- /MarkdownTOC -->
## property(name)
Returns details for a property name, such as vendor prefix, used hack etc. Using for safe test of declaration property names, i.e. `Declaration.property`.
```js
var csstree = require('css-tree');
csstree.property('*-vendor-property');
// {
// basename: 'property',
// name: '-vendor-property',
// hack: '*',
// vendor: '-vendor-',
// prefix: '*-vendor-',
// custom: false
// }
csstree.property('--test-var');
// {
// basename: '--test-var',
// name: '--test-var',
// hack: '',
// vendor: '',
// prefix: '',
// custom: true
// };
```
`property()` function normalizes a name to lower case, except custom property names since they are case sensitive. It returns the same immutable (freezed) object for the same input (input after normalization).
```js
csstree.property('name') === csstree.property('NAME') // true
csstree.property('NAME').name === 'name' // true
csstree.property('--custom') === csstree.property('--Custom') // false
var info = csstree.property('NAME');
info.name === 'name'; //
info.name = 'foo'; // have no effect
info.name === 'name'; // true
```
Supported hacks:
- `_` in the beginning
- `+` in the beginning
- `#` in the beginning
- `*` in the beginning
- `$` in the beginning
- `/` in the beginning
- `//` in the beginning
## keyword(name)
Mostly the same as `property()` function, but without hack detection. Using for any identifier except declaration property name.
```js
var csstree = require('css-tree');
csstree.keyword('-vendor-keyword');
// {
// basename: 'keyword',
// name: '-vendor-keyword',
// vendor: '-vendor-',
// prefix: '-vendor-',
// custom: false
// };
```
## clone(ast)
Make AST deep copy.
```js
var orig = csstree.parse('.test { color: red }');
var copy = csstree.clone(orig);
csstree.walk(copy, function(node) {
if (node.type === 'Class') {
node.name = 'replaced';
}
});
console.log(csstree.generate(orig));
// .test{color:red}
console.log(csstree.generate(copy));
// .replaced{color:red}
```
## fromPlainObject(object)
`fromPlainObject()` walks through AST and coverts each `children` value into a `List` instance when value is an array.
```js
var csstree = require('css-tree');
var ast = {
type: 'SelectorList',
children: []
};
console.log(Array.isArray(ast.children)); // true
console.log(ast.children instanceof csstree.List); // false
ast = csstree.fromPlainObject(ast);
console.log(Array.isArray(ast.children)); // false
console.log(ast.children instanceof csstree.List); // true
```
Function mutates the passed AST. Use `clone()` function before passing AST to `fromPlainObject()` in case you want to avoid original tree mutation.
```js
astClone = csstree.fromPlainObject(csstree.clone(ast));
```
## toPlainObject(ast)
`fromPlainObject()` walks through AST and coverts each `children` value to regular array when value is a `List` instance.
```js
var csstree = require('css-tree');
var ast = {
type: 'SelectorList',
children: new List()
};
console.log(Array.isArray(ast.children)); // false
console.log(ast.children instanceof csstree.List); // true
ast = csstree.toPlainObject(ast);
console.log(Array.isArray(ast.children)); // true
console.log(ast.children instanceof csstree.List); // false
```
Function mutates the passed AST. Use `clone()` function before passing AST to `toPlainObject()` in case you want to avoid original tree mutation.
```js
ast = csstree.toPlainObject(csstree.clone(ast));
```
+28
View File
@@ -0,0 +1,28 @@
var List = require('../utils/list');
module.exports = function createConvertors(walk) {
return {
fromPlainObject: function(ast) {
walk(ast, {
enter: function(node) {
if (node.children && node.children instanceof List === false) {
node.children = new List().fromArray(node.children);
}
}
});
return ast;
},
toPlainObject: function(ast) {
walk(ast, {
leave: function(node) {
if (node.children && node.children instanceof List) {
node.children = node.children.toArray();
}
}
});
return ast;
}
};
};
+3
View File
@@ -0,0 +1,3 @@
var createConvertor = require('./create');
module.exports = createConvertor(require('../walker'));
+68
View File
@@ -0,0 +1,68 @@
'use strict';
var sourceMap = require('./sourceMap');
var hasOwnProperty = Object.prototype.hasOwnProperty;
function processChildren(node, delimeter) {
var list = node.children;
var prev = null;
if (typeof delimeter !== 'function') {
list.forEach(this.node, this);
} else {
list.forEach(function(node) {
if (prev !== null) {
delimeter.call(this, prev);
}
this.node(node);
prev = node;
}, this);
}
}
module.exports = function createGenerator(config) {
function processNode(node) {
if (hasOwnProperty.call(types, node.type)) {
types[node.type].call(this, node);
} else {
throw new Error('Unknown node type: ' + node.type);
}
}
var types = {};
if (config.node) {
for (var name in config.node) {
types[name] = config.node[name].generate;
}
}
return function(node, options) {
var buffer = '';
var handlers = {
children: processChildren,
node: processNode,
chunk: function(chunk) {
buffer += chunk;
},
result: function() {
return buffer;
}
};
if (options) {
if (typeof options.decorator === 'function') {
handlers = options.decorator(handlers);
}
if (options.sourceMap) {
handlers = sourceMap(handlers);
}
}
handlers.node(node);
return handlers.result();
};
};
+4
View File
@@ -0,0 +1,4 @@
var createGenerator = require('./create');
var config = require('../syntax/config/parser');
module.exports = createGenerator(config);
+97
View File
@@ -0,0 +1,97 @@
'use strict';
var SourceMapGenerator = require('source-map').SourceMapGenerator;
var trackNodes = {
Atrule: true,
Selector: true,
Declaration: true
};
module.exports = function generateSourceMap(handlers) {
var map = new SourceMapGenerator();
var line = 1;
var column = 0;
var generated = {
line: 1,
column: 0
};
var original = {
line: 0, // should be zero to add first mapping
column: 0
};
var sourceMappingActive = false;
var activatedGenerated = {
line: 1,
column: 0
};
var activatedMapping = {
generated: activatedGenerated
};
var handlersNode = handlers.node;
handlers.node = function(node) {
if (node.loc && node.loc.start && trackNodes.hasOwnProperty(node.type)) {
var nodeLine = node.loc.start.line;
var nodeColumn = node.loc.start.column - 1;
if (original.line !== nodeLine ||
original.column !== nodeColumn) {
original.line = nodeLine;
original.column = nodeColumn;
generated.line = line;
generated.column = column;
if (sourceMappingActive) {
sourceMappingActive = false;
if (generated.line !== activatedGenerated.line ||
generated.column !== activatedGenerated.column) {
map.addMapping(activatedMapping);
}
}
sourceMappingActive = true;
map.addMapping({
source: node.loc.source,
original: original,
generated: generated
});
}
}
handlersNode.call(this, node);
if (sourceMappingActive && trackNodes.hasOwnProperty(node.type)) {
activatedGenerated.line = line;
activatedGenerated.column = column;
}
};
var handlersChunk = handlers.chunk;
handlers.chunk = function(chunk) {
for (var i = 0; i < chunk.length; i++) {
if (chunk.charCodeAt(i) === 10) { // \n
line++;
column = 0;
} else {
column++;
}
}
handlersChunk(chunk);
};
var handlersResult = handlers.result;
handlers.result = function() {
if (sourceMappingActive) {
map.addMapping(activatedMapping);
}
return {
css: handlersResult(),
map: map
};
};
return handlers;
};
+3
View File
@@ -0,0 +1,3 @@
'use strict';
module.exports = require('./syntax');
+363
View File
@@ -0,0 +1,363 @@
'use strict';
var SyntaxReferenceError = require('./error').SyntaxReferenceError;
var MatchError = require('./error').MatchError;
var names = require('../utils/names');
var generic = require('./generic');
var parse = require('./grammar/parse');
var generate = require('./grammar/generate');
var walk = require('./grammar/walk');
var match = require('./match');
var trace = require('./trace');
var search = require('./search');
var getStructureFromConfig = require('./structure').getStructureFromConfig;
var cssWideKeywords = parse('inherit | initial | unset');
var cssWideKeywordsWithExpression = parse('inherit | initial | unset | <expression>');
function dumpMapSyntax(map, syntaxAsAst) {
var result = {};
for (var name in map) {
if (map[name].syntax) {
result[name] = syntaxAsAst ? map[name].syntax : generate(map[name].syntax);
}
}
return result;
}
function unwrapNode(item) {
return item && item.data;
}
function valueHasVar(value) {
var hasVar = false;
this.syntax.walk(value, function(node) {
if (node.type === 'Function' && node.name.toLowerCase() === 'var') {
hasVar = true;
}
});
return hasVar;
}
// check node is \0 or \9 hack
function isHack(node) {
return node.type === 'Identifier' && /^\\[09]/.test(node.name);
}
// white spaces, comments and some hacks can to be ignored at the end of value
function isNextMayToBeIgnored(cursor) {
while (cursor !== null) {
if (cursor.data.type !== 'WhiteSpace' &&
cursor.data.type !== 'Comment' &&
!isHack(cursor.data)) {
return false;
}
cursor = cursor.next;
}
return true;
}
function buildMatchResult(match, error) {
return {
matched: match,
error: error,
getTrace: trace.getTrace,
isType: trace.isType,
isProperty: trace.isProperty,
isKeyword: trace.isKeyword
};
}
function matchSyntax(lexer, syntax, node, useCommon) {
var result;
if (!node || !node.children) {
return buildMatchResult(null, new Error('Node has no children'));
}
if (valueHasVar.call(lexer, node)) {
return buildMatchResult(null, new Error('Matching for a tree with var() is not supported'));
}
if (useCommon) {
result = match(lexer, lexer.valueCommonSyntax, node.children.head);
}
if (!useCommon || !result.match) {
result = syntax.match(node.children.head);
if (!result.match) {
return buildMatchResult(null, new MatchError('Mismatch', lexer, syntax.syntax, node, result.badNode || unwrapNode(result.next) || node));
}
}
// enhance top-level match wrapper
if (result.match.type === 'ASTNode') {
result.match = {
syntax: {
type: syntax.type,
name: syntax.name
},
match: [result.match]
};
} else if (result.match.syntax.type === 'Group') {
result.match.syntax = {
type: syntax.type,
name: syntax.name
};
}
if (result.next && !isNextMayToBeIgnored(result.next)) {
return buildMatchResult(null, new MatchError('Uncomplete match', lexer, syntax.syntax, node, result.badNode || unwrapNode(result.next) || node));
}
return buildMatchResult(result.match, null);
}
var Lexer = function(config, syntax, structure) {
this.valueCommonSyntax = cssWideKeywords;
this.syntax = syntax;
this.generic = false;
this.properties = {};
this.types = {};
this.structure = structure || getStructureFromConfig(config);
if (config) {
if (config.generic) {
this.generic = true;
for (var name in generic) {
this.addType_(name, generic[name]);
}
}
if (config.types) {
for (var name in config.types) {
this.addType_(name, config.types[name]);
}
}
if (config.properties) {
for (var name in config.properties) {
this.addProperty_(name, config.properties[name]);
}
}
}
};
Lexer.prototype = {
structure: {},
checkStructure: function(ast) {
function collectWarning(node, message) {
warns.push({
node: node,
message: message
});
}
var structure = this.structure;
var warns = [];
this.syntax.walk(ast, function(node) {
if (structure.hasOwnProperty(node.type)) {
structure[node.type].check(node, collectWarning);
} else {
collectWarning(node, 'Unknown node type `' + node.type + '`');
}
});
return warns.length ? warns : false;
},
createDescriptor: function(syntax, type, name) {
var self = this;
var descriptor = {
type: type,
name: name,
syntax: null,
match: null
};
if (typeof syntax === 'function') {
// convert syntax to pseudo syntax node
// NOTE: that's not a part of match result tree
syntax = {
type: 'ASTNode',
match: syntax
};
descriptor.match = function(item) {
return match(self, syntax, item);
};
} else {
if (typeof syntax === 'string') {
// lazy parsing on first access
Object.defineProperty(descriptor, 'syntax', {
get: function() {
Object.defineProperty(descriptor, 'syntax', {
value: parse(syntax)
});
return descriptor.syntax;
}
});
} else {
descriptor.syntax = syntax;
}
descriptor.match = function(item) {
return match(self, descriptor.syntax, item);
};
}
return descriptor;
},
addProperty_: function(name, syntax) {
this.properties[name] = this.createDescriptor(syntax, 'Property', name);
},
addType_: function(name, syntax) {
this.types[name] = this.createDescriptor(syntax, 'Type', name);
if (syntax === generic.expression) {
this.valueCommonSyntax = cssWideKeywordsWithExpression;
}
},
matchDeclaration: function(node) {
if (node.type !== 'Declaration') {
return buildMatchResult(null, new Error('Not a Declaration node'));
}
return this.matchProperty(node.property, node.value);
},
matchProperty: function(propertyName, value) {
var property = names.property(propertyName);
// don't match syntax for a custom property
if (property.custom) {
return buildMatchResult(null, new Error('Lexer matching doesn\'t applicable for custom properties'));
}
var propertySyntax = property.vendor
? this.getProperty(property.name) || this.getProperty(property.basename)
: this.getProperty(property.name);
if (!propertySyntax) {
return buildMatchResult(null, new SyntaxReferenceError('Unknown property', propertyName));
}
return matchSyntax(this, propertySyntax, value, true);
},
matchType: function(typeName, value) {
var typeSyntax = this.getType(typeName);
if (!typeSyntax) {
return buildMatchResult(null, new SyntaxReferenceError('Unknown type', typeName));
}
return matchSyntax(this, typeSyntax, value, false);
},
match: function(syntax, value) {
if (!syntax || !syntax.type) {
return buildMatchResult(null, new SyntaxReferenceError('Bad syntax'));
}
if (!syntax.match) {
syntax = this.createDescriptor(syntax);
}
return matchSyntax(this, syntax, value, false);
},
findValueFragments: function(propertyName, value, type, name) {
return search.matchFragments(this, value, this.matchProperty(propertyName, value), type, name);
},
findDeclarationValueFragments: function(declaration, type, name) {
return search.matchFragments(this, declaration.value, this.matchDeclaration(declaration), type, name);
},
findAllFragments: function(ast, type, name) {
var result = [];
this.syntax.walk(ast, {
visit: 'Declaration',
enter: function(declaration) {
result.push.apply(result, this.findDeclarationValueFragments(declaration, type, name));
}.bind(this)
});
return result;
},
getProperty: function(name) {
return this.properties.hasOwnProperty(name) ? this.properties[name] : null;
},
getType: function(name) {
return this.types.hasOwnProperty(name) ? this.types[name] : null;
},
validate: function() {
function validate(syntax, name, broken, descriptor) {
if (broken.hasOwnProperty(name)) {
return broken[name];
}
broken[name] = false;
if (descriptor.syntax !== null) {
walk(descriptor.syntax, function(node) {
if (node.type !== 'Type' && node.type !== 'Property') {
return;
}
var map = node.type === 'Type' ? syntax.types : syntax.properties;
var brokenMap = node.type === 'Type' ? brokenTypes : brokenProperties;
if (!map.hasOwnProperty(node.name) || validate(syntax, node.name, brokenMap, map[node.name])) {
broken[name] = true;
}
}, this);
}
}
var brokenTypes = {};
var brokenProperties = {};
for (var key in this.types) {
validate(this, key, brokenTypes, this.types[key]);
}
for (var key in this.properties) {
validate(this, key, brokenProperties, this.properties[key]);
}
brokenTypes = Object.keys(brokenTypes).filter(function(name) {
return brokenTypes[name];
});
brokenProperties = Object.keys(brokenProperties).filter(function(name) {
return brokenProperties[name];
});
if (brokenTypes.length || brokenProperties.length) {
return {
types: brokenTypes,
properties: brokenProperties
};
}
return null;
},
dump: function(syntaxAsAst) {
return {
generic: this.generic,
types: dumpMapSyntax(this.types, syntaxAsAst),
properties: dumpMapSyntax(this.properties, syntaxAsAst)
};
},
toString: function() {
return JSON.stringify(this.dump());
}
};
module.exports = Lexer;
+82
View File
@@ -0,0 +1,82 @@
'use strict';
var createCustomError = require('../utils/createCustomError');
var generateGrammar = require('./grammar/generate');
function getLocation(node, point) {
var loc = node && node.loc && node.loc[point];
return loc
? { offset: loc.offset,
line: loc.line,
column: loc.column }
: null;
}
var SyntaxReferenceError = function(type, referenceName) {
var error = createCustomError(
'SyntaxReferenceError',
type + (referenceName ? ' `' + referenceName + '`' : '')
);
error.reference = referenceName;
return error;
};
var MatchError = function(message, lexer, syntax, value, badNode) {
var error = createCustomError('SyntaxMatchError', message);
var errorOffset = -1;
var start = getLocation(badNode, 'start');
var end = getLocation(badNode, 'end');
var css = lexer.syntax.generate(value, {
decorator: function(handlers) {
var bufferOffset = 0;
var handlersChunk = handlers.chunk;
handlers.chunk = function(chunk) {
bufferOffset += chunk.length;
handlersChunk(chunk);
};
var handlersNode = handlers.node;
handlers.node = function(node) {
if (node === badNode) {
errorOffset = bufferOffset;
}
handlersNode.call(this, node);
};
return handlers;
}
});
if (errorOffset === -1) {
errorOffset = css.length;
}
error.rawMessage = message;
error.syntax = syntax ? generateGrammar(syntax) : '<generic>';
error.css = css;
error.mismatchOffset = errorOffset;
error.loc = {
source: badNode && badNode.loc && badNode.loc.source || '<unknown>',
start: start,
end: end
};
error.line = start ? start.line : undefined;
error.column = start ? start.column : undefined;
error.offset = start ? start.offset : undefined;
error.message = message + '\n' +
' syntax: ' + error.syntax + '\n' +
' value: ' + (error.css || '<empty string>') + '\n' +
' --------' + new Array(error.mismatchOffset + 1).join('-') + '^';
return error;
};
module.exports = {
SyntaxReferenceError: SyntaxReferenceError,
MatchError: MatchError
};
+219
View File
@@ -0,0 +1,219 @@
'use strict';
var names = require('../utils/names.js');
// https://www.w3.org/TR/css-values-3/#lengths
var LENGTH = {
// absolute length units
'px': true,
'mm': true,
'cm': true,
'in': true,
'pt': true,
'pc': true,
'q': true,
// relative length units
'em': true,
'ex': true,
'ch': true,
'rem': true,
// viewport-percentage lengths
'vh': true,
'vw': true,
'vmin': true,
'vmax': true,
'vm': true
};
var ANGLE = {
'deg': true,
'grad': true,
'rad': true,
'turn': true
};
var TIME = {
's': true,
'ms': true
};
var FREQUENCY = {
'hz': true,
'khz': true
};
// https://www.w3.org/TR/css-values-3/#resolution (https://drafts.csswg.org/css-values/#resolution)
var RESOLUTION = {
'dpi': true,
'dpcm': true,
'dppx': true,
'x': true // https://github.com/w3c/csswg-drafts/issues/461
};
// https://drafts.csswg.org/css-grid/#fr-unit
var FLEX = {
'fr': true
};
// https://www.w3.org/TR/css3-speech/#mixing-props-voice-volume
var DECIBEL = {
'db': true
};
// https://www.w3.org/TR/css3-speech/#voice-props-voice-pitch
var SEMITONES = {
'st': true
};
// can be used wherever <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> values are allowed
// https://drafts.csswg.org/css-values/#calc-notation
function isCalc(node) {
if (node.data.type !== 'Function') {
return false;
}
var keyword = names.keyword(node.data.name);
// check the function name
return (
keyword.name === 'calc' ||
keyword.name === '-moz-calc' ||
keyword.name === '-webkit-calc'
);
}
function astNode(type) {
return function(node) {
return node.data.type === type;
};
}
function dimension(type) {
return function(node) {
return isCalc(node) ||
(node.data.type === 'Dimension' && type.hasOwnProperty(node.data.unit.toLowerCase()));
};
}
function zeroUnitlessDimension(type) {
return function(node) {
return isCalc(node) ||
(node.data.type === 'Dimension' && type.hasOwnProperty(node.data.unit.toLowerCase())) ||
(node.data.type === 'Number' && Number(node.data.value) === 0);
};
}
function attr(node) {
return node.data.type === 'Function' && node.data.name.toLowerCase() === 'attr';
}
function number(node) {
return isCalc(node) || node.data.type === 'Number';
}
function numberZeroOne(node) {
if (isCalc(node) || node.data.type === 'Number') {
var value = Number(node.data.value);
return value >= 0 && value <= 1;
}
return false;
}
function numberOneOrGreater(node) {
if (isCalc(node) || node.data.type === 'Number') {
return Number(node.data.value) >= 1;
}
return false;
}
// TODO: fail on 10e-2
function integer(node) {
return isCalc(node) ||
(node.data.type === 'Number' && node.data.value.indexOf('.') === -1);
}
// TODO: fail on 10e-2
function positiveInteger(node) {
return isCalc(node) ||
(node.data.type === 'Number' && node.data.value.indexOf('.') === -1 && node.data.value.charAt(0) !== '-');
}
function percentage(node) {
return isCalc(node) ||
node.data.type === 'Percentage';
}
function hexColor(node) {
if (node.data.type !== 'HexColor') {
return false;
}
var hex = node.data.value;
return /^[0-9a-fA-F]{3,8}$/.test(hex) &&
(hex.length === 3 || hex.length === 4 || hex.length === 6 || hex.length === 8);
}
function expression(node) {
return node.data.type === 'Function' && node.data.name.toLowerCase() === 'expression';
}
// https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident
// https://drafts.csswg.org/css-values-4/#identifier-value
function customIdent(node) {
if (node.data.type !== 'Identifier') {
return false;
}
var name = node.data.name.toLowerCase();
// § 3.2. Author-defined Identifiers: the <custom-ident> type
// The CSS-wide keywords are not valid <custom-ident>s
if (name === 'unset' || name === 'initial' || name === 'inherit') {
return false;
}
// The default keyword is reserved and is also not a valid <custom-ident>
if (name === 'default') {
return false;
}
// TODO: ignore property specific keywords (as described https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident)
return true;
}
module.exports = {
'angle': zeroUnitlessDimension(ANGLE),
'attr()': attr,
'custom-ident': customIdent,
'decibel': dimension(DECIBEL),
'dimension': astNode('Dimension'),
'frequency': dimension(FREQUENCY),
'flex': dimension(FLEX),
'hex-color': hexColor,
'id-selector': astNode('IdSelector'), // element( <id-selector> )
'ident': astNode('Identifier'),
'integer': integer,
'length': zeroUnitlessDimension(LENGTH),
'number': number,
'number-zero-one': numberZeroOne,
'number-one-or-greater': numberOneOrGreater,
'percentage': percentage,
'positive-integer': positiveInteger,
'resolution': dimension(RESOLUTION),
'semitones': dimension(SEMITONES),
'string': astNode('String'),
'time': dimension(TIME),
'unicode-range': astNode('UnicodeRange'),
'url': astNode('Url'),
// old IE stuff
'progid': astNode('Raw'),
'expression': expression
};
+20
View File
@@ -0,0 +1,20 @@
'use strict';
var createCustomError = require('../../utils/createCustomError');
var SyntaxParseError = function(message, syntaxStr, offset) {
var error = createCustomError('SyntaxParseError', message);
error.rawMessage = message;
error.syntax = syntaxStr;
error.offset = offset;
error.message = error.rawMessage + '\n' +
' ' + error.syntax + '\n' +
'--' + new Array((error.offset || error.syntax.length) + 1).join('-') + '^';
return error;
};
module.exports = {
SyntaxParseError: SyntaxParseError
};
+106
View File
@@ -0,0 +1,106 @@
'use strict';
function isNodeType(node, type) {
return node && node.type === type;
}
function serializeMultiplier(multiplier) {
if (multiplier.min === 0 && multiplier.max === 0) {
return '*';
}
if (multiplier.min === 0 && multiplier.max === 1) {
return '?';
}
if (multiplier.min === 1 && multiplier.max === 0) {
return multiplier.comma ? '#' : '+';
}
if (multiplier.min === 1 && multiplier.max === 1) {
return '';
}
return (
(multiplier.comma ? '#' : '') +
'{' + multiplier.min + (multiplier.min !== multiplier.max ? ',' + (multiplier.max !== 0 ? multiplier.max : '') : '') + '}'
);
}
function generateSequence(node, forceBraces, decorate) {
var result = '';
if (node.explicit || forceBraces) {
result += '[' + (!isNodeType(node.terms[0], 'Comma') ? ' ' : '');
}
result += node.terms.map(function(term) {
return generate(term, forceBraces, decorate);
}).join(node.combinator === ' ' ? ' ' : ' ' + node.combinator + ' ');
if (node.explicit || forceBraces) {
result += ' ]';
}
return result;
}
function generateParentheses(group, forceBraces, decorate) {
if (!group.terms.length) {
return '()';
}
return '( ' + generateSequence(group, forceBraces, decorate) + ' )';
}
function generate(node, forceBraces, decorate) {
var result;
switch (node.type) {
case 'Group':
result =
generateSequence(node, forceBraces, decorate) +
(node.disallowEmpty ? '!' : '') +
serializeMultiplier(node.multiplier);
break;
case 'Keyword':
result = node.name;
break;
case 'Function':
result = node.name + generateParentheses(node.children, forceBraces, decorate);
break;
case 'Parentheses': // replace for seq('(' seq(...node.children) ')')
result = generateParentheses(node.children, forceBraces, decorate);
break;
case 'Type':
result = '<' + node.name + '>';
break;
case 'Property':
result = '<\'' + node.name + '\'>';
break;
case 'Combinator': // remove?
case 'Slash': // replace for String? '/'
case 'Percent': // replace for String? '%'
case 'String':
case 'Comma':
result = node.value;
break;
default:
throw new Error('Unknown node type `' + node.type + '`');
}
if (typeof decorate === 'function') {
result = decorate(result, node);
}
return result;
}
module.exports = generate;
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
SyntaxParseError: require('./error').SyntaxParseError,
parse: require('./parse'),
generate: require('./generate'),
walk: require('./walk')
};
+503
View File
@@ -0,0 +1,503 @@
'use strict';
var SyntaxParseError = require('./error').SyntaxParseError;
var TAB = 9;
var N = 10;
var F = 12;
var R = 13;
var SPACE = 32;
var EXCLAMATIONMARK = 33; // !
var NUMBERSIGN = 35; // #
var PERCENTSIGN = 37; // %
var AMPERSAND = 38; // &
var APOSTROPHE = 39; // '
var LEFTPARENTHESIS = 40; // (
var RIGHTPARENTHESIS = 41; // )
var ASTERISK = 42; // *
var PLUSSIGN = 43; // +
var COMMA = 44; // ,
var SOLIDUS = 47; // /
var LESSTHANSIGN = 60; // <
var GREATERTHANSIGN = 62; // >
var QUESTIONMARK = 63; // ?
var LEFTSQUAREBRACKET = 91; // [
var RIGHTSQUAREBRACKET = 93; // ]
var LEFTCURLYBRACKET = 123; // {
var VERTICALLINE = 124; // |
var RIGHTCURLYBRACKET = 125; // }
var COMBINATOR_PRECEDENCE = {
' ': 1,
'&&': 2,
'||': 3,
'|': 4
};
var MULTIPLIER_DEFAULT = {
comma: false,
min: 1,
max: 1
};
var MULTIPLIER_ZERO_OR_MORE = {
comma: false,
min: 0,
max: 0
};
var MULTIPLIER_ONE_OR_MORE = {
comma: false,
min: 1,
max: 0
};
var MULTIPLIER_ONE_OR_MORE_COMMA_SEPARATED = {
comma: true,
min: 1,
max: 0
};
var MULTIPLIER_ZERO_OR_ONE = {
comma: false,
min: 0,
max: 1
};
var NAME_CHAR = (function() {
var array = typeof Uint32Array === 'function' ? new Uint32Array(128) : new Array(128);
for (var i = 0; i < 128; i++) {
array[i] = /[a-zA-Z0-9\-]/.test(String.fromCharCode(i)) ? 1 : 0;
}
return array;
})();
var Tokenizer = function(str) {
this.str = str;
this.pos = 0;
};
Tokenizer.prototype = {
charCode: function() {
return this.pos < this.str.length ? this.str.charCodeAt(this.pos) : 0;
},
nextCharCode: function() {
return this.pos + 1 < this.str.length ? this.str.charCodeAt(this.pos + 1) : 0;
},
substringToPos: function(end) {
return this.str.substring(this.pos, this.pos = end);
},
eat: function(code) {
if (this.charCode() !== code) {
error(this, this.pos, 'Expect `' + String.fromCharCode(code) + '`');
}
this.pos++;
}
};
function scanSpaces(tokenizer) {
var end = tokenizer.pos + 1;
for (; end < tokenizer.str.length; end++) {
var code = tokenizer.str.charCodeAt(end);
if (code !== R && code !== N && code !== F && code !== SPACE && code !== TAB) {
break;
}
}
return tokenizer.substringToPos(end);
}
function scanWord(tokenizer) {
var end = tokenizer.pos;
for (; end < tokenizer.str.length; end++) {
var code = tokenizer.str.charCodeAt(end);
if (code >= 128 || NAME_CHAR[code] === 0) {
break;
}
}
if (tokenizer.pos === end) {
error(tokenizer, tokenizer.pos, 'Expect a keyword');
}
return tokenizer.substringToPos(end);
}
function scanNumber(tokenizer) {
var end = tokenizer.pos;
for (; end < tokenizer.str.length; end++) {
var code = tokenizer.str.charCodeAt(end);
if (code < 48 || code > 57) {
break;
}
}
if (tokenizer.pos === end) {
error(tokenizer, tokenizer.pos, 'Expect a number');
}
return tokenizer.substringToPos(end);
}
function scanString(tokenizer) {
var end = tokenizer.str.indexOf('\'', tokenizer.pos + 1);
if (end === -1) {
error(tokenizer, tokenizer.str.length, 'Expect a quote');
}
return tokenizer.substringToPos(end + 1);
}
function readMultiplierRange(tokenizer, comma) {
var min = null;
var max = null;
tokenizer.eat(LEFTCURLYBRACKET);
min = scanNumber(tokenizer);
if (tokenizer.charCode() === COMMA) {
tokenizer.pos++;
if (tokenizer.charCode() !== RIGHTCURLYBRACKET) {
max = scanNumber(tokenizer);
}
} else {
max = min;
}
tokenizer.eat(RIGHTCURLYBRACKET);
return {
comma: comma,
min: Number(min),
max: max ? Number(max) : 0
};
}
function readMultiplier(tokenizer) {
switch (tokenizer.charCode()) {
case ASTERISK:
tokenizer.pos++;
return MULTIPLIER_ZERO_OR_MORE;
case PLUSSIGN:
tokenizer.pos++;
return MULTIPLIER_ONE_OR_MORE;
case QUESTIONMARK:
tokenizer.pos++;
return MULTIPLIER_ZERO_OR_ONE;
case NUMBERSIGN:
tokenizer.pos++;
if (tokenizer.charCode() !== LEFTCURLYBRACKET) {
return MULTIPLIER_ONE_OR_MORE_COMMA_SEPARATED;
}
return readMultiplierRange(tokenizer, true);
case LEFTCURLYBRACKET:
return readMultiplierRange(tokenizer, false);
}
return MULTIPLIER_DEFAULT;
}
function maybeMultiplied(tokenizer, node) {
var multiplier = readMultiplier(tokenizer);
if (multiplier !== MULTIPLIER_DEFAULT) {
return {
type: 'Group',
terms: [node],
combinator: '|', // `|` combinator is simplest in implementation (and therefore faster)
disallowEmpty: false,
multiplier: multiplier,
explicit: false
};
}
return node;
}
function readProperty(tokenizer) {
var name;
tokenizer.eat(LESSTHANSIGN);
tokenizer.eat(APOSTROPHE);
name = scanWord(tokenizer);
tokenizer.eat(APOSTROPHE);
tokenizer.eat(GREATERTHANSIGN);
return maybeMultiplied(tokenizer, {
type: 'Property',
name: name
});
}
function readType(tokenizer) {
var name;
tokenizer.eat(LESSTHANSIGN);
name = scanWord(tokenizer);
if (tokenizer.charCode() === LEFTPARENTHESIS &&
tokenizer.nextCharCode() === RIGHTPARENTHESIS) {
tokenizer.pos += 2;
name += '()';
}
tokenizer.eat(GREATERTHANSIGN);
return maybeMultiplied(tokenizer, {
type: 'Type',
name: name
});
}
function readKeywordOrFunction(tokenizer) {
var children = null;
var name;
name = scanWord(tokenizer);
if (tokenizer.charCode() === LEFTPARENTHESIS) {
tokenizer.pos++;
children = readImplicitGroup(tokenizer);
tokenizer.eat(RIGHTPARENTHESIS);
return maybeMultiplied(tokenizer, {
type: 'Function',
name: name,
children: children
});
}
return maybeMultiplied(tokenizer, {
type: 'Keyword',
name: name
});
}
function regroupTerms(terms, combinators) {
function createGroup(terms, combinator) {
return {
type: 'Group',
terms: terms,
combinator: combinator,
disallowEmpty: false,
multiplier: MULTIPLIER_DEFAULT,
explicit: false
};
}
combinators = Object.keys(combinators).sort(function(a, b) {
return COMBINATOR_PRECEDENCE[a] - COMBINATOR_PRECEDENCE[b];
});
while (combinators.length > 0) {
var combinator = combinators.shift();
for (var i = 0, subgroupStart = 0; i < terms.length; i++) {
var term = terms[i];
if (term.type === 'Combinator') {
if (term.value === combinator) {
if (subgroupStart === -1) {
subgroupStart = i - 1;
}
terms.splice(i, 1);
i--;
} else {
if (subgroupStart !== -1 && i - subgroupStart > 1) {
terms.splice(
subgroupStart,
i - subgroupStart,
createGroup(terms.slice(subgroupStart, i), combinator)
);
i = subgroupStart + 1;
}
subgroupStart = -1;
}
}
}
if (subgroupStart !== -1 && combinators.length) {
terms.splice(
subgroupStart,
i - subgroupStart,
createGroup(terms.slice(subgroupStart, i), combinator)
);
}
}
return combinator;
}
function readImplicitGroup(tokenizer) {
var terms = [];
var combinators = {};
var token;
var prevToken = null;
var prevTokenPos = tokenizer.pos;
while (token = peek(tokenizer)) {
if (token.type !== 'Spaces') {
if (token.type === 'Combinator') {
// check for combinator in group beginning and double combinator sequence
if (prevToken === null || prevToken.type === 'Combinator') {
error(tokenizer, prevTokenPos, 'Unexpected combinator');
}
combinators[token.value] = true;
} else if (prevToken !== null && prevToken.type !== 'Combinator') {
combinators[' '] = true; // a b
terms.push({
type: 'Combinator',
value: ' '
});
}
terms.push(token);
prevToken = token;
prevTokenPos = tokenizer.pos;
}
}
// check for combinator in group ending
if (prevToken !== null && prevToken.type === 'Combinator') {
error(tokenizer, tokenizer.pos - prevTokenPos, 'Unexpected combinator');
}
return {
type: 'Group',
terms: terms,
combinator: regroupTerms(terms, combinators) || ' ',
disallowEmpty: false,
multiplier: MULTIPLIER_DEFAULT,
explicit: false
};
}
function readGroup(tokenizer) {
var result;
tokenizer.eat(LEFTSQUAREBRACKET);
result = readImplicitGroup(tokenizer);
tokenizer.eat(RIGHTSQUAREBRACKET);
result.explicit = true;
result.multiplier = readMultiplier(tokenizer);
if (tokenizer.charCode() === EXCLAMATIONMARK) {
tokenizer.pos++;
result.disallowEmpty = true;
}
return result;
}
function peek(tokenizer) {
var code = tokenizer.charCode();
if (code < 128 && NAME_CHAR[code] === 1) {
return readKeywordOrFunction(tokenizer);
}
switch (code) {
case LEFTSQUAREBRACKET:
return readGroup(tokenizer);
case LESSTHANSIGN:
if (tokenizer.nextCharCode() === APOSTROPHE) {
return readProperty(tokenizer);
} else {
return readType(tokenizer);
}
case VERTICALLINE:
return {
type: 'Combinator',
value: tokenizer.substringToPos(tokenizer.nextCharCode() === VERTICALLINE ? tokenizer.pos + 2 : tokenizer.pos + 1)
};
case AMPERSAND:
tokenizer.pos++;
tokenizer.eat(AMPERSAND);
return {
type: 'Combinator',
value: '&&'
};
case COMMA:
tokenizer.pos++;
return {
type: 'Comma',
value: ','
};
case SOLIDUS:
tokenizer.pos++;
return {
type: 'Slash',
value: '/'
};
case PERCENTSIGN: // looks like exception, needs for attr()'s <type-or-unit>
tokenizer.pos++;
return {
type: 'Percent',
value: '%'
};
case LEFTPARENTHESIS:
tokenizer.pos++;
var children = readImplicitGroup(tokenizer);
tokenizer.eat(RIGHTPARENTHESIS);
return {
type: 'Parentheses',
children: children
};
case APOSTROPHE:
return {
type: 'String',
value: scanString(tokenizer)
};
case SPACE:
case TAB:
case N:
case R:
case F:
return {
type: 'Spaces',
value: scanSpaces(tokenizer)
};
}
}
function error(tokenizer, pos, msg) {
throw new SyntaxParseError(msg || 'Unexpected input', tokenizer.str, pos);
}
function parse(str) {
var tokenizer = new Tokenizer(str);
var result = readImplicitGroup(tokenizer);
if (tokenizer.pos !== str.length) {
error(tokenizer, tokenizer.pos);
}
// reduce redundant groups with single group term
if (result.terms.length === 1 && result.terms[0].type === 'Group') {
result = result.terms[0];
}
return result;
}
// warm up parse to elimitate code branches that never execute
// fix soft deoptimizations (insufficient type feedback)
parse('[a&&<b>#|<\'c\'>*||e(){2,} f{2} /,(% g#{1,2})]!');
module.exports = parse;
+55
View File
@@ -0,0 +1,55 @@
'use strict';
var noop = function() {};
function ensureFunction(value) {
return typeof value === 'function' ? value : noop;
}
module.exports = function(node, fn, context) {
function walk(node) {
enter.call(context, node);
switch (node.type) {
case 'Group':
node.terms.forEach(walk);
break;
case 'Function':
case 'Parentheses':
walk(node.children);
break;
case 'Keyword':
case 'Type':
case 'Property':
case 'Combinator':
case 'Comma':
case 'Slash':
case 'String':
case 'Percent':
break;
default:
throw new Error('Unknown type: ' + node.type);
}
leave.call(context, node);
}
var enter = noop;
var leave = noop;
if (typeof fn === 'function') {
enter = fn;
} else if (fn) {
enter = ensureFunction(fn.enter);
leave = ensureFunction(fn.leave);
}
if (enter === noop && leave === noop) {
throw new Error('Neither `enter` nor `leave` walker handler is set or both aren\'t a function');
}
walk(node, context);
};
+6
View File
@@ -0,0 +1,6 @@
'use strict';
module.exports = {
Lexer: require('./Lexer'),
grammar: require('./grammar')
};
+515
View File
@@ -0,0 +1,515 @@
'use strict';
var names = require('../utils/names');
var MULTIPLIER_DEFAULT = {
comma: false,
min: 1,
max: 1
};
function skipSpaces(node) {
while (node !== null && (node.data.type === 'WhiteSpace' || node.data.type === 'Comment')) {
node = node.next;
}
return node;
}
function putResult(buffer, match) {
var type = match.type || match.syntax.type;
// ignore groups
if (type === 'Group') {
buffer.push.apply(buffer, match.match);
} else {
buffer.push(match);
}
}
function matchToJSON() {
return {
type: this.syntax.type,
name: this.syntax.name,
match: this.match,
node: this.node
};
}
function buildMatchNode(badNode, lastNode, next, match) {
if (badNode) {
return {
badNode: badNode,
lastNode: null,
next: null,
match: null
};
}
return {
badNode: null,
lastNode: lastNode,
next: next,
match: match
};
}
function matchGroup(lexer, syntaxNode, node) {
var result = [];
var buffer;
var multiplier = syntaxNode.multiplier || MULTIPLIER_DEFAULT;
var min = multiplier.min;
var max = multiplier.max === 0 ? Infinity : multiplier.max;
var lastCommaTermCount;
var lastComma;
var matchCount = 0;
var lastNode = null;
var badNode = null;
mismatch:
while (matchCount < max) {
node = skipSpaces(node);
buffer = [];
switch (syntaxNode.combinator) {
case '|':
for (var i = 0; i < syntaxNode.terms.length; i++) {
var term = syntaxNode.terms[i];
var res = matchSyntax(lexer, term, node);
if (res.match) {
putResult(buffer, res.match);
node = res.next;
break; // continue matching
} else if (res.badNode) {
badNode = res.badNode;
break mismatch;
} else if (res.lastNode) {
lastNode = res.lastNode;
}
}
if (buffer.length === 0) {
break mismatch; // nothing found -> stop matching
}
break;
case ' ':
var beforeMatchNode = node;
var lastMatchedTerm = null;
var hasTailMatch = false;
var commaMissed = false;
for (var i = 0; i < syntaxNode.terms.length; i++) {
var term = syntaxNode.terms[i];
var res = matchSyntax(lexer, term, node);
if (res.match) {
if (term.type === 'Comma' && i !== 0 && !hasTailMatch) {
// recover cursor to state before last match and stop matching
lastNode = node && node.data;
node = beforeMatchNode;
break mismatch;
}
// non-empty match (res.next will refer to another node)
if (res.next !== node) {
// match should be preceded by a comma
if (commaMissed) {
lastNode = node && node.data;
node = beforeMatchNode;
break mismatch;
}
hasTailMatch = term.type !== 'Comma';
lastMatchedTerm = term;
}
putResult(buffer, res.match);
node = skipSpaces(res.next);
} else if (res.badNode) {
badNode = res.badNode;
break mismatch;
} else {
if (res.lastNode) {
lastNode = res.lastNode;
}
// it's ok when comma doesn't match when no matches yet
// but only if comma is not first or last term
if (term.type === 'Comma' && i !== 0 && i !== syntaxNode.terms.length - 1) {
if (hasTailMatch) {
commaMissed = true;
}
continue;
}
// recover cursor to state before last match and stop matching
lastNode = res.lastNode || (node && node.data);
node = beforeMatchNode;
break mismatch;
}
}
// don't allow empty match when [ ]!
if (!lastMatchedTerm && syntaxNode.disallowEmpty) {
// empty match but shouldn't
// recover cursor to state before last match and stop matching
lastNode = node && node.data;
node = beforeMatchNode;
break mismatch;
}
// don't allow comma at the end but only if last term isn't a comma
if (lastMatchedTerm && lastMatchedTerm.type === 'Comma' && term.type !== 'Comma') {
lastNode = node && node.data;
node = beforeMatchNode;
break mismatch;
}
break;
case '&&':
var beforeMatchNode = node;
var lastMatchedTerm = null;
var terms = syntaxNode.terms.slice();
while (terms.length) {
var wasMatch = false;
var emptyMatched = 0;
for (var i = 0; i < terms.length; i++) {
var term = terms[i];
var res = matchSyntax(lexer, term, node);
if (res.match) {
// non-empty match (res.next will refer to another node)
if (res.next !== node) {
lastMatchedTerm = term;
} else {
emptyMatched++;
continue;
}
wasMatch = true;
terms.splice(i--, 1);
putResult(buffer, res.match);
node = skipSpaces(res.next);
break;
} else if (res.badNode) {
badNode = res.badNode;
break mismatch;
} else if (res.lastNode) {
lastNode = res.lastNode;
}
}
if (!wasMatch) {
// terms left, but they all are optional
if (emptyMatched === terms.length) {
break;
}
// not ok
lastNode = node && node.data;
node = beforeMatchNode;
break mismatch;
}
}
if (!lastMatchedTerm && syntaxNode.disallowEmpty) { // don't allow empty match when [ ]!
// empty match but shouldn't
// recover cursor to state before last match and stop matching
lastNode = node && node.data;
node = beforeMatchNode;
break mismatch;
}
break;
case '||':
var beforeMatchNode = node;
var lastMatchedTerm = null;
var terms = syntaxNode.terms.slice();
while (terms.length) {
var wasMatch = false;
var emptyMatched = 0;
for (var i = 0; i < terms.length; i++) {
var term = terms[i];
var res = matchSyntax(lexer, term, node);
if (res.match) {
// non-empty match (res.next will refer to another node)
if (res.next !== node) {
lastMatchedTerm = term;
} else {
emptyMatched++;
continue;
}
wasMatch = true;
terms.splice(i--, 1);
putResult(buffer, res.match);
node = skipSpaces(res.next);
break;
} else if (res.badNode) {
badNode = res.badNode;
break mismatch;
} else if (res.lastNode) {
lastNode = res.lastNode;
}
}
if (!wasMatch) {
break;
}
}
// don't allow empty match
if (!lastMatchedTerm && (emptyMatched !== terms.length || syntaxNode.disallowEmpty)) {
// empty match but shouldn't
// recover cursor to state before last match and stop matching
lastNode = node && node.data;
node = beforeMatchNode;
break mismatch;
}
break;
}
// flush buffer
result.push.apply(result, buffer);
matchCount++;
if (!node) {
break;
}
if (multiplier.comma) {
if (lastComma && lastCommaTermCount === result.length) {
// nothing match after comma
break mismatch;
}
node = skipSpaces(node);
if (node !== null && node.data.type === 'Operator' && node.data.value === ',') {
result.push({
syntax: syntaxNode,
match: [{
type: 'ASTNode',
node: node.data,
childrenMatch: null
}]
});
lastCommaTermCount = result.length;
lastComma = node;
node = node.next;
} else {
lastNode = node !== null ? node.data : null;
break mismatch;
}
}
}
// console.log(syntaxNode.type, badNode, lastNode);
if (lastComma && lastCommaTermCount === result.length) {
// nothing match after comma
node = lastComma;
result.pop();
}
return buildMatchNode(badNode, lastNode, node, matchCount < min ? null : {
syntax: syntaxNode,
match: result,
toJSON: matchToJSON
});
}
function matchSyntax(lexer, syntaxNode, node) {
var badNode = null;
var lastNode = null;
var match = null;
switch (syntaxNode.type) {
case 'Group':
return matchGroup(lexer, syntaxNode, node);
case 'Function':
// expect a function node
if (!node || node.data.type !== 'Function') {
break;
}
var keyword = names.keyword(node.data.name);
var name = syntaxNode.name.toLowerCase();
// check function name with vendor consideration
if (name !== keyword.name) {
break;
}
var res = matchSyntax(lexer, syntaxNode.children, node.data.children.head);
if (!res.match || res.next) {
badNode = res.badNode || res.lastNode || (res.next ? res.next.data : null) || node.data;
break;
}
match = [{
type: 'ASTNode',
node: node.data,
childrenMatch: res.match.match
}];
// Use node.next instead of res.next here since syntax is matching
// for internal list and it should be completelly matched (res.next is null at this point).
// Therefore function is matched and we are going to next node
node = node.next;
break;
case 'Parentheses':
if (!node || node.data.type !== 'Parentheses') {
break;
}
var res = matchSyntax(lexer, syntaxNode.children, node.data.children.head);
if (!res.match || res.next) {
badNode = res.badNode || res.lastNode || (res.next ? res.next.data : null) || node.data; // TODO: case when res.next === null
break;
}
match = [{
type: 'ASTNode',
node: node.data,
childrenMatch: res.match.match
}];
node = res.next;
break;
case 'Type':
var typeSyntax = lexer.getType(syntaxNode.name);
if (!typeSyntax) {
throw new Error('Unknown syntax type `' + syntaxNode.name + '`');
}
var res = typeSyntax.match(node);
if (!res.match) {
badNode = res && res.badNode; // TODO: case when res.next === null
lastNode = (res && res.lastNode) || (node && node.data);
break;
}
node = res.next;
putResult(match = [], res.match);
if (match.length === 0) {
match = null;
}
break;
case 'Property':
var propertySyntax = lexer.getProperty(syntaxNode.name);
if (!propertySyntax) {
throw new Error('Unknown property `' + syntaxNode.name + '`');
}
var res = propertySyntax.match(node);
if (!res.match) {
badNode = res && res.badNode; // TODO: case when res.next === null
lastNode = (res && res.lastNode) || (node && node.data);
break;
}
node = res.next;
putResult(match = [], res.match);
if (match.length === 0) {
match = null;
}
break;
case 'Keyword':
if (!node) {
break;
}
if (node.data.type === 'Identifier') {
var keyword = names.keyword(node.data.name);
var keywordName = keyword.name;
var name = syntaxNode.name.toLowerCase();
// drop \0 and \9 hack from keyword name
if (keywordName.indexOf('\\') !== -1) {
keywordName = keywordName.replace(/\\[09].*$/, '');
}
if (name !== keywordName) {
break;
}
} else {
// keyword may to be a number (e.g. font-weight: 400 )
if (node.data.type !== 'Number' || node.data.value !== syntaxNode.name) {
break;
}
}
match = [{
type: 'ASTNode',
node: node.data,
childrenMatch: null
}];
node = node.next;
break;
case 'Slash':
case 'Comma':
if (!node || node.data.type !== 'Operator' || node.data.value !== syntaxNode.value) {
break;
}
match = [{
type: 'ASTNode',
node: node.data,
childrenMatch: null
}];
node = node.next;
break;
case 'String':
if (!node || node.data.type !== 'String') {
break;
}
match = [{
type: 'ASTNode',
node: node.data,
childrenMatch: null
}];
node = node.next;
break;
case 'ASTNode':
if (node && syntaxNode.match(node)) {
match = {
type: 'ASTNode',
node: node.data,
childrenMatch: null
};
node = node.next;
}
return buildMatchNode(badNode, lastNode, node, match);
default:
throw new Error('Not implemented yet node type: ' + syntaxNode.type);
}
return buildMatchNode(badNode, lastNode, node, match === null ? null : {
syntax: syntaxNode,
match: match,
toJSON: matchToJSON
});
};
module.exports = matchSyntax;
+66
View File
@@ -0,0 +1,66 @@
var List = require('../utils/list');
function getFirstMatchNode(matchNode) {
if (matchNode.type === 'ASTNode') {
return matchNode.node;
}
return getFirstMatchNode(matchNode.match[0]);
}
function getLastMatchNode(matchNode) {
if (matchNode.type === 'ASTNode') {
return matchNode.node;
}
return getLastMatchNode(matchNode.match[matchNode.match.length - 1]);
}
function matchFragments(lexer, ast, match, type, name) {
function findFragments(matchNode) {
if (matchNode.type === 'ASTNode') {
return;
}
if (matchNode.syntax.type === type &&
matchNode.syntax.name === name) {
var start = getFirstMatchNode(matchNode);
var end = getLastMatchNode(matchNode);
lexer.syntax.walk(ast, function(node, item, list) {
if (node === start) {
var nodes = new List();
do {
nodes.appendData(item.data);
if (item.data === end) {
break;
}
item = item.next;
} while (item !== null);
fragments.push({
parent: list,
nodes: nodes
});
}
});
}
matchNode.match.forEach(findFragments);
}
var fragments = [];
if (match.matched !== null) {
findFragments(match.matched);
}
return fragments;
}
module.exports = {
matchFragments: matchFragments
};
+163
View File
@@ -0,0 +1,163 @@
var List = require('../utils/list');
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isValidNumber(value) {
// Number.isInteger(value) && value >= 0
return (
typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value &&
value >= 0
);
}
function isValidLocation(loc) {
return (
Boolean(loc) &&
isValidNumber(loc.offset) &&
isValidNumber(loc.line) &&
isValidNumber(loc.column)
);
}
function createNodeStructureChecker(type, fields) {
return function checkNode(node, warn) {
if (!node || node.constructor !== Object) {
return warn(node, 'Type of node should be an Object');
}
for (var key in node) {
var valid = true;
if (hasOwnProperty.call(node, key) === false) {
continue;
}
if (key === 'type') {
if (node.type !== type) {
warn(node, 'Wrong node type `' + node.type + '`, expected `' + type + '`');
}
} else if (key === 'loc') {
if (node.loc === null) {
continue;
} else if (node.loc && node.loc.constructor === Object) {
if (typeof node.loc.source !== 'string') {
key += '.source';
} else if (!isValidLocation(node.loc.start)) {
key += '.start';
} else if (!isValidLocation(node.loc.end)) {
key += '.end';
} else {
continue;
}
}
valid = false;
} else if (fields.hasOwnProperty(key)) {
for (var i = 0, valid = false; !valid && i < fields[key].length; i++) {
var fieldType = fields[key][i];
switch (fieldType) {
case String:
valid = typeof node[key] === 'string';
break;
case Boolean:
valid = typeof node[key] === 'boolean';
break;
case null:
valid = node[key] === null;
break;
default:
if (typeof fieldType === 'string') {
valid = node[key] && node[key].type === fieldType;
} else if (Array.isArray(fieldType)) {
valid = node[key] instanceof List;
}
}
}
} else {
warn(node, 'Unknown field `' + key + '` for ' + type + ' node type');
}
if (!valid) {
warn(node, 'Bad value for `' + type + '.' + key + '`');
}
}
for (var key in fields) {
if (hasOwnProperty.call(fields, key) &&
hasOwnProperty.call(node, key) === false) {
warn(node, 'Field `' + type + '.' + key + '` is missed');
}
}
};
}
function processStructure(name, nodeType) {
var structure = nodeType.structure;
var fields = {
type: String,
loc: true
};
var docs = {
type: '"' + name + '"'
};
for (var key in structure) {
if (hasOwnProperty.call(structure, key) === false) {
continue;
}
var docsTypes = [];
var fieldTypes = fields[key] = Array.isArray(structure[key])
? structure[key].slice()
: [structure[key]];
for (var i = 0; i < fieldTypes.length; i++) {
var fieldType = fieldTypes[i];
if (fieldType === String || fieldType === Boolean) {
docsTypes.push(fieldType.name);
} else if (fieldType === null) {
docsTypes.push('null');
} else if (typeof fieldType === 'string') {
docsTypes.push('<' + fieldType + '>');
} else if (Array.isArray(fieldType)) {
docsTypes.push('List'); // TODO: use type enum
} else {
throw new Error('Wrong value `' + fieldType + '` in `' + name + '.' + key + '` structure definition');
}
}
docs[key] = docsTypes.join(' | ');
}
return {
docs: docs,
check: createNodeStructureChecker(name, fields)
};
}
module.exports = {
getStructureFromConfig: function(config) {
var structure = {};
if (config.node) {
for (var name in config.node) {
if (hasOwnProperty.call(config.node, name)) {
var nodeType = config.node[name];
if (nodeType.structure) {
structure[name] = processStructure(name, nodeType);
} else {
throw new Error('Missed `structure` field in `' + name + '` node type definition');
}
}
}
}
return structure;
}
};
+76
View File
@@ -0,0 +1,76 @@
function getTrace(node) {
function hasMatch(matchNode) {
if (matchNode.type === 'ASTNode') {
if (matchNode.node === node) {
result = [];
return true;
}
if (matchNode.childrenMatch) {
// use for-loop for better perfomance
for (var i = 0; i < matchNode.childrenMatch.length; i++) {
if (hasMatch(matchNode.childrenMatch[i])) {
return true;
}
}
}
} else {
// use for-loop for better perfomance
for (var i = 0; i < matchNode.match.length; i++) {
if (hasMatch(matchNode.match[i])) {
if (matchNode.syntax.type === 'Type' ||
matchNode.syntax.type === 'Property' ||
matchNode.syntax.type === 'Keyword') {
result.unshift(matchNode.syntax);
}
return true;
}
}
}
return false;
}
var result = null;
if (this.matched !== null) {
hasMatch(this.matched);
}
return result;
}
function testNode(match, node, fn) {
var trace = getTrace.call(match, node);
if (trace === null) {
return false;
}
return trace.some(fn);
}
function isType(node, type) {
return testNode(this, node, function(matchNode) {
return matchNode.type === 'Type' && matchNode.name === type;
});
}
function isProperty(node, property) {
return testNode(this, node, function(matchNode) {
return matchNode.type === 'Property' && matchNode.name === property;
});
}
function isKeyword(node) {
return testNode(this, node, function(matchNode) {
return matchNode.type === 'Keyword';
});
}
module.exports = {
getTrace: getTrace,
isType: isType,
isProperty: isProperty,
isKeyword: isKeyword
};
+177
View File
@@ -0,0 +1,177 @@
'use strict';
var Tokenizer = require('../tokenizer');
var List = require('../utils/list');
var sequence = require('./sequence');
var noop = function() {};
function createParseContext(name) {
return function() {
return this[name]();
};
}
function processConfig(config) {
var parserConfig = {
context: {},
scope: {},
atrule: {},
pseudo: {}
};
if (config.parseContext) {
for (var name in config.parseContext) {
switch (typeof config.parseContext[name]) {
case 'function':
parserConfig.context[name] = config.parseContext[name];
break;
case 'string':
parserConfig.context[name] = createParseContext(config.parseContext[name]);
break;
}
}
}
if (config.scope) {
for (var name in config.scope) {
parserConfig.scope[name] = config.scope[name];
}
}
if (config.atrule) {
for (var name in config.atrule) {
var atrule = config.atrule[name];
if (atrule.parse) {
parserConfig.atrule[name] = atrule.parse;
}
}
}
if (config.pseudo) {
for (var name in config.pseudo) {
var pseudo = config.pseudo[name];
if (pseudo.parse) {
parserConfig.pseudo[name] = pseudo.parse;
}
}
}
if (config.node) {
for (var name in config.node) {
parserConfig[name] = config.node[name].parse;
}
}
return parserConfig;
}
module.exports = function createParser(config) {
var parser = {
scanner: new Tokenizer(),
filename: '<unknown>',
needPositions: false,
onParseError: noop,
onParseErrorThrow: false,
parseAtrulePrelude: true,
parseRulePrelude: true,
parseValue: true,
parseCustomProperty: false,
readSequence: sequence,
createList: function() {
return new List();
},
createSingleNodeList: function(node) {
return new List().appendData(node);
},
getFirstListNode: function(list) {
return list && list.first();
},
getLastListNode: function(list) {
return list.last();
},
parseWithFallback: function(consumer, fallback) {
var startToken = this.scanner.currentToken;
try {
return consumer.call(this);
} catch (e) {
if (this.onParseErrorThrow) {
throw e;
}
var fallbackNode = fallback.call(this, startToken);
this.onParseErrorThrow = true;
this.onParseError(e, fallbackNode);
this.onParseErrorThrow = false;
return fallbackNode;
}
},
getLocation: function(start, end) {
if (this.needPositions) {
return this.scanner.getLocationRange(
start,
end,
this.filename
);
}
return null;
},
getLocationFromList: function(list) {
if (this.needPositions) {
var head = this.getFirstListNode(list);
var tail = this.getLastListNode(list);
return this.scanner.getLocationRange(
head !== null ? head.loc.start.offset - this.scanner.startOffset : this.scanner.tokenStart,
tail !== null ? tail.loc.end.offset - this.scanner.startOffset : this.scanner.tokenStart,
this.filename
);
}
return null;
}
};
config = processConfig(config || {});
for (var key in config) {
parser[key] = config[key];
}
return function(source, options) {
options = options || {};
var context = options.context || 'default';
var ast;
parser.scanner.setSource(source, options.offset, options.line, options.column);
parser.filename = options.filename || '<unknown>';
parser.needPositions = Boolean(options.positions);
parser.onParseError = typeof options.onParseError === 'function' ? options.onParseError : noop;
parser.onParseErrorThrow = false;
parser.parseAtrulePrelude = 'parseAtrulePrelude' in options ? Boolean(options.parseAtrulePrelude) : true;
parser.parseRulePrelude = 'parseRulePrelude' in options ? Boolean(options.parseRulePrelude) : true;
parser.parseValue = 'parseValue' in options ? Boolean(options.parseValue) : true;
parser.parseCustomProperty = 'parseCustomProperty' in options ? Boolean(options.parseCustomProperty) : false;
if (!parser.context.hasOwnProperty(context)) {
throw new Error('Unknown context `' + context + '`');
}
ast = parser.context[context].call(parser, options);
if (!parser.scanner.eof) {
parser.scanner.error();
}
return ast;
};
};
+4
View File
@@ -0,0 +1,4 @@
var createParser = require('./create');
var config = require('../syntax/config/parser');
module.exports = createParser(config);
+54
View File
@@ -0,0 +1,54 @@
var TYPE = require('../tokenizer').TYPE;
var WHITESPACE = TYPE.WhiteSpace;
var COMMENT = TYPE.Comment;
module.exports = function readSequence(recognizer) {
var children = this.createList();
var child = null;
var context = {
recognizer: recognizer,
space: null,
ignoreWS: false,
ignoreWSAfter: false
};
this.scanner.skipSC();
while (!this.scanner.eof) {
switch (this.scanner.tokenType) {
case COMMENT:
this.scanner.next();
continue;
case WHITESPACE:
if (context.ignoreWS) {
this.scanner.next();
} else {
context.space = this.WhiteSpace();
}
continue;
}
child = recognizer.getNode.call(this, context);
if (child === undefined) {
break;
}
if (context.space !== null) {
children.push(context.space);
context.space = null;
}
children.push(child);
if (context.ignoreWSAfter) {
context.ignoreWSAfter = false;
context.ignoreWS = true;
} else {
context.ignoreWS = false;
}
}
return children;
};
+8
View File
@@ -0,0 +1,8 @@
module.exports = {
parse: {
prelude: null,
block: function() {
return this.Block(true);
}
}
};
+38
View File
@@ -0,0 +1,38 @@
var TYPE = require('../../tokenizer').TYPE;
var STRING = TYPE.String;
var IDENTIFIER = TYPE.Identifier;
var URL = TYPE.Url;
var LEFTPARENTHESIS = TYPE.LeftParenthesis;
module.exports = {
parse: {
prelude: function() {
var children = this.createList();
this.scanner.skipSC();
switch (this.scanner.tokenType) {
case STRING:
children.push(this.String());
break;
case URL:
children.push(this.Url());
break;
default:
this.scanner.error('String or url() is expected');
}
if (this.scanner.lookupNonWSType(0) === IDENTIFIER ||
this.scanner.lookupNonWSType(0) === LEFTPARENTHESIS) {
children.push(this.WhiteSpace());
children.push(this.MediaQueryList());
}
return children;
},
block: null
}
};
+7
View File
@@ -0,0 +1,7 @@
module.exports = {
'font-face': require('./font-face'),
'import': require('./import'),
'media': require('./media'),
'page': require('./page'),
'supports': require('./supports')
};
+12
View File
@@ -0,0 +1,12 @@
module.exports = {
parse: {
prelude: function() {
return this.createSingleNodeList(
this.MediaQueryList()
);
},
block: function() {
return this.Block(false);
}
}
};
+12
View File
@@ -0,0 +1,12 @@
module.exports = {
parse: {
prelude: function() {
return this.createSingleNodeList(
this.SelectorList()
);
},
block: function() {
return this.Block(true);
}
}
};
+99
View File
@@ -0,0 +1,99 @@
var TYPE = require('../../tokenizer').TYPE;
var WHITESPACE = TYPE.WhiteSpace;
var COMMENT = TYPE.Comment;
var IDENTIFIER = TYPE.Identifier;
var FUNCTION = TYPE.Function;
var LEFTPARENTHESIS = TYPE.LeftParenthesis;
var HYPHENMINUS = TYPE.HyphenMinus;
var COLON = TYPE.Colon;
function consumeRaw() {
return this.createSingleNodeList(
this.Raw(this.scanner.currentToken, 0, 0, false, false)
);
}
function parentheses() {
var index = 0;
this.scanner.skipSC();
// TODO: make it simplier
if (this.scanner.tokenType === IDENTIFIER) {
index = 1;
} else if (this.scanner.tokenType === HYPHENMINUS &&
this.scanner.lookupType(1) === IDENTIFIER) {
index = 2;
}
if (index !== 0 && this.scanner.lookupNonWSType(index) === COLON) {
return this.createSingleNodeList(
this.Declaration()
);
}
return readSequence.call(this);
}
function readSequence() {
var children = this.createList();
var space = null;
var child;
this.scanner.skipSC();
scan:
while (!this.scanner.eof) {
switch (this.scanner.tokenType) {
case WHITESPACE:
space = this.WhiteSpace();
continue;
case COMMENT:
this.scanner.next();
continue;
case FUNCTION:
child = this.Function(consumeRaw, this.scope.AtrulePrelude);
break;
case IDENTIFIER:
child = this.Identifier();
break;
case LEFTPARENTHESIS:
child = this.Parentheses(parentheses, this.scope.AtrulePrelude);
break;
default:
break scan;
}
if (space !== null) {
children.push(space);
space = null;
}
children.push(child);
}
return children;
}
module.exports = {
parse: {
prelude: function() {
var children = readSequence.call(this);
if (this.getFirstListNode(children) === null) {
this.scanner.error('Condition is expected');
}
return children;
},
block: function() {
return this.Block(false);
}
}
};
+8
View File
@@ -0,0 +1,8 @@
var data = require('../../../data');
module.exports = {
generic: true,
types: data.types,
properties: data.properties,
node: require('../node')
};
+94
View File
@@ -0,0 +1,94 @@
var hasOwnProperty = Object.prototype.hasOwnProperty;
var shape = {
generic: true,
types: {},
properties: {},
parseContext: {},
scope: {},
atrule: ['parse'],
pseudo: ['parse'],
node: ['name', 'structure', 'parse', 'generate', 'walkContext']
};
function isObject(value) {
return value && value.constructor === Object;
}
function copy(value) {
if (isObject(value)) {
var res = {};
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
res[key] = value[key];
}
}
return res;
} else {
return value;
}
}
function extend(dest, src) {
for (var key in src) {
if (hasOwnProperty.call(src, key)) {
if (isObject(dest[key])) {
extend(dest[key], copy(src[key]));
} else {
dest[key] = copy(src[key]);
}
}
}
}
function mix(dest, src, shape) {
for (var key in shape) {
if (hasOwnProperty.call(shape, key) === false) {
continue;
}
if (shape[key] === true) {
if (key in src) {
if (hasOwnProperty.call(src, key)) {
dest[key] = copy(src[key]);
}
}
} else if (shape[key]) {
if (isObject(shape[key])) {
var res = {};
extend(res, dest[key]);
extend(res, src[key]);
dest[key] = res;
} else if (Array.isArray(shape[key])) {
var res = {};
var innerShape = shape[key].reduce(function(s, k) {
s[k] = true;
return s;
}, {});
for (var name in dest[key]) {
if (hasOwnProperty.call(dest[key], name)) {
res[name] = {};
if (dest[key] && dest[key][name]) {
mix(res[name], dest[key][name], innerShape);
}
}
}
for (var name in src[key]) {
if (hasOwnProperty.call(src[key], name)) {
if (!res[name]) {
res[name] = {};
}
if (src[key] && src[key][name]) {
mix(res[name], src[key][name], innerShape);
}
}
}
dest[key] = res;
}
}
}
return dest;
}
module.exports = function(dest, src) {
return mix(dest, src, shape);
};
+25
View File
@@ -0,0 +1,25 @@
module.exports = {
parseContext: {
default: 'StyleSheet',
stylesheet: 'StyleSheet',
atrule: 'Atrule',
atrulePrelude: function(options) {
return this.AtrulePrelude(options.atrule ? String(options.atrule) : null);
},
mediaQueryList: 'MediaQueryList',
mediaQuery: 'MediaQuery',
rule: 'Rule',
selectorList: 'SelectorList',
selector: 'Selector',
block: function() {
return this.Block(true);
},
declarationList: 'DeclarationList',
declaration: 'Declaration',
value: 'Value'
},
scope: require('../scope'),
atrule: require('../atrule'),
pseudo: require('../pseudo'),
node: require('../node')
};
+3
View File
@@ -0,0 +1,3 @@
module.exports = {
node: require('../node')
};
+76
View File
@@ -0,0 +1,76 @@
var List = require('../utils/list');
var Tokenizer = require('../tokenizer');
var Lexer = require('../lexer/Lexer');
var grammar = require('../lexer/grammar');
var createParser = require('../parser/create');
var createGenerator = require('../generator/create');
var createConvertor = require('../convertor/create');
var createWalker = require('../walker/create');
var clone = require('../utils/clone');
var names = require('../utils/names');
var mix = require('./config/mix');
function assign(dest, src) {
for (var key in src) {
dest[key] = src[key];
}
return dest;
}
function createSyntax(config) {
var parse = createParser(config);
var walk = createWalker(config);
var generate = createGenerator(config);
var convert = createConvertor(walk);
var syntax = {
List: List,
Tokenizer: Tokenizer,
Lexer: Lexer,
vendorPrefix: names.vendorPrefix,
keyword: names.keyword,
property: names.property,
isCustomProperty: names.isCustomProperty,
grammar: grammar,
lexer: null,
createLexer: function(config) {
return new Lexer(config, syntax, syntax.lexer.structure);
},
parse: parse,
walk: walk,
generate: generate,
clone: clone,
fromPlainObject: convert.fromPlainObject,
toPlainObject: convert.toPlainObject,
createSyntax: function(config) {
return createSyntax(mix({}, config));
},
fork: function(extension) {
var base = mix({}, config); // copy of config
return createSyntax(
typeof extension === 'function'
? extension(base, assign)
: mix(base, extension)
);
}
};
syntax.lexer = new Lexer({
generic: true,
types: config.types,
properties: config.properties,
node: config.node
}, syntax);
return syntax;
};
exports.create = function(config) {
return createSyntax(mix({}, config));
};
+13
View File
@@ -0,0 +1,13 @@
// https://drafts.csswg.org/css-images-4/#element-notation
// https://developer.mozilla.org/en-US/docs/Web/CSS/element
module.exports = function() {
this.scanner.skipSC();
var children = this.createSingleNodeList(
this.IdSelector()
);
this.scanner.skipSC();
return children;
};
+7
View File
@@ -0,0 +1,7 @@
// legacy IE function
// expression '(' raw ')'
module.exports = function() {
return this.createSingleNodeList(
this.Raw(this.scanner.currentToken, 0, 0, false, false)
);
};
+40
View File
@@ -0,0 +1,40 @@
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var COMMA = TYPE.Comma;
var SEMICOLON = TYPE.Semicolon;
var HYPHENMINUS = TYPE.HyphenMinus;
var EXCLAMATIONMARK = TYPE.ExclamationMark;
// var '(' ident (',' <value>? )? ')'
module.exports = function() {
var children = this.createList();
this.scanner.skipSC();
var identStart = this.scanner.tokenStart;
this.scanner.eat(HYPHENMINUS);
if (this.scanner.source.charCodeAt(this.scanner.tokenStart) !== HYPHENMINUS) {
this.scanner.error('HyphenMinus is expected');
}
this.scanner.eat(IDENTIFIER);
children.push({
type: 'Identifier',
loc: this.getLocation(identStart, this.scanner.tokenStart),
name: this.scanner.substrToCursor(identStart)
});
this.scanner.skipSC();
if (this.scanner.tokenType === COMMA) {
children.push(this.Operator());
children.push(this.parseCustomProperty
? this.Value(null)
: this.Raw(this.scanner.currentToken, EXCLAMATIONMARK, SEMICOLON, false, false)
);
}
return children;
};
+20
View File
@@ -0,0 +1,20 @@
function merge() {
var dest = {};
for (var i = 0; i < arguments.length; i++) {
var src = arguments[i];
for (var key in src) {
dest[key] = src[key];
}
}
return dest;
}
module.exports = require('./create').create(
merge(
require('./config/lexer'),
require('./config/parser'),
require('./config/walker')
)
);
+180
View File
@@ -0,0 +1,180 @@
var cmpChar = require('../../tokenizer').cmpChar;
var isNumber = require('../../tokenizer').isNumber;
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var NUMBER = TYPE.Number;
var PLUSSIGN = TYPE.PlusSign;
var HYPHENMINUS = TYPE.HyphenMinus;
var N = 110; // 'n'.charCodeAt(0)
var DISALLOW_SIGN = true;
var ALLOW_SIGN = false;
function checkTokenIsInteger(scanner, disallowSign) {
var pos = scanner.tokenStart;
if (scanner.source.charCodeAt(pos) === PLUSSIGN ||
scanner.source.charCodeAt(pos) === HYPHENMINUS) {
if (disallowSign) {
scanner.error();
}
pos++;
}
for (; pos < scanner.tokenEnd; pos++) {
if (!isNumber(scanner.source.charCodeAt(pos))) {
scanner.error('Unexpected input', pos);
}
}
}
// An+B microsyntax https://www.w3.org/TR/css-syntax-3/#anb
module.exports = {
name: 'AnPlusB',
structure: {
a: [String, null],
b: [String, null]
},
parse: function() {
var start = this.scanner.tokenStart;
var end = start;
var prefix = '';
var a = null;
var b = null;
if (this.scanner.tokenType === NUMBER ||
this.scanner.tokenType === PLUSSIGN) {
checkTokenIsInteger(this.scanner, ALLOW_SIGN);
prefix = this.scanner.getTokenValue();
this.scanner.next();
end = this.scanner.tokenStart;
}
if (this.scanner.tokenType === IDENTIFIER) {
var bStart = this.scanner.tokenStart;
if (cmpChar(this.scanner.source, bStart, HYPHENMINUS)) {
if (prefix === '') {
prefix = '-';
bStart++;
} else {
this.scanner.error('Unexpected hyphen minus');
}
}
if (!cmpChar(this.scanner.source, bStart, N)) {
this.scanner.error();
}
a = prefix === '' ? '1' :
prefix === '+' ? '+1' :
prefix === '-' ? '-1' :
prefix;
var len = this.scanner.tokenEnd - bStart;
if (len > 1) {
// ..n-..
if (this.scanner.source.charCodeAt(bStart + 1) !== HYPHENMINUS) {
this.scanner.error('Unexpected input', bStart + 1);
}
if (len > 2) {
// ..n-{number}..
this.scanner.tokenStart = bStart + 2;
} else {
// ..n- {number}
this.scanner.next();
this.scanner.skipSC();
}
checkTokenIsInteger(this.scanner, DISALLOW_SIGN);
b = '-' + this.scanner.getTokenValue();
this.scanner.next();
end = this.scanner.tokenStart;
} else {
prefix = '';
this.scanner.next();
end = this.scanner.tokenStart;
this.scanner.skipSC();
if (this.scanner.tokenType === HYPHENMINUS ||
this.scanner.tokenType === PLUSSIGN) {
prefix = this.scanner.getTokenValue();
this.scanner.next();
this.scanner.skipSC();
}
if (this.scanner.tokenType === NUMBER) {
checkTokenIsInteger(this.scanner, prefix !== '');
if (!isNumber(this.scanner.source.charCodeAt(this.scanner.tokenStart))) {
prefix = this.scanner.source.charAt(this.scanner.tokenStart);
this.scanner.tokenStart++;
}
if (prefix === '') {
// should be an operator before number
this.scanner.error();
} else if (prefix === '+') {
// plus is using by default
prefix = '';
}
b = prefix + this.scanner.getTokenValue();
this.scanner.next();
end = this.scanner.tokenStart;
} else {
if (prefix) {
this.scanner.eat(NUMBER);
}
}
}
} else {
if (prefix === '' || prefix === '+') { // no number
this.scanner.error(
'Number or identifier is expected',
this.scanner.tokenStart + (
this.scanner.tokenType === PLUSSIGN ||
this.scanner.tokenType === HYPHENMINUS
)
);
}
b = prefix;
}
return {
type: 'AnPlusB',
loc: this.getLocation(start, end),
a: a,
b: b
};
},
generate: function(node) {
var a = node.a !== null && node.a !== undefined;
var b = node.b !== null && node.b !== undefined;
if (a) {
this.chunk(
node.a === '+1' ? '+n' :
node.a === '1' ? 'n' :
node.a === '-1' ? '-n' :
node.a + 'n'
);
if (b) {
b = String(node.b);
if (b.charAt(0) === '-' || b.charAt(0) === '+') {
this.chunk(b.charAt(0));
this.chunk(b.substr(1));
} else {
this.chunk('+');
this.chunk(b);
}
}
} else {
this.chunk(String(node.b));
}
}
};
+106
View File
@@ -0,0 +1,106 @@
var TYPE = require('../../tokenizer').TYPE;
var ATRULE = TYPE.Atrule;
var SEMICOLON = TYPE.Semicolon;
var LEFTCURLYBRACKET = TYPE.LeftCurlyBracket;
var RIGHTCURLYBRACKET = TYPE.RightCurlyBracket;
function consumeRaw(startToken) {
return this.Raw(startToken, SEMICOLON, LEFTCURLYBRACKET, false, true);
}
function isDeclarationBlockAtrule() {
for (var offset = 1, type; type = this.scanner.lookupType(offset); offset++) {
if (type === RIGHTCURLYBRACKET) {
return true;
}
if (type === LEFTCURLYBRACKET ||
type === ATRULE) {
return false;
}
}
return false;
}
module.exports = {
name: 'Atrule',
structure: {
name: String,
prelude: ['AtrulePrelude', 'Raw', null],
block: ['Block', null]
},
parse: function() {
var start = this.scanner.tokenStart;
var name;
var nameLowerCase;
var prelude = null;
var block = null;
this.scanner.eat(ATRULE);
name = this.scanner.substrToCursor(start + 1);
nameLowerCase = name.toLowerCase();
this.scanner.skipSC();
// parse prelude
if (this.scanner.eof === false &&
this.scanner.tokenType !== LEFTCURLYBRACKET &&
this.scanner.tokenType !== SEMICOLON) {
if (this.parseAtrulePrelude) {
prelude = this.parseWithFallback(this.AtrulePrelude.bind(this, name), consumeRaw);
// turn empty AtrulePrelude into null
if (prelude.type === 'AtrulePrelude' && prelude.children.head === null) {
prelude = null;
}
} else {
prelude = consumeRaw.call(this, this.scanner.currentToken);
}
this.scanner.skipSC();
}
switch (this.scanner.tokenType) {
case SEMICOLON:
this.scanner.next();
break;
case LEFTCURLYBRACKET:
if (this.atrule.hasOwnProperty(nameLowerCase) &&
typeof this.atrule[nameLowerCase].block === 'function') {
block = this.atrule[nameLowerCase].block.call(this);
} else {
// TODO: should consume block content as Raw?
block = this.Block(isDeclarationBlockAtrule.call(this));
}
break;
}
return {
type: 'Atrule',
loc: this.getLocation(start, this.scanner.tokenStart),
name: name,
prelude: prelude,
block: block
};
},
generate: function(node) {
this.chunk('@');
this.chunk(node.name);
if (node.prelude !== null) {
this.chunk(' ');
this.node(node.prelude);
}
if (node.block) {
this.node(node.block);
} else {
this.chunk(';');
}
},
walkContext: 'atrule'
};
+51
View File
@@ -0,0 +1,51 @@
var TYPE = require('../../tokenizer').TYPE;
var SEMICOLON = TYPE.Semicolon;
var LEFTCURLYBRACKET = TYPE.LeftCurlyBracket;
module.exports = {
name: 'AtrulePrelude',
structure: {
children: [[]]
},
parse: function(name) {
var children = null;
if (name !== null) {
name = name.toLowerCase();
}
this.scanner.skipSC();
if (this.atrule.hasOwnProperty(name) &&
typeof this.atrule[name].prelude === 'function') {
// custom consumer
children = this.atrule[name].prelude.call(this);
} else {
// default consumer
children = this.readSequence(this.scope.AtrulePrelude);
}
this.scanner.skipSC();
if (this.scanner.eof !== true &&
this.scanner.tokenType !== LEFTCURLYBRACKET &&
this.scanner.tokenType !== SEMICOLON) {
this.scanner.error('Semicolon or block is expected');
}
if (children === null) {
children = this.createList();
}
return {
type: 'AtrulePrelude',
loc: this.getLocationFromList(children),
children: children
};
},
generate: function(node) {
this.children(node);
},
walkContext: 'atrulePrelude'
};
+162
View File
@@ -0,0 +1,162 @@
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var STRING = TYPE.String;
var DOLLARSIGN = TYPE.DollarSign;
var ASTERISK = TYPE.Asterisk;
var COLON = TYPE.Colon;
var EQUALSSIGN = TYPE.EqualsSign;
var LEFTSQUAREBRACKET = TYPE.LeftSquareBracket;
var RIGHTSQUAREBRACKET = TYPE.RightSquareBracket;
var CIRCUMFLEXACCENT = TYPE.CircumflexAccent;
var VERTICALLINE = TYPE.VerticalLine;
var TILDE = TYPE.Tilde;
function getAttributeName() {
if (this.scanner.eof) {
this.scanner.error('Unexpected end of input');
}
var start = this.scanner.tokenStart;
var expectIdentifier = false;
var checkColon = true;
if (this.scanner.tokenType === ASTERISK) {
expectIdentifier = true;
checkColon = false;
this.scanner.next();
} else if (this.scanner.tokenType !== VERTICALLINE) {
this.scanner.eat(IDENTIFIER);
}
if (this.scanner.tokenType === VERTICALLINE) {
if (this.scanner.lookupType(1) !== EQUALSSIGN) {
this.scanner.next();
this.scanner.eat(IDENTIFIER);
} else if (expectIdentifier) {
this.scanner.error('Identifier is expected', this.scanner.tokenEnd);
}
} else if (expectIdentifier) {
this.scanner.error('Vertical line is expected');
}
if (checkColon && this.scanner.tokenType === COLON) {
this.scanner.next();
this.scanner.eat(IDENTIFIER);
}
return {
type: 'Identifier',
loc: this.getLocation(start, this.scanner.tokenStart),
name: this.scanner.substrToCursor(start)
};
}
function getOperator() {
var start = this.scanner.tokenStart;
var tokenType = this.scanner.tokenType;
if (tokenType !== EQUALSSIGN && // =
tokenType !== TILDE && // ~=
tokenType !== CIRCUMFLEXACCENT && // ^=
tokenType !== DOLLARSIGN && // $=
tokenType !== ASTERISK && // *=
tokenType !== VERTICALLINE // |=
) {
this.scanner.error('Attribute selector (=, ~=, ^=, $=, *=, |=) is expected');
}
if (tokenType === EQUALSSIGN) {
this.scanner.next();
} else {
this.scanner.next();
this.scanner.eat(EQUALSSIGN);
}
return this.scanner.substrToCursor(start);
}
// '[' S* attrib_name ']'
// '[' S* attrib_name S* attrib_matcher S* [ IDENT | STRING ] S* attrib_flags? S* ']'
module.exports = {
name: 'AttributeSelector',
structure: {
name: 'Identifier',
matcher: [String, null],
value: ['String', 'Identifier', null],
flags: [String, null]
},
parse: function() {
var start = this.scanner.tokenStart;
var name;
var matcher = null;
var value = null;
var flags = null;
this.scanner.eat(LEFTSQUAREBRACKET);
this.scanner.skipSC();
name = getAttributeName.call(this);
this.scanner.skipSC();
if (this.scanner.tokenType !== RIGHTSQUAREBRACKET) {
// avoid case `[name i]`
if (this.scanner.tokenType !== IDENTIFIER) {
matcher = getOperator.call(this);
this.scanner.skipSC();
value = this.scanner.tokenType === STRING
? this.String()
: this.Identifier();
this.scanner.skipSC();
}
// attribute flags
if (this.scanner.tokenType === IDENTIFIER) {
flags = this.scanner.getTokenValue();
this.scanner.next();
this.scanner.skipSC();
}
}
this.scanner.eat(RIGHTSQUAREBRACKET);
return {
type: 'AttributeSelector',
loc: this.getLocation(start, this.scanner.tokenStart),
name: name,
matcher: matcher,
value: value,
flags: flags
};
},
generate: function(node) {
var flagsPrefix = ' ';
this.chunk('[');
this.node(node.name);
if (node.matcher !== null) {
this.chunk(node.matcher);
if (node.value !== null) {
this.node(node.value);
// space between string and flags is not required
if (node.value.type === 'String') {
flagsPrefix = '';
}
}
}
if (node.flags !== null) {
this.chunk(flagsPrefix);
this.chunk(node.flags);
}
this.chunk(']');
}
};
+90
View File
@@ -0,0 +1,90 @@
var TYPE = require('../../tokenizer').TYPE;
var WHITESPACE = TYPE.WhiteSpace;
var COMMENT = TYPE.Comment;
var SEMICOLON = TYPE.Semicolon;
var ATRULE = TYPE.Atrule;
var LEFTCURLYBRACKET = TYPE.LeftCurlyBracket;
var RIGHTCURLYBRACKET = TYPE.RightCurlyBracket;
function consumeRaw(startToken) {
return this.Raw(startToken, 0, 0, false, true);
}
function consumeRule() {
return this.parseWithFallback(this.Rule, consumeRaw);
}
function consumeRawDeclaration(startToken) {
return this.Raw(startToken, 0, SEMICOLON, true, true);
}
function consumeDeclaration() {
if (this.scanner.tokenType === SEMICOLON) {
return consumeRawDeclaration.call(this, this.scanner.currentToken);
}
var node = this.parseWithFallback(this.Declaration, consumeRawDeclaration);
if (this.scanner.tokenType === SEMICOLON) {
this.scanner.next();
}
return node;
}
module.exports = {
name: 'Block',
structure: {
children: [[
'Atrule',
'Rule',
'Declaration'
]]
},
parse: function(isDeclaration) {
var consumer = isDeclaration ? consumeDeclaration : consumeRule;
var start = this.scanner.tokenStart;
var children = this.createList();
this.scanner.eat(LEFTCURLYBRACKET);
scan:
while (!this.scanner.eof) {
switch (this.scanner.tokenType) {
case RIGHTCURLYBRACKET:
break scan;
case WHITESPACE:
case COMMENT:
this.scanner.next();
break;
case ATRULE:
children.push(this.parseWithFallback(this.Atrule, consumeRaw));
break;
default:
children.push(consumer.call(this));
}
}
if (!this.scanner.eof) {
this.scanner.eat(RIGHTCURLYBRACKET);
}
return {
type: 'Block',
loc: this.getLocation(start, this.scanner.tokenStart),
children: children
};
},
generate: function(node) {
this.chunk('{');
this.children(node, function(prev) {
if (prev.type === 'Declaration') {
this.chunk(';');
}
});
this.chunk('}');
},
walkContext: 'block'
};
+33
View File
@@ -0,0 +1,33 @@
var TYPE = require('../../tokenizer').TYPE;
var LEFTSQUAREBRACKET = TYPE.LeftSquareBracket;
var RIGHTSQUAREBRACKET = TYPE.RightSquareBracket;
module.exports = {
name: 'Brackets',
structure: {
children: [[]]
},
parse: function(readSequence, recognizer) {
var start = this.scanner.tokenStart;
var children = null;
this.scanner.eat(LEFTSQUAREBRACKET);
children = readSequence.call(this, recognizer);
if (!this.scanner.eof) {
this.scanner.eat(RIGHTSQUAREBRACKET);
}
return {
type: 'Brackets',
loc: this.getLocation(start, this.scanner.tokenStart),
children: children
};
},
generate: function(node) {
this.chunk('[');
this.children(node);
this.chunk(']');
}
};
+19
View File
@@ -0,0 +1,19 @@
var CDC = require('../../tokenizer').TYPE.CDC;
module.exports = {
name: 'CDC',
structure: [],
parse: function() {
var start = this.scanner.tokenStart;
this.scanner.eat(CDC); // -->
return {
type: 'CDC',
loc: this.getLocation(start, this.scanner.tokenStart)
};
},
generate: function() {
this.chunk('-->');
}
};
+19
View File
@@ -0,0 +1,19 @@
var CDO = require('../../tokenizer').TYPE.CDO;
module.exports = {
name: 'CDO',
structure: [],
parse: function() {
var start = this.scanner.tokenStart;
this.scanner.eat(CDO); // <!--
return {
type: 'CDO',
loc: this.getLocation(start, this.scanner.tokenStart)
};
},
generate: function() {
this.chunk('<!--');
}
};
+24
View File
@@ -0,0 +1,24 @@
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var FULLSTOP = TYPE.FullStop;
// '.' ident
module.exports = {
name: 'ClassSelector',
structure: {
name: String
},
parse: function() {
this.scanner.eat(FULLSTOP);
return {
type: 'ClassSelector',
loc: this.getLocation(this.scanner.tokenStart - 1, this.scanner.tokenEnd),
name: this.scanner.consume(IDENTIFIER)
};
},
generate: function(node) {
this.chunk('.');
this.chunk(node.name);
}
};
+43
View File
@@ -0,0 +1,43 @@
var TYPE = require('../../tokenizer').TYPE;
var PLUSSIGN = TYPE.PlusSign;
var SOLIDUS = TYPE.Solidus;
var GREATERTHANSIGN = TYPE.GreaterThanSign;
var TILDE = TYPE.Tilde;
// + | > | ~ | /deep/
module.exports = {
name: 'Combinator',
structure: {
name: String
},
parse: function() {
var start = this.scanner.tokenStart;
switch (this.scanner.tokenType) {
case GREATERTHANSIGN:
case PLUSSIGN:
case TILDE:
this.scanner.next();
break;
case SOLIDUS:
this.scanner.next();
this.scanner.expectIdentifier('deep');
this.scanner.eat(SOLIDUS);
break;
default:
this.scanner.error('Combinator is expected');
}
return {
type: 'Combinator',
loc: this.getLocation(start, this.scanner.tokenStart),
name: this.scanner.substrToCursor(start)
};
},
generate: function(node) {
this.chunk(node.name);
}
};
+35
View File
@@ -0,0 +1,35 @@
var TYPE = require('../../tokenizer').TYPE;
var ASTERISK = TYPE.Asterisk;
var SOLIDUS = TYPE.Solidus;
// '/*' .* '*/'
module.exports = {
name: 'Comment',
structure: {
value: String
},
parse: function() {
var start = this.scanner.tokenStart;
var end = this.scanner.tokenEnd;
if ((end - start + 2) >= 2 &&
this.scanner.source.charCodeAt(end - 2) === ASTERISK &&
this.scanner.source.charCodeAt(end - 1) === SOLIDUS) {
end -= 2;
}
this.scanner.next();
return {
type: 'Comment',
loc: this.getLocation(start, this.scanner.tokenStart),
value: this.scanner.source.substring(start + 2, end)
};
},
generate: function(node) {
this.chunk('/*');
this.chunk(node.value);
this.chunk('*/');
}
};
+144
View File
@@ -0,0 +1,144 @@
var isCustomProperty = require('../../utils/names').isCustomProperty;
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var COLON = TYPE.Colon;
var EXCLAMATIONMARK = TYPE.ExclamationMark;
var SOLIDUS = TYPE.Solidus;
var ASTERISK = TYPE.Asterisk;
var DOLLARSIGN = TYPE.DollarSign;
var HYPHENMINUS = TYPE.HyphenMinus;
var SEMICOLON = TYPE.Semicolon;
var PLUSSIGN = TYPE.PlusSign;
var NUMBERSIGN = TYPE.NumberSign;
function consumeValueRaw(startToken) {
return this.Raw(startToken, EXCLAMATIONMARK, SEMICOLON, false, true);
}
function consumeCustomPropertyRaw(startToken) {
return this.Raw(startToken, EXCLAMATIONMARK, SEMICOLON, false, false);
}
function consumeValue() {
var startValueToken = this.scanner.currentToken;
var value = this.Value();
if (value.type !== 'Raw' &&
this.scanner.eof === false &&
this.scanner.tokenType !== SEMICOLON &&
this.scanner.tokenType !== EXCLAMATIONMARK &&
this.scanner.isBalanceEdge(startValueToken) === false) {
this.scanner.error();
}
return value;
}
module.exports = {
name: 'Declaration',
structure: {
important: [Boolean, String],
property: String,
value: ['Value', 'Raw']
},
parse: function() {
var start = this.scanner.tokenStart;
var startToken = this.scanner.currentToken;
var property = readProperty.call(this);
var customProperty = isCustomProperty(property);
var parseValue = customProperty ? this.parseCustomProperty : this.parseValue;
var consumeRaw = customProperty ? consumeCustomPropertyRaw : consumeValueRaw;
var important = false;
var value;
this.scanner.skipSC();
this.scanner.eat(COLON);
if (!customProperty) {
this.scanner.skipSC();
}
if (parseValue) {
value = this.parseWithFallback(consumeValue, consumeRaw);
} else {
value = consumeRaw.call(this, this.scanner.currentToken);
}
if (this.scanner.tokenType === EXCLAMATIONMARK) {
important = getImportant(this.scanner);
this.scanner.skipSC();
}
// Do not include semicolon to range per spec
// https://drafts.csswg.org/css-syntax/#declaration-diagram
if (this.scanner.eof === false &&
this.scanner.tokenType !== SEMICOLON &&
this.scanner.isBalanceEdge(startToken) === false) {
this.scanner.error();
}
return {
type: 'Declaration',
loc: this.getLocation(start, this.scanner.tokenStart),
important: important,
property: property,
value: value
};
},
generate: function(node) {
this.chunk(node.property);
this.chunk(':');
this.node(node.value);
if (node.important) {
this.chunk(node.important === true ? '!important' : '!' + node.important);
}
},
walkContext: 'declaration'
};
function readProperty() {
var start = this.scanner.tokenStart;
var prefix = 0;
// hacks
switch (this.scanner.tokenType) {
case ASTERISK:
case DOLLARSIGN:
case PLUSSIGN:
case NUMBERSIGN:
prefix = 1;
break;
// TODO: not sure we should support this hack
case SOLIDUS:
prefix = this.scanner.lookupType(1) === SOLIDUS ? 2 : 1;
break;
}
if (this.scanner.lookupType(prefix) === HYPHENMINUS) {
prefix++;
}
if (prefix) {
this.scanner.skip(prefix);
}
this.scanner.eat(IDENTIFIER);
return this.scanner.substrToCursor(start);
}
// ! ws* important
function getImportant(scanner) {
scanner.eat(EXCLAMATIONMARK);
scanner.skipSC();
var important = scanner.consume(IDENTIFIER);
// store original value in case it differ from `important`
// for better original source restoring and hacks like `!ie` support
return important === 'important' ? true : important;
}
+48
View File
@@ -0,0 +1,48 @@
var TYPE = require('../../tokenizer').TYPE;
var WHITESPACE = TYPE.WhiteSpace;
var COMMENT = TYPE.Comment;
var SEMICOLON = TYPE.Semicolon;
function consumeRaw(startToken) {
return this.Raw(startToken, 0, SEMICOLON, true, true);
}
module.exports = {
name: 'DeclarationList',
structure: {
children: [[
'Declaration'
]]
},
parse: function() {
var children = this.createList();
scan:
while (!this.scanner.eof) {
switch (this.scanner.tokenType) {
case WHITESPACE:
case COMMENT:
case SEMICOLON:
this.scanner.next();
break;
default:
children.push(this.parseWithFallback(this.Declaration, consumeRaw));
}
}
return {
type: 'DeclarationList',
loc: this.getLocationFromList(children),
children: children
};
},
generate: function(node) {
this.children(node, function(prev) {
if (prev.type === 'Declaration') {
this.chunk(';');
}
});
}
};
+45
View File
@@ -0,0 +1,45 @@
var NUMBER = require('../../tokenizer').TYPE.Number;
// special reader for units to avoid adjoined IE hacks (i.e. '1px\9')
function readUnit(scanner) {
var unit = scanner.getTokenValue();
var backSlashPos = unit.indexOf('\\');
if (backSlashPos > 0) {
// patch token offset
scanner.tokenStart += backSlashPos;
// return part before backslash
return unit.substring(0, backSlashPos);
}
// no backslash in unit name
scanner.next();
return unit;
}
// number ident
module.exports = {
name: 'Dimension',
structure: {
value: String,
unit: String
},
parse: function() {
var start = this.scanner.tokenStart;
var value = this.scanner.consume(NUMBER);
var unit = readUnit(this.scanner);
return {
type: 'Dimension',
loc: this.getLocation(start, this.scanner.tokenStart),
value: value,
unit: unit
};
},
generate: function(node) {
this.chunk(node.value);
this.chunk(node.unit);
}
};
+39
View File
@@ -0,0 +1,39 @@
var TYPE = require('../../tokenizer').TYPE;
var RIGHTPARENTHESIS = TYPE.RightParenthesis;
// <function-token> <sequence> ')'
module.exports = {
name: 'Function',
structure: {
name: String,
children: [[]]
},
parse: function(readSequence, recognizer) {
var start = this.scanner.tokenStart;
var name = this.scanner.consumeFunctionName();
var nameLowerCase = name.toLowerCase();
var children;
children = recognizer.hasOwnProperty(nameLowerCase)
? recognizer[nameLowerCase].call(this, recognizer)
: readSequence.call(this, recognizer);
if (!this.scanner.eof) {
this.scanner.eat(RIGHTPARENTHESIS);
}
return {
type: 'Function',
loc: this.getLocation(start, this.scanner.tokenStart),
name: name,
children: children
};
},
generate: function(node) {
this.chunk(node.name);
this.chunk('(');
this.children(node);
this.chunk(')');
},
walkContext: 'function'
};
+74
View File
@@ -0,0 +1,74 @@
var isHex = require('../../tokenizer').isHex;
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var NUMBER = TYPE.Number;
var NUMBERSIGN = TYPE.NumberSign;
function consumeHexSequence(scanner, required) {
if (!isHex(scanner.source.charCodeAt(scanner.tokenStart))) {
if (required) {
scanner.error('Unexpected input', scanner.tokenStart);
} else {
return;
}
}
for (var pos = scanner.tokenStart + 1; pos < scanner.tokenEnd; pos++) {
var code = scanner.source.charCodeAt(pos);
// break on non-hex char
if (!isHex(code)) {
// break token, exclude symbol
scanner.tokenStart = pos;
return;
}
}
// token is full hex sequence, go to next token
scanner.next();
}
// # ident
module.exports = {
name: 'HexColor',
structure: {
value: String
},
parse: function() {
var start = this.scanner.tokenStart;
this.scanner.eat(NUMBERSIGN);
scan:
switch (this.scanner.tokenType) {
case NUMBER:
consumeHexSequence(this.scanner, true);
// if token is identifier then number consists of hex only,
// try to add identifier to result
if (this.scanner.tokenType === IDENTIFIER) {
consumeHexSequence(this.scanner, false);
}
break;
case IDENTIFIER:
consumeHexSequence(this.scanner, true);
break;
default:
this.scanner.error('Number or identifier is expected');
}
return {
type: 'HexColor',
loc: this.getLocation(start, this.scanner.tokenStart),
value: this.scanner.substrToCursor(start + 1) // skip #
};
},
generate: function(node) {
this.chunk('#');
this.chunk(node.value);
}
};
+24
View File
@@ -0,0 +1,24 @@
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var NUMBERSIGN = TYPE.NumberSign;
// '#' ident
module.exports = {
name: 'IdSelector',
structure: {
name: String
},
parse: function() {
this.scanner.eat(NUMBERSIGN);
return {
type: 'IdSelector',
loc: this.getLocation(this.scanner.tokenStart - 1, this.scanner.tokenEnd),
name: this.scanner.consume(IDENTIFIER)
};
},
generate: function(node) {
this.chunk('#');
this.chunk(node.name);
}
};
+19
View File
@@ -0,0 +1,19 @@
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
module.exports = {
name: 'Identifier',
structure: {
name: String
},
parse: function() {
return {
type: 'Identifier',
loc: this.getLocation(this.scanner.tokenStart, this.scanner.tokenEnd),
name: this.scanner.consume(IDENTIFIER)
};
},
generate: function(node) {
this.chunk(node.name);
}
};
+73
View File
@@ -0,0 +1,73 @@
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var NUMBER = TYPE.Number;
var LEFTPARENTHESIS = TYPE.LeftParenthesis;
var RIGHTPARENTHESIS = TYPE.RightParenthesis;
var COLON = TYPE.Colon;
var SOLIDUS = TYPE.Solidus;
module.exports = {
name: 'MediaFeature',
structure: {
name: String,
value: ['Identifier', 'Number', 'Dimension', 'Ratio', null]
},
parse: function() {
var start = this.scanner.tokenStart;
var name;
var value = null;
this.scanner.eat(LEFTPARENTHESIS);
this.scanner.skipSC();
name = this.scanner.consume(IDENTIFIER);
this.scanner.skipSC();
if (this.scanner.tokenType !== RIGHTPARENTHESIS) {
this.scanner.eat(COLON);
this.scanner.skipSC();
switch (this.scanner.tokenType) {
case NUMBER:
if (this.scanner.lookupType(1) === IDENTIFIER) {
value = this.Dimension();
} else if (this.scanner.lookupNonWSType(1) === SOLIDUS) {
value = this.Ratio();
} else {
value = this.Number();
}
break;
case IDENTIFIER:
value = this.Identifier();
break;
default:
this.scanner.error('Number, dimension, ratio or identifier is expected');
}
this.scanner.skipSC();
}
this.scanner.eat(RIGHTPARENTHESIS);
return {
type: 'MediaFeature',
loc: this.getLocation(start, this.scanner.tokenStart),
name: name,
value: value
};
},
generate: function(node) {
this.chunk('(');
this.chunk(node.name);
if (node.value !== null) {
this.chunk(':');
this.node(node.value);
}
this.chunk(')');
}
};
+68
View File
@@ -0,0 +1,68 @@
var TYPE = require('../../tokenizer').TYPE;
var WHITESPACE = TYPE.WhiteSpace;
var COMMENT = TYPE.Comment;
var IDENTIFIER = TYPE.Identifier;
var LEFTPARENTHESIS = TYPE.LeftParenthesis;
module.exports = {
name: 'MediaQuery',
structure: {
children: [[
'Identifier',
'MediaFeature',
'WhiteSpace'
]]
},
parse: function() {
this.scanner.skipSC();
var children = this.createList();
var child = null;
var space = null;
scan:
while (!this.scanner.eof) {
switch (this.scanner.tokenType) {
case COMMENT:
this.scanner.next();
continue;
case WHITESPACE:
space = this.WhiteSpace();
continue;
case IDENTIFIER:
child = this.Identifier();
break;
case LEFTPARENTHESIS:
child = this.MediaFeature();
break;
default:
break scan;
}
if (space !== null) {
children.push(space);
space = null;
}
children.push(child);
}
if (child === null) {
this.scanner.error('Identifier or parenthesis is expected');
}
return {
type: 'MediaQuery',
loc: this.getLocationFromList(children),
children: children
};
},
generate: function(node) {
this.children(node);
}
};
+36
View File
@@ -0,0 +1,36 @@
var COMMA = require('../../tokenizer').TYPE.Comma;
module.exports = {
name: 'MediaQueryList',
structure: {
children: [[
'MediaQuery'
]]
},
parse: function(relative) {
var children = this.createList();
this.scanner.skipSC();
while (!this.scanner.eof) {
children.push(this.MediaQuery(relative));
if (this.scanner.tokenType !== COMMA) {
break;
}
this.scanner.next();
}
return {
type: 'MediaQueryList',
loc: this.getLocationFromList(children),
children: children
};
},
generate: function(node) {
this.children(node, function() {
this.chunk(',');
});
}
};
+52
View File
@@ -0,0 +1,52 @@
// https://drafts.csswg.org/css-syntax-3/#the-anb-type
module.exports = {
name: 'Nth',
structure: {
nth: ['AnPlusB', 'Identifier'],
selector: ['SelectorList', null]
},
parse: function(allowOfClause) {
this.scanner.skipSC();
var start = this.scanner.tokenStart;
var end = start;
var selector = null;
var query;
if (this.scanner.lookupValue(0, 'odd') || this.scanner.lookupValue(0, 'even')) {
query = this.Identifier();
} else {
query = this.AnPlusB();
}
this.scanner.skipSC();
if (allowOfClause && this.scanner.lookupValue(0, 'of')) {
this.scanner.next();
selector = this.SelectorList();
if (this.needPositions) {
end = this.getLastListNode(selector.children).loc.end.offset;
}
} else {
if (this.needPositions) {
end = query.loc.end.offset;
}
}
return {
type: 'Nth',
loc: this.getLocation(start, end),
nth: query,
selector: selector
};
},
generate: function(node) {
this.node(node.nth);
if (node.selector !== null) {
this.chunk(' of ');
this.node(node.selector);
}
}
};
+18
View File
@@ -0,0 +1,18 @@
var NUMBER = require('../../tokenizer').TYPE.Number;
module.exports = {
name: 'Number',
structure: {
value: String
},
parse: function() {
return {
type: 'Number',
loc: this.getLocation(this.scanner.tokenStart, this.scanner.tokenEnd),
value: this.scanner.consume(NUMBER)
};
},
generate: function(node) {
this.chunk(node.value);
}
};
+21
View File
@@ -0,0 +1,21 @@
// '/' | '*' | ',' | ':' | '+' | '-'
module.exports = {
name: 'Operator',
structure: {
value: String
},
parse: function() {
var start = this.scanner.tokenStart;
this.scanner.next();
return {
type: 'Operator',
loc: this.getLocation(start, this.scanner.tokenStart),
value: this.scanner.substrToCursor(start)
};
},
generate: function(node) {
this.chunk(node.value);
}
};
+33
View File
@@ -0,0 +1,33 @@
var TYPE = require('../../tokenizer').TYPE;
var LEFTPARENTHESIS = TYPE.LeftParenthesis;
var RIGHTPARENTHESIS = TYPE.RightParenthesis;
module.exports = {
name: 'Parentheses',
structure: {
children: [[]]
},
parse: function(readSequence, recognizer) {
var start = this.scanner.tokenStart;
var children = null;
this.scanner.eat(LEFTPARENTHESIS);
children = readSequence.call(this, recognizer);
if (!this.scanner.eof) {
this.scanner.eat(RIGHTPARENTHESIS);
}
return {
type: 'Parentheses',
loc: this.getLocation(start, this.scanner.tokenStart),
children: children
};
},
generate: function(node) {
this.chunk('(');
this.children(node);
this.chunk(')');
}
};
+27
View File
@@ -0,0 +1,27 @@
var TYPE = require('../../tokenizer').TYPE;
var NUMBER = TYPE.Number;
var PERCENTSIGN = TYPE.PercentSign;
module.exports = {
name: 'Percentage',
structure: {
value: String
},
parse: function() {
var start = this.scanner.tokenStart;
var number = this.scanner.consume(NUMBER);
this.scanner.eat(PERCENTSIGN);
return {
type: 'Percentage',
loc: this.getLocation(start, this.scanner.tokenStart),
value: number
};
},
generate: function(node) {
this.chunk(node.value);
this.chunk('%');
}
};
+61
View File
@@ -0,0 +1,61 @@
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var FUNCTION = TYPE.Function;
var COLON = TYPE.Colon;
var RIGHTPARENTHESIS = TYPE.RightParenthesis;
// : ident [ '(' .. ')' ]?
module.exports = {
name: 'PseudoClassSelector',
structure: {
name: String,
children: [['Raw'], null]
},
parse: function() {
var start = this.scanner.tokenStart;
var children = null;
var name;
var nameLowerCase;
this.scanner.eat(COLON);
if (this.scanner.tokenType === FUNCTION) {
name = this.scanner.consumeFunctionName();
nameLowerCase = name.toLowerCase();
if (this.pseudo.hasOwnProperty(nameLowerCase)) {
this.scanner.skipSC();
children = this.pseudo[nameLowerCase].call(this);
this.scanner.skipSC();
} else {
children = this.createList();
children.push(
this.Raw(this.scanner.currentToken, 0, 0, false, false)
);
}
this.scanner.eat(RIGHTPARENTHESIS);
} else {
name = this.scanner.consume(IDENTIFIER);
}
return {
type: 'PseudoClassSelector',
loc: this.getLocation(start, this.scanner.tokenStart),
name: name,
children: children
};
},
generate: function(node) {
this.chunk(':');
this.chunk(node.name);
if (node.children !== null) {
this.chunk('(');
this.children(node);
this.chunk(')');
}
},
walkContext: 'function'
};
+62
View File
@@ -0,0 +1,62 @@
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var FUNCTION = TYPE.Function;
var COLON = TYPE.Colon;
var RIGHTPARENTHESIS = TYPE.RightParenthesis;
// :: ident [ '(' .. ')' ]?
module.exports = {
name: 'PseudoElementSelector',
structure: {
name: String,
children: [['Raw'], null]
},
parse: function() {
var start = this.scanner.tokenStart;
var children = null;
var name;
var nameLowerCase;
this.scanner.eat(COLON);
this.scanner.eat(COLON);
if (this.scanner.tokenType === FUNCTION) {
name = this.scanner.consumeFunctionName();
nameLowerCase = name.toLowerCase();
if (this.pseudo.hasOwnProperty(nameLowerCase)) {
this.scanner.skipSC();
children = this.pseudo[nameLowerCase].call(this);
this.scanner.skipSC();
} else {
children = this.createList();
children.push(
this.Raw(this.scanner.currentToken, 0, 0, false, false)
);
}
this.scanner.eat(RIGHTPARENTHESIS);
} else {
name = this.scanner.consume(IDENTIFIER);
}
return {
type: 'PseudoElementSelector',
loc: this.getLocation(start, this.scanner.tokenStart),
name: name,
children: children
};
},
generate: function(node) {
this.chunk('::');
this.chunk(node.name);
if (node.children !== null) {
this.chunk('(');
this.children(node);
this.chunk(')');
}
},
walkContext: 'function'
};
+57
View File
@@ -0,0 +1,57 @@
var isNumber = require('../../tokenizer').isNumber;
var TYPE = require('../../tokenizer').TYPE;
var NUMBER = TYPE.Number;
var SOLIDUS = TYPE.Solidus;
var FULLSTOP = TYPE.FullStop;
// Terms of <ratio> should to be a positive number (not zero or negative)
// (see https://drafts.csswg.org/mediaqueries-3/#values)
// However, -o-min-device-pixel-ratio takes fractional values as a ratio's term
// and this is using by various sites. Therefore we relax checking on parse
// to test a term is unsigned number without exponent part.
// Additional checks may to be applied on lexer validation.
function consumeNumber(scanner) {
var value = scanner.consumeNonWS(NUMBER);
for (var i = 0; i < value.length; i++) {
var code = value.charCodeAt(i);
if (!isNumber(code) && code !== FULLSTOP) {
scanner.error('Unsigned number is expected', scanner.tokenStart - value.length + i);
}
}
if (Number(value) === 0) {
scanner.error('Zero number is not allowed', scanner.tokenStart - value.length);
}
return value;
}
// <positive-integer> S* '/' S* <positive-integer>
module.exports = {
name: 'Ratio',
structure: {
left: String,
right: String
},
parse: function() {
var start = this.scanner.tokenStart;
var left = consumeNumber(this.scanner);
var right;
this.scanner.eatNonWS(SOLIDUS);
right = consumeNumber(this.scanner);
return {
type: 'Ratio',
loc: this.getLocation(start, this.scanner.tokenStart),
left: left,
right: right
};
},
generate: function(node) {
this.chunk(node.left);
this.chunk('/');
this.chunk(node.right);
}
};
+34
View File
@@ -0,0 +1,34 @@
module.exports = {
name: 'Raw',
structure: {
value: String
},
parse: function(startToken, endTokenType1, endTokenType2, includeTokenType2, excludeWhiteSpace) {
var startOffset = this.scanner.getTokenStart(startToken);
var endOffset;
this.scanner.skip(
this.scanner.getRawLength(
startToken,
endTokenType1,
endTokenType2,
includeTokenType2
)
);
if (excludeWhiteSpace && this.scanner.tokenStart > startOffset) {
endOffset = this.scanner.getOffsetExcludeWS();
} else {
endOffset = this.scanner.tokenStart;
}
return {
type: 'Raw',
loc: this.getLocation(startOffset, endOffset),
value: this.scanner.source.substring(startOffset, endOffset)
};
},
generate: function(node) {
this.chunk(node.value);
}
};
+53
View File
@@ -0,0 +1,53 @@
var TYPE = require('../../tokenizer').TYPE;
var LEFTCURLYBRACKET = TYPE.LeftCurlyBracket;
function consumeRaw(startToken) {
return this.Raw(startToken, LEFTCURLYBRACKET, 0, false, true);
}
function consumePrelude() {
var prelude = this.SelectorList();
if (prelude.type !== 'Raw' &&
this.scanner.eof === false &&
this.scanner.tokenType !== LEFTCURLYBRACKET) {
this.scanner.error();
}
return prelude;
}
module.exports = {
name: 'Rule',
structure: {
prelude: ['SelectorList', 'Raw'],
block: ['Block']
},
parse: function() {
var startToken = this.scanner.currentToken;
var startOffset = this.scanner.tokenStart;
var prelude;
var block;
if (this.parseRulePrelude) {
prelude = this.parseWithFallback(consumePrelude, consumeRaw);
} else {
prelude = consumeRaw.call(this, startToken);
}
block = this.Block(true);
return {
type: 'Rule',
loc: this.getLocation(startOffset, this.scanner.tokenStart),
prelude: prelude,
block: block
};
},
generate: function(node) {
this.node(node.prelude);
this.node(node.block);
},
walkContext: 'rule'
};
+32
View File
@@ -0,0 +1,32 @@
module.exports = {
name: 'Selector',
structure: {
children: [[
'TypeSelector',
'IdSelector',
'ClassSelector',
'AttributeSelector',
'PseudoClassSelector',
'PseudoElementSelector',
'Combinator',
'WhiteSpace'
]]
},
parse: function() {
var children = this.readSequence(this.scope.Selector);
// nothing were consumed
if (this.getFirstListNode(children) === null) {
this.scanner.error('Selector is expected');
}
return {
type: 'Selector',
loc: this.getLocationFromList(children),
children: children
};
},
generate: function(node) {
this.children(node);
}
};
+39
View File
@@ -0,0 +1,39 @@
var TYPE = require('../../tokenizer').TYPE;
var COMMA = TYPE.Comma;
module.exports = {
name: 'SelectorList',
structure: {
children: [[
'Selector',
'Raw'
]]
},
parse: function() {
var children = this.createList();
while (!this.scanner.eof) {
children.push(this.Selector());
if (this.scanner.tokenType === COMMA) {
this.scanner.next();
continue;
}
break;
}
return {
type: 'SelectorList',
loc: this.getLocationFromList(children),
children: children
};
},
generate: function(node) {
this.children(node, function() {
this.chunk(',');
});
},
walkContext: 'selector'
};
+18
View File
@@ -0,0 +1,18 @@
var STRING = require('../../tokenizer').TYPE.String;
module.exports = {
name: 'String',
structure: {
value: String
},
parse: function() {
return {
type: 'String',
loc: this.getLocation(this.scanner.tokenStart, this.scanner.tokenEnd),
value: this.scanner.consume(STRING)
};
},
generate: function(node) {
this.chunk(node.value);
}
};
+81
View File
@@ -0,0 +1,81 @@
var TYPE = require('../../tokenizer').TYPE;
var WHITESPACE = TYPE.WhiteSpace;
var COMMENT = TYPE.Comment;
var EXCLAMATIONMARK = TYPE.ExclamationMark;
var ATRULE = TYPE.Atrule;
var CDO = TYPE.CDO;
var CDC = TYPE.CDC;
function consumeRaw(startToken) {
return this.Raw(startToken, 0, 0, false, false);
}
module.exports = {
name: 'StyleSheet',
structure: {
children: [[
'Comment',
'CDO',
'CDC',
'Atrule',
'Rule',
'Raw'
]]
},
parse: function() {
var start = this.scanner.tokenStart;
var children = this.createList();
var child;
scan:
while (!this.scanner.eof) {
switch (this.scanner.tokenType) {
case WHITESPACE:
this.scanner.next();
continue;
case COMMENT:
// ignore comments except exclamation comments (i.e. /*! .. */) on top level
if (this.scanner.source.charCodeAt(this.scanner.tokenStart + 2) !== EXCLAMATIONMARK) {
this.scanner.next();
continue;
}
child = this.Comment();
break;
case CDO: // <!--
child = this.CDO();
break;
case CDC: // -->
child = this.CDC();
break;
// CSS Syntax Module Level 3
// §2.2 Error handling
// At the "top level" of a stylesheet, an <at-keyword-token> starts an at-rule.
case ATRULE:
child = this.parseWithFallback(this.Atrule, consumeRaw);
break;
// Anything else starts a qualified rule ...
default:
child = this.parseWithFallback(this.Rule, consumeRaw);
}
children.push(child);
}
return {
type: 'StyleSheet',
loc: this.getLocation(start, this.scanner.tokenStart),
children: children
};
},
generate: function(node) {
this.children(node);
},
walkContext: 'stylesheet'
};
+53
View File
@@ -0,0 +1,53 @@
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var ASTERISK = TYPE.Asterisk;
var VERTICALLINE = TYPE.VerticalLine;
function eatIdentifierOrAsterisk() {
if (this.scanner.tokenType !== IDENTIFIER &&
this.scanner.tokenType !== ASTERISK) {
this.scanner.error('Identifier or asterisk is expected');
}
this.scanner.next();
}
// ident
// ident|ident
// ident|*
// *
// *|ident
// *|*
// |ident
// |*
module.exports = {
name: 'TypeSelector',
structure: {
name: String
},
parse: function() {
var start = this.scanner.tokenStart;
if (this.scanner.tokenType === VERTICALLINE) {
this.scanner.next();
eatIdentifierOrAsterisk.call(this);
} else {
eatIdentifierOrAsterisk.call(this);
if (this.scanner.tokenType === VERTICALLINE) {
this.scanner.next();
eatIdentifierOrAsterisk.call(this);
}
}
return {
type: 'TypeSelector',
loc: this.getLocation(start, this.scanner.tokenStart),
name: this.scanner.substrToCursor(start)
};
},
generate: function(node) {
this.chunk(node.name);
}
};
+125
View File
@@ -0,0 +1,125 @@
var isHex = require('../../tokenizer').isHex;
var TYPE = require('../../tokenizer').TYPE;
var IDENTIFIER = TYPE.Identifier;
var NUMBER = TYPE.Number;
var PLUSSIGN = TYPE.PlusSign;
var HYPHENMINUS = TYPE.HyphenMinus;
var FULLSTOP = TYPE.FullStop;
var QUESTIONMARK = TYPE.QuestionMark;
function scanUnicodeNumber(scanner) {
for (var pos = scanner.tokenStart + 1; pos < scanner.tokenEnd; pos++) {
var code = scanner.source.charCodeAt(pos);
// break on fullstop or hyperminus/plussign after exponent
if (code === FULLSTOP || code === PLUSSIGN) {
// break token, exclude symbol
scanner.tokenStart = pos;
return false;
}
}
return true;
}
// https://drafts.csswg.org/css-syntax-3/#urange
function scanUnicodeRange(scanner) {
var hexStart = scanner.tokenStart + 1; // skip +
var hexLength = 0;
scan: {
if (scanner.tokenType === NUMBER) {
if (scanner.source.charCodeAt(scanner.tokenStart) !== FULLSTOP && scanUnicodeNumber(scanner)) {
scanner.next();
} else if (scanner.source.charCodeAt(scanner.tokenStart) !== HYPHENMINUS) {
break scan;
}
} else {
scanner.next(); // PLUSSIGN
}
if (scanner.tokenType === HYPHENMINUS) {
scanner.next();
}
if (scanner.tokenType === NUMBER) {
scanner.next();
}
if (scanner.tokenType === IDENTIFIER) {
scanner.next();
}
if (scanner.tokenStart === hexStart) {
scanner.error('Unexpected input', hexStart);
}
}
// validate for U+x{1,6} or U+x{1,6}-x{1,6}
// where x is [0-9a-fA-F]
for (var i = hexStart, wasHyphenMinus = false; i < scanner.tokenStart; i++) {
var code = scanner.source.charCodeAt(i);
if (isHex(code) === false && (code !== HYPHENMINUS || wasHyphenMinus)) {
scanner.error('Unexpected input', i);
}
if (code === HYPHENMINUS) {
// hex sequence shouldn't be an empty
if (hexLength === 0) {
scanner.error('Unexpected input', i);
}
wasHyphenMinus = true;
hexLength = 0;
} else {
hexLength++;
// too long hex sequence
if (hexLength > 6) {
scanner.error('Too long hex sequence', i);
}
}
}
// check we have a non-zero sequence
if (hexLength === 0) {
scanner.error('Unexpected input', i - 1);
}
// U+abc???
if (!wasHyphenMinus) {
// consume as many U+003F QUESTION MARK (?) code points as possible
for (; hexLength < 6 && !scanner.eof; scanner.next()) {
if (scanner.tokenType !== QUESTIONMARK) {
break;
}
hexLength++;
}
}
}
module.exports = {
name: 'UnicodeRange',
structure: {
value: String
},
parse: function() {
var start = this.scanner.tokenStart;
this.scanner.next(); // U or u
scanUnicodeRange(this.scanner);
return {
type: 'UnicodeRange',
loc: this.getLocation(start, this.scanner.tokenStart),
value: this.scanner.substrToCursor(start)
};
},
generate: function(node) {
this.chunk(node.value);
}
};
+49
View File
@@ -0,0 +1,49 @@
var TYPE = require('../../tokenizer').TYPE;
var STRING = TYPE.String;
var URL = TYPE.Url;
var RAW = TYPE.Raw;
var RIGHTPARENTHESIS = TYPE.RightParenthesis;
// url '(' S* (string | raw) S* ')'
module.exports = {
name: 'Url',
structure: {
value: ['String', 'Raw']
},
parse: function() {
var start = this.scanner.tokenStart;
var value;
this.scanner.eat(URL);
this.scanner.skipSC();
switch (this.scanner.tokenType) {
case STRING:
value = this.String();
break;
case RAW:
value = this.Raw(this.scanner.currentToken, 0, RAW, true, false);
break;
default:
this.scanner.error('String or Raw is expected');
}
this.scanner.skipSC();
this.scanner.eat(RIGHTPARENTHESIS);
return {
type: 'Url',
loc: this.getLocation(start, this.scanner.tokenStart),
value: value
};
},
generate: function(node) {
this.chunk('url');
this.chunk('(');
this.node(node.value);
this.chunk(')');
}
};
+19
View File
@@ -0,0 +1,19 @@
module.exports = {
name: 'Value',
structure: {
children: [[]]
},
parse: function() {
var start = this.scanner.tokenStart;
var children = this.readSequence(this.scope.Value);
return {
type: 'Value',
loc: this.getLocation(start, this.scanner.tokenStart),
children: children
};
},
generate: function(node) {
this.children(node);
}
};
+26
View File
@@ -0,0 +1,26 @@
var WHITESPACE = require('../../tokenizer').TYPE.WhiteSpace;
var SPACE = Object.freeze({
type: 'WhiteSpace',
loc: null,
value: ' '
});
module.exports = {
name: 'WhiteSpace',
structure: {
value: String
},
parse: function() {
this.scanner.eat(WHITESPACE);
return SPACE;
// return {
// type: 'WhiteSpace',
// loc: this.getLocation(this.scanner.tokenStart, this.scanner.tokenEnd),
// value: this.scanner.consume(WHITESPACE)
// };
},
generate: function(node) {
this.chunk(node.value);
}
};
+42
View File
@@ -0,0 +1,42 @@
module.exports = {
AnPlusB: require('./AnPlusB'),
Atrule: require('./Atrule'),
AtrulePrelude: require('./AtrulePrelude'),
AttributeSelector: require('./AttributeSelector'),
Block: require('./Block'),
Brackets: require('./Brackets'),
CDC: require('./CDC'),
CDO: require('./CDO'),
ClassSelector: require('./ClassSelector'),
Combinator: require('./Combinator'),
Comment: require('./Comment'),
Declaration: require('./Declaration'),
DeclarationList: require('./DeclarationList'),
Dimension: require('./Dimension'),
Function: require('./Function'),
HexColor: require('./HexColor'),
Identifier: require('./Identifier'),
IdSelector: require('./IdSelector'),
MediaFeature: require('./MediaFeature'),
MediaQuery: require('./MediaQuery'),
MediaQueryList: require('./MediaQueryList'),
Nth: require('./Nth'),
Number: require('./Number'),
Operator: require('./Operator'),
Parentheses: require('./Parentheses'),
Percentage: require('./Percentage'),
PseudoClassSelector: require('./PseudoClassSelector'),
PseudoElementSelector: require('./PseudoElementSelector'),
Ratio: require('./Ratio'),
Raw: require('./Raw'),
Rule: require('./Rule'),
Selector: require('./Selector'),
SelectorList: require('./SelectorList'),
String: require('./String'),
StyleSheet: require('./StyleSheet'),
TypeSelector: require('./TypeSelector'),
UnicodeRange: require('./UnicodeRange'),
Url: require('./Url'),
Value: require('./Value'),
WhiteSpace: require('./WhiteSpace')
};
+9
View File
@@ -0,0 +1,9 @@
var DISALLOW_OF_CLAUSE = false;
module.exports = {
parse: function nth() {
return this.createSingleNodeList(
this.Nth(DISALLOW_OF_CLAUSE)
);
}
};
+9
View File
@@ -0,0 +1,9 @@
var ALLOW_OF_CLAUSE = true;
module.exports = {
parse: function nthWithOfClause() {
return this.createSingleNodeList(
this.Nth(ALLOW_OF_CLAUSE)
);
}
};

Some files were not shown because too many files have changed in this diff Show More