This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.3 KiB

  1. from __future__ import absolute_import
  2. import unittest
  3. import logging
  4. import os
  5. import sys
  6. logging.basicConfig(level=logging.INFO)
  7. from lark.tools.nearley import create_code_for_nearley_grammar
  8. NEARLEY_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'nearley'))
  9. BUILTIN_PATH = os.path.join(NEARLEY_PATH, 'builtin')
  10. class TestNearley(unittest.TestCase):
  11. def test_css(self):
  12. css_example_grammar = """
  13. # http://www.w3.org/TR/css3-color/#colorunits
  14. @builtin "whitespace.ne"
  15. @builtin "number.ne"
  16. @builtin "postprocessors.ne"
  17. csscolor -> "#" hexdigit hexdigit hexdigit hexdigit hexdigit hexdigit {%
  18. function(d) {
  19. return {
  20. "r": parseInt(d[1]+d[2], 16),
  21. "g": parseInt(d[3]+d[4], 16),
  22. "b": parseInt(d[5]+d[6], 16),
  23. }
  24. }
  25. %}
  26. | "#" hexdigit hexdigit hexdigit {%
  27. function(d) {
  28. return {
  29. "r": parseInt(d[1]+d[1], 16),
  30. "g": parseInt(d[2]+d[2], 16),
  31. "b": parseInt(d[3]+d[3], 16),
  32. }
  33. }
  34. %}
  35. | "rgb" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ ")" {% $({"r": 4, "g": 8, "b": 12}) %}
  36. | "hsl" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ ")" {% $({"h": 4, "s": 8, "l": 12}) %}
  37. | "rgba" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ "," _ decimal _ ")" {% $({"r": 4, "g": 8, "b": 12, "a": 16}) %}
  38. | "hsla" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ "," _ decimal _ ")" {% $({"h": 4, "s": 8, "l": 12, "a": 16}) %}
  39. hexdigit -> [a-fA-F0-9]
  40. colnum -> unsigned_int {% id %} | percentage {%
  41. function(d) {return Math.floor(d[0]*255); }
  42. %}
  43. """
  44. code = create_code_for_nearley_grammar(css_example_grammar, 'csscolor', BUILTIN_PATH, './')
  45. d = {}
  46. exec (code, d)
  47. parse = d['parse']
  48. c = parse('#a199ff')
  49. assert c['r'] == 161
  50. assert c['g'] == 153
  51. assert c['b'] == 255
  52. c = parse('rgb(255, 70%, 3)')
  53. assert c['r'] == 255
  54. assert c['g'] == 178
  55. assert c['b'] == 3
  56. if __name__ == '__main__':
  57. unittest.main()