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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +33 -0
- data/README.md +4 -0
- data/benchmark/dfa_stretch.rb +149 -0
- data/benchmark/lrama_lexer.rb +79 -96
- data/benchmark/regexp_parser_corpus.rb +35 -0
- data/benchmark/regexp_parser_parity.rb +89 -0
- data/benchmark/regexp_parser_scanner.rb +159 -0
- data/docs/README.md +4 -1
- data/docs/adr/0021-ruby-34-minimum.md +23 -0
- data/docs/adr/0022-immutable-tokens-and-locations.md +22 -0
- data/docs/adr/0023-stable-explicit-firstmatch.md +21 -0
- data/docs/adr/0024-opt-in-ractor-sharing.md +24 -0
- data/docs/adr/0025-explicit-whole-token-acceleration.md +26 -0
- data/docs/adr/0026-retain-direct-dispatch.md +22 -0
- data/docs/adr/0033-action-free-recognition.md +33 -0
- data/docs/adr/0034-lexer-checkpoints.md +25 -0
- data/docs/adr/0035-parser-token-expectations.md +27 -0
- data/docs/adr/0038-replay-named-regexp-captures.md +23 -0
- data/docs/adr/0039-input-stack.md +25 -0
- data/docs/adr/0040-runtime-delimiters.md +23 -0
- data/docs/adr/0041-post-lexical-indentation.md +24 -0
- data/docs/adr/0042-capture-delegation.md +23 -0
- data/docs/adr/0043-expand-reusable-rules-explicitly.md +27 -0
- data/docs/adr/0044-import-oedipus-firstmatch.md +26 -0
- data/docs/assets/playground-absence-and-diagnostics.gif +0 -0
- data/docs/explanation/backends.md +5 -4
- data/docs/how-to/integrate-with-lrama.md +9 -8
- data/docs/how-to/integrate-with-racc.md +9 -0
- data/docs/how-to/migrate-from-oedipus-lex.md +43 -0
- data/docs/how-to/parser-driven-lexing.md +48 -0
- data/docs/how-to/try-playground-demos.md +13 -0
- data/docs/internals/regexp-parser-experiment.md +67 -0
- data/docs/perf-log.md +120 -8
- data/docs/reference/README.md +1 -1
- data/docs/reference/actions.md +106 -0
- data/docs/reference/cli.md +75 -4
- data/docs/reference/diagnostics.md +3 -9
- data/docs/reference/dsl.md +66 -3
- data/docs/reference/public-api.md +8 -1
- data/docs/reference/regexp.md +27 -4
- data/docs/reference/ruby-lsp.md +15 -0
- data/docs/reference/runtime.md +163 -2
- data/docs/tutorial/build-a-calculator-parser.md +47 -0
- data/examples/with_lrama/README.md +3 -3
- data/lib/flexr/automaton/accel.rb +1 -0
- data/lib/flexr/automaton/compiler.rb +15 -0
- data/lib/flexr/automaton/dfa.rb +0 -33
- data/lib/flexr/automaton/keyword_tables.rb +14 -8
- data/lib/flexr/automaton/reference_dfa.rb +38 -0
- data/lib/flexr/cli.rb +118 -18
- data/lib/flexr/codegen/table.rb +7 -0
- data/lib/flexr/configuration.rb +18 -1
- data/lib/flexr/dsl.rb +14 -3
- data/lib/flexr/generated.rb +4 -0
- data/lib/flexr/generator.rb +39 -7
- data/lib/flexr/importer/oedipus_lex.rb +229 -0
- data/lib/flexr/importer.rb +7 -2
- data/lib/flexr/ir.rb +1 -1
- data/lib/flexr/options.rb +3 -0
- data/lib/flexr/project_template.rb +46 -0
- data/lib/flexr/project_templates/common/.gitignore +1 -0
- data/lib/flexr/project_templates/common/lexer.flexr.rb +12 -0
- data/lib/flexr/project_templates/common/test_calculator.rb +15 -0
- data/lib/flexr/project_templates/lrama/Gemfile +9 -0
- data/lib/flexr/project_templates/lrama/README.md +17 -0
- data/lib/flexr/project_templates/lrama/Rakefile +18 -0
- data/lib/flexr/project_templates/lrama/calculator.rb +28 -0
- data/lib/flexr/project_templates/lrama/parser.y +72 -0
- data/lib/flexr/project_templates/racc/Gemfile +8 -0
- data/lib/flexr/project_templates/racc/README.md +15 -0
- data/lib/flexr/project_templates/racc/Rakefile +14 -0
- data/lib/flexr/project_templates/racc/calculator.rb +22 -0
- data/lib/flexr/project_templates/racc/parser.y +19 -0
- data/lib/flexr/regexp/ast.rb +2 -0
- data/lib/flexr/regexp/parser.rb +13 -11
- data/lib/flexr/regexp/tokenizer.rb +2 -2
- data/lib/flexr/rules.rb +53 -0
- data/lib/flexr/runtime/buffer.rb +1 -1
- data/lib/flexr/runtime/captures.rb +46 -0
- data/lib/flexr/runtime/channels.rb +2 -1
- data/lib/flexr/runtime/checkpoint.rb +116 -0
- data/lib/flexr/runtime/core.rb +55 -43
- data/lib/flexr/runtime/delegation.rb +123 -0
- data/lib/flexr/runtime/delimiters.rb +89 -0
- data/lib/flexr/runtime/firstmatch.rb +266 -0
- data/lib/flexr/runtime/indentation.rb +235 -0
- data/lib/flexr/runtime/input_stack.rb +48 -0
- data/lib/flexr/runtime/interpreter.rb +36 -314
- data/lib/flexr/runtime/recognizer.rb +106 -0
- data/lib/flexr/runtime.rb +10 -0
- data/lib/flexr/skeleton/verification.rb +103 -0
- data/lib/flexr/skeleton.rb +208 -0
- data/lib/flexr/source/fixes.rb +145 -0
- data/lib/flexr/source/prism_reader.rb +187 -25
- data/lib/flexr/testing.rb +5 -2
- data/lib/flexr/unicode/reference_regexp.rb +29 -11
- data/lib/flexr/version.rb +1 -1
- data/lib/ruby_lsp/flexr/addon.rb +88 -13
- data/lib/ruby_lsp/flexr/navigation.rb +231 -0
- data/lib/ruby_lsp/flexr/ranges.rb +40 -0
- data/sig/flexr.rbs +33 -3
- data/site/README.md +22 -7
- data/site/ruby/presets/heredoc.flexr.rb +15 -0
- data/site/ruby/presets/html_javascript.rb +12 -0
- data/site/ruby/presets/html_js.flexr.rb +14 -0
- data/site/ruby/presets/indentation.flexr.rb +14 -0
- data/site/scripts/prepare-playground.mjs +16 -6
- data/site/scripts/stable-release.mjs +4 -1
- data/site/src/content/docs/learn/parser-integration.md +23 -8
- data/site/src/content/docs/reference/cli.md +3 -0
- data/site/src/content/docs/reference/dsl.md +1 -0
- data/site/src/content/docs/reference/runtime.md +26 -0
- data/site/src/pages/playground.astro +15 -1
- data/site/src/playground/client.js +30 -1
- data/site/src/playground/issue.mjs +19 -0
- data/site/src/playground/runtime.mjs +4 -3
- data/site/src/playground/worker.mjs +1 -1
- data/site/tests/browser/playground.spec.mjs +64 -0
- data/site/tests/playground-issue.test.mjs +15 -0
- data/site/tests/playground-release.test.mjs +62 -11
- data/site/tests/playground-runtime.test.mjs +48 -0
- data/test/ruby_lsp_addon_spec.rb +174 -0
- metadata +63 -1
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
begin
|
|
4
|
+
require "prism"
|
|
5
|
+
rescue LoadError
|
|
6
|
+
raise Flexr::CompileError, "Prism is required for oedipus_lex import. Install it with gem install prism"
|
|
7
|
+
end
|
|
8
|
+
require_relative "../source/static_eval"
|
|
9
|
+
|
|
10
|
+
module Flexr
|
|
11
|
+
class Importer
|
|
12
|
+
class OedipusLex
|
|
13
|
+
REGEXP = %r{\A(/(?:\\.|[^/\\])*/)([a-zA-Z]*)(?:\s+(.*))?\z}
|
|
14
|
+
SECTION = /\A(macros?|rules?|options?|inner|start)\s*(?:#.*)?\z/
|
|
15
|
+
LITERALS = [Prism::SymbolNode, Prism::StringNode, Prism::IntegerNode, Prism::FloatNode,
|
|
16
|
+
Prism::TrueNode, Prism::FalseNode, Prism::NilNode].freeze
|
|
17
|
+
|
|
18
|
+
def initialize(path, source)
|
|
19
|
+
@path = path
|
|
20
|
+
@source = source.force_encoding(Encoding::UTF_8)
|
|
21
|
+
@macros = {}
|
|
22
|
+
@rules = []
|
|
23
|
+
@warnings = []
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def run
|
|
27
|
+
if @source.valid_encoding?
|
|
28
|
+
@source.each_line.with_index(1) { |line, number| read_line(line.strip, number) }
|
|
29
|
+
warn_at(1, "add a lexer class declaration") unless @class_name
|
|
30
|
+
warn_at(1, "close the specification with end") unless @closed
|
|
31
|
+
warn_at(1, "add an importable rule to the rule section") if @rules.empty? && @warnings.empty?
|
|
32
|
+
else
|
|
33
|
+
warn_at(1, "convert the source to UTF-8 before importing")
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
complete = @warnings.empty?
|
|
37
|
+
Result.new(source: complete ? render : nil, warnings: @warnings.freeze, complete?: complete)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
private
|
|
41
|
+
|
|
42
|
+
def read_line(line, number)
|
|
43
|
+
if line.start_with?("#")
|
|
44
|
+
coding = line[/\b(?:en)?coding:\s*([\w-]+)/i, 1] if number <= 2
|
|
45
|
+
warn_at(number, "convert the source to UTF-8 and update the encoding comment") if coding && coding.upcase != "UTF-8"
|
|
46
|
+
return
|
|
47
|
+
end
|
|
48
|
+
return if line.empty?
|
|
49
|
+
return read_class(line, number) unless @class_name
|
|
50
|
+
return warn_at(number, "move Ruby footer code to a separate file") if @closed
|
|
51
|
+
|
|
52
|
+
if line.match?(/\Aend\s*(?:#.*)?\z/)
|
|
53
|
+
@closed = true
|
|
54
|
+
elsif (heading = SECTION.match(line))
|
|
55
|
+
@section = heading[1].delete_suffix("s")
|
|
56
|
+
elsif @section == "macro"
|
|
57
|
+
read_macro(line, number)
|
|
58
|
+
elsif @section == "rule"
|
|
59
|
+
read_rule(line, number)
|
|
60
|
+
elsif @section == "option"
|
|
61
|
+
warn_at(number, "unsupported option #{line.split.first.inspect}. Reproduce its behavior in the lexer or parser wrapper")
|
|
62
|
+
elsif @section
|
|
63
|
+
warn_at(number, "unsupported #{@section} code. Move it to the lexer or parser wrapper")
|
|
64
|
+
else
|
|
65
|
+
warn_at(number, "unexpected section content. Use a macro or rule section")
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def read_class(line, number)
|
|
70
|
+
header = line.match(/\Aclass\s+([A-Z][A-Za-z0-9_]*)\s*([^#]*)(?:#.*)?\z/)
|
|
71
|
+
return warn_at(number, "unsupported Ruby header. Move it to a separate file before the lexer class") unless header
|
|
72
|
+
|
|
73
|
+
@class_name = header[1]
|
|
74
|
+
return if header[2].strip.empty?
|
|
75
|
+
|
|
76
|
+
warn_at(number, "unsupported superclass or qualified class. Adapt the parser to a separate Flexr lexer")
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def read_macro(line, number)
|
|
80
|
+
name, literal = line.split(/\s+/, 2)
|
|
81
|
+
return warn_at(number, "define a macro as CONSTANT /regexp/") unless name.match?(/\A[A-Z][A-Za-z0-9_]*\z/) && literal
|
|
82
|
+
return warn_at(number, "duplicate macro #{name}. Keep one definition before its uses") if @macros.key?(name)
|
|
83
|
+
|
|
84
|
+
regexp, tail = parse_regexp(literal, number)
|
|
85
|
+
return unless regexp
|
|
86
|
+
return warn_at(number, "unexpected text after macro regexp. Remove it or use a comment") unless blank_or_comment?(tail)
|
|
87
|
+
|
|
88
|
+
@macros[name] = regexp
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def read_rule(line, number)
|
|
92
|
+
case line
|
|
93
|
+
when /\A:\s/, /\A\|/
|
|
94
|
+
return warn_at(number, "unsupported guard group. Preserve the group guard when rewriting its rules")
|
|
95
|
+
when /\A:\w+/
|
|
96
|
+
return warn_at(number, "unsupported rule state. Migrate state eligibility and transitions together")
|
|
97
|
+
when /\A\w+[?!]?\s/
|
|
98
|
+
return warn_at(number, "unsupported rule predicate. Move the predicate into explicit lexer state or parser logic")
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
regexp, action = parse_regexp(line, number)
|
|
102
|
+
return unless regexp
|
|
103
|
+
|
|
104
|
+
emission = translate_action(action, number)
|
|
105
|
+
return unless emission
|
|
106
|
+
return unless supported_rule_regexp?(regexp, number)
|
|
107
|
+
|
|
108
|
+
pattern = regexp.casefold? ? regexp.to_s : regexp.source
|
|
109
|
+
@rules << if emission == :skip
|
|
110
|
+
" rule(::Regexp.new(#{pattern.dump}), skip: true)"
|
|
111
|
+
else
|
|
112
|
+
" rule(::Regexp.new(#{pattern.dump})) { #{emission} }"
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def parse_regexp(line, number)
|
|
117
|
+
match = REGEXP.match(line)
|
|
118
|
+
return warn_at(number, "expected a slash-delimited regexp followed by an optional action") unless match
|
|
119
|
+
return warn_at(number, "unsupported regexp flag #{match[2].inspect}. Use no flag, /i, or /o") unless %w[i o].include?(match[2]) || match[2].empty?
|
|
120
|
+
|
|
121
|
+
literal = match[1] + match[2]
|
|
122
|
+
node = expression(literal)
|
|
123
|
+
return warn_at(number, "invalid regexp. Check its delimiters and escapes") unless node.is_a?(Prism::RegularExpressionNode) || node.is_a?(Prism::InterpolatedRegularExpressionNode)
|
|
124
|
+
return if node.is_a?(Prism::InterpolatedRegularExpressionNode) && !valid_macros?(node, number)
|
|
125
|
+
|
|
126
|
+
[Source::StaticEval.new(literal, constants: @macros).call(node), match[3].to_s]
|
|
127
|
+
rescue StaticResolutionError => e
|
|
128
|
+
detail = e.diagnostic.note.split("; runtime mode", 2).first
|
|
129
|
+
warn_at(number, "cannot import regexp: #{detail}")
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def valid_macros?(node, number)
|
|
133
|
+
node.parts.each do |part|
|
|
134
|
+
next if part.is_a?(Prism::StringNode)
|
|
135
|
+
|
|
136
|
+
body = part.is_a?(Prism::EmbeddedStatementsNode) ? part.statements&.body : nil
|
|
137
|
+
return warn_at(number, "unsupported regexp interpolation. Reference only declared regexp macros") unless body&.one? && body.first.is_a?(Prism::ConstantReadNode)
|
|
138
|
+
|
|
139
|
+
name = body.first.name.to_s
|
|
140
|
+
return warn_at(number, "undefined regexp macro #{name}. Declare it before use") unless @macros.key?(name)
|
|
141
|
+
end
|
|
142
|
+
true
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def supported_rule_regexp?(regexp, number)
|
|
146
|
+
return warn_at(number, "rewrite Unicode property or POSIX class patterns before importing because Ruby and flexr may use different Unicode tables") if Regexp::Matcher.reference?(regexp, encoding: Encoding::UTF_8)
|
|
147
|
+
|
|
148
|
+
ast = Regexp::Parser.new(regexp.source, options: regexp.options).parse
|
|
149
|
+
return warn_at(number, "rewrite regexp anchors against the input position before importing") if anchor?(ast)
|
|
150
|
+
return warn_at(number, "rewrite the regexp to consume input because it can match an empty string") if Regexp::AST.nullable?(ast)
|
|
151
|
+
return warn_at(number, "rewrite absence groups before using the firstmatch backend") if Regexp::AST.absence?(ast)
|
|
152
|
+
|
|
153
|
+
true
|
|
154
|
+
rescue CompileError => e
|
|
155
|
+
help = e.diagnostic&.help
|
|
156
|
+
warn_at(number, help ? "#{e.message} (#{help})" : e.message)
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def anchor?(node)
|
|
160
|
+
return true if node.is_a?(Regexp::AST::Anchor)
|
|
161
|
+
return anchor?(node.child) if node.respond_to?(:child)
|
|
162
|
+
|
|
163
|
+
node.respond_to?(:children) && node.children.any? { |child| anchor?(child) }
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
def translate_action(action, number)
|
|
167
|
+
return :skip if blank_or_comment?(action)
|
|
168
|
+
return warn_at(number, "unsupported state action. Translate the state transition and emitted token together") if
|
|
169
|
+
action.match?(/\A(?::\w+|nil)(?:\s|\z)/)
|
|
170
|
+
|
|
171
|
+
call = expression("proc #{action}")
|
|
172
|
+
if call.is_a?(Prism::CallNode) && call.receiver.nil? && call.name == :proc &&
|
|
173
|
+
call.arguments.nil? && call.block.is_a?(Prism::BlockNode) && call.block.parameters.nil?
|
|
174
|
+
body = call.block.body&.body
|
|
175
|
+
return :skip if body.nil? || (body.one? && skip_action?(body.first))
|
|
176
|
+
pair = body.first if body.one?
|
|
177
|
+
converted = convert_pair(pair)
|
|
178
|
+
return converted if converted
|
|
179
|
+
end
|
|
180
|
+
warn_at(number, "unsupported Ruby action. Translate it manually to emit(token, value) or skip")
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def skip_action?(node)
|
|
184
|
+
node.is_a?(Prism::NilNode) || (node.is_a?(Prism::NextNode) && node.arguments.nil?)
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
def convert_pair(pair)
|
|
188
|
+
return unless pair.is_a?(Prism::ArrayNode) && pair.elements.length == 2
|
|
189
|
+
|
|
190
|
+
kind, value = pair.elements
|
|
191
|
+
return unless kind.is_a?(Prism::StringNode) || kind.is_a?(Prism::SymbolNode) || simple_call?(kind, :text)
|
|
192
|
+
return if kind.is_a?(Prism::SymbolNode) && kind.unescaped == "state"
|
|
193
|
+
return unless LITERALS.any? { |literal| value.is_a?(literal) } || simple_call?(value, :text) || text_conversion?(value)
|
|
194
|
+
|
|
195
|
+
"emit(#{kind.slice}, #{value.slice})"
|
|
196
|
+
end
|
|
197
|
+
|
|
198
|
+
def text_conversion?(node)
|
|
199
|
+
node.is_a?(Prism::CallNode) && %i[to_i to_f to_sym].include?(node.name) &&
|
|
200
|
+
node.arguments.nil? && node.block.nil? && simple_call?(node.receiver, :text)
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
def simple_call?(node, name)
|
|
204
|
+
node.is_a?(Prism::CallNode) && node.slice == name.to_s
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
def expression(source)
|
|
208
|
+
parsed = Prism.parse(source)
|
|
209
|
+
statements = parsed.value.statements.body
|
|
210
|
+
statements.first if parsed.success? && statements.one?
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
def blank_or_comment?(text)
|
|
214
|
+
text.empty? || text.start_with?("#")
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
def warn_at(number, message)
|
|
218
|
+
@warnings << "#{@path}:#{number}: #{message}"
|
|
219
|
+
nil
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
def render
|
|
223
|
+
lines = ["# frozen_string_literal: true", "", 'require "flexr"', "",
|
|
224
|
+
"class #{@class_name} < Flexr::Lexer", " backend :firstmatch", *@rules, "end", ""]
|
|
225
|
+
lines.join("\n")
|
|
226
|
+
end
|
|
227
|
+
end
|
|
228
|
+
end
|
|
229
|
+
end
|
data/lib/flexr/importer.rb
CHANGED
|
@@ -8,8 +8,13 @@ module Flexr
|
|
|
8
8
|
|
|
9
9
|
class UnsupportedFormatError < CompileError; end
|
|
10
10
|
|
|
11
|
-
def self.import(path)
|
|
12
|
-
new(path, File.binread(path)).run
|
|
11
|
+
def self.import(path, from: nil)
|
|
12
|
+
return new(path, File.binread(path)).run unless from
|
|
13
|
+
raise ArgumentError, "unsupported import format: #{from.inspect}" unless from == :oedipus_lex
|
|
14
|
+
raise UnsupportedFormatError, "oedipus_lex import expects a .rex file" unless File.extname(path).downcase == ".rex"
|
|
15
|
+
|
|
16
|
+
require_relative "importer/oedipus_lex"
|
|
17
|
+
OedipusLex.new(path, File.binread(path)).run
|
|
13
18
|
end
|
|
14
19
|
|
|
15
20
|
def initialize(path, source)
|
data/lib/flexr/ir.rb
CHANGED
|
@@ -4,7 +4,7 @@ module Flexr
|
|
|
4
4
|
module IR
|
|
5
5
|
Rule = Struct.new(
|
|
6
6
|
:index, :patterns, :trailing, :action, :states, :bol_only, :end_anchor, :location,
|
|
7
|
-
:pattern_conditions, :trailing_dfa, :channel, :priority,
|
|
7
|
+
:pattern_conditions, :trailing_dfa, :channel, :priority, :emits, :capture_patterns,
|
|
8
8
|
keyword_init: true
|
|
9
9
|
) do
|
|
10
10
|
def skip?
|
data/lib/flexr/options.rb
CHANGED
|
@@ -6,6 +6,7 @@ module Flexr
|
|
|
6
6
|
Options = Struct.new(
|
|
7
7
|
:backend, :token_kind, :accel, :standalone, :eval_mode, :table_compression,
|
|
8
8
|
:table_format, :max_dfa_states, :warn_level, :warn_as_error, :color, :format, :overrides, :grammar, :target,
|
|
9
|
+
:dry_run, :import_format,
|
|
9
10
|
keyword_init: true
|
|
10
11
|
) do
|
|
11
12
|
def self.default
|
|
@@ -30,6 +31,8 @@ module Flexr
|
|
|
30
31
|
validate_value!(warn_level, %i[all default none], :warn_level)
|
|
31
32
|
validate_value!(color, %i[auto always never], :color)
|
|
32
33
|
validate_value!(format, %i[human json lrama], :format)
|
|
34
|
+
raise ArgumentError, "unsupported import format: #{import_format.inspect}" unless
|
|
35
|
+
import_format.nil? || import_format == :oedipus_lex
|
|
33
36
|
raise ArgumentError, "unsupported target: #{target.inspect}" unless target.nil? || target == "2.0"
|
|
34
37
|
raise ArgumentError, "--target requires static check; remove --eval" if target && eval_mode
|
|
35
38
|
raise ArgumentError, "unsupported max_dfa_states: #{max_dfa_states.inspect}" unless max_dfa_states.is_a?(Integer) && max_dfa_states.positive?
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Flexr
|
|
4
|
+
module ProjectTemplate
|
|
5
|
+
ROOT = File.join(__dir__, "project_templates")
|
|
6
|
+
NAME = /\A[A-Za-z0-9][A-Za-z0-9_-]*\z/
|
|
7
|
+
PARSERS = %w[lrama racc].freeze
|
|
8
|
+
COMMON_FILES = %w[.gitignore lexer.flexr.rb test_calculator.rb].freeze
|
|
9
|
+
PARSER_FILES = %w[Gemfile README.md Rakefile calculator.rb parser.y].freeze
|
|
10
|
+
|
|
11
|
+
module_function
|
|
12
|
+
|
|
13
|
+
def create(name, parser:)
|
|
14
|
+
raise ArgumentError, "project name must start with a letter or digit and contain only letters, digits, hyphens, or underscores" unless
|
|
15
|
+
NAME.match?(name)
|
|
16
|
+
raise ArgumentError, "--parser must be lrama or racc" unless PARSERS.include?(parser)
|
|
17
|
+
|
|
18
|
+
files = COMMON_FILES.to_h { |file| [file, File.binread(File.join(ROOT, "common", file))] }
|
|
19
|
+
PARSER_FILES.each { |file| files[file] = File.binread(File.join(ROOT, parser, file)) }
|
|
20
|
+
destination = File.expand_path(name)
|
|
21
|
+
create_directory(destination)
|
|
22
|
+
write_files(destination, files)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def create_directory(destination)
|
|
26
|
+
Dir.mkdir(destination)
|
|
27
|
+
rescue Errno::EEXIST
|
|
28
|
+
raise Flexr::Error, "project path already exists: #{destination}"
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def write_files(destination, files)
|
|
32
|
+
written = []
|
|
33
|
+
files.each do |name, content|
|
|
34
|
+
path = File.join(destination, name)
|
|
35
|
+
File.open(path, "wbx") do |file|
|
|
36
|
+
written << path
|
|
37
|
+
file.write(content)
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
rescue SystemCallError, IOError
|
|
41
|
+
written.reverse_each { |path| File.unlink(path) }
|
|
42
|
+
Dir.rmdir(destination) if Dir.empty?(destination)
|
|
43
|
+
raise
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
/build/
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "flexr"
|
|
4
|
+
|
|
5
|
+
class CalculatorLexer < Flexr::Lexer
|
|
6
|
+
emits :INTEGER, :PLUS, :MINUS
|
|
7
|
+
|
|
8
|
+
rule(/[ \t\r\n]+/, skip: true)
|
|
9
|
+
rule(/[0-9]+/) { emit :INTEGER, text.to_i }
|
|
10
|
+
rule("+", emit: :PLUS)
|
|
11
|
+
rule("-", emit: :MINUS)
|
|
12
|
+
end
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "minitest/autorun"
|
|
4
|
+
require_relative "calculator"
|
|
5
|
+
|
|
6
|
+
class CalculatorTest < Minitest::Test
|
|
7
|
+
def test_adds_and_subtracts
|
|
8
|
+
assert_equal 11, Calculator.evaluate("12 + 3 - 4")
|
|
9
|
+
assert_equal(-5, Calculator.evaluate("2 - 4 - 3"))
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
def test_rejects_an_incomplete_expression
|
|
13
|
+
assert_raises(ArgumentError) { Calculator.evaluate("12 +") }
|
|
14
|
+
end
|
|
15
|
+
end
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Lrama calculator
|
|
2
|
+
|
|
3
|
+
Use Ruby 3.4 or later and a C compiler named `cc`. Set `CC` to use a different
|
|
4
|
+
compiler executable.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
bundle install
|
|
8
|
+
bundle exec rake test
|
|
9
|
+
bundle exec ruby calculator.rb '12 + 3 - 4'
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The calculator prints `11`. The lexer in `lexer.flexr.rb` produces tokens.
|
|
13
|
+
`calculator.rb` passes their kinds and values to the compiled parser. Lrama
|
|
14
|
+
generates C from `parser.y`. The parser accepts results and integer tokens in
|
|
15
|
+
the signed 64-bit range.
|
|
16
|
+
|
|
17
|
+
Run `bundle exec rake build` to generate and compile the parser.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rake/testtask"
|
|
4
|
+
|
|
5
|
+
file "build/parser.c" => "parser.y" do
|
|
6
|
+
mkdir_p "build"
|
|
7
|
+
sh Gem.bin_path("lrama", "lrama"), "-o", "build/parser.c", "parser.y"
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
file "build/calculator_parser" => "build/parser.c" do
|
|
11
|
+
sh ENV.fetch("CC", "cc"), "-o", "build/calculator_parser", "build/parser.c"
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
task build: "build/calculator_parser"
|
|
15
|
+
|
|
16
|
+
Rake::TestTask.new(:test) { |test| test.pattern = "test_calculator.rb" }
|
|
17
|
+
task test: :build
|
|
18
|
+
task default: :test
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "open3"
|
|
4
|
+
require_relative "lexer.flexr"
|
|
5
|
+
|
|
6
|
+
module Calculator
|
|
7
|
+
PARSER = File.expand_path("build/calculator_parser", __dir__)
|
|
8
|
+
|
|
9
|
+
def self.evaluate(source)
|
|
10
|
+
tokens = CalculatorLexer.new(source).each_token.map do |kind, value|
|
|
11
|
+
kind == :INTEGER ? "n#{value}\n" : value
|
|
12
|
+
end.join
|
|
13
|
+
output, error, status = Open3.capture3([PARSER, PARSER], stdin_data: tokens, binmode: true)
|
|
14
|
+
raise ArgumentError, error.strip unless status.success?
|
|
15
|
+
|
|
16
|
+
Integer(output, 10)
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
if $PROGRAM_NAME == __FILE__
|
|
21
|
+
abort "Usage: ruby calculator.rb '12 + 3 - 4'" unless ARGV.length == 1
|
|
22
|
+
|
|
23
|
+
begin
|
|
24
|
+
puts Calculator.evaluate(ARGV.first)
|
|
25
|
+
rescue ArgumentError, Flexr::LexError => e
|
|
26
|
+
abort e.message
|
|
27
|
+
end
|
|
28
|
+
end
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
%{
|
|
2
|
+
#include <errno.h>
|
|
3
|
+
#include <inttypes.h>
|
|
4
|
+
#include <stdio.h>
|
|
5
|
+
%}
|
|
6
|
+
|
|
7
|
+
%code provides {
|
|
8
|
+
static int yylex(YYSTYPE *value, YYLTYPE *location);
|
|
9
|
+
static void yyerror(YYLTYPE *location, const char *message);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
%locations
|
|
13
|
+
|
|
14
|
+
%union {
|
|
15
|
+
int64_t number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
%token <number> INTEGER
|
|
19
|
+
%token PLUS MINUS
|
|
20
|
+
%type <number> expression
|
|
21
|
+
|
|
22
|
+
%%
|
|
23
|
+
input:
|
|
24
|
+
expression { printf("%" PRId64 "\n", $1); }
|
|
25
|
+
;
|
|
26
|
+
|
|
27
|
+
expression:
|
|
28
|
+
INTEGER { $$ = $1; }
|
|
29
|
+
| expression PLUS INTEGER {
|
|
30
|
+
if ($1 > INT64_MAX - $3) {
|
|
31
|
+
yyerror(NULL, "integer overflow");
|
|
32
|
+
YYABORT;
|
|
33
|
+
}
|
|
34
|
+
$$ = $1 + $3;
|
|
35
|
+
}
|
|
36
|
+
| expression MINUS INTEGER {
|
|
37
|
+
if ($1 < INT64_MIN + $3) {
|
|
38
|
+
yyerror(NULL, "integer overflow");
|
|
39
|
+
YYABORT;
|
|
40
|
+
}
|
|
41
|
+
$$ = $1 - $3;
|
|
42
|
+
}
|
|
43
|
+
;
|
|
44
|
+
%%
|
|
45
|
+
|
|
46
|
+
static int yylex(YYSTYPE *value, YYLTYPE *location) {
|
|
47
|
+
(void)location;
|
|
48
|
+
switch (getchar()) {
|
|
49
|
+
case 'n': {
|
|
50
|
+
char line[64], *end;
|
|
51
|
+
if (!fgets(line, sizeof line, stdin)) return YYUNDEF;
|
|
52
|
+
errno = 0;
|
|
53
|
+
intmax_t number = strtoimax(line, &end, 10);
|
|
54
|
+
if (errno || end == line || *end != '\n' || number < 0 || number > INT64_MAX) return YYUNDEF;
|
|
55
|
+
value->number = number;
|
|
56
|
+
return INTEGER;
|
|
57
|
+
}
|
|
58
|
+
case '+': return PLUS;
|
|
59
|
+
case '-': return MINUS;
|
|
60
|
+
case EOF: return YYEOF;
|
|
61
|
+
default: return YYUNDEF;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
static void yyerror(YYLTYPE *location, const char *message) {
|
|
66
|
+
(void)location;
|
|
67
|
+
fprintf(stderr, "%s\n", message);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
int main(void) {
|
|
71
|
+
return yyparse();
|
|
72
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Racc calculator
|
|
2
|
+
|
|
3
|
+
Run these commands with Ruby 3.4 or later:
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
bundle install
|
|
7
|
+
bundle exec rake test
|
|
8
|
+
bundle exec ruby calculator.rb '12 + 3 - 4'
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The calculator prints `11`. The lexer in `lexer.flexr.rb` turns input into
|
|
12
|
+
tokens. Racc builds a Ruby parser from `parser.y` and uses the lexer's
|
|
13
|
+
`racc_next_token` method to read those tokens.
|
|
14
|
+
|
|
15
|
+
Run `bundle exec rake build` to regenerate the parser without running tests.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rake/testtask"
|
|
4
|
+
|
|
5
|
+
file "build/parser.rb" => "parser.y" do
|
|
6
|
+
mkdir_p "build"
|
|
7
|
+
sh Gem.bin_path("racc", "racc"), "-o", "build/parser.rb", "parser.y"
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
task build: "build/parser.rb"
|
|
11
|
+
|
|
12
|
+
Rake::TestTask.new(:test) { |test| test.pattern = "test_calculator.rb" }
|
|
13
|
+
task test: :build
|
|
14
|
+
task default: :test
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "lexer.flexr"
|
|
4
|
+
require_relative "build/parser"
|
|
5
|
+
|
|
6
|
+
module Calculator
|
|
7
|
+
def self.evaluate(source)
|
|
8
|
+
CalculatorParser.new.parse(CalculatorLexer.new(source))
|
|
9
|
+
rescue Racc::ParseError => e
|
|
10
|
+
raise ArgumentError, e.message
|
|
11
|
+
end
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
if $PROGRAM_NAME == __FILE__
|
|
15
|
+
abort "Usage: ruby calculator.rb '12 + 3 - 4'" unless ARGV.length == 1
|
|
16
|
+
|
|
17
|
+
begin
|
|
18
|
+
puts Calculator.evaluate(ARGV.first)
|
|
19
|
+
rescue ArgumentError, Flexr::LexError => e
|
|
20
|
+
abort e.message
|
|
21
|
+
end
|
|
22
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
class CalculatorParser
|
|
2
|
+
token INTEGER PLUS MINUS
|
|
3
|
+
|
|
4
|
+
rule
|
|
5
|
+
expression
|
|
6
|
+
: INTEGER { result = val[0] }
|
|
7
|
+
| expression PLUS INTEGER { result = val[0] + val[2] }
|
|
8
|
+
| expression MINUS INTEGER { result = val[0] - val[2] }
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
---- inner
|
|
12
|
+
def parse(lexer)
|
|
13
|
+
@lexer = lexer
|
|
14
|
+
do_parse
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def next_token
|
|
18
|
+
@lexer.racc_next_token
|
|
19
|
+
end
|
data/lib/flexr/regexp/ast.rb
CHANGED
|
@@ -14,6 +14,7 @@ module Flexr
|
|
|
14
14
|
Absence = Struct.new(:child, :loc, keyword_init: true)
|
|
15
15
|
Difference = Struct.new(:left, :right, :loc, keyword_init: true)
|
|
16
16
|
EmbeddedDFA = Struct.new(:dfa)
|
|
17
|
+
NamedCapture = Struct.new(:opening, :child, keyword_init: true)
|
|
17
18
|
Anchor = Struct.new(:kind, :loc, keyword_init: true)
|
|
18
19
|
TrailMark = Struct.new(:rule_id, :loc, keyword_init: true)
|
|
19
20
|
CharClass = Struct.new(:ranges, :negated, :loc, keyword_init: true)
|
|
@@ -54,6 +55,7 @@ module Flexr
|
|
|
54
55
|
case node
|
|
55
56
|
when Empty, Anchor, Star then true
|
|
56
57
|
when Repeat then node.minimum.zero? || nullable?(node.child)
|
|
58
|
+
when NamedCapture then nullable?(node.child)
|
|
57
59
|
when Seq then node.children.all? { |child| nullable?(child) }
|
|
58
60
|
when Alt then node.children.any? { |child| nullable?(child) }
|
|
59
61
|
when Absence then !nullable?(node.child)
|
data/lib/flexr/regexp/parser.rb
CHANGED
|
@@ -16,11 +16,14 @@ module Flexr
|
|
|
16
16
|
|
|
17
17
|
attr_reader :source
|
|
18
18
|
|
|
19
|
-
def initialize(source, options: 0, encoding: Encoding::UTF_8, unicode: false
|
|
19
|
+
def initialize(source, options: 0, encoding: Encoding::UTF_8, unicode: false, preserve_captures: false,
|
|
20
|
+
capture_offsets: nil)
|
|
20
21
|
@source = source
|
|
21
22
|
@options = options
|
|
22
23
|
@encoding = encoding
|
|
23
24
|
@unicode = unicode
|
|
25
|
+
@capture_offsets = capture_offsets
|
|
26
|
+
@preserve_captures = preserve_captures
|
|
24
27
|
@index = 0
|
|
25
28
|
@class_depth = 0
|
|
26
29
|
offset = 0
|
|
@@ -136,12 +139,13 @@ module Flexr
|
|
|
136
139
|
prefix = parse_group_prefix
|
|
137
140
|
return AST::Empty.new(loc: span(starting)) if prefix == :global
|
|
138
141
|
else
|
|
139
|
-
|
|
142
|
+
@capture_offsets&.push(@byte_offsets.fetch(starting))
|
|
140
143
|
end
|
|
141
144
|
node = parse_expression
|
|
142
145
|
expect(")")
|
|
143
146
|
@options = saved_options if prefix
|
|
144
147
|
return AST::Absence.new(child: node, loc: span(starting)) if prefix == :absence
|
|
148
|
+
return AST::NamedCapture.new(opening: prefix, child: node) if prefix.is_a?(String)
|
|
145
149
|
|
|
146
150
|
node
|
|
147
151
|
end
|
|
@@ -185,10 +189,8 @@ module Flexr
|
|
|
185
189
|
raise unsupported("atomic groups",
|
|
186
190
|
'for unescaped single-line quoted text, a DFA-compatible rewrite is rule(/"[^"\n]*"/); keep the action; removing atomic groups can change matches')
|
|
187
191
|
end
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
"when only grouping is needed, rewrite rule(/(?<word>ab)/) as rule(/(?:ab)/); keep the action; capture-dependent patterns need a separate rewrite")
|
|
191
|
-
end
|
|
192
|
+
return named_capture_prefix("<", ">") if consume?("<")
|
|
193
|
+
return named_capture_prefix("'", "'") if consume?("'")
|
|
192
194
|
if peek_prefix?("(")
|
|
193
195
|
raise unsupported("conditional groups",
|
|
194
196
|
"for this optional-prefix conditional, rewrite rule(/(a)?(?(1)b|c)/) as rule(/(?:ab|c)/); keep the action; other conditions need separate rules or state checks")
|
|
@@ -201,6 +203,11 @@ module Flexr
|
|
|
201
203
|
raise unsupported("unsupported group syntax", "use a non-capturing group (?:...)")
|
|
202
204
|
end
|
|
203
205
|
|
|
206
|
+
def named_capture_prefix(opener, closer)
|
|
207
|
+
name = read_until(closer)
|
|
208
|
+
@preserve_captures ? "#{opener}#{name}#{closer}" : true
|
|
209
|
+
end
|
|
210
|
+
|
|
204
211
|
def update_option(flag, enabled)
|
|
205
212
|
bit = { "i" => ::Regexp::IGNORECASE, "m" => ::Regexp::MULTILINE, "x" => ::Regexp::EXTENDED }.fetch(flag)
|
|
206
213
|
@options = enabled ? (@options | bit) : (@options & ~bit)
|
|
@@ -537,11 +544,6 @@ module Flexr
|
|
|
537
544
|
node.children.any? { |child| anchor_nested_in_alternative?(child) }
|
|
538
545
|
end
|
|
539
546
|
|
|
540
|
-
def warn_capture
|
|
541
|
-
# The parser intentionally treats captures as non-capturing. Diagnostics
|
|
542
|
-
# are exposed by the source compiler where a source location is known.
|
|
543
|
-
end
|
|
544
|
-
|
|
545
547
|
def reject_postfix_quantifier
|
|
546
548
|
return unless ["?", "+"].include?(current)
|
|
547
549
|
|