Class Source
From a file on disk
Each file is represented as a canonical object, indexed by the absolute, canonical path name of the file. File content is read eagerly and may be optionally cached. Sample usage:assert file.getName().endsWith(".java") :
"Imagine 'c:\\sources\\Example.java' file";
String language = Source.findLanguage(file);
Source source = Source.newBuilder(language, file).build();
assert file.getName().equals(source.getName());
assert file.getPath().equals(source.getPath());
assert file.toUri().equals(source.getURI());
newBuilder(String, TruffleFile) method.
Read from a URL
One can read remote or in JAR resources using thenewBuilder(String, java.net.URL)
factory: URL resource = relativeClass.getResource("sample.js");
Source source = Source.newBuilder("js", resource)
.build();
assert resource.toExternalForm().equals(source.getPath());
assert "sample.js".equals(source.getName());
assert resource.toURI().equals(source.getURI());
Source.SourceBuilder.build() method is called.
Source from a literal text
An anonymous immutable code snippet can be created from a string via thenewBuilder(String, CharSequence, String) factory method: Source source = Source.newBuilder("js", "function() {\n"
+ " return 'Hi';\n"
+ "}\n", "hi.js").build();
assert "hi.js".equals(source.getName());
Reading from a stream
If one has aReader one can convert its content into a Source via
newBuilder(String, java.io.Reader, String) method: Reader stream = new InputStreamReader(
relativeClass.getResourceAsStream("sample.js")
);
Source source = Source.newBuilder("js", stream, "sample.js")
.build();
assert "sample.js".equals(source.getName());
Source.SourceBuilder.build() method is called.
Reading from bytes
Sources can be created from bytes. Please note that all character related methods will throw anUnsupportedOperationException if that is the case.
byte[] bytes = new byte[] {/* Binary */};
Source source = Source.newBuilder("llvm",
ByteSequence.create(bytes),
"<literal>").build();
Attributes
The source object can be associated with various attributes likegetName() ,
(), getMimeType() and these are immutable. The system makes the best
effort to derive values of these attributes from the location and/or content of the
Source object. However, to give the user that creates the source control over these
attributes, the API offers an easy way to alter values of these attributes.
Character and binary based Sources
A source isbyte or character based, or none of
those when no content is specified. For literal sources it depends on
whether the byte or character based factory method was used. When the source was loaded from a
file or url then the default
MIME type of the provided language will be used to determine whether bytes or characters should
be loaded. The behavior can be customized by specifying a MIME type or content explicitly. If the specified or
inferred MIME type starts with 'text/ or the MIME types is null then it
will be interpreted as character based, otherwise byte based.- Since:
- 0.8 or earlier
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionfinal classclass -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final CharSequenceConstant to be used as an argument toSource.SourceBuilder.content(CharSequence)to set no content to the Source built. -
Method Summary
Modifier and TypeMethodDescriptionfinal SourceSectioncreateSection(int lineNumber) Creates a representation of a line of text in the source identified only by line number, from which the character information will be computed.final SourceSectioncreateSection(int charIndex, int length) Creates a representation of a contiguous region of text in the source.final SourceSectioncreateSection(int startLine, int startColumn, int length) Creates a representation of a contiguous region of text in the source.final SourceSectioncreateSection(int startLine, int startColumn, int endLine, int endColumn) Create representation of a contiguous region in the source that does not have the character content available.final SourceSectionReturns an unavailable source section indicating that the source location is not available.final booleanstatic StringfindLanguage(TruffleFile file) Returns the first language that supports evaluating the probed mime type of a givenfile.static StringfindLanguage(String mimeType) Returns the first installed language that supports evaluating sources for a given MIME type.static StringfindLanguage(URL url) Returns the first language that supports evaluating the probed mime type of a givenURL.static StringfindMimeType(TruffleFile file) Returns the probed MIME type for a given file, ornullif no MIME type could be resolved.static StringfindMimeType(URL url) Returns the probed MIME type for a given url, ornullif no MIME type could be resolved.abstract ByteSequencegetBytes()Returns the bytes of the source if it is abyte based source.abstract CharSequenceReturns all characters of the source.final CharSequencegetCharacters(int lineNumber) Gets the text (not including a possible terminating newline) in a (1-based) numbered line.final intgetColumnNumber(int offset) Given a 0-based character offset, return the 1-based number of the column at the position.abstract StringReturns the language this source was created with.final intGets the number of characters or bytes of the source.final intThe number of text lines in the source, including empty lines; characters at the end of the source without a terminating newline count as a line.final intgetLineLength(int lineNumber) The number of characters (not counting a possible terminating newline) in a (1-based) numbered line.final intgetLineNumber(int offset) Given a 0-based character offset, return the 1-based number of the line that includes the position.final intgetLineStartOffset(int lineNumber) Given a 1-based line number, return the 0-based offset of the first character in the line.abstract StringReturns the MIME type that is associated with this source.abstract StringgetName()Returns the name of this resource holding a guest language program.final OptionValuesgetOptions(TruffleLanguage<?> language) Returns the parsed option values of the given source for the given language.abstract StringgetPath()The fully qualified name of the source.final ReaderAccess to the source contents.final URIgetURI()Get URI of the source.abstract URLgetURL()The URL if the source is retrieved via URL.abstract booleanhasBytes()Returnstrueif this source represents a byte based source, elsefalse.abstract booleanReturnstrueif this source represents a character based source, elsefalse.final inthashCode()abstract booleanisCached()Returnstrueif code caching is enabled for this source.abstract booleanCheck whether this source has been marked as interactive.abstract booleanCheck whether this source has been marked as internal, meaning that it has been provided by the infrastructure, language implementation, or system library.static Source.LiteralBuildernewBuilder(Source source) Creates a new source builder that inherits from the given Source.static Source.SourceBuildernewBuilder(String language, TruffleFile file) Creates a new file based source builder from a given file.static Source.SourceBuildernewBuilder(String language, Reader source, String name) Creates new character based literal source from a reader.static Source.LiteralBuildernewBuilder(String language, CharSequence characters, String name) Creates a new character based literal source from a character sequence.static Source.SourceBuildernewBuilder(String language, URL url) Creates a new URL based source builder from a given URL.static Source.LiteralBuildernewBuilder(String language, ByteSequence bytes, String name) Creates a new byte based literal source from a byte sequence.subSource(int baseCharIndex, int length) toString()
-
Field Details
-
CONTENT_NONE
Constant to be used as an argument toSource.SourceBuilder.content(CharSequence)to set no content to the Source built. The created sections will contain location information only and no characters. That's useful mainly when the source code is not available, but there are relative file paths, like in Java bytecode or LLVM bitcode. It's up to tools to resolve those relative paths and use the section location in resolved sources.- Since:
- 19.0
-
-
Method Details
-
getLanguage
-
getName
-
getPath
The fully qualified name of the source. In case this source originates from aFileorTruffleFile, then the path is the normalized,canonical path. IfcanonicalizePath(false)is used when building the source thenTruffleFile.getPath()is used instead. If the source originates from anURL, then it's the path component of the URL.- Since:
- 0.8 or earlier
-
isInternal
public abstract boolean isInternal()Check whether this source has been marked as internal, meaning that it has been provided by the infrastructure, language implementation, or system library. Internal sources are presumed to be irrelevant to guest language programmers, as well as possibly confusing and revealing of language implementation details.On the other hand, tools should be free to make internal sources visible in (possibly privileged) modes that are useful for language implementors.
One can specify whether a source is internal when
building it.- Returns:
- whether this source is marked as internal
- Since:
- 0.15
-
isCached
public abstract boolean isCached()Returnstrueif code caching is enabled for this source. Iftruethen the source does not require parsing every time this source is evaluated. Iffalsethen the source requires parsing every time the source is evaluated but does not remember any state. Disabling caching may be useful if the source is known to only be evaluated once.- Returns:
- whether this source is allowed to be cached
- Since:
- 19.0
-
isInteractive
public abstract boolean isInteractive()Check whether this source has been marked as interactive. Interactive sources are provided by an entity which is able to interactively read output and provide an input during the source execution; that can be a user I/O through an interactive shell for instance.Depending on
language interactivecapability, when interactive sources are executed, the appropriate result can be passed directly to the environmentoutput streamorerror streamandinput streamcan be used to read user input during the execution, to clarify the execution behavior by asking questions for instance. Non-interactive languages are expected to ignore this property.One can specify whether a source is interactive when
building it.- Returns:
- whether this source is marked as interactive
- Since:
- 0.21
-
equals
-
hashCode
-
subSource
- Parameters:
baseCharIndex- 0-based index of the first character of the sub-rangelength- the number of characters in the sub-range- Returns:
- a new instance representing a sub-range of another Source
- Throws:
IllegalArgumentException- if the specified sub-range is not contained in the baseUnsupportedOperationException- if this source cannot containcharacters.- Since:
- 0.15
-
getCharacters
Returns all characters of the source.- Throws:
UnsupportedOperationException- if this source cannot containcharacters.- Since:
- 0.28
-
hasBytes
public abstract boolean hasBytes()Returnstrueif this source represents a byte based source, elsefalse. A source is either a byte based, a character based, or withno content, but never both byte and character based at the same time.The method
getBytes()is only supported if this method returnstrue.- Since:
- 19.0
- See Also:
-
hasCharacters
public abstract boolean hasCharacters()Returnstrueif this source represents a character based source, elsefalse. A source is either a byte based, a character based, or withno content, but never both byte and character based at the same time.The following methods are only supported if
hasCharacters()istrue:- Since:
- 19.0
-
getBytes
Returns the bytes of the source if it is abyte based source.- Throws:
UnsupportedOperationException- if this source cannot containbytes.- Since:
- 19.0
- See Also:
-
getURL
The URL if the source is retrieved via URL.- Returns:
- URL or
null - Since:
- 0.8 or earlier
-
getURI
Get URI of the source. Every source has an associatedURI, which can be used as a persistent identification of the source. For example one canregister a breakpoint using a URIto a source that isn't loaded yet and it will be activated when the source is evaluated. TheURIreturned by this method should be as unique as possible, yet it can happen that differentsourcesreturn the samegetURI()- for example when content of afile on a diskchanges and is re-loaded.- Returns:
- a URI, it's never
null - Since:
- 0.14
-
getMimeType
Returns the MIME type that is associated with this source. Sources have anullMIME type by default. If the MIME type isnullthen thedefault MIME typeof the language will be used to interpret the source. If set explicitly then the language needs tosupportthe MIME type in order toContext.eval(org.graalvm.polyglot.Source)evaluate} the source. If notnullthe MIME type is already verified containing no spaces and a '/' between group and sub-group. An example for a valid MIME type is:text/javascript.The MIME type can be guessed by the system based on
filesorurls- Returns:
- MIME type of this source or
null, if not explicitly set. - Since:
- 19.0
- See Also:
-
getReader
-
getLength
public final int getLength()Gets the number of characters or bytes of the source.- Throws:
UnsupportedOperationException- if this source does not containcharacters, norbytes.- Since:
- 0.8
-
getCharacters
Gets the text (not including a possible terminating newline) in a (1-based) numbered line. Causes the contents of this source to be loaded if they are loaded lazily.- Throws:
UnsupportedOperationException- if this source cannot containcharacters.- Since:
- 0.28
-
getLineCount
public final int getLineCount()The number of text lines in the source, including empty lines; characters at the end of the source without a terminating newline count as a line. Causes the contents of this source to be loaded if they are loaded lazily.- Throws:
UnsupportedOperationException- if this source cannot containcharacters.- Since:
- 0.8 or earlier
-
getLineNumber
Given a 0-based character offset, return the 1-based number of the line that includes the position. Causes the contents of this source to be loaded if they are loaded lazily.- Throws:
UnsupportedOperationException- if this source cannot containcharacters.IllegalArgumentException- if the offset is outside the text contents- Since:
- 0.8 or earlier
-
getColumnNumber
Given a 0-based character offset, return the 1-based number of the column at the position. Causes the contents of this source to be loaded if they are loaded lazily.- Throws:
UnsupportedOperationException- if this source cannot containcharacters.IllegalArgumentException- if the offset is outside the text contents- Since:
- 0.8 or earlier
-
getLineStartOffset
Given a 1-based line number, return the 0-based offset of the first character in the line.- Throws:
UnsupportedOperationException- if this source cannot containcharacters.IllegalArgumentException- if there is no such line in the text- Since:
- 0.8 or earlier
-
getLineLength
The number of characters (not counting a possible terminating newline) in a (1-based) numbered line. Causes the contents of this source to be loaded if they are loaded lazily.- Throws:
UnsupportedOperationException- if this source cannot containcharacters.IllegalArgumentException- if there is no such line in the text- Since:
- 0.8 or earlier
-
getOptions
Returns the parsed option values of the given source for the given language. Options can be specified by implementingTruffleLanguage.getSourceOptionDescriptors(). When accessing source options during parsing, useTruffleLanguage.ParsingRequest.getOptionValues()instead of this method, to avoid parsing the options twice.Note that options may not be validated beforehand, which can result in an
IllegalArgumentExceptionif validation fails. If the source was parsed previously, all options are guaranteed to have been validated. Otherwise, this method validates only the options of the current language.- Parameters:
language- the language accessible viaTruffleLanguage.LanguageReference- Returns:
- the parsed
OptionValuesfor the specified source - Throws:
IllegalArgumentException- if option validation fails- Since:
- 25.0
- See Also:
-
createSection
public final SourceSection createSection(int startLine, int startColumn, int endLine, int endColumn) Create representation of a contiguous region in the source that does not have the character content available.- Parameters:
startLine- 1-based line number of the first character in the sectionstartColumn- 1-based column number of the first character in the section, or-1when the column is not definedendLine- 1-based line number of the last character in the sectionendColumn- 1-based column number of the last character in the section, or-1when the column is not defined- Throws:
UnsupportedOperationException- if this source hasbytes.- Since:
- 19.0
-
createSection
Creates a representation of a line of text in the source identified only by line number, from which the character information will be computed. Please note that calling this method does cause thecodeof this source to be loaded, if there is any. If nocodeisavailable, a SourceSection withoutcharacter contentis created with thestart lineand the sameend linedefined only.- Parameters:
lineNumber- 1-based line number of the first character in the section- Returns:
- newly created object representing the specified line
- Throws:
UnsupportedOperationException- if this source containsbytes.IllegalArgumentException- if the given lineNumber does not exist the source- Since:
- 0.17
-
createSection
Creates a representation of a contiguous region of text in the source. Please note that calling this method does only cause thecodeof this source to be loaded if assertions enabled. The bounds of the source section are only verified if assertions (-ea) are enabled in the host system. AnIllegalArgumentExceptionis thrown if the given indices are out of bounds of the source bounds.- Parameters:
charIndex- 0-based position of the first character in the sectionlength- the number of characters in the section- Returns:
- newly created object representing the specified region
- Throws:
UnsupportedOperationException- if this source cannot containcharacters.IllegalArgumentException- if charIndex < 0 or length < 0; in case assertions are enabled also if the given bounds are out of the source bounds.- Since:
- 0.17
-
createSection
Creates a representation of a contiguous region of text in the source. When character content is available, computes thecharIndexvalue by building a text map of lines in the source. Please note that calling this method does cause thecodeof this source to be loaded, if there is any. If nocodeisavailable,UnsupportedOperationExceptionis thrown. UsecreateSection(int, int, int, int)to create a SourceSection without character content.- Parameters:
startLine- 1-based line number of the first character in the sectionstartColumn- 1-based column number of the first character in the sectionlength- the number of characters in the section- Returns:
- newly created object representing the specified region
- Throws:
UnsupportedOperationException- if this source does not containcharacters.IllegalArgumentException- if arguments are outside the text of the source bounds- Since:
- 0.17
- See Also:
-
toString
-
newBuilder
public static Source.LiteralBuilder newBuilder(String language, CharSequence characters, String name) Creates a new character based literal source from a character sequence. The given characters must not mutate after they were accessed for the first time.Use this method for sources that do originate from a literal. For file or URL sources use the appropriate builder constructor and
Source.SourceBuilder.content(CharSequence).Example usage:
Source source = Source.newBuilder("js", "function() {\n" + " return 'Hi';\n" + "}\n", "hi.js").build(); assert "hi.js".equals(source.getName());- Parameters:
language- the language id, must not benullcharacters- the character sequence or string, must not benullname- the name of the source, ifnullthen"Unnamed"will be used as name.- Since:
- 19.0
-
newBuilder
Creates a new byte based literal source from a byte sequence. The given bytes must not mutate after they were accessed for the first time.Use this method for sources that do originate from a literal. For file or URL sources use the appropriate builder constructor and
Source.SourceBuilder.content(ByteSequence).Example usage:
byte[] bytes = new byte[] {/* Binary */}; Source source = Source.newBuilder("llvm", ByteSequence.create(bytes), "<literal>").build();- Parameters:
language- the language id, must not benullbytes- the byte sequence or string, must not benullname- the name of the source, ifnullthen"Unnamed"will be used as name.- Since:
- 19.0
-
newBuilder
Creates a new file based source builder from a given file. A file based source is either interpreted asbinaryorcharactersource depending on thedefault MIME typeof the language, thecontentsor the specifiedMIME type. A language may be detected from an existing file usingfindLanguage(TruffleFile).Example usage:
assert file.getName().endsWith(".java") : "Imagine 'c:\\sources\\Example.java' file"; String language = Source.findLanguage(file); Source source = Source.newBuilder(language, file).build(); assert file.getName().equals(source.getName()); assert file.getPath().equals(source.getPath()); assert file.toUri().equals(source.getURI());- Parameters:
language- the language id, must not benullfile- the file to use and load, must not benull- Since:
- 19.0
-
newBuilder
Creates a new URL based source builder from a given URL. A URL based source is either interpreted asbinaryorcharactersource depending on thedefault MIME typeof the language, thecontentsor the specifiedMIME type. A language may be detected from an existing file usingfindLanguage(URL).Example usage:
URL resource = relativeClass.getResource("sample.js"); Source source = Source.newBuilder("js", resource) .build(); assert resource.toExternalForm().equals(source.getPath()); assert "sample.js".equals(source.getName()); assert resource.toURI().equals(source.getURI());- Parameters:
language- the language id, must not benullurl- the URL to use and load, must not benull- Since:
- 19.0
-
newBuilder
Creates new character based literal source from a reader.Use this method for sources that do originate from a literal. For file or URL sources use the appropriate builder constructor and
Source.SourceBuilder.content(CharSequence).Example usage:
Reader stream = new InputStreamReader( relativeClass.getResourceAsStream("sample.js") ); Source source = Source.newBuilder("js", stream, "sample.js") .build(); assert "sample.js".equals(source.getName());- Since:
- 19.0
-
newBuilder
Creates a new source builder that inherits from the given Source. The Source properties can be modified using the builder methods.- Parameters:
source- the source to inherit the properties from- Since:
- 19.2.0
-
findLanguage
Returns the first language that supports evaluating the probed mime type of a givenfile. This method is a shortcut for:String mimeType = Source.findMimeType(file); return mimeType != null ? Source.findLanguage(mimeType) : null;
- Parameters:
file- the file to find the first language for- Throws:
IOException- if an error opening the file occurred.- Since:
- 19.0
- See Also:
-
findLanguage
Returns the first language that supports evaluating the probed mime type of a givenURL. This method is a shortcut for:String mimeType = Source.findMimeType(url); return mimeType != null ? Source.findLanguage(mimeType) : null;
- Parameters:
url- the url to find the first language for- Throws:
IOException- if an error opening the url occurred.- Since:
- 19.0
- See Also:
-
findMimeType
Returns the probed MIME type for a given file, ornullif no MIME type could be resolved. Typically the MIME type is identified using the file extension and/or using its contents. Probing the MIME type of anTruffleFilemay require to opening the file.- Throws:
IOException- if an error opening the file occurred.SecurityException- if the usedfilesystemdenied file reading.- Since:
- 19.0
- See Also:
-
findMimeType
Returns the probed MIME type for a given url, ornullif no MIME type could be resolved. Typically the MIME type is identified using the file extension, connection meta-data and/or using it contents. Returnsnullif the language of the given file could not be detected. Probing the language of an URL may require to open a new URL connection.- Throws:
IOException- if an error opening the url occurred.SecurityException- if the usedfilesystemdenied file reading.- Since:
- 19.0
- See Also:
-
findLanguage
Returns the first installed language that supports evaluating sources for a given MIME type. Returnsnullif no language was found that supports a given MIME type. The languages are queried in the same order as returned byEngine.getLanguages().- Since:
- 19.0
-