kgcss 1.1.0__tar.gz → 1.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. {kgcss-1.1.0/src/kgcss.egg-info → kgcss-1.2.0}/PKG-INFO +1 -1
  2. {kgcss-1.1.0 → kgcss-1.2.0}/pyproject.toml +18 -8
  3. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/__init__.py +14 -1
  4. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/_version.py +1 -1
  5. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/compat.py +2 -2
  6. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/build.py +6 -4
  7. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/declarations.py +22 -6
  8. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/imports.py +6 -5
  9. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/rules.py +93 -14
  10. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/selector_list.py +9 -8
  11. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/serializer.py +8 -6
  12. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/state.py +8 -1
  13. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/stylesheet.py +103 -9
  14. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/urls.py +8 -6
  15. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/values.py +1 -1
  16. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/fonts.py +3 -1
  17. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/matching.py +42 -18
  18. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/selectors.py +1 -1
  19. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/shorthands.py +23 -18
  20. kgcss-1.2.0/src/kgcss/supports.py +294 -0
  21. {kgcss-1.1.0 → kgcss-1.2.0/src/kgcss.egg-info}/PKG-INFO +1 -1
  22. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss.egg-info/SOURCES.txt +3 -0
  23. {kgcss-1.1.0 → kgcss-1.2.0}/tests/suite.py +1 -1
  24. kgcss-1.2.0/tests/test_api.py +67 -0
  25. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_colors.py +8 -8
  26. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_compat.py +18 -18
  27. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_cssom_declarations.py +3 -3
  28. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_cssom_mutation.py +5 -5
  29. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_cssom_rules.py +32 -0
  30. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_cssom_serialize.py +1 -1
  31. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_cssom_urls.py +14 -0
  32. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_cssom_values.py +2 -2
  33. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_fonts.py +1 -1
  34. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_media.py +7 -4
  35. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_safety.py +3 -3
  36. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_select.py +41 -1
  37. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_select_vs_css_selectors.py +1 -1
  38. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_selectors.py +4 -4
  39. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_serialize.py +1 -1
  40. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_shorthands.py +14 -6
  41. kgcss-1.2.0/tests/test_supports.py +313 -0
  42. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_syntax.py +12 -12
  43. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_threads.py +6 -6
  44. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_tokenizer.py +3 -3
  45. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_writer.py +1 -1
  46. {kgcss-1.1.0 → kgcss-1.2.0}/LICENSE +0 -0
  47. {kgcss-1.1.0 → kgcss-1.2.0}/MANIFEST.in +0 -0
  48. {kgcss-1.1.0 → kgcss-1.2.0}/README.md +0 -0
  49. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/color.c +0 -0
  50. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/kgcss.h +0 -0
  51. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/module.c +0 -0
  52. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/objects.h +0 -0
  53. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/properties.c +0 -0
  54. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/select.c +0 -0
  55. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/selectors.c +0 -0
  56. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/selectors.h +0 -0
  57. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/serialize.c +0 -0
  58. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/syntax.c +0 -0
  59. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/tokenizer.c +0 -0
  60. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/tokenizer_impl.h +0 -0
  61. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/tokens.h +0 -0
  62. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/types.c +0 -0
  63. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/urls.c +0 -0
  64. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/values.c +0 -0
  65. {kgcss-1.1.0 → kgcss-1.2.0}/csrc/writer.c +0 -0
  66. {kgcss-1.1.0 → kgcss-1.2.0}/setup.cfg +0 -0
  67. {kgcss-1.1.0 → kgcss-1.2.0}/setup.py +0 -0
  68. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/_encodings.py +0 -0
  69. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/_kgcss.pyi +0 -0
  70. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/colors.py +0 -0
  71. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/__init__.py +0 -0
  72. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/cssom/exceptions.py +0 -0
  73. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/decode.py +0 -0
  74. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/enums.py +0 -0
  75. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/escaping.py +0 -0
  76. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/grammar.py +0 -0
  77. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/media.py +0 -0
  78. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/py.typed +0 -0
  79. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/syntax.py +0 -0
  80. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss/tokenizer.py +0 -0
  81. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss.egg-info/dependency_links.txt +0 -0
  82. {kgcss-1.1.0 → kgcss-1.2.0}/src/kgcss.egg-info/top_level.txt +0 -0
  83. {kgcss-1.1.0 → kgcss-1.2.0}/tests/__init__.py +0 -0
  84. {kgcss-1.1.0 → kgcss-1.2.0}/tests/conftest.py +0 -0
  85. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/An+B.json +0 -0
  86. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/LICENSE +0 -0
  87. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/README.rst +0 -0
  88. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/VENDORED +0 -0
  89. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/blocks_contents.json +0 -0
  90. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_function_4.json +0 -0
  91. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_functions_5.json +0 -0
  92. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_hexadecimal_3.json +0 -0
  93. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_hexadecimal_4.json +0 -0
  94. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_hsl_3.json +0 -0
  95. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_hsl_4.json +0 -0
  96. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_hwb_4.json +0 -0
  97. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_keywords_3.json +0 -0
  98. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_keywords_4.json +0 -0
  99. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_lab_4.json +0 -0
  100. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_lch_4.json +0 -0
  101. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_oklab_4.json +0 -0
  102. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/color_oklch_4.json +0 -0
  103. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/component_value_list.json +0 -0
  104. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/declaration_list.json +0 -0
  105. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/one_component_value.json +0 -0
  106. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/one_declaration.json +0 -0
  107. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/one_rule.json +0 -0
  108. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/rule_list.json +0 -0
  109. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/stylesheet.json +0 -0
  110. {kgcss-1.1.0 → kgcss-1.2.0}/tests/css-parsing-tests/stylesheet_bytes.json +0 -0
  111. {kgcss-1.1.0 → kgcss-1.2.0}/tests/data/css_selectors_shakespeare.html +0 -0
  112. {kgcss-1.1.0 → kgcss-1.2.0}/tests/selector_oracle.py +0 -0
  113. {kgcss-1.1.0 → kgcss-1.2.0}/tests/strategies.py +0 -0
  114. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_css_parsing_suite.py +0 -0
  115. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_cssom_imports.py +0 -0
  116. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_cssom_properties.py +0 -0
  117. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_decode.py +0 -0
  118. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_grammar.py +0 -0
  119. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_native.py +0 -0
  120. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_properties.py +0 -0
  121. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_readme.py +0 -0
  122. {kgcss-1.1.0 → kgcss-1.2.0}/tests/test_values.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kgcss
3
- Version: 1.1.0
3
+ Version: 1.2.0
4
4
  Summary: Fast and comprehensive CSS handling: tokenizing, parsing, a mutable object model, serialization, selector matching, media queries, colors, fonts and shorthands, with a C99 backend
5
5
  Author-email: Kovid Goyal <kovid@kovidgoyal.net>
6
6
  License-Expression: BSD-3-Clause
@@ -34,7 +34,7 @@ dev = [
34
34
  "hypothesis>=6.100",
35
35
  "setuptools>=77", # for tools/sanitize_tests.py, which builds the extension directly
36
36
  "ruff>=0.8",
37
- "mypy>=1.13",
37
+ "ty>=0.0.1a0",
38
38
  # Select works on any ElementTree-style tree, the tests use lxml trees
39
39
  "lxml>=5",
40
40
  "lxml-stubs>=0.5",
@@ -134,11 +134,21 @@ quote-style = "single"
134
134
  exclude = ["*.md"]
135
135
 
136
136
  # ---------------------------------------------------------------------------
137
- # mypy
137
+ # ty
138
138
  # ---------------------------------------------------------------------------
139
- [tool.mypy]
140
- python_version = "3.14"
141
- strict = true
142
- files = ["src", "tests", "tools", "bench"]
143
- mypy_path = "src"
144
- warn_unreachable = true
139
+ [tool.ty.environment]
140
+ python-version = "3.14"
141
+
142
+ [tool.ty.src]
143
+ include = ["src", "tests", "tools", "bench", "setup.py"]
144
+
145
+ [tool.ty.analysis]
146
+ # Suppress with ty: ignore[rule] comments only
147
+ respect-type-ignore-comments = false
148
+
149
+ [tool.ty.rules]
150
+ unused-ignore-comment = "error"
151
+ possibly-unresolved-reference = "error"
152
+
153
+ [tool.ty.terminal]
154
+ error-on-warning = true
@@ -69,10 +69,17 @@ from kgcss.decode import decode_stylesheet, lookup_encoding
69
69
  from kgcss.escaping import serialize_identifier, serialize_string
70
70
  from kgcss.fonts import FontDict, parse_font, parse_font_family, serialize_font, serialize_font_family
71
71
  from kgcss.grammar import CSS_WIDE_KEYWORDS, is_color, matches
72
- from kgcss.matching import Select
72
+ from kgcss.matching import ElementTreeLike, Select
73
73
  from kgcss.media import MediaFeature, MediaQuery, media_matches, parse_media_queries
74
74
  from kgcss.selectors import INAPPROPRIATE_PSEUDO_CLASSES, rename_classes, rename_ids
75
75
  from kgcss.shorthands import INITIAL_VALUES, condense_shorthands, expand_shorthand, longhands
76
+ from kgcss.supports import (
77
+ SupportsCondition,
78
+ SupportsDeclaration,
79
+ SupportsFunction,
80
+ parse_supports_condition,
81
+ supports_matches,
82
+ )
76
83
  from kgcss.tokenizer import ParseError
77
84
 
78
85
  __all__ = [
@@ -90,6 +97,7 @@ __all__ = [
90
97
  'DeclarationBlock',
91
98
  'DeclarationList',
92
99
  'DocumentRule',
100
+ 'ElementTreeLike',
93
101
  'ErrorHandler',
94
102
  'ExpressionError',
95
103
  'FontDict',
@@ -125,6 +133,9 @@ __all__ = [
125
133
  'StartingStyleRule',
126
134
  'StyleRule',
127
135
  'Stylesheet',
136
+ 'SupportsCondition',
137
+ 'SupportsDeclaration',
138
+ 'SupportsFunction',
128
139
  'SupportsRule',
129
140
  'UnknownAtRule',
130
141
  '__version__',
@@ -147,6 +158,7 @@ __all__ = [
147
158
  'parse_selectors',
148
159
  'parse_style',
149
160
  'parse_stylesheet',
161
+ 'parse_supports_condition',
150
162
  'parse_value',
151
163
  'remove_url_values',
152
164
  'rename_classes',
@@ -159,4 +171,5 @@ __all__ = [
159
171
  'serialize_font_family',
160
172
  'serialize_identifier',
161
173
  'serialize_string',
174
+ 'supports_matches',
162
175
  ]
@@ -1,3 +1,3 @@
1
1
  # License: BSD-3-Clause Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
2
2
 
3
- __version__ = '1.1.0'
3
+ __version__ = '1.2.0'
@@ -912,10 +912,10 @@ def getUrls(sheet: CSSStyleSheet) -> Iterator[str]:
912
912
 
913
913
  def replaceUrls(
914
914
  sheetOrStyle: CSSStyleSheet | CSSStyleDeclaration,
915
- replacer: Callable[[str], str],
915
+ replacer: Callable[[str], str | None],
916
916
  ignoreImportRules: bool = False,
917
917
  ) -> None:
918
- """Replace every URL with replacer(url)."""
918
+ """Replace every URL with replacer(url). A URL for which it returns None is left as it is."""
919
919
  replace_urls(sheetOrStyle._obj, replacer, ignore_imports=ignoreImportRules)
920
920
 
921
921
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  from collections.abc import Iterable, Sequence
6
6
  from enum import Enum, auto
7
- from typing import TYPE_CHECKING, cast
7
+ from typing import cast
8
8
 
9
9
  from kgcss.cssom.rules import (
10
10
  CSS_WHITESPACE,
@@ -49,9 +49,6 @@ from kgcss.syntax import (
49
49
  )
50
50
  from kgcss.tokenizer import TokenStream, TokenType
51
51
 
52
- if TYPE_CHECKING:
53
- from kgcss.cssom.stylesheet import Stylesheet
54
-
55
52
 
56
53
  class Context(Enum):
57
54
  """Where rules are being built, which decides what is valid."""
@@ -387,3 +384,8 @@ def parse_rule_text(text: str, context: Context, log: ErrorHandler | None = None
387
384
  message = state.errors[-1].message if state.errors else 'Invalid rule'
388
385
  raise CSSSyntaxError(f'{message}: {text!r}')
389
386
  return rule
387
+
388
+
389
+ # Names used only in annotations. Imported at the end, after this module is complete, because of
390
+ # import cycles, so that annotations can be evaluated at run time (inspect.signature(), help())
391
+ from kgcss.cssom.stylesheet import Stylesheet # noqa: E402
@@ -3,7 +3,7 @@
3
3
  """Declaration blocks and properties."""
4
4
 
5
5
  from collections.abc import Iterable, Iterator, MutableSequence
6
- from typing import TYPE_CHECKING, cast, overload
6
+ from typing import cast, overload
7
7
  from weakref import ReferenceType, ref
8
8
 
9
9
  from kgcss._kgcss import PropertyData, build_properties
@@ -22,10 +22,6 @@ from kgcss.syntax import (
22
22
  )
23
23
  from kgcss.tokenizer import ParseError, TokenType, tokenize
24
24
 
25
- if TYPE_CHECKING:
26
- from kgcss.cssom.rules import Comment, Rule
27
- from kgcss.cssom.serializer import SerializeOptions
28
-
29
25
  CSS_WHITESPACE = ' \t\n\r\f'
30
26
  CLOSERS = frozenset((TokenType.RIGHT_CURLY, TokenType.RIGHT_PAREN, TokenType.RIGHT_SQUARE))
31
27
 
@@ -257,6 +253,20 @@ class Property(PropertyData):
257
253
  self._parsed = None
258
254
  self._changed()
259
255
 
256
+ def value_to_css(self, options: SerializeOptions | None = None) -> str:
257
+ """The value alone, serialized as in a stylesheet: normalized with the default options ('.50em 0px'
258
+ is '0.5em 0'). value is the text as written. With style='preserve', an unmodified value is written
259
+ as it is in the source."""
260
+ from kgcss.cssom.serializer import DEFAULT_OPTIONS, property_value_text
261
+
262
+ options = options or DEFAULT_OPTIONS
263
+ if options.style == 'preserve' and not self._dirty and self._node is not None and self._value_from_node:
264
+ from kgcss.cssom.serializer import values_complete
265
+
266
+ if values_complete(self._node.value):
267
+ return self.value
268
+ return property_value_text(self, options)
269
+
260
270
  def __repr__(self) -> str:
261
271
  imp = ' !important' if self._priority else ''
262
272
  return f'<Property {self._name}: {self.value!r}{imp}>'
@@ -559,7 +569,7 @@ def block_from_nodes(nodes: NodeList | Iterable[Declaration | Token], parent_rul
559
569
  # The properties are created in C (csrc/properties.c), which also exempts them from garbage
560
570
  # collection: they cannot be part of a reference cycle, see Property.parent.
561
571
  if not isinstance(nodes, NodeList | list):
562
- nodes = cast('list[Declaration | Token]', list(nodes))
572
+ nodes = list(nodes)
563
573
  built, has_comments = build_properties(nodes, Property, ref(block))
564
574
  items = cast('list[Property | Comment]', built)
565
575
  if has_comments:
@@ -608,3 +618,9 @@ def parse_style(text: str, *, log: ErrorHandler | None = None) -> DeclarationBlo
608
618
  block, errors = parse_declarations(text, None, state)
609
619
  block.errors = errors
610
620
  return block
621
+
622
+
623
+ # Names used only in annotations. Imported at the end, after this module is complete, because of
624
+ # import cycles, so that annotations can be evaluated at run time (inspect.signature(), help())
625
+ from kgcss.cssom.rules import Comment, Rule # noqa: E402
626
+ from kgcss.cssom.serializer import SerializeOptions # noqa: E402
@@ -4,16 +4,11 @@
4
4
 
5
5
  import posixpath
6
6
  from collections.abc import Callable
7
- from typing import TYPE_CHECKING
8
7
  from urllib.parse import urljoin, urlsplit, urlunsplit
9
8
 
10
9
  from kgcss.syntax import AtRule, QualifiedRule, parse_block_contents
11
10
  from kgcss.tokenizer import ParseError
12
11
 
13
- if TYPE_CHECKING:
14
- from kgcss.cssom.rules import GroupingRule, ImportRule, Rule
15
- from kgcss.cssom.stylesheet import Stylesheet
16
-
17
12
  # Called with the URL of an imported sheet, resolved against the importing sheet's href.
18
13
  # Returns (encoding, text), where text is str or bytes, or None (or a None text) if the
19
14
  # sheet does not exist. An empty text is an empty sheet.
@@ -253,3 +248,9 @@ def parse_wrapper(text: str) -> GroupingRule:
253
248
  rule = parse_rule_text(text + ' {}', Context.TOP)
254
249
  assert isinstance(rule, GroupingRule)
255
250
  return rule
251
+
252
+
253
+ # Names used only in annotations. Imported at the end, after this module is complete, because of
254
+ # import cycles, so that annotations can be evaluated at run time (inspect.signature(), help())
255
+ from kgcss.cssom.rules import GroupingRule, ImportRule, Rule # noqa: E402
256
+ from kgcss.cssom.stylesheet import Stylesheet # noqa: E402
@@ -5,21 +5,22 @@
5
5
  import threading
6
6
  from collections.abc import Callable, Iterable, Iterator, MutableSequence, Sequence
7
7
  from enum import Enum, unique
8
- from typing import TYPE_CHECKING, ClassVar, Self, final, overload
8
+ from typing import ClassVar, Literal, Self, cast, final, overload
9
9
 
10
10
  from kgcss.cssom.declarations import DeclarationBlock, block_from_nodes, parse_declarations
11
11
  from kgcss.cssom.exceptions import CSSSyntaxError, SelectorSyntaxError
12
- from kgcss.cssom.selector_list import Selector, SelectorList, validate_selector_list
13
- from kgcss.cssom.state import SheetState, SourceLike
12
+ from kgcss.cssom.state import SheetState, SourceLike, SupportsRichComparison
13
+ from kgcss.media import MediaFeature, MediaQuery
14
14
  from kgcss.selectors import compile_selectors
15
+ from kgcss.supports import (
16
+ SupportsCondition,
17
+ SupportsDeclaration,
18
+ SupportsFunction,
19
+ import_condition,
20
+ parse_supports_condition,
21
+ )
15
22
  from kgcss.syntax import AtRule, Declaration, QualifiedRule, Token
16
23
 
17
- if TYPE_CHECKING:
18
- from _typeshed import SupportsRichComparison
19
-
20
- from kgcss.cssom.stylesheet import Stylesheet
21
- from kgcss.media import MediaFeature, MediaQuery
22
-
23
24
  CSS_WHITESPACE = ' \t\n\r\f'
24
25
  # Rules built by the API rather than parsed have no sheet state, and so no sheet lock: this one guards the
25
26
  # lazy creation of their parts, so that concurrent readers get the same objects. It is only taken on first use.
@@ -157,6 +158,7 @@ class Rule:
157
158
  text = serialize(self, SerializeOptions(style='preserve', drop_empty_rules=False))
158
159
  new = _build.parse_rule_text(text, context_of(self))
159
160
  assert type(new) is type(self), (text, new)
161
+ assert isinstance(new, type(self)) # for the type checker
160
162
  return new
161
163
 
162
164
  def __deepcopy__(self, memo: dict[int, object]) -> Self:
@@ -299,9 +301,50 @@ class RuleList(MutableSequence[Rule]):
299
301
  self._items.sort(key=key, reverse=reverse)
300
302
  self._changed()
301
303
 
302
- def of_type(self, *types: RuleType) -> list[Rule]:
303
- """The rules in this list (not recursive) of any of the given types."""
304
- return [r for r in self._items if r.type in types]
304
+ # One type gives a list of its class, for type checkers
305
+ @overload
306
+ def of_type(self, rule_type: Literal[RuleType.STYLE], /) -> list[StyleRule]: ...
307
+ @overload
308
+ def of_type(self, rule_type: Literal[RuleType.IMPORT], /) -> list[ImportRule]: ...
309
+ @overload
310
+ def of_type(self, rule_type: Literal[RuleType.MEDIA], /) -> list[MediaRule]: ...
311
+ @overload
312
+ def of_type(self, rule_type: Literal[RuleType.FONT_FACE], /) -> list[FontFaceRule]: ...
313
+ @overload
314
+ def of_type(self, rule_type: Literal[RuleType.PAGE], /) -> list[PageRule]: ...
315
+ @overload
316
+ def of_type(self, rule_type: Literal[RuleType.MARGIN], /) -> list[MarginRule]: ...
317
+ @overload
318
+ def of_type(self, rule_type: Literal[RuleType.CHARSET], /) -> list[CharsetRule]: ...
319
+ @overload
320
+ def of_type(self, rule_type: Literal[RuleType.NAMESPACE], /) -> list[NamespaceRule]: ...
321
+ @overload
322
+ def of_type(self, rule_type: Literal[RuleType.SUPPORTS], /) -> list[SupportsRule]: ...
323
+ @overload
324
+ def of_type(self, rule_type: Literal[RuleType.CONTAINER], /) -> list[ContainerRule]: ...
325
+ @overload
326
+ def of_type(self, rule_type: Literal[RuleType.LAYER_BLOCK], /) -> list[LayerBlockRule]: ...
327
+ @overload
328
+ def of_type(self, rule_type: Literal[RuleType.LAYER_STATEMENT], /) -> list[LayerStatementRule]: ...
329
+ @overload
330
+ def of_type(self, rule_type: Literal[RuleType.SCOPE], /) -> list[ScopeRule]: ...
331
+ @overload
332
+ def of_type(self, rule_type: Literal[RuleType.STARTING_STYLE], /) -> list[StartingStyleRule]: ...
333
+ @overload
334
+ def of_type(self, rule_type: Literal[RuleType.DOCUMENT], /) -> list[DocumentRule]: ...
335
+ @overload
336
+ def of_type(self, rule_type: Literal[RuleType.NESTED_DECLARATIONS], /) -> list[NestedDeclarationsRule]: ...
337
+ @overload
338
+ def of_type(self, rule_type: Literal[RuleType.COMMENT], /) -> list[Comment]: ...
339
+ @overload
340
+ def of_type(self, rule_type: Literal[RuleType.UNKNOWN], /) -> list[UnknownAtRule]: ...
341
+ @overload
342
+ def of_type(self, *types: RuleType) -> list[Rule]: ...
343
+ def of_type[R: Rule](self, *types: RuleType) -> list[R]:
344
+ """The rules in this list (not recursive) of any of the given types. With one type, type checkers
345
+ know the class of the rules: of_type(RuleType.STYLE) is a list[StyleRule]."""
346
+ # R is the class of the rules of the overload that was chosen
347
+ return cast('list[R]', [r for r in self._items if r.type in types])
305
348
 
306
349
  def __repr__(self) -> str:
307
350
  return f'<RuleList of {len(self._items)} rules>'
@@ -745,6 +788,23 @@ class SupportsRule(GroupingRule):
745
788
  def condition_text(self, value: str) -> None:
746
789
  self.prelude_text = value
747
790
 
791
+ @property
792
+ def condition(self) -> SupportsCondition:
793
+ """The parsed condition (kgcss.supports), cached by text. A condition that does not parse is
794
+ kept, with valid=False. Reading it does not change condition_text."""
795
+ return parse_supports_condition(self.prelude_text)
796
+
797
+ def matches(
798
+ self,
799
+ *,
800
+ declaration: Callable[[SupportsDeclaration], bool],
801
+ function: Callable[[SupportsFunction], bool] | None = None,
802
+ ) -> bool:
803
+ """Whether the condition is true, with the callbacks of kgcss.supports.supports_matches():
804
+ declaration(d) says whether a declaration is supported, function(f) whether selector(),
805
+ font-tech(), font-format() or at-rule() is. A condition that does not parse is false."""
806
+ return self.condition.matches(declaration=declaration, function=function)
807
+
748
808
 
749
809
  @final
750
810
  class ContainerRule(GroupingRule):
@@ -918,6 +978,22 @@ class ImportRule(Rule):
918
978
  self._loaded = loaded
919
979
  return loaded[1]
920
980
 
981
+ @property
982
+ def supports_condition(self) -> SupportsCondition | None:
983
+ """The parsed condition of supports() (kgcss.supports), None if there is none. Like the condition
984
+ of @supports, but it can also be a bare declaration: supports(display: grid)."""
985
+ return None if self._supports is None else import_condition(self._supports)
986
+
987
+ def supports_matches(
988
+ self,
989
+ *,
990
+ declaration: Callable[[SupportsDeclaration], bool],
991
+ function: Callable[[SupportsFunction], bool] | None = None,
992
+ ) -> bool:
993
+ """Whether the condition of supports() is true, as for SupportsRule.matches(). True if there is none."""
994
+ c = self.supports_condition
995
+ return c is None or c.matches(declaration=declaration, function=function)
996
+
921
997
  def _adopt_contents(self) -> None:
922
998
  self.media._owner = self
923
999
  self._loaded = None
@@ -1075,7 +1151,10 @@ class UnknownAtRule(Rule):
1075
1151
  return f' @{self.name}'
1076
1152
 
1077
1153
 
1078
- # At the end, since build imports this module. Used through the module object, so
1079
- # it works whichever of the two modules is imported first.
1154
+ # At the end, since these modules import this one. build and imports are used through the module object, so
1155
+ # that works whichever module is imported first. The names imported from selector_list and stylesheet are only
1156
+ # used in methods and annotations, which are evaluated lazily.
1080
1157
  import kgcss.cssom.build as _build # noqa: E402
1081
1158
  import kgcss.cssom.imports as _imports # noqa: E402
1159
+ from kgcss.cssom.selector_list import Selector, SelectorList, validate_selector_list # noqa: E402
1160
+ from kgcss.cssom.stylesheet import Stylesheet # noqa: E402
@@ -8,10 +8,12 @@ specificity or pseudo-element is first needed.
8
8
  """
9
9
 
10
10
  from collections.abc import Callable, Iterable, Iterator, MutableSequence
11
- from typing import TYPE_CHECKING, overload
11
+ from typing import overload
12
12
 
13
+ from kgcss._kgcss import CompiledSelector
13
14
  from kgcss.cssom.exceptions import SelectorSyntaxError
14
15
  from kgcss.cssom.serializer import normalize_selector
16
+ from kgcss.cssom.state import SupportsRichComparison
15
17
  from kgcss.selectors import (
16
18
  ComplexSelector,
17
19
  NameMap,
@@ -26,13 +28,6 @@ from kgcss.selectors import (
26
28
  from kgcss.syntax import Block, Function, parse_component_value_list
27
29
  from kgcss.tokenizer import TokenType
28
30
 
29
- if TYPE_CHECKING:
30
- from _typeshed import SupportsRichComparison
31
-
32
- from kgcss._kgcss import CompiledSelector
33
- from kgcss.cssom.rules import StyleRule
34
- from kgcss.cssom.stylesheet import Stylesheet
35
-
36
31
  CSS_WHITESPACE = ' \t\n\r\f'
37
32
  INVALID_IN_SELECTORS = frozenset((
38
33
  TokenType.SEMICOLON, TokenType.RIGHT_CURLY, TokenType.RIGHT_PAREN, TokenType.RIGHT_SQUARE,
@@ -400,3 +395,9 @@ def invalid_selectors(sheet: Stylesheet) -> list[tuple[StyleRule, Selector, Sele
400
395
  except SelectorSyntaxError as e:
401
396
  ans.append((rule, selector, e))
402
397
  return ans
398
+
399
+
400
+ # Names used only in annotations. Imported at the end, after this module is complete, because of
401
+ # import cycles, so that annotations can be evaluated at run time (inspect.signature(), help())
402
+ from kgcss.cssom.rules import StyleRule # noqa: E402
403
+ from kgcss.cssom.stylesheet import Stylesheet # noqa: E402
@@ -16,7 +16,7 @@ calibre normalizations (S3). Escapes are always kept as written.
16
16
  import codecs
17
17
  from collections.abc import Iterable, Iterator
18
18
  from dataclasses import dataclass
19
- from typing import TYPE_CHECKING, Final, Literal
19
+ from typing import Final, Literal
20
20
 
21
21
  from kgcss._kgcss import write_declarations as c_write_declarations
22
22
  from kgcss._kgcss import write_values as c_write_values
@@ -26,11 +26,6 @@ from kgcss.escaping import serialize_identifier, serialize_string
26
26
  from kgcss.syntax import Block, ComponentValueList, Declaration, Function, Token, parse_component_value_list
27
27
  from kgcss.tokenizer import TokenType
28
28
 
29
- if TYPE_CHECKING:
30
- from kgcss.cssom.declarations import DeclarationBlock, Property
31
- from kgcss.cssom.rules import Rule
32
- from kgcss.cssom.stylesheet import Stylesheet
33
-
34
29
 
35
30
  @dataclass(frozen=True, slots=True, kw_only=True)
36
31
  class SerializeOptions:
@@ -869,3 +864,10 @@ def encode_text(text: str, charset: str | None) -> bytes:
869
864
  encoding = lookup_encoding(charset) if charset else None
870
865
  codec = python_codec(encoding) if encoding else 'utf-8'
871
866
  return text.encode(codec, 'kgcss-css-escape')
867
+
868
+
869
+ # Names used only in annotations. Imported at the end, after this module is complete, because of
870
+ # import cycles, so that annotations can be evaluated at run time (inspect.signature(), help())
871
+ from kgcss.cssom.declarations import DeclarationBlock, Property # noqa: E402
872
+ from kgcss.cssom.rules import Rule # noqa: E402
873
+ from kgcss.cssom.stylesheet import Stylesheet # noqa: E402
@@ -7,7 +7,7 @@ import threading
7
7
  from collections.abc import Callable
8
8
  from dataclasses import dataclass
9
9
  from types import TracebackType
10
- from typing import Protocol
10
+ from typing import Protocol, Self
11
11
 
12
12
  from kgcss.tokenizer import ParseError, TokenStream
13
13
 
@@ -19,6 +19,13 @@ type ErrorHandler = Callable[[ParseError], None] | logging.Logger
19
19
  SYNTAX_ERROR_KINDS = frozenset(('invalid-rule', 'invalid-declaration'))
20
20
 
21
21
 
22
+ class SupportsRichComparison(Protocol):
23
+ """A sort key: a value that can be compared with others of its kind. Like typeshed's protocol of the
24
+ same name, which only exists for type checkers, so it cannot be used in annotations evaluated at run time."""
25
+
26
+ def __lt__(self, other: Self, /) -> bool: ...
27
+
28
+
22
29
  class SourceLike(Protocol):
23
30
  """Where an object came from. Syntax nodes and tokens satisfy this, so
24
31
  parsed rules simply keep their syntax node."""
@@ -3,16 +3,31 @@
3
3
  """The Stylesheet class, parse_stylesheet() and parse_rule()."""
4
4
 
5
5
  from collections.abc import Iterator, MutableMapping, Sequence
6
- from typing import TYPE_CHECKING
6
+ from typing import Literal, overload
7
7
 
8
8
  from kgcss.cssom.rules import (
9
9
  CharsetRule,
10
+ Comment,
11
+ ContainerRule,
12
+ DocumentRule,
13
+ FontFaceRule,
14
+ ImportRule,
15
+ LayerBlockRule,
16
+ LayerStatementRule,
10
17
  LazyBlockRule,
18
+ MarginRule,
19
+ MediaRule,
11
20
  NamespaceRule,
12
21
  NestedDeclarationsRule,
22
+ PageRule,
13
23
  Rule,
14
24
  RuleList,
15
25
  RuleType,
26
+ ScopeRule,
27
+ StartingStyleRule,
28
+ StyleRule,
29
+ SupportsRule,
30
+ UnknownAtRule,
16
31
  delete_from,
17
32
  insert_into,
18
33
  set_sheet,
@@ -22,12 +37,6 @@ from kgcss.decode import Buffer
22
37
  from kgcss.syntax import parse_stylesheet as parse_syntax_tree
23
38
  from kgcss.tokenizer import ParseError
24
39
 
25
- if TYPE_CHECKING:
26
- from kgcss.cssom.declarations import DeclarationBlock
27
- from kgcss.cssom.imports import ImportFetcher
28
- from kgcss.cssom.rules import ImportRule
29
- from kgcss.cssom.serializer import SerializeOptions
30
-
31
40
 
32
41
  class NamespaceMap(MutableMapping[str, str]):
33
42
  """The namespaces of a sheet, prefix to URI, backed by its @namespace rules. The default namespace
@@ -155,6 +164,86 @@ class Stylesheet:
155
164
  index = i + 1
156
165
  return insert_into(rules, rule, index, Context.TOP)
157
166
 
167
+ # One type gives rules of its class, for type checkers
168
+ @overload
169
+ def iter_rules(
170
+ self, rule_type: Literal[RuleType.STYLE], /, *, recursive: bool = True, follow_imports: bool = False
171
+ ) -> Iterator[StyleRule]: ...
172
+ @overload
173
+ def iter_rules(
174
+ self, rule_type: Literal[RuleType.IMPORT], /, *, recursive: bool = True, follow_imports: bool = False
175
+ ) -> Iterator[ImportRule]: ...
176
+ @overload
177
+ def iter_rules(
178
+ self, rule_type: Literal[RuleType.MEDIA], /, *, recursive: bool = True, follow_imports: bool = False
179
+ ) -> Iterator[MediaRule]: ...
180
+ @overload
181
+ def iter_rules(
182
+ self, rule_type: Literal[RuleType.FONT_FACE], /, *, recursive: bool = True, follow_imports: bool = False
183
+ ) -> Iterator[FontFaceRule]: ...
184
+ @overload
185
+ def iter_rules(
186
+ self, rule_type: Literal[RuleType.PAGE], /, *, recursive: bool = True, follow_imports: bool = False
187
+ ) -> Iterator[PageRule]: ...
188
+ @overload
189
+ def iter_rules(
190
+ self, rule_type: Literal[RuleType.MARGIN], /, *, recursive: bool = True, follow_imports: bool = False
191
+ ) -> Iterator[MarginRule]: ...
192
+ @overload
193
+ def iter_rules(
194
+ self, rule_type: Literal[RuleType.CHARSET], /, *, recursive: bool = True, follow_imports: bool = False
195
+ ) -> Iterator[CharsetRule]: ...
196
+ @overload
197
+ def iter_rules(
198
+ self, rule_type: Literal[RuleType.NAMESPACE], /, *, recursive: bool = True, follow_imports: bool = False
199
+ ) -> Iterator[NamespaceRule]: ...
200
+ @overload
201
+ def iter_rules(
202
+ self, rule_type: Literal[RuleType.SUPPORTS], /, *, recursive: bool = True, follow_imports: bool = False
203
+ ) -> Iterator[SupportsRule]: ...
204
+ @overload
205
+ def iter_rules(
206
+ self, rule_type: Literal[RuleType.CONTAINER], /, *, recursive: bool = True, follow_imports: bool = False
207
+ ) -> Iterator[ContainerRule]: ...
208
+ @overload
209
+ def iter_rules(
210
+ self, rule_type: Literal[RuleType.LAYER_BLOCK], /, *, recursive: bool = True, follow_imports: bool = False
211
+ ) -> Iterator[LayerBlockRule]: ...
212
+ @overload
213
+ def iter_rules(
214
+ self, rule_type: Literal[RuleType.LAYER_STATEMENT], /, *, recursive: bool = True, follow_imports: bool = False
215
+ ) -> Iterator[LayerStatementRule]: ...
216
+ @overload
217
+ def iter_rules(
218
+ self, rule_type: Literal[RuleType.SCOPE], /, *, recursive: bool = True, follow_imports: bool = False
219
+ ) -> Iterator[ScopeRule]: ...
220
+ @overload
221
+ def iter_rules(
222
+ self, rule_type: Literal[RuleType.STARTING_STYLE], /, *, recursive: bool = True, follow_imports: bool = False
223
+ ) -> Iterator[StartingStyleRule]: ...
224
+ @overload
225
+ def iter_rules(
226
+ self, rule_type: Literal[RuleType.DOCUMENT], /, *, recursive: bool = True, follow_imports: bool = False
227
+ ) -> Iterator[DocumentRule]: ...
228
+ @overload
229
+ def iter_rules(
230
+ self,
231
+ rule_type: Literal[RuleType.NESTED_DECLARATIONS],
232
+ /,
233
+ *,
234
+ recursive: bool = True,
235
+ follow_imports: bool = False,
236
+ ) -> Iterator[NestedDeclarationsRule]: ...
237
+ @overload
238
+ def iter_rules(
239
+ self, rule_type: Literal[RuleType.COMMENT], /, *, recursive: bool = True, follow_imports: bool = False
240
+ ) -> Iterator[Comment]: ...
241
+ @overload
242
+ def iter_rules(
243
+ self, rule_type: Literal[RuleType.UNKNOWN], /, *, recursive: bool = True, follow_imports: bool = False
244
+ ) -> Iterator[UnknownAtRule]: ...
245
+ @overload
246
+ def iter_rules(self, *types: RuleType, recursive: bool = True, follow_imports: bool = False) -> Iterator[Rule]: ...
158
247
  def iter_rules(self, *types: RuleType, recursive: bool = True, follow_imports: bool = False) -> Iterator[Rule]:
159
248
  """All rules in document order, optionally only of the given types.
160
249
 
@@ -164,8 +253,6 @@ class Stylesheet:
164
253
  sheets follow their @import rule, loading them if needed; their
165
254
  parent_style_sheet is the imported sheet.
166
255
  """
167
- from kgcss.cssom.rules import ImportRule
168
-
169
256
  stack: list[Iterator[Rule]] = [iter(self.rules)]
170
257
  while stack:
171
258
  rule = next(stack[-1], None)
@@ -356,3 +443,10 @@ def parse_rule(text: str, *, log: ErrorHandler | None = None) -> Rule:
356
443
  from kgcss.cssom.build import Context, parse_rule_text
357
444
 
358
445
  return parse_rule_text(text, Context.TOP, log)
446
+
447
+
448
+ # Names used only in annotations. Imported at the end, after this module is complete, because of
449
+ # import cycles, so that annotations can be evaluated at run time (inspect.signature(), help())
450
+ from kgcss.cssom.declarations import DeclarationBlock # noqa: E402
451
+ from kgcss.cssom.imports import ImportFetcher # noqa: E402
452
+ from kgcss.cssom.serializer import SerializeOptions # noqa: E402