Last active
March 5, 2022 13:30
-
-
Save myitcv/2a2ac679ae027d52c26d to your computer and use it in GitHub Desktop.
Ruby parsing stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'ripper' | |
require 'pp' | |
exp = ARGV.join(" ") | |
p Ripper.sexp(exp) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sexp_processor' | |
require 'sexp_path' | |
require 'ripper' | |
require 'pp' | |
_ = $wildcard = Object.new | |
___ = $remainder = Object.new | |
paths = ARGV.slice!(1..-1) | |
patterns = ARGF.readlines.reject { |x| x.match /^[ \t]*#/ }.reject { |x| x.match /^[ \t]*$/ }.map do |p_s| | |
begin | |
p = eval(p_s) | |
rescue | |
puts "Failed to parse search expression: #{p_s}" | |
exit 1 | |
end | |
p | |
end | |
ARGV.shift | |
def match file, ast, root_pattern, pattern | |
return false if ast.nil? | |
if ast.is_a?(Array) | |
if (ast.size == pattern.size || (pattern.last == $remainder && ast.size >= (pattern.size - 1))) | |
# we could match | |
# if we have a remainder in the pattern use that as a limit on the index check | |
limit_check = ast.size | |
if pattern.last == $remainder | |
limit_check = pattern.size - 1 | |
end | |
matched = true | |
ast.each_with_index do |o, i| | |
break if i >= limit_check | |
next if pattern[i] == $wildcard | |
if pattern[i].is_a? Array | |
matched &&= match file, ast[i], root_pattern, pattern[i] | |
else | |
matched &&= ast[i] == pattern[i] | |
end | |
end | |
if matched | |
if pattern == root_pattern | |
# TODO add more print options here | |
case pattern[0] | |
when :call, :const_path_ref | |
line, col = ast.last.last | |
puts "#{file}:#{line}:#{col}" | |
when :class | |
line, col = ast[1].last.last | |
puts "#{file}:#{line}:#{col}" | |
else | |
puts "#{file}: #{ast}" | |
end | |
else | |
return true | |
end | |
end | |
end | |
ast.each do |x| | |
match file, x, root_pattern, pattern | |
end | |
end | |
return false | |
end | |
paths.each do |path| | |
Dir.glob("#{path}/**/*.rb").each do |file| | |
code = File.read(file) | |
sexp = Ripper.sexp(code) | |
patterns.each do |pattern| | |
match file, sexp, pattern, pattern | |
end | |
end | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'ripper' | |
require 'pp' | |
path = ARGV.shift | |
pp Ripper.sexp(File.read(path)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment