Eclipse text editor get incomplete code AST - eclipse

I am wondering is there a way to get the AST of an incomplete code fragment that the user inputs. For example, lets imagine that the code looks something like this:
String str = "This is some string";
int length = str.length +
Can I get the AST of such code? This is not syntactically correct, but I would still need the AST.
Additionally, would I be able to inject such code into the text editor? Ideally, I would add it as a string, but AST format could do as well.
Update 1:
To be precise, would I be able to use the ASTParser in some way so I get something like the following AST for the last line:
=
/ \
decl length +
/
str.length
Partial Answer:
JDT's ASTParser can be used with setStatementsRecovery which will yield the following AST:
=
/ \
decl length str.length
It is not exactly the desired solution, but someone may find it useful, like I did.

I don't understand what you are trying to achieve exactly, but depending on your syntax and the tools used, you could get an incomplete AST. From your code, such an AST could be as follows:
__ = __
/ \
decl length fail

Related

Removing Data Type From Tuple When Printing In Scala

I currently have two maps: -
mapBuffer = Map[String, ListBuffer[(Int, String, Float)]
personalMapBuffer = Map[mapBuffer, String]
The idea of what I'm trying to do is create a list of something, and then allow a user to create a personalised list which includes a comment, so they'd have their own list of maps.
I am simply trying to print information as everything is good from the above.
To print the Key from mapBuffer, I use: -
mapBuffer.foreach(line => println(line._1))
This returns: -
Sample String 1
Sample String 2
To print the same thing from personalMapBuffer, I am using: -
personalMapBuffer.foreach(line => println(line._1.map(_._1)))
However, this returns: -
List(Sample String 1)
List(Sample String 2)
I obviously would like it to just return "Sample String" and remove the List() aspect. I'm assuming this has something to do with the .map function, although this was the only way I could find to access a tuple within a tuple. Is there a simple way to remove the data type? I was hoping for something simple like: -
line._1.map(_._1).removeDataType
But obviously no such pre-function exists. I'm very new to Scala so this might be something extremely simple (which I hope it is haha) or it could be a bit more complex. Any help would be great.
Thanks.
What you see if default List.toString behaviour. You build your own string with mkString operation :
val separator = ","
personalMapBuffer.foreach(line => println(line._1.map(_._1.mkString(separator))))
which will produce desired result of Sample String 1 or Sample String 1, Sample String 2 if there will be 2 strings.
Hope this helps!
I have found a way to get the result I was looking for, however I'm not sure if it's the best way.
The .map() method just returns a collection. You can see more info on that here:- https://www.geeksforgeeks.org/scala-map-method/
By using any sort of specific element finder at the end, I'm able to return only the element and not the data type. For example: -
line._1.map(_._1).head
As I was writing this Ivan Kurchenko replied above suggesting I use .mkString. This also works and looks a little bit better than .head in my mind.
line._1.map(_._1).mkString("")
Again, I'm not 100% if this is the most efficient way but if it is necessary for something, this way has worked for me for now.

kdb/q - geting an expression by location to its containing source code string?

I'm playing around with Q's new .Q.trp, and the debug object which you're given in case of an error.
From what I see, the debug object contains a string representation of the source code where the error occured, as well as the offset in that string where the error was triggered.
For example,
{
something: 123;
x: 123; ThisThrowsAnError[456;789]; y: 123;
}[]
when executing above code, the debug object would contain this code in its entirity, as well as the offset pointing to (the beginning of) ThisThrowsAnError[].
My question is - based on this information, how can I extract the entire statement that cuased the error?
For example, in above example, I'd like to extract "ThisThorwsAnError[456;789]".
Things I've thought of so far...
Extract string from the offset, until the end of line. Doesn't work though, as there might be other statements in the same line (e.g. the "y: 123" above)
Parse the source code (literally, with "parse"). But then what..? The output could be anything (e.g. a lambda or a statement list), and then whatever it is still needs to be mapped back to the source locations somehow
Appreciate any ideas! Thanks

Any way in coan to have it not evaluate certain parts of my code base?

Hitting "##-operator does not compose a token in definition" using coan with a macro definition like this:
#define MY_STRINGIFY_CONCAT_MACRO(_x) \
a = #_x; \
b = #_x; \
c = prefix_ ## _x;
... which, from my compiler's perspective, is perfectly valid.
Having this code in x.c, then
$ coan source -gw x.c
coan: /home/andreasl/c/onion/no_ear/x.c: line 4: error 0x0081b: ##-operator does not compose a token in definition >>a = #_x; b = #_x; c = prefix_ ## _x;<< of "MY_STRINGIFY_CONCAT_MACRO(_x)"
(For those interested in debugging this: it doesn't occur if you omit either first or second stringification.)
Not expecting to get this fixed anytime soon, I'd like to know if there's some (undocumented) way to mark given section of my code for being 'ignored' (so passed through 'as is') by coan, e.g. some special
#ifndef COAN_PLEASE_ACCEPT_AND_LEAVE_AS_IS
...
#endif
... I could enclose such code with?
Or any other idea how to deal with this elegantly?
(I'm currently working this around by writing extra code allowing me to omit one of the two stringifications.)
> coan --version
coan, version 6.0.1 for 64 bit Unix/Linux(built Sep 15 2014,18:42:46)

What does dollar sign do in scala

When I was reading spark source code here, I saw code like $(a_variable).
What does it mean?
I copy the code here:
final val blockSize: IntParam = new IntParam(this, "blockSize",
"Block size for stacking input data in matrices. Data is stacked within partitions." +
" If block size is more than remaining data in a partition then " +
"it is adjusted to the size of this data. Recommended size is between 10 and 1000",
ParamValidators.gt(0))
/** #group getParam */
final def getBlockSize: Int = $(blockSize)
That isn't special Scala syntax, it's a method name. In Scala $ is a legal identifier. The method is inherited from the org.apache.spark.ml.param.Param trait.
See the source.
I believe that the dollar sign is usually used for string interpolation. What that means is that if I want to use a val(ue)/var(iable) inside a string (denoted with an s before the first double quotation), I can access such vals/vars using the $ sign. Otherwise, we won't be able to use vals/vars inside a string since it would not know how to escape the string characters.
Example:
val favoriteFruit = "strawberry"
val strawberryCount = 12
println(s"My favorite fruit is ${favoriteFruit}. I've had ${strawberryCount} pieces today!") // string interpolation
In your case, however it seems that $ is a shortcut to getOrDefault the var/val (as sourced by #Michael Zajac and #kingledion...gets the value/variable. If it does not exist, gets the default value/variable). Using getOrDefault may be a more robust solution in cases in which you expect the parameter to not always have a corresponding value, for which you can set a default value.

Parsing options that take more than one value with scopt in scala

I am using scopt to parse command line arguments in scala. I want it to be able to parse options with more than one value. For instance, the range option, if specified, should take exactly two values.
--range 25 45
Coming, from python background, I am basically looking for a way to do the following with scopt instead of python's argparse:
parser.add_argument("--range", default=None, nargs=2, type=float,
metavar=('start', 'end'),
help=(" Foo bar start and stop "))
I dont think minOccurs and maxOccurs solves my problem exactly, nor the key:value example in its help.
Looking at the source code, this is not possible. The Read type class used has a member tuplesToRead, but it doesn't seem to be working when you force it to 2 instead of 1. You will have to make a feature request, I guess, or work around this by using --min 25 --max 45, or --range '25 45' with a custom Read instance that splits this string into two parts. As #roterl noted, this is not a standard way of parsing.
It should be ok if only your values are delimited with something else than a space...
--range 25-45
... although you need to split them manually. Parse it with something like:
opt[String]('r', "range").action { (x, c) =>
val rx = "([0-9]+)\\-([0-9]+)".r
val rx(from, to) = x
c.copy(from = from.toInt, to = to.toInt)
}
// ...
println(s" Got range ${parsedArgs.from}..${parsedArgs.to}")