I am editing a cod pragmatically through editing the AST in Eclipse CDT, put after perform the refactor using Change#perform method, I found the code to be formatted, example here I am just cast a function call to be void
//Old code
Publish(Author_id, Content);
//New code
(void) Publish(
Author_id,
Content);
As you see the method has been formatted to be in 3 lines, how to stop this action?
My code sample that do refactoring
INodeFactory factory = ast.getASTNodeFactory();
IASTNode newNode = rewriter.createLiteralNode("( void )"+selectedNode.getRawSignature());
rewriter.replace(selectedNode, newNode, null);
Change change = rewriter.rewriteAST();
change = change.perform(new NullProgressMonitor());
I believe you have two options:
Configure CDT's built-in formatter to format the code the way you like it. In this case, based on the appearance of the "New code", it looks like Line Wrapping -> Function calls -> Arguments -> Line wrapping policy is set to one of the "Wrap all elements" options. You can change it to something you like better.
Implement the org.eclipse.cdt.core.CodeFormatter extension point to provide an alternative formatter that behaves differently from the default code formatter (for example, it could do nothing).
UPDATE: I don't know where to find an example of this, but assuming you're familiar with implementing Eclipse extension points in general, here is the reference for this one. The steps would be:
Write a class that extends org.eclipse.cdt.core.formatter.CodeFormatter and implements the format() method
Ad an <extension ...> tag to your plugin's plugin.xml referencing your class
Related
I don't or can't modify the Java source code. The goal to configure just the Kotlin compiler to know what is nullable and what isn't.
You can specify the type manually if you know something will never be null. For example, if you have the following Java code:
public static Foo test() {
return null;
}
and you call it in Kotlin like this:
val result = Foo.test()
then result will have a type of Foo! by default – which means it can be either Foo or Foo?.. the compiler doesn't have enough information to determine that.
However, you can force the type manually:
val result: Foo = Foo.test()
// use "result" as a non-nullable type
Of course, if at runtime that is not true, you'll get a NullPointerException.
For reference, please check the documentation.
I don't know of a way to configure the compiler for this, but IntelliJ IDEA has a feature that allows you to add annotations to code via an XML file called external annotations.
You can add the Jetbrains #Nullable and #NotNull annotations to library code, but when I've tried it, it only results in compiler warnings rather than errors when you use incorrect nullability in your code. These same annotations generate compiler errors when used directly in the source code. I don't know why there is a difference in behavior.
You can use extension functions for this. If you have a method String foo() in the class Test, you can define the extension function
fun Test.safeFoo(): String = this.foo()!!
The advantage is that the code is pretty obious.
The disadvantage of this approach is that you need to write a lot of boiler plate code. You also have to define the extension function in a place where all your modules or projects can see it. Also, writing that much code just to avoid !! feels like overkill.
It should also be possible to write a Kotlin compiler extension which generates them for you but the extension would need to know which methods never return null.
I've recently joined a codebase that no one seemed to ever run SonarLint against, and now every test class I open in IntelliJ is highlighted like a Christmas tree - all test methods are public, even though JUnit5 is used.
Tired of removing those public modifiers manually, I decided to implement an SSR template to do that for me. However, I can't seem to make it work with method parameter annotations! (which seem to be rather usual thing with JMockit)
The best I can have thus far is this:
Open Edit->Find->Replace structurally
Paste this into Search field:
#$MethodAnnotation$
public void $MethodName$(#mockit.Injectable $ParameterType$ $Parameter$) {
$statement$;
}
Choose file type: Java - Class Member
Add filter for MethodAnnotation variable: Text=org.junit.jupiter.api.Test
Add Min=0 for statement and Parameter variables
Paste this into Replace field:
#$MethodAnnotation$
void $MethodName$(#Injectable $ParameterType$ $Parameter$) {
$statement$;
}
(mind the indentation, otherwise it will be problematic!)
Select Complete match value for Search target
Find
As you can see, the annotation is hard-coded, which of course limits the applicability of this snippet seriously.
Is this a problem with IntelliJ or rather my bad knowledge of SSR? What would be a proposed solution?
I want to modify the behavior of some function without being the author of that function. What I control is that I can ask the author to follow some pattern, e.g. use a base class, use a certain decorator, property etc.
If in python, I would use a decorator to change the behavior of a method.
As an example, My goal: Improve code coverage by automatically testing over multiple input data.
Pseudo code:
#implementation SomeTestSuiteClass
// If in python, I would add a decorator here to change the behavior of the following method
-(void)testSample1 {
input = SpecialProvider();
output = FeatureToTest(input);
SpecialAssert(output);
}
#end
What I want: During test, the testSample1 method will be called multiple times. Each time, the SpecialProvider will emit a different input data. Same for the SpecialAssert, which can verify the output corresponding to the given input.
SpecialProvider and SpecialAssert will be API under my control/ownership (i.e. I write them).
The SomeTestSuiteClass together with the testSample1 will be written by the user (i.e. test writer).
Is there a way for Objective-C to achieve "what I want" above?
You could mock objects and/or its methods using objective-c runtime or some third party frameworks. I discourage it though. That is a sign of poor architecture choices in the 1st place. The main problem in your approach are hidden dependencies in your code directly referencing
SpecialProvider & SpecialAssert symbols directly.
A much better way to this would be like this:
-(void)testSample1:(SpecialProvider*)provider assert:(BOOL (^)(parameterTypes))assertBlock {
input = provider;
output = FeatureToTest(input);
if (assertBlock != nil) {
assertBlock(output);
}
}
Since Objective-c does not support default argument values like Swift does you could emulate it with:
-(void)testSample1 {
[self testSample1:DefaultSpecialProvider() assert:DefaultAssert()];
}
not to call the explicit -(void)testSample1:(SpecialProvider*)provider assert:(BOOL (^)(parameterTypes))assertBlock all the time, however in tests you would always use the explicit 2 argument variant to allow substituting the implementation(s) not being under test.
Further improvement idea:
Put the SpecialProvider and SpecialAssert behind protocols(i.e. equivalent of interfaces in other programming languages) so you can easily exchange the implementation.
I'am writing a code indentor using ANTLR4 and Java. I have successfully generated the lexer and the parser. And the approach i am using is to walk through the generated parse tree.
ParseTreeWalker mywalker = new ParseTreeWalker();
mywalker.walk(myListener, myTree);
The auto-generated *BaseListener has methods like below...
#Override public void enterEveryRule(ParserRuleContext ctx) { }
I'm very new to ANTLR. But, As I understand, I need to extend *BaseListener and override the relevant methods and write code to indent, So my question is what are the methods that I should be overriding for indenting the input code file? Or if there is an alternate approach I should take, please let me know.
Thanks!
None. You don't need a parser for this task and you are limiting yourself to valid code, when you require a parser (hence you cannot reformat code with a syntax error). Instead take the lexer and iterate over all tokens. Keep a state to know where you are (a block, a function, whatever) and indent according to that.
There are some nice libraries for testing in Scala (Specs, ScalaTest, ScalaCheck). However, with Scala's powerful type system, important parts of an API being developed in Scala are expressed statically, usually in the form of some undesirable or disallowed behavior being prevented by the compiler.
So, what is the best way to test whether something is prevented by the compiler when designing an library or other API? It is unsatisfying to comment out code that is supposed to be uncompilable and then uncomment it to verify.
A contrived example testing List:
val list: List[Int] = List(1, 2, 3)
// should not compile
// list.add("Chicka-Chicka-Boom-Boom")
Does one of the existing testing libraries handle cases like this? Is there an approach that people use that works?
The approach I was considering was to embed code in a triple-quote string or an xml element and call the compiler in my test. Calling code looking something like this:
should {
notCompile(<code>
val list: List[Int] = List(1, 2, 3)
list.add("Chicka-Chicka-Boom-Boom")
</code>)
}
Or, something along the lines of an expect-type script called on the interpreter.
I have created some specs executing some code snippets and checking the results of the interpreter.
You can have a look at the Snippets trait. The idea is to store in some org.specs.util.Property[Snippet] the code to execute:
val it: Property[Snippet] = Property(Snippet(""))
"import scala.collection.List" prelude it // will be prepended to any code in the it snippet
"val list: List[Int] = List(1, 2, 3)" snip it // snip some code (keeping the prelude)
"list.add("Chicka-Chicka-Boom-Boom")" add it // add some code to the previously snipped code. A new snip would remove the previous code (except the prelude)
execute(it) must include("error: value add is not a member of List[Int]") // check the interpreter output
The main drawback I found with this approach was the slowness of the interpreter. I don't know yet how this could be sped up.
Eric.