Web browser has a CSS parser inside to parse CSS and generate the CSSOM tree according to CSS syntax module, together with the DOM, to build the render tree, which is in turn used by the browser to layout and paint the web page.
CSS syntax is simple, and so the parser will be much simpler than a general programming language parser. A CSS parser contains two main steps:
CSS ↓ (tokenizing by tokenizer) ↓ tokens ↓ (parsing by parser) ↓ AST
Parse tree is a one-to-one mapping from the grammar to a tree-form. AST represents the structure of the code in a compact and useful way that facilitates convenient analysis and further processing. Parsers usually either construct ASTs directly in their actions, or first construct parse trees and then convert them to ASTs.
CSS parsers can also be found inside CSS processors (Sass, Less, PostCSS, etc.) or toolset like CSSTree. These custom open-source CSS parser implementations are W3C spec compliant and focus on CSS analyzing and source-to-source transforming tasks with following expected features:
Custom CSS parsers can define output AST formats themselves and those formats don’t need to be compatible between parsers. The ASTs produced by CSS parsers could then be transformed by plugins, then serialized into pure CSS string by a stringifier.
CSS ↓ (tokenizing by tokenizer) ↓ tokens ↓ (parsing by parser) ↓ AST ↓ (transforming by plugins) ↓ modified AST ↓ (serializing by stringifier) ↓ new CSS
The only requirement for serialization is that it must round-trip with parsing, that is, parsing the stylesheet must produce the same data structures as parsing, serializing, and parsing again, except for consecutive whitespace tokens, which may be collapsed into a single token.
Being able to process and transform CSS before running in browser is powerful and open to a lot of possibilities like using latest CSS features, stripping unused styles, auto vendor prefixing, checking accessibility, optimizing performance, and you name it.