Skip to content

Commit

Permalink
Add SyntaxError#path
Browse files Browse the repository at this point in the history
  • Loading branch information
wasabigeek committed Feb 2, 2024
1 parent 90bfaa0 commit 9785f9f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
11 changes: 11 additions & 0 deletions spec/ruby/core/kernel/eval_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,17 @@
}
end

ruby_version_is "3.2" do
it "includes path in syntax error" do
expected = 'speccing.rb'
-> {
eval('if true',TOPLEVEL_BINDING, expected)
}.should raise_error(SyntaxError) { |e|
e.path.should == expected
}
end
end

it "evaluates string with given filename and negative linenumber" do
expected_file = 'speccing.rb'
-> {
Expand Down
27 changes: 27 additions & 0 deletions src/main/java/org/truffleruby/core/exception/SyntaxErrorNodes.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,17 @@
import org.truffleruby.annotations.CoreMethod;
import org.truffleruby.builtins.CoreMethodArrayArgumentsNode;
import org.truffleruby.annotations.CoreModule;
import org.truffleruby.core.encoding.Encodings;
import org.truffleruby.core.klass.RubyClass;
import org.truffleruby.core.string.RubyString;
import org.truffleruby.annotations.Visibility;
import org.truffleruby.language.objects.AllocationTracing;

import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.object.Shape;
import com.oracle.truffle.api.source.Source;

@CoreModule(value = "SyntaxError", isClass = true)
public abstract class SyntaxErrorNodes {
Expand All @@ -35,4 +40,26 @@ RubySyntaxError allocateSyntaxError(RubyClass rubyClass) {

}

@CoreMethod(names = "path")
public abstract static class PathNode extends CoreMethodArrayArgumentsNode {

@Specialization
RubyString path(RubySyntaxError syntaxError) {
if (!syntaxError.hasSourceLocation()) {
return coreStrings().UNKNOWN.createInstance(getContext());
}

Source source;
try {
source = syntaxError.getSourceLocation().getSource();
} catch (UnsupportedMessageException e) {
throw CompilerDirectives.shouldNotReachHere(e);
}

var path = getLanguage().getPathToTStringCache().getCachedPath(source);
return createString(path, Encodings.UTF_8);
}

}

}

0 comments on commit 9785f9f

Please sign in to comment.