This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

84 lignes
2.6 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. def test_include(self):
  57. fn = os.path.join(NEARLEY_PATH, 'test/grammars/folder-test.ne')
  58. with open(fn) as f:
  59. grammar = f.read()
  60. code = create_code_for_nearley_grammar(grammar, 'main', BUILTIN_PATH, os.path.dirname(fn))
  61. d = {}
  62. exec (code, d)
  63. parse = d['parse']
  64. parse('a')
  65. parse('b')
  66. if __name__ == '__main__':
  67. unittest.main()