Skip to content

Commit

Permalink
Streamline parser config and extract lexers
Browse files Browse the repository at this point in the history
  • Loading branch information
elia committed Apr 20, 2018
1 parent 2788245 commit 5031748
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 42 deletions.
63 changes: 21 additions & 42 deletions lib/opal/parser.rb
Expand Up @@ -4,14 +4,6 @@
require 'opal/rewriter'
require 'opal/parser/patch'

if RUBY_ENGINE != 'opal'
begin
require 'c_lexer'
rescue LoadError
$stderr.puts 'Failed to load CLexer, using pure Ruby lexer'
end
end

module Opal
module Source
class Buffer < Parser::Source::Buffer
Expand All @@ -22,34 +14,28 @@ def self.recognize_encoding(string)
end

module Parser
module OpalDefaults
def self.included(klass)
klass.extend(ClassMethods)
klass.diagnostics_consumer = ->(diagnostic) {
$stderr.puts(diagnostic.render)
}
end

module DefaultConfig
module ClassMethods
attr_accessor :diagnostics_consumer

def default_parser
parser = super

parser.diagnostics.all_errors_are_fatal = true
parser.diagnostics.ignore_warnings = false

parser.diagnostics.consumer =
if RUBY_ENGINE == 'opal'
->(diag) {}
else
diagnostics_consumer
end

parser.diagnostics.consumer = diagnostics_consumer
parser
end
end

def self.included(klass)
klass.extend(ClassMethods)
klass.diagnostics_consumer = ->(diagnostic) do
if RUBY_ENGINE != 'opal'
$stderr.puts(diagnostic.render)
end
end
end

def initialize(*)
super(Opal::AST::Builder.new)
end
Expand All @@ -65,26 +51,19 @@ def rewrite(node)
end
end

class WithRubyLexer < ::Parser::Ruby25
include OpalDefaults
end
class << self
attr_accessor :default_parser_class

if defined?(::Parser::Ruby25WithCLexer)
class WithCLexer < ::Parser::Ruby25WithCLexer
include OpalDefaults
def default_parser
default_parser_class.default_parser
end
end
end
end

def self.default_parser_class
if defined?(WithCLexer)
WithCLexer
else
WithRubyLexer
end
end
require 'opal/parser/with_ruby_lexer'

def self.default_parser
default_parser_class.default_parser
end
end
if RUBY_ENGINE != 'opal'
require 'opal/parser/with_c_lexer'
end

12 changes: 12 additions & 0 deletions lib/opal/parser/with_c_lexer.rb
@@ -0,0 +1,12 @@
begin
require 'c_lexer'
rescue LoadError
$stderr.puts 'Failed to load CLexer, using pure Ruby lexer'
end

if defined? Parser::Ruby25WithCLexer
class Opal::Parser::WithCLexer < Parser::Ruby25WithCLexer
include Opal::Parser::DefaultConfig
Opal::Parser.default_parser_class = self
end
end
4 changes: 4 additions & 0 deletions lib/opal/parser/with_ruby_lexer.rb
@@ -0,0 +1,4 @@
class Opal::Parser::WithRubyLexer < Parser::Ruby25
include Opal::Parser::DefaultConfig
Opal::Parser.default_parser_class = self
end

0 comments on commit 5031748

Please sign in to comment.