flexr 2.1.0 → 2.2.0

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 (124) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +33 -0
  3. data/README.md +4 -0
  4. data/benchmark/dfa_stretch.rb +149 -0
  5. data/benchmark/lrama_lexer.rb +79 -96
  6. data/benchmark/regexp_parser_corpus.rb +35 -0
  7. data/benchmark/regexp_parser_parity.rb +89 -0
  8. data/benchmark/regexp_parser_scanner.rb +159 -0
  9. data/docs/README.md +4 -1
  10. data/docs/adr/0021-ruby-34-minimum.md +23 -0
  11. data/docs/adr/0022-immutable-tokens-and-locations.md +22 -0
  12. data/docs/adr/0023-stable-explicit-firstmatch.md +21 -0
  13. data/docs/adr/0024-opt-in-ractor-sharing.md +24 -0
  14. data/docs/adr/0025-explicit-whole-token-acceleration.md +26 -0
  15. data/docs/adr/0026-retain-direct-dispatch.md +22 -0
  16. data/docs/adr/0033-action-free-recognition.md +33 -0
  17. data/docs/adr/0034-lexer-checkpoints.md +25 -0
  18. data/docs/adr/0035-parser-token-expectations.md +27 -0
  19. data/docs/adr/0038-replay-named-regexp-captures.md +23 -0
  20. data/docs/adr/0039-input-stack.md +25 -0
  21. data/docs/adr/0040-runtime-delimiters.md +23 -0
  22. data/docs/adr/0041-post-lexical-indentation.md +24 -0
  23. data/docs/adr/0042-capture-delegation.md +23 -0
  24. data/docs/adr/0043-expand-reusable-rules-explicitly.md +27 -0
  25. data/docs/adr/0044-import-oedipus-firstmatch.md +26 -0
  26. data/docs/assets/playground-absence-and-diagnostics.gif +0 -0
  27. data/docs/explanation/backends.md +5 -4
  28. data/docs/how-to/integrate-with-lrama.md +9 -8
  29. data/docs/how-to/integrate-with-racc.md +9 -0
  30. data/docs/how-to/migrate-from-oedipus-lex.md +43 -0
  31. data/docs/how-to/parser-driven-lexing.md +48 -0
  32. data/docs/how-to/try-playground-demos.md +13 -0
  33. data/docs/internals/regexp-parser-experiment.md +67 -0
  34. data/docs/perf-log.md +120 -8
  35. data/docs/reference/README.md +1 -1
  36. data/docs/reference/actions.md +106 -0
  37. data/docs/reference/cli.md +75 -4
  38. data/docs/reference/diagnostics.md +3 -9
  39. data/docs/reference/dsl.md +66 -3
  40. data/docs/reference/public-api.md +8 -1
  41. data/docs/reference/regexp.md +27 -4
  42. data/docs/reference/ruby-lsp.md +15 -0
  43. data/docs/reference/runtime.md +163 -2
  44. data/docs/tutorial/build-a-calculator-parser.md +47 -0
  45. data/examples/with_lrama/README.md +3 -3
  46. data/lib/flexr/automaton/accel.rb +1 -0
  47. data/lib/flexr/automaton/compiler.rb +15 -0
  48. data/lib/flexr/automaton/dfa.rb +0 -33
  49. data/lib/flexr/automaton/keyword_tables.rb +14 -8
  50. data/lib/flexr/automaton/reference_dfa.rb +38 -0
  51. data/lib/flexr/cli.rb +118 -18
  52. data/lib/flexr/codegen/table.rb +7 -0
  53. data/lib/flexr/configuration.rb +18 -1
  54. data/lib/flexr/dsl.rb +14 -3
  55. data/lib/flexr/generated.rb +4 -0
  56. data/lib/flexr/generator.rb +39 -7
  57. data/lib/flexr/importer/oedipus_lex.rb +229 -0
  58. data/lib/flexr/importer.rb +7 -2
  59. data/lib/flexr/ir.rb +1 -1
  60. data/lib/flexr/options.rb +3 -0
  61. data/lib/flexr/project_template.rb +46 -0
  62. data/lib/flexr/project_templates/common/.gitignore +1 -0
  63. data/lib/flexr/project_templates/common/lexer.flexr.rb +12 -0
  64. data/lib/flexr/project_templates/common/test_calculator.rb +15 -0
  65. data/lib/flexr/project_templates/lrama/Gemfile +9 -0
  66. data/lib/flexr/project_templates/lrama/README.md +17 -0
  67. data/lib/flexr/project_templates/lrama/Rakefile +18 -0
  68. data/lib/flexr/project_templates/lrama/calculator.rb +28 -0
  69. data/lib/flexr/project_templates/lrama/parser.y +72 -0
  70. data/lib/flexr/project_templates/racc/Gemfile +8 -0
  71. data/lib/flexr/project_templates/racc/README.md +15 -0
  72. data/lib/flexr/project_templates/racc/Rakefile +14 -0
  73. data/lib/flexr/project_templates/racc/calculator.rb +22 -0
  74. data/lib/flexr/project_templates/racc/parser.y +19 -0
  75. data/lib/flexr/regexp/ast.rb +2 -0
  76. data/lib/flexr/regexp/parser.rb +13 -11
  77. data/lib/flexr/regexp/tokenizer.rb +2 -2
  78. data/lib/flexr/rules.rb +53 -0
  79. data/lib/flexr/runtime/buffer.rb +1 -1
  80. data/lib/flexr/runtime/captures.rb +46 -0
  81. data/lib/flexr/runtime/channels.rb +2 -1
  82. data/lib/flexr/runtime/checkpoint.rb +116 -0
  83. data/lib/flexr/runtime/core.rb +55 -43
  84. data/lib/flexr/runtime/delegation.rb +123 -0
  85. data/lib/flexr/runtime/delimiters.rb +89 -0
  86. data/lib/flexr/runtime/firstmatch.rb +266 -0
  87. data/lib/flexr/runtime/indentation.rb +235 -0
  88. data/lib/flexr/runtime/input_stack.rb +48 -0
  89. data/lib/flexr/runtime/interpreter.rb +36 -314
  90. data/lib/flexr/runtime/recognizer.rb +106 -0
  91. data/lib/flexr/runtime.rb +10 -0
  92. data/lib/flexr/skeleton/verification.rb +103 -0
  93. data/lib/flexr/skeleton.rb +208 -0
  94. data/lib/flexr/source/fixes.rb +145 -0
  95. data/lib/flexr/source/prism_reader.rb +187 -25
  96. data/lib/flexr/testing.rb +5 -2
  97. data/lib/flexr/unicode/reference_regexp.rb +29 -11
  98. data/lib/flexr/version.rb +1 -1
  99. data/lib/ruby_lsp/flexr/addon.rb +88 -13
  100. data/lib/ruby_lsp/flexr/navigation.rb +231 -0
  101. data/lib/ruby_lsp/flexr/ranges.rb +40 -0
  102. data/sig/flexr.rbs +33 -3
  103. data/site/README.md +22 -7
  104. data/site/ruby/presets/heredoc.flexr.rb +15 -0
  105. data/site/ruby/presets/html_javascript.rb +12 -0
  106. data/site/ruby/presets/html_js.flexr.rb +14 -0
  107. data/site/ruby/presets/indentation.flexr.rb +14 -0
  108. data/site/scripts/prepare-playground.mjs +16 -6
  109. data/site/scripts/stable-release.mjs +4 -1
  110. data/site/src/content/docs/learn/parser-integration.md +23 -8
  111. data/site/src/content/docs/reference/cli.md +3 -0
  112. data/site/src/content/docs/reference/dsl.md +1 -0
  113. data/site/src/content/docs/reference/runtime.md +26 -0
  114. data/site/src/pages/playground.astro +15 -1
  115. data/site/src/playground/client.js +30 -1
  116. data/site/src/playground/issue.mjs +19 -0
  117. data/site/src/playground/runtime.mjs +4 -3
  118. data/site/src/playground/worker.mjs +1 -1
  119. data/site/tests/browser/playground.spec.mjs +64 -0
  120. data/site/tests/playground-issue.test.mjs +15 -0
  121. data/site/tests/playground-release.test.mjs +62 -11
  122. data/site/tests/playground-runtime.test.mjs +48 -0
  123. data/test/ruby_lsp_addon_spec.rb +174 -0
  124. metadata +63 -1
@@ -0,0 +1,231 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyLsp
4
+ module Flexr
5
+ module Navigation
6
+ module_function
7
+
8
+ def lexer_class?(node)
9
+ return false unless node.is_a?(Prism::ClassNode) && node.superclass
10
+
11
+ node.superclass.slice.delete(" ").delete_prefix("::") == "Flexr::Lexer"
12
+ end
13
+
14
+ def specification_at(reference, source)
15
+ offset = reference.location.start_offset
16
+ program = Prism.parse(source).value
17
+ pending = [program]
18
+ scope = nil
19
+ until pending.empty?
20
+ node = pending.pop
21
+ next unless (node.location.start_offset...node.location.end_offset).cover?(offset)
22
+
23
+ scope = node if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode) || node.is_a?(Prism::SingletonClassNode)
24
+ pending.concat(node.compact_child_nodes)
25
+ end
26
+ Specification.new(scope) if lexer_class?(scope)
27
+ end
28
+
29
+ class Specification
30
+ CompletionSite = Data.define(:location, :prefix)
31
+ STATE_CHANGES = %i[begin_state push push_state state=].freeze
32
+ BLOCKS = %i[state all_states].freeze
33
+ DECLARATIONS = %i[rule state all_states emits keywords on_eof].freeze
34
+
35
+ def initialize(klass)
36
+ @klass = klass
37
+ @declarations = declarations(klass.body).flat_map { |call| [call, *nested_declarations(call)] }
38
+ end
39
+
40
+ def state_definitions(reference, call)
41
+ return [] unless action_call?(call) && STATE_CHANGES.include?(call.name)
42
+ return [] unless same_location?(arguments(call).first, reference)
43
+
44
+ name = literal_name(reference)
45
+ return [] unless name
46
+
47
+ @declarations.select { |declaration| declaration.name == :state && declaration.block }.flat_map do |declaration|
48
+ arguments(declaration).filter_map { |node| node.location if literal_name(node) == name }
49
+ end
50
+ end
51
+
52
+ def completion_site(node, call, source:, recover_utf8:)
53
+ return unless node.equal?(call)
54
+
55
+ if call.name == :emit && action_call?(call)
56
+ return symbol_site(arguments(call).first) if arguments(call).drop(1).all? { |argument| individually_located?(argument) }
57
+
58
+ return
59
+ end
60
+ return unless %i[rule on_eof].include?(call.name) && @declarations.any? { |declaration| same_location?(declaration, call) }
61
+
62
+ symbol_site(keyword_value(call, :emit)) || recovered_emit_site(call, source, recover_utf8)
63
+ end
64
+
65
+ def token_names(excluding:)
66
+ @declarations.flat_map do |call|
67
+ case call.name
68
+ when :emits
69
+ arguments(call).flat_map { |argument| literal_names(argument) }
70
+ when :rule
71
+ symbol = keyword_value(call, :emit)
72
+ same_location?(symbol, excluding) ? [] : [literal_name(symbol)]
73
+ when :keywords
74
+ [literal_name(keyword_value(call, :among)), *keyword_token_names(arguments(call).first)]
75
+ else
76
+ []
77
+ end
78
+ end.compact.uniq.sort
79
+ end
80
+
81
+ def outline(ranges)
82
+ symbols(@klass.body, ranges)
83
+ end
84
+
85
+ private
86
+
87
+ def symbol_site(node)
88
+ CompletionSite.new(node.location, node.unescaped) if node.is_a?(Prism::SymbolNode)
89
+ end
90
+
91
+ def individually_located?(argument)
92
+ argument.is_a?(Prism::CallNode) || argument.is_a?(Prism::ConstantReadNode) || argument.is_a?(Prism::ConstantPathNode)
93
+ end
94
+
95
+ def recovered_emit_site(declaration, source, recover_utf8)
96
+ body = declaration.block&.body
97
+ return unless body.is_a?(Prism::StatementsNode)
98
+
99
+ emit = body.body.reverse.find { |statement| !statement.is_a?(Prism::MissingNode) }
100
+ return unless emit.is_a?(Prism::CallNode) && emit.name == :emit && action_call?(emit)
101
+
102
+ if emit.arguments
103
+ return symbol_site(arguments(emit).first) if recover_utf8 && arguments(emit).one? && !emit.location.slice_lines.ascii_only?
104
+
105
+ return
106
+ end
107
+
108
+ # Without parentheses Prism leaves the trailing colon outside the recovered call.
109
+ offset = emit.message_loc.end_offset
110
+ suffix = source.byteslice(offset..)
111
+ colon = /\A[ \t]+(:)(?=[ \t]*(?:[}#\r\n]|\z))/.match(suffix)
112
+ return unless colon
113
+
114
+ location = emit.message_loc.copy(start_offset: offset + colon.begin(1), length: 1)
115
+ CompletionSite.new(location, "")
116
+ end
117
+
118
+ def declarations(body)
119
+ return [] unless body.is_a?(Prism::StatementsNode)
120
+
121
+ body.body.select { |call| call.is_a?(Prism::CallNode) && !call.receiver && DECLARATIONS.include?(call.name) }
122
+ end
123
+
124
+ def nested_declarations(call)
125
+ return [] unless BLOCKS.include?(call.name) && call.block.is_a?(Prism::BlockNode)
126
+
127
+ declarations(call.block.body).flat_map { |nested| [nested, *nested_declarations(nested)] }
128
+ end
129
+
130
+ def action_call?(call)
131
+ return false unless call && (!call.receiver || call.receiver.is_a?(Prism::SelfNode))
132
+
133
+ @declarations.any? do |declaration|
134
+ block = declaration.block
135
+ %i[rule on_eof].include?(declaration.name) && block.is_a?(Prism::BlockNode) &&
136
+ (block.location.start_offset...block.location.end_offset).cover?(call.location.start_offset)
137
+ end
138
+ end
139
+
140
+ def same_location?(node, other)
141
+ node && node.location.start_offset == other.location.start_offset && node.location.end_offset == other.location.end_offset
142
+ end
143
+
144
+ def arguments(call)
145
+ call.arguments&.arguments || []
146
+ end
147
+
148
+ def keyword_value(call, key)
149
+ options = arguments(call).last
150
+ return unless options.is_a?(Prism::KeywordHashNode)
151
+
152
+ pair = options.elements.find { |item| item.is_a?(Prism::AssocNode) && literal_name(item.key) == key.to_s }
153
+ pair&.value
154
+ end
155
+
156
+ def literal_name(node)
157
+ node.unescaped if node.is_a?(Prism::SymbolNode) || node.is_a?(Prism::StringNode)
158
+ end
159
+
160
+ def literal_names(node)
161
+ return node.elements.flat_map { |item| literal_names(item) } if node.is_a?(Prism::ArrayNode)
162
+
163
+ [literal_name(node)]
164
+ end
165
+
166
+ def keyword_token_names(node)
167
+ case node
168
+ when Prism::ArrayNode
169
+ literal_names(node).compact.map(&:upcase)
170
+ when Prism::HashNode
171
+ node.elements.grep(Prism::AssocNode).map { |pair| literal_name(pair.value) }
172
+ else
173
+ []
174
+ end
175
+ end
176
+
177
+ def symbols(body, ranges)
178
+ declarations(body).filter_map do |call|
179
+ case call.name
180
+ when :rule
181
+ pattern = arguments(call).first
182
+ label = pattern&.slice.to_s.lines.first.to_s.strip
183
+ name = label.empty? ? "rule" : "rule #{label}"
184
+ document_symbol(call, name, Constant::SymbolKind::METHOD, pattern&.location, [], ranges)
185
+ when :state, :all_states
186
+ next unless call.block.is_a?(Prism::BlockNode)
187
+
188
+ names = arguments(call).grep_v(Prism::KeywordHashNode)
189
+ name = [call.name, *names.map(&:slice)].join(" ")
190
+ selection = names.one? ? names.first.location : call.message_loc
191
+ children = symbols(call.block.body, ranges)
192
+ document_symbol(call, name, Constant::SymbolKind::NAMESPACE, selection, children, ranges)
193
+ end
194
+ end
195
+ end
196
+
197
+ def document_symbol(call, name, kind, selection, children, ranges)
198
+ Interface::DocumentSymbol.new(
199
+ name: name, kind: kind, range: ranges.location(call.location),
200
+ selection_range: ranges.location(selection || call.message_loc), children: children
201
+ )
202
+ end
203
+ end
204
+
205
+ class Outline
206
+ def initialize(builder, dispatcher, encoding)
207
+ @builder = builder
208
+ @encoding = encoding
209
+ @lexer_symbols = {}
210
+ dispatcher.register(self, :on_class_node_enter, :on_class_node_leave)
211
+ end
212
+
213
+ def on_class_node_enter(node)
214
+ return unless Navigation.lexer_class?(node)
215
+
216
+ ranges = Ranges.new(node.location.source_lines.join, @encoding)
217
+ symbol = @builder.last
218
+ symbol.children.concat(Specification.new(node).outline(ranges))
219
+ @lexer_symbols[node] = symbol
220
+ end
221
+
222
+ def on_class_node_leave(node)
223
+ @lexer_symbols.delete(node)&.children&.sort_by! do |symbol|
224
+ position = symbol.range.start
225
+ [position.line, position.character]
226
+ end
227
+ end
228
+ end
229
+ end
230
+ end
231
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyLsp
4
+ module Flexr
5
+ class Ranges
6
+ def initialize(source, encoding)
7
+ @source = source
8
+ @encoding = encoding
9
+ @line_starts = [0]
10
+ offset = 0
11
+ source.each_line do |line|
12
+ offset += line.bytesize
13
+ @line_starts << offset if line.end_with?("\n")
14
+ end
15
+ end
16
+
17
+ def location(location)
18
+ range(location.start_offset, location.end_offset)
19
+ end
20
+
21
+ def range(first, last)
22
+ Interface::Range.new(start: position(first), end: position(last))
23
+ end
24
+
25
+ private
26
+
27
+ def position(offset)
28
+ offset = [offset, @source.bytesize].min
29
+ line = (@line_starts.bsearch_index { |start| start > offset } || @line_starts.length) - 1
30
+ column = @source.byteslice(@line_starts.fetch(line)...offset).delete_suffix("\r")
31
+ character = case @encoding
32
+ when Encoding::UTF_8 then column.bytesize
33
+ when Encoding::UTF_16LE then column.encode(Encoding::UTF_16LE).bytesize / 2
34
+ else column.length
35
+ end
36
+ Interface::Position.new(line: line, character: character)
37
+ end
38
+ end
39
+ end
40
+ end
data/sig/flexr.rbs CHANGED
@@ -4,6 +4,7 @@ module Flexr
4
4
  type pattern = String | ::Regexp | Pattern
5
5
  type pattern_operand = pattern | Array[pattern_operand]
6
6
  type token = [untyped, untyped] | Runtime::Token
7
+ type rule_identity = Symbol | Integer
7
8
  type source_location = [Integer, Integer]
8
9
  type cancellation = (^() -> untyped) | (^(Lexer) -> untyped) | _Cancellation | _ContextCancellation
9
10
  type recovery_action = :skip | :raise | :token | :halt
@@ -40,8 +41,23 @@ module Flexr
40
41
  def !: () -> Pattern
41
42
  end
42
43
 
44
+ module Rules
45
+ module Use
46
+ def use: (::Module) -> nil
47
+ end
48
+
49
+ def rule: (pattern | Array[pattern], ?skip: bool, ?emit: untyped, ?followed_by: pattern?, ?channel: Symbol, ?priority: Integer, ?emits: (Symbol | Array[Symbol])?) ?{ () [self: Lexer] -> untyped } -> nil
50
+ def pattern: (*pattern_operand) -> Pattern
51
+ def upto: (pattern_operand) -> Pattern
52
+ end
53
+
54
+ class Recognizer
55
+ def match: (String, Integer) -> [rule_identity, Integer]?
56
+ | [Result] (String, Integer) { (rule_identity, Integer) -> Result } -> Result?
57
+ end
58
+
43
59
  module DSL
44
- def rule: (pattern | Array[pattern], ?skip: bool, ?emit: untyped, ?followed_by: pattern?, ?channel: Symbol, ?priority: Integer) ?{ () [self: Lexer] -> untyped } -> nil
60
+ def rule: (pattern | Array[pattern], ?skip: bool, ?emit: untyped, ?followed_by: pattern?, ?channel: Symbol, ?priority: Integer, ?emits: (Symbol | Array[Symbol])?) ?{ () [self: Lexer] -> untyped } -> nil
45
61
  def pattern: (*pattern_operand) -> Pattern
46
62
  def upto: (pattern_operand) -> Pattern
47
63
  def state: (*(Symbol | String), ?inclusive: bool) { () [self: singleton(Lexer)] -> untyped } -> void
@@ -49,22 +65,29 @@ module Flexr
49
65
  def on_eof: () { () [self: Lexer] -> untyped } -> void
50
66
  def emits: (*untyped) -> void
51
67
  def keywords: (Array[String] | Hash[String, Symbol], among: Symbol) -> nil
68
+ def indentation: (newline: Symbol, indent: Symbol, dedent: Symbol, ?brackets: Array[String], ?tab_width: Integer) -> nil
52
69
  def backend: (:table | :direct | :auto | :firstmatch | String) -> void
53
70
  def token_kind: (:array | :struct | :yield | String) -> void
54
71
  def encoding: (Encoding | String) -> void
55
72
  def option: (*(Symbol | String)) -> void
56
73
  def accel: (:auto | :strscan | :regexp | :none | String) -> void
74
+ def recognizer: (?state: Symbol) -> Recognizer
57
75
  end
58
76
 
59
77
  class Lexer
60
78
  extend DSL
79
+ extend Rules::Use
61
80
 
62
81
  def initialize: (String | _Input, ?filename: String?, ?error_mode: Symbol, ?max_token_size: Integer, ?max_lookahead_size: Integer?, ?max_buffer_size: Integer, ?max_state_stack: Integer, ?max_steps: Integer?, ?cancellation: cancellation?, ?retain_input: bool, ?chunk_size: Integer) -> void
63
- def next_token: () -> token?
82
+ def next_token: (?expect: Array[Symbol]?) -> token?
64
83
  def tokens: (?channels: (:default | :all)) -> Array[token]
65
84
  def each_token: () -> Enumerator[token, self]
66
85
  | () { (untyped, ?untyped) -> untyped } -> self
67
- def racc_next_token: () -> [untyped, untyped]
86
+ def racc_next_token: (?expect: Array[Symbol]?) -> [untyped, untyped]
87
+ def checkpoint: () -> Runtime::Checkpoint
88
+ def restore: (Runtime::Checkpoint) -> self
89
+ def seek: (Integer) -> self
90
+ def push_input: (String | _Input, ?filename: String?) -> nil
68
91
 
69
92
  attr_reader filename: String?
70
93
  attr_reader error_mode: Symbol
@@ -74,6 +97,8 @@ module Flexr
74
97
  attr_writer on_error: error_handler?
75
98
  def input: () -> String
76
99
  def text: () -> String
100
+ def captures: () -> Hash[Symbol, String?]
101
+ def delegate: (singleton(Lexer), capture: Symbol) -> nil
77
102
  def text_bytesize: () -> Integer
78
103
  def last_location: () -> Runtime::Location
79
104
  def byte_pos: () -> Integer
@@ -94,9 +119,14 @@ module Flexr
94
119
  alias state= begin_state
95
120
  def less: (Integer) -> nil
96
121
  def more: () -> true
122
+ def scan_until: (String) -> String?
123
+ def scan_until_line: (String) -> String?
97
124
  end
98
125
 
99
126
  module Runtime
127
+ class Checkpoint
128
+ end
129
+
100
130
  class Token < ::Data
101
131
  def self.new: (?type: untyped, ?value: untyped, ?location: Location?) -> instance
102
132
  attr_reader type: untyped
data/site/README.md CHANGED
@@ -10,14 +10,19 @@ page switch to the same topic under `/flexr/stable/` when that topic exists in
10
10
  the release. If a topic is available in only one version, the link opens
11
11
  Getting started in the other version.
12
12
 
13
- `pnpm dev` and `pnpm build` copy the pinned release's Markdown from Git into
14
- the ignored `src/content/docs/stable/` directory. Fetch the release tag with
15
- `git fetch --tags` if it is missing from your clone. GitHub Pages also uses
16
- that tag's Ruby library and example presets for the public Playground.
13
+ `pnpm dev` and `pnpm build` copy the release's Markdown from Git into the
14
+ ignored `src/content/docs/stable/` directory. The GitHub Pages build selects
15
+ the latest published stable GitHub release. Its tag supplies both the
16
+ documentation and the public Playground's Ruby library and example presets.
17
+ After publishing the gem and GitHub Release, the release workflow refreshes
18
+ Pages when GitHub lists that tag as its latest stable release.
17
19
 
18
- After a new stable gem is public on RubyGems and its Git tag is available,
19
- update `stableReleaseTag` in `scripts/stable-release.mjs`. Run
20
- `FLEXR_PLAYGROUND_STABLE=1 pnpm build` to reproduce the deployment build.
20
+ Local builds default to `v2.0.0`. To reproduce a Pages build for a specific
21
+ release, fetch its tag if needed and pass it to the build:
22
+
23
+ ```sh
24
+ FLEXR_STABLE_RELEASE_TAG=v2.0.0 FLEXR_PLAYGROUND_STABLE=1 pnpm build
25
+ ```
21
26
 
22
27
  ## Local development
23
28
 
@@ -45,6 +50,8 @@ produces them, including the Ruby distribution's license and notice.
45
50
  The first Run lazily creates a worker and downloads the runtime. Every run starts
46
51
  a new Ruby VM, loads the specification, compiles with flexr, executes its actions,
47
52
  and returns tokens, real diagnostics, DOT, trace steps, and generated Ruby.
53
+ When the worker loads flexr, the version label shows the value that the gemspec
54
+ uses for the bundled source.
48
55
  Prism 1.7.0 is available in the pinned Ruby 4.0.0 WASM build, so both runtime and
49
56
  generated execution are tested. The static DSL restrictions of `flexr check` and
50
57
  the generator apply. Specifications must be self-contained or use the bundled
@@ -55,6 +62,14 @@ The original three presets remain editable starting points. TOML, GraphQL, and
55
62
  SQL subset presets load the actual repository example sources, packaged at build
56
63
  time, so their lexer rules are maintained in one place.
57
64
 
65
+ The context presets show `INDENT` and `DEDENT` locations, heredoc bodies delimited
66
+ by the tag in each opener, and JavaScript tokens with locations in the enclosing
67
+ HTML. The HTML preset loads a small JavaScript lexer bundled in the WASM library
68
+ files. To use the generated HTML lexer locally, place the child lexer at
69
+ `playground/html_javascript.rb` on Ruby's load path. A public build offers this
70
+ preset when both Ruby files are in the pinned release.
71
+ [JavaScript lexer source](ruby/presets/html_javascript.rb)
72
+
58
73
  The main page stops execution after five seconds; runtime download/startup has a
59
74
  30-second limit. Source and input are limited to 20,000 characters each, DFA
60
75
  construction to 1024 states, and output to 4 MB. Graphviz loads in a separate
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Lexer < Flexr::Lexer
4
+ rule(/<<(?<tag>[A-Z_]+)\r?\n/) do
5
+ body = scan_until_line(captures.fetch(:tag))
6
+ if body
7
+ emit :HEREDOC, body
8
+ else
9
+ error!("missing heredoc terminator")
10
+ end
11
+ end
12
+
13
+ rule(/[a-z]+/, emit: :WORD)
14
+ rule(/[ \t\r\n]+/, skip: true)
15
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ class PlaygroundJavaScriptLexer < Flexr::Lexer
4
+ token_kind :struct
5
+
6
+ rule("let", emit: :JS_LET)
7
+ rule(/[a-zA-Z_$][a-zA-Z_$0-9]*/, emit: :JS_IDENT)
8
+ rule(/[0-9]+/, emit: :JS_NUMBER)
9
+ rule(%r{[=+*/-]}, emit: :JS_OPERATOR)
10
+ rule(/[();]/, emit: :JS_PUNCTUATION)
11
+ rule(/\s+/, channel: :whitespace)
12
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "playground/html_javascript"
4
+
5
+ class Lexer < Flexr::Lexer
6
+ token_kind :struct
7
+
8
+ rule(%r{<script>(?<js>(?~</script>))</script>}) do
9
+ delegate PlaygroundJavaScriptLexer, capture: :js
10
+ end
11
+ rule(%r{</?[a-zA-Z][^>]*>}, emit: :HTML_TAG)
12
+ rule(/[^<\s]+/, emit: :HTML_TEXT)
13
+ rule(/\s+/, channel: :whitespace)
14
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Lexer < Flexr::Lexer
4
+ token_kind :struct
5
+ indentation newline: :NEWLINE, indent: :INDENT, dedent: :DEDENT, brackets: ["()"], tab_width: 4
6
+
7
+ rule("if", emit: :IF)
8
+ rule(/[a-z_][a-z_0-9]*/, emit: :IDENT)
9
+ rule(":", emit: :COLON)
10
+ rule(/[()]/, emit: :PAREN)
11
+ rule(/\r?\n/, emit: :NEWLINE)
12
+ rule(/[ \t]+/, channel: :whitespace)
13
+ rule(/#[^\r\n]*/, channel: :comment)
14
+ end
@@ -24,8 +24,7 @@ if (useStable) {
24
24
  }
25
25
  files['/app/playground.rb'] = await readFile(path.join(site, 'ruby/playground.rb'), 'utf8');
26
26
  await mkdir(output, { recursive: true });
27
- const payload = JSON.stringify({ files });
28
- await writeFile(path.join(output, 'flexr.json'), payload);
27
+ const readSource = async filename => useStable ? readStableFile(filename) : readFile(path.join(root, filename), 'utf8');
29
28
  const inputs = {
30
29
  toml: 'title = "flexr"',
31
30
  graphql: 'query { user(id: 12) { name } }',
@@ -34,8 +33,7 @@ const inputs = {
34
33
  const presets = {};
35
34
  for (const [name, input] of Object.entries(inputs)) {
36
35
  const filename = `examples/${name}/lexer.flexr.rb`;
37
- const source = useStable ? readStableFile(filename) : await readFile(path.join(root, filename), 'utf8');
38
- presets[name] = { source, input };
36
+ presets[name] = { source: await readSource(filename), input };
39
37
  }
40
38
  const updatedPresets = {
41
39
  absence: '/* 前 */first /* another comment */second',
@@ -43,14 +41,26 @@ const updatedPresets = {
43
41
  keywords: 'if iffy else end',
44
42
  trivia: '# note\nalpha \tbeta',
45
43
  priority: 'if ifx',
44
+ indentation: 'if ready:\n run()\nfinish()',
45
+ heredoc: '<<FIRST\nhello\nFIRST\n<<SECOND\nworld\nSECOND\nnext',
46
46
  };
47
47
  const releasedPresets = useStable ? stableFiles('site/ruby/presets') : null;
48
48
  for (const [name, input] of Object.entries(updatedPresets)) {
49
49
  const filename = `site/ruby/presets/${name}.flexr.rb`;
50
50
  if (releasedPresets && !releasedPresets.includes(filename)) continue;
51
- const source = useStable ? readStableFile(filename) : await readFile(path.join(root, filename), 'utf8');
52
- presets[name] = { source, input };
51
+ presets[name] = { source: await readSource(filename), input };
52
+ }
53
+ const htmlPreset = 'site/ruby/presets/html_js.flexr.rb';
54
+ const javascriptLexer = 'site/ruby/presets/html_javascript.rb';
55
+ if (!releasedPresets || [htmlPreset, javascriptLexer].every(filename => releasedPresets.includes(filename))) {
56
+ files['/app/lib/playground/html_javascript.rb'] = await readSource(javascriptLexer);
57
+ presets['html-js'] = {
58
+ source: await readSource(htmlPreset),
59
+ input: '<p>Before</p>\n<script>\nlet x = 2;\n</script>\n<p>After</p>',
60
+ };
53
61
  }
62
+ const payload = JSON.stringify({ files });
63
+ await writeFile(path.join(output, 'flexr.json'), payload);
54
64
  await writeFile(path.join(output, 'presets.json'), JSON.stringify(presets));
55
65
  const wasm = path.join(site, 'node_modules/@ruby/4.0-wasm-wasi/dist');
56
66
  await cp(path.join(wasm, 'ruby+stdlib.wasm'), path.join(output, 'ruby.wasm'));
@@ -1,7 +1,10 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { fileURLToPath } from 'node:url';
3
3
 
4
- export const stableReleaseTag = 'v2.0.0';
4
+ export const stableReleaseTag = process.env.FLEXR_STABLE_RELEASE_TAG ?? 'v2.0.0';
5
+ if (!/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(stableReleaseTag)) {
6
+ throw new Error('FLEXR_STABLE_RELEASE_TAG must be a vX.Y.Z release tag.');
7
+ }
5
8
 
6
9
  const root = fileURLToPath(new URL('../../', import.meta.url));
7
10
  const ref = `refs/tags/${stableReleaseTag}`;
@@ -7,21 +7,36 @@ The lexer/parser boundary should be explicit: the lexer owns characters and loca
7
7
 
8
8
  ## Racc protocol
9
9
 
10
- For a Racc parser, expose `racc_next_token` as a pair of token kind and semantic value:
10
+ A Racc parser can forward requests from its `next_token` method to the
11
+ Flexr lexer's `racc_next_token` method. It returns a pair of token kind and
12
+ semantic value, with `[false, "$end"]` at EOF.
11
13
 
12
14
  ```ruby
13
- def racc_next_token
14
- token = @lexer.next_token
15
- return [false, false] if token.nil?
16
-
17
- [token.type, token.value]
15
+ def next_token
16
+ @lexer.racc_next_token
18
17
  end
19
18
  ```
20
19
 
21
- Declare the token names in both the lexer and parser grammar. Keep EOF behavior in one adapter rather than duplicating it in every action.
20
+ Declare the token names in both the lexer and parser grammar. Generate a working project with `flexr new NAME --parser racc`. [Racc calculator tutorial](https://github.com/ydah/flexr/blob/main/docs/tutorial/build-a-calculator-parser.md#racc).
21
+
22
+ ## Parser token expectations
23
+
24
+ Pass an array of expected terminal Symbols to `next_token` or `racc_next_token`.
25
+ Flexr applies the lexer backend's rule ordering after filtering by `emit:` or a rule-level `emits:` annotation.
26
+ Skip rules, trivia channels, and unannotated action blocks remain eligible.
27
+
28
+ ```ruby
29
+ # At the start of a Ruby expression, / can begin a regexp literal.
30
+ lexer.next_token(expect: %i[REGEXP INTEGER IDENT])
31
+ # After an operand, / can be division.
32
+ lexer.next_token(expect: %i[DIV PLUS])
33
+ ```
34
+
35
+ The parser adapter supplies the array for each request.
36
+ See the [Ruby slash and JavaScript template examples on GitHub](https://github.com/ydah/flexr/blob/main/docs/how-to/parser-driven-lexing.md).
22
37
 
23
38
  ## Lrama protocol
24
39
 
25
- Lrama integrations use the same basic token/value contract. The example in [`examples/with_lrama`](https://github.com/ydah/flexr/tree/main/examples/with_lrama) shows the complete wiring.
40
+ Lrama generates C. The generated flexr project feeds the lexer's token kinds and values to the compiled parser. Start with `flexr new NAME --parser lrama` and a C compiler. [Lrama calculator tutorial](https://github.com/ydah/flexr/blob/main/docs/tutorial/build-a-calculator-parser.md#lrama).
26
41
 
27
42
  `emits` is useful for diagnostics and parser integration, but it does not replace the parser grammar's token declarations. See [tokens and locations](/flexr/reference/tokens-and-locations/) for return shapes.
@@ -10,6 +10,7 @@ The main commands are:
10
10
  | `flexr check SPEC` | Parse and diagnose a specification |
11
11
  | `flexr generate SPEC -o OUTPUT` | Write generated Ruby |
12
12
  | `flexr trace SPEC INPUT` | Show automaton state, acceptance, and transitions |
13
+ | `flexr new NAME --parser PARSER` | Create a calculator project for Racc or Lrama |
13
14
  | `flexr --help` | Print command and option help |
14
15
 
15
16
  Use `check` in CI and treat warnings according to the compatibility policy of your project. `trace` describes DFA behavior; it is not an input-string logging command.
@@ -20,3 +21,5 @@ bundle exec flexr generate examples/calculator/lexer.flexr.rb -o tmp/calculator_
20
21
  ```
21
22
 
22
23
  For complete options, output formats, and exit status behavior, see the repository's [CLI reference](https://github.com/ydah/flexr/blob/main/docs/reference/cli.md).
24
+
25
+ Follow the [calculator parser tutorial](https://github.com/ydah/flexr/blob/main/docs/tutorial/build-a-calculator-parser.md) to build a new project.
@@ -6,6 +6,7 @@ description: The stable lexer specification methods and their role.
6
6
  | API | Purpose |
7
7
  | --- | --- |
8
8
  | `rule(pattern, skip: false, emit: nil, followed_by: nil)` | Register a matching rule and action |
9
+ | `use(rule_set)` | Insert rules from a module extended with `Flexr::Rules` |
9
10
  | `on_eof` | Define end-of-input behavior |
10
11
  | `emits(*kinds)` | Declare token kinds for diagnostics and parser integration |
11
12
  | `state(name)` | Define a named start condition |
@@ -13,4 +13,30 @@ lexer.each_token { |type, value| consume(type, value) }
13
13
 
14
14
  The runtime tracks byte position, line, column, and the last token location. Buffering and encoding behavior follow the options declared by the lexer. EOF is represented by the runtime's end-of-input result and should be normalized by a parser adapter.
15
15
 
16
+ ## Indentation
17
+
18
+ Use `indentation` when line indentation defines blocks.
19
+ Emit a newline token and skip spaces and comments in the lexer rules.
20
+
21
+ ```ruby
22
+ class LayoutLexer < Flexr::Lexer
23
+ token_kind :struct
24
+ indentation newline: :NEWLINE, indent: :INDENT, dedent: :DEDENT,
25
+ brackets: %w[() [] {}], tab_width: 4
26
+ rule(/\r?\n/, emit: :NEWLINE)
27
+ rule(/[ \t]+/, skip: true)
28
+ rule(/#[^\r\n]*/, skip: true)
29
+ rule(/[a-z]+/, emit: :WORD)
30
+ rule(/[()\[\]{}]/, emit: :BRACKET)
31
+ end
32
+
33
+ LayoutLexer.new("root\n child\nend").tokens.map(&:type)
34
+ # => [:WORD, :NEWLINE, :INDENT, :WORD, :NEWLINE, :DEDENT, :WORD]
35
+ ```
36
+
37
+ Blank and comment-only lines do not affect layout.
38
+ Newlines inside brackets are suppressed.
39
+ Structured layout tokens have a zero-width location at the next content token or at EOF.
40
+ Included inputs have their own indentation levels and emit final dedents before the parent input resumes.
41
+
16
42
  See the repository's [runtime reference](https://github.com/ydah/flexr/blob/main/docs/reference/runtime.md) for constructor options, `less`, `more`, `echo`, state transitions, and error hooks.