zk.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. -- LPEG lexer for the zkas zk language
  2. local l = require('lexer')
  3. local token, word_match = l.token, l.word_match
  4. local P, R, S = lpeg.P, lpeg.R, lpeg.S
  5. local lex = l.new('zk', {fold_by_indentation = true})
  6. -- Whitespace.
  7. local indent = #l.starts_line(S(' \t')) *
  8. (token(l.WHITESPACE, ' ') + token('indent_error', '\t'))^1
  9. lex:add_rule('indent', indent)
  10. lex:add_style('indent_error', {back = l.colors.red})
  11. lex:add_rule('whitespace', token(l.WHITESPACE, S(' \t')^1 + l.newline^1))
  12. -- Comments.
  13. local comment = token(l.COMMENT, '#' * l.nonnewline_esc^0)
  14. lex:add_rule('comment', comment)
  15. -- Strings.
  16. local dq_str = P('U')^-1 * l.range('"', true)
  17. local string = token(l.STRING, dq_str)
  18. lex:add_rule('string', string)
  19. -- Numbers.
  20. local number = token(l.NUMBER, l.integer)
  21. lex:add_rule('number', number)
  22. -- Keywords.
  23. local keyword = token(l.KEYWORD, word_match{
  24. 'k', "field", 'constant', 'witness', 'circuit',
  25. })
  26. lex:add_rule('keyword', keyword)
  27. -- Constants.
  28. local constant = token(l.CONSTANT, word_match{
  29. 'true', 'false',
  30. 'VALUE_COMMIT_VALUE', 'VALUE_COMMIT_RANDOM', 'NULLIFIER_K',
  31. })
  32. lex:add_rule('constant', constant)
  33. -- Types.
  34. local type = token(l.TYPE, word_match{
  35. 'EcPoint', 'EcFixedPoint', 'EcFixedPointBase', 'EcFixedPointShort',
  36. 'EcNiPoint', 'Base', 'BaseArray', 'Scalar', 'ScalarArray',
  37. 'MerklePath', 'Uint32', 'Uint64',
  38. })
  39. lex:add_rule('type', type)
  40. -- Instructions.
  41. local instruction = token('instruction', word_match{
  42. 'ec_add', 'ec_mul', 'ec_mul_base', 'ec_mul_short', 'ec_mul_var_base',
  43. 'ec_get_x', 'ec_get_y',
  44. 'base_add', 'base_mul', 'base_sub',
  45. 'poseidon_hash', 'merkle_root',
  46. 'range_check', 'less_than_strict', 'less_than_loose', 'bool_check',
  47. 'cond_select', 'zero_cond', 'witness_base',
  48. 'constrain_equal_base', 'constrain_equal_point',
  49. 'constrain_instance', 'debug',
  50. })
  51. lex:add_rule('instruction', instruction)
  52. -- Identifiers.
  53. local identifier = token(l.IDENTIFIER, l.word)
  54. lex:add_rule('identifier', identifier)
  55. -- Operators.
  56. local operator = token(l.OPERATOR, S('(){}=;,'))
  57. lex:add_rule('operator', operator)
  58. return lex