I'm looking for an example (in XText) of how to implement code completion on an user defined objects members. As far as I can see I need to use IScope, but how all this wires together is unclear.
Given that trait is a user defined type, how do I go about building a grammar to code complete / validate the methods contained within String when I type name.?
trait String {
def toLowerCase(): String
def toUpperCase(): String
}
val name = new String()
name.toLowerCase()
Thanks
It highly depends on your grammar what you have to do to adopt scoping.
Let us say you have a grammar like
Model:
statements+=Statement+
;
Statement:
Trait | VarDef | Call
;
Trait:
"trait" name=ID "{"
ops+=Operation*
"}"
;
Operation:
"def" name=ID "()" ":" type=[Trait]
;
VarDef:
"val" name=ID "=" "new" type=[Trait] "()"
;
Call:
var=[VarDef] "." op=[Operation] "()"
;
then your scopeprovider would look like
public class MyDslScopeProvider extends AbstractDeclarativeScopeProvider {
IScope scope_Call_op(Call call, EReference ref) {
return Scopes.scopeFor(call.getVar().getType().getOps());
}
}
You can find a blog series on the topic here:
https://web.archive.org/web/20130129085620/http://blogs.itemis.de/stundzig/archives/773
In my book on Xtext, "Implementing Domain-Specific Languages with Xtext and Xtend", https://www.packtpub.com/application-development/implementing-domain-specific-languages-xtext-and-xtend , there is a chapter about scoping for a "smaller" Java language (dealing also with inheritance). You can find the sources of examples here: https://github.com/LorenzoBettini/packtpub-xtext-book-examples
Related
I am new to Generic Classes and Generic Methods. I have a simple cpode:
Func<string, string> selector = str => str.ToUpper();
string[] words = { "orange", "apple", "Article", "elephant" };
IEnumerable<String> aWords = words.Select(selector);
When I look at Select method it says:
IEnumerable<String> IEnumerable<String>.Select<String, String>(Func<string,string> collector)
How does Select generic method knows that String,String types are coming? Does it implicitly come from "selector" delegate? I am really confused.
Thanks
The C# compiler infers the type arguments for Select so that you don't have to type them. It burns those types into the compiled assembly.
Does it implicitly come from "selector" delegate?
Exactly. C# has some type inference so that you have to type less.
The Select method itself has no idea what piece of code called it. All it knows is that the type arguments are properly provided.
This Groovy script runs fine:
println 0;
class MyClass
{
public MyClass(int j) {};
public MyClass method() {return this};
}
This one fails with a compilation error ("unexpected token: public at line: 5, column: 4")
println 0;
class myClass
{
public myClass(int j) {};
public myClass method() {return this};
}
The only difference is the capitalization of the class name. I know the convention is for class names to be capitalized, but I thought it was just a convention. What exactly causes the compile error?
According to a Groovy mailing list thread from 2008, where a similar question was posed, Paul King explained:
Yes, the grammar currently looks for uppercase types only in declarations (apart from the primitive types).
In a more recent, unresolved Groovy JIRA ticket regarding lowercase class names, blackdrag comments that:
The problem is that in Groovy (unlike Java) variable names, method names and class names can share a context, making it ambiguous.
Barring a deeper exploration of the tokenizer, I'll just chalk this up as another minor inconsistency between Java and Groovy due to Groovy's syntax flexibility. And instead of thoroughly implementing a way to tell if a token is a type or method name in this context, Groovy takes a short cut and only assumes it can be a type name if the token matches a primitive or begins with a capital letter, as conventional Java types would.
In the following code from section 4.7.2 of the Alloy book, what does the this keyword refer to?
module library/list [t]
sig List {}
sig NonEmptyList extends List {next: List, element: t}
...
fun List.first : t {this.element}
fun List.rest : List {this.next}
fun List.addFront (e: t): List {
{p: List | p.next = this and p.element = e}
}
I would appreciate if you give me an elaborate description of this usage in Alloy.
Section 4.5.2 of Software Abstractions describes (among other things) what it calls the 'receiver' convention, that is the syntactic shorthand of writing functions and predicates as
fun X.f[y : Y, ...] { ... this ... }
instead of
fun f[x : X, y : Y, ...] { ... x ... }
That is, the declaration
fun List.first : t {this.element}
is equivalent to (and shorthand / syntactic sugar for)
fun first[x : List] : t {x.element}
And similarly for the other examples you give. The parallel would be even stronger if we said the long form was
fun first[this : List] : t {this.element}
but while this is a useful illustration, it's not legal: this is a keyword and cannot be used as an ordinary variable name.
You ask for an "elaborate description" of the usage of this in Alloy. Here's a survey. The keyword this can be used in the following situations:
In declarations and signature facts, this acts as a variable implicitly bound to each instance of the signature. So a declaration of the form
sig Foo { ... } { copacetic[this] }
is equivalent to
sig Foo { ... }
fact { all f : Foo | copacetic[f] }
In declarations and signature facts, every reference to a field f declared or inherited by the signature is implicitly expanded to this.f, where this is implicitly bound as described above, unless the reference is prefixed with #. The example at the end of 4.2.4 illustrates the semantics.
In the declaration bodies of functions and predicates declared using the 'receiver' convention, the keyword this acts as a variable implicitly bound to the first argument of the function or predicate. The example at the end of 4.5.2 illustrates this, as does the example cited here by the OP.
The 'receiver' convention is defined in section B.7.5 of the language reference.
All of these are pointed to from the entry for this in the index of Software Abstractions; for more information, read the relevant passages.
How to use String in Alloy?
What kind of function or operators for String are supported in Alloy?
I searched questions here and find String is a keyword in Alloy.
But I cannot find any reference about how to use String in Alloy.
Could you give one? If not, is possible to give a brief about String in Alloy?
You can actually use strings in Alloy, but only as literals to specify constant values (i.e., no string operations are supported, and Alloy does not implement a string solver). That said, the main use of strings is Alloy is to assign constant string literals to some fields for the sole purpose of making the generated instances more readable when visualized. Here is a simple example
sig Person {
name: String,
email: String
}
one sig P1 extends Person {} {
name = "Joe"
email = "joe#email.com"
}
run {
some p: Person | p.name != "Joe"
}
I read use keyword in Groovy. But could not come out with, for what it has been exactly been used. And i also come with category classes, under this topic,what is that too? And from, Groovy In Action
class StringCalculationCategory {
static def plus(String self, String operand) {
try {
return self.toInteger() + operand.toInteger()
} catch (NumberFormatException fallback) {
return (self << operand).toString()
}
}
}
use (StringCalculationCategory) {
assert 1 == '1' + '0'
assert 2 == '1' + '1'
assert 'x1' == 'x' + '1'
}
With the above code, can anyone say what is the use of use keyword in groovy? And also what the above code does?
See the Pimp My Library Pattern for what use does.
In your case it overloads the String.add(something) operator. If both Strings can be used as integers (toInteger() doesn't throw an exception), it returns the sum of those two numbers, otherwise it returns the concatenation of the Strings.
use is useful if you have a class you don't have the source code for (eg in a library) and you want to add new methods to that class.
By the way, this post in Dustin Marx's blog Inspired by Actual Events states:
The use "keyword" is actually NOT a keyword, but is a method on
Groovy's GDK extension of the Object class and is provided via
Object.use(Category, Closure). There are numerous other methods
provided on the Groovy GDK Object that provide convenient access to
functionality and might appear like language keywords or functions
because they don't need an object's name to proceed them. I tend not
to use variables in my Groovy scripts with these names (such as is,
println, and sleep) to avoid potential readability issues.
There are other similar "keywords" that are actually methods of the Object class, such as with. The Groovy JDK documentation has a list of such methods.
A very good illustration is groovy.time.TimeCategory. When used together with use() it allows for a very clean and readable date/time declarations.
Example:
use (TimeCategory) {
final now = new Date()
final threeMonthsAgo = now - 3.months
final nextWeek = now + 1.week
}