@@ -29,6 +29,29 @@ class AstParser
2929
3030 attr_reader :parser , :language
3131
32+ @parser_paths_cache = { }
33+
34+ class << self
35+ def find_parser_path ( language , platform , arch )
36+ cache_key = "#{ language } -#{ platform } -#{ arch } "
37+ return @parser_paths_cache [ cache_key ] if @parser_paths_cache . key? ( cache_key )
38+
39+ extension = platform == 'darwin' ? 'dylib' : 'so'
40+ parser_file = "libtree-sitter-#{ language } -#{ platform } -#{ arch } .#{ extension } "
41+
42+ parser_paths = [
43+ File . join ( File . dirname ( __FILE__ ) , '..' , '..' , 'parsers' , parser_file ) , # Relative to this file
44+ File . join ( Gem ::Specification . find_by_name ( 'emerge' ) . gem_dir , 'parsers' , parser_file ) # Installed gem path
45+ ]
46+
47+ parser_path = parser_paths . find { |path | File . exist? ( path ) }
48+ raise "No language grammar found for #{ language } . Searched in: #{ parser_paths . join ( ', ' ) } " unless parser_path
49+
50+ @parser_paths_cache [ cache_key ] = parser_path
51+ parser_path
52+ end
53+ end
54+
3255 def initialize ( language )
3356 @parser = TreeSitter ::Parser . new
3457 @language = language
@@ -52,11 +75,7 @@ def initialize(language)
5275 raise "Unsupported architecture: #{ RUBY_PLATFORM } "
5376 end
5477
55- extension = platform == 'darwin' ? 'dylib' : 'so'
56- parser_file = "libtree-sitter-#{ language } -#{ platform } -#{ arch } .#{ extension } "
57- parser_path = File . join ( 'parsers' , parser_file )
58- raise "No language grammar found for #{ language } " unless File . exist? ( parser_path )
59-
78+ parser_path = self . class . find_parser_path ( language , platform , arch )
6079 @parser . language = TreeSitter ::Language . load ( language , parser_path )
6180 end
6281
0 commit comments