Hopefully this is a really quick one ;) I have written a lexer / parser specification in ANTLR3, and am targeting the CSharp2 target. The generated code works correctly, but I can't get ANTLR to put the C# output into a namespace.
The relevant section of the Grammar file is as follows:
grammar MyGrammar;
options
{
language = CSharp2;
output = AST;
ASTLabelType = CommonTree;
}
To generate the correct namespace, I have tried:
#namespace { MyNamespace }
and
#lexer::namespace { MyNamespace }
#parser::namespace { MyNamespace }
but both of these generate errors, claiming that the file has no rules.
Any help is appreciated.
I use this for a combined lexer and parser (and it generates the namespace correctly):
grammar Test;
options
{
language=CSharp2;
}
#lexer::namespace {
My.Name.Space
}
#parser::namespace {
My.Name.Space
}
DIGIT : '0'..'9';
simple : DIGIT EOF;
So i wonder why your version didn't work - maybe you want to try this simple example and see if it works for you.
It seems that the #namespace directive needs to be placed AFTER the tokens{} block. All good now...
With language = 'CSharp3'; (and CSharp2 as well), you can do:
#lexer::namespace {
My.Name.Space
}
#parser::namespace {
My.Name.Space
}
which generates:
} // namespace
My.Name.Space <-- compile error here
at the end of lexer and parser code. If I write:
#lexer::namespace {My.Name.Space}
#parser::namespace {My.Name.Space}
it works fine and generates:
} // namespace My.Name.Space <-- within the line comment, no error of course
Related
Say we have:
class MyClass {
myProperty: string
}
Is there any built in function or easy way to get JSON like this?:
{
"myProperty": "string"
}
EDIT: My end goal is I want to dynamically print typed class definitions to a web view, in some kind of structured object syntax like JSON. I'm trying to make a server API that will return the schema for various custom classes - for example http://myserver.com/MyClass should return MyClass's properties and their types as a JSON string or other structured representation.
Evert is correct, however a workaround can look like this
class MyClass {
myProperty: string = 'string'
}
JSON.stringify(new MyClass) // shows what you want
In other words, setting a default property value lets TS compile properties to JS
If the above solution is not acceptable, then I would suggest you parsing TS files with your classes with https://dsherret.github.io/ts-simple-ast/.
Typescript class properties exist at build-time only. They are removed from your source after compiling to .js. As such, there is no run-time way to get to the class properties.
Your code snippet compiles to:
var MyClass = /** #class */ (function () {
function MyClass() {
}
return MyClass;
}());
As you can see, the property disappeared.
Based on your update, I had this exact problem. This is how I solved it.
My JSON-based API uses json-schema across the board for type validation, and also exposes these schemas for clients to re-use.
I used an npm package to automatically convert json-schema to Typescript.
This works brilliantly.
I've created a method, and the return is Result<R> in a class of MyClass<R>, but the error message is: 'kotlin.Result' cannot be used as a return type
I've also looked into the Result source code for some hints; why is this so?
Test code (using v. 1.3-RC).
class MyClass<R>(val r: R) {
fun f(): Result<R> { // error here
return Result.success(r)
}
}
fun main(args: Array<String>) {
val s = Result.success(1)
val m = MyClass(s)
}
From the Kotlin KEEP:
The rationale behind these limitations is that future versions of
Kotlin may expand and/or change semantics of functions that return
Result type and null-safety operators may change their semantics when
used on values of Result type. In order to avoid breaking existing
code in the future releases of Kotin and leave door open for those
changes, the corresponding uses produce an error now. Exceptions to
this rule are made for carefully-reviewed declarations in the standard
library that are part of the Result type API itself.
Note: if you just want to experiment with the Result type you can bypass this limitation by supplying a Kotlin compiler argument -Xallow-result-return-type.
When using Gradle on Java or Android project:
Define the compiler argument on Kotlin compilation task. It applies both for production code and tests.
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
}
}
When using Gradle on Multiplatform project:
Define the compiler argument for each target compilation. It applies both for production code and tests.
kotlin {
targets.all {
compilations.all {
kotlinOptions {
freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
}
}
}
}
android {
kotlinOptions {
freeCompilerArgs = ["-Xallow-result-return-type"]
}
}
If you using android this solution for gradle
If using maven:
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<jvmTarget>1.8</jvmTarget>
<args>
<arg>-Xallow-result-return-type</arg>
</args>
</configuration>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
If using gradle:
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]
}
Source: http://rustyrazorblade.com/post/2018/2018-12-06-kotlin-result/
Update the kotlin version to 1.5 or above. See:
https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/result.md#limitations-legacy
I am porting a library from AS3 to Haxe and I need to make a method accepting variable number of arguments. Target is a *.swc library.
My question relates to this one but none of the suggested solutions outputs a method with the required signature: someMethod(...params)
Instead, the produced method is: someMethod(params:*=null)
This won't compile in AS3 projects using the library and the used code is beyond my reach. Is there a way to do this, perhaps macros?
Well, that's a great question. And, it turns out there is a way to do it!
Basically, __arguments__ is a special identifier on the Flash target, mostly used to access the special local variable arguments. But it can also be used in the method signature, in which case it changes the output from test(args: *) to test(...__arguments__).
A quick example (live on Try Haxe):
class Test {
static function test(__arguments__:Array<Int>)
{
return 'arguments were: ${__arguments__.join(", ")}';
}
static function main():Void
{
// the haxe typed way
trace(test([1]));
trace(test([1,2]));
trace(test([1,2,3]));
// using varargs within haxe code as well
// actually, just `var testm:Dynamic = test` would have worked, but let's not add more hacks here
var testm = Reflect.makeVarArgs(cast test); // cast needed because Array<Int> != Array<Dynamic>
trace(testm([1]));
trace(testm([1,2]));
trace(testm([1,2,3]));
}
}
Most importantly, this generates the following:
static protected function test(...__arguments__) : String {
return "arguments were: " + __arguments__.join(", ");
}
The C++17 standard says that the std::in_place constructors of std::optional must be explicit (the same was with boost::optional). But why?? What is the reason behind this?
It forbids to have a nice code like this:
struct Value
{
Value(int) { }
};
std::optional<Value> giveValueFive()
{
return {std::in_place, 5};
}
I have the following groovy code :
class FileWalker {
private String dir
public static void onEachFile(String dir,IAction ia) {
new File(dir).eachFileRecurse {
ia.perform(it)
}
}
}
walker = new FileWalker()
walker.onEachFile(args[0],new PrintAction())
I noticed that if I place a def in front of walker , the script works. Shouldn't this work the way it is now ?
You don't need a def in groovyConsole or in a groovy script. I consider it good programming practice to have it, but the language will work without it and add those types of variables to the scripts binding.
I'm not sure about the rest of your code (as it won't compile as you've posted it). But you either have a really old version of groovy or something else is wrong with your config or the rest of your code.
With the addition of a stub for the missing IAction interface and PrintAction class, I'm able to get it to run without modification:
interface IAction {
def perform(obj)
}
class PrintAction implements IAction{
def perform(obj) {
println obj
}
}
class FileWalker {
private String dir
public static void onEachFile(String dir,IAction ia) {
new File(dir).eachFileRecurse {
ia.perform(it)
}
}
}
walker = new FileWalker()
walker.onEachFile(args[0],new PrintAction())
I created a dummy directory with "foo/bar" and "foo/baz" files.
If I save it to "walkFiles.groovy" and call it from the command line with
groovy walkFiles.groovy foo
It prints:
foo/bar
foo/baz
This is with the latest version of groovy:
groovy -v
Groovy Version: 1.6-RC-3 JVM: 1.5.0_16
In scripting mode (or via "groovyConsole"), you need a declaration of walker with "def" before using it. A Groovy script file is translated into a derivative class of class Script before it get compiled. So, every declaration needs to be done properly.
On the other hand, when you're running a script in "groovysh" (or using an instance of class GroovyShell), its mechanism automatically binds every referencing object without the need of declaration.
updated:
My above answer would be wrong as I decompiled a .class of Groovy and found that it's using a binding object inside the script as well. Thus my first paragraph was indeed wrong.