- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
[Compiler] String to AST?
Mon, 2011-01-24, 16:16
I would like to convert an arbitrary string to it's "compiled" AST
representation as the scala interpreter does (I guess). So a compiler
plugin could e.g assign someString to "HELLO WORLD":
@StringAnnotation("""("hello world").toString.toUpperCase""")
var someString = ""
My current first shot plugin does in short:
* runafter parser
* create a new representation only compiler and a VirtualFile with the
annotation content
* compile and print unit.body
see: http://paste.pocoo.org/show/326025/
a)
Right now, "object o{val x = 0}" returns an AST, but e.g. "var x = 1+ 2"
doesn't because it wouldn't be a valid .scala file. How can I fix this?
b)
Is onlyPresentation a good choice? Should I instead overriding
computeInternalPhases with the appropriate phases or use -Ystop:phase?
c)
Is it possible to bind the environment of the outer compiler to the
inner one, so that e.g.
var x = _
(...)
@StringAnnotation("x += 3")
would work?
I found following code[1] using an interpreter and one variable which
does something similar:
Interpreter interpreter = new Interpreter(settings);
String[] context = { "FOO" };
interpreter.bind("context", "Array[String]", context);
interpreter
.interpret("de.tutorials.scala2.Test.main(context)");
context[0] = "BAR";
interpreter
.interpret("de.tutorials.scala2.Test.main(context)");
[1]
http://www.tutorials.de/java/320639-beispiel-zur-einbindung-des-scala-in...
thanks
Thu, 2011-01-27, 05:07
#2
Re: [Compiler] String to AST?
On 26.01.11 17:11, Linas wrote:
> Wrap your string into something that would make valid, then cut out the
> relevant section of AST?
You're right, this would work in a simple case. I would like to do write
a templating plugin where usecases like c) are possible and I'm stuck now :(
I put the question on stackoverflow:
http://stackoverflow.com/questions/4810657/compile-string-to-ast-inside-...
thanks
stefan
> a)
> Right now, "object o{val x = 0}" returns an AST, but e.g. "var x = 1+ 2"
> doesn't because it wouldn't be a valid .scala file. How can I fix this?
Wrap your string into something that would make valid, then cut out the
relevant section of AST? For example:
class Wrapper {
def wrapper() {
//your string goes here
}
}
The AST of the Wrapper should be the same every time, so cutting out the
wrapped portion should not be hard.
Linas.