lombok-1.16.18/000077500000000000000000000000001312655740700131655ustar00rootroot00000000000000lombok-1.16.18/.gitignore000066400000000000000000000004251312655740700151560ustar00rootroot00000000000000/testenvironment.properties /bin /build /dist /ivyCache /google.properties /debug /*.launch /ssh.configuration /findbugsReport.html /lib /.settings /.project /.classpath /.factorypath /lombok.iml /.idea *.markdown.html /junit*.properties /eclipse.location /.apt_generated/ /outlombok-1.16.18/AUTHORS000066400000000000000000000022571312655740700142430ustar00rootroot00000000000000Lombok contributors in alphabetical order: Bulgakov Alexander Christian Sterzl DaveLaw Dave Brosius Dawid Rusin Enrique da Costa Cambio Jappe van der Hel Liu DongMiao Luan Nico Maarten Mulders Mart Hagenaars Peter Grant Philipp Eichhorn Rabea Gransberger Reinier Zwitserloot Robbert Jan Grootjans Roel Spilker Sander Koning Szymon Pacanowski Taiki Sugawara Thomas Darimont Yun Zhi Lin By adding your name to this list, you grant full and irrevocable copyright and patent indemnity to Project Lombok and all use of Project Lombok, and you certify that you have the right to do so for all commits you add to Project Lombok. lombok-1.16.18/LICENSE000066400000000000000000000020641312655740700141740ustar00rootroot00000000000000Copyright (C) 2009-2015 The Project Lombok Authors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lombok-1.16.18/README000066400000000000000000000012021312655740700140400ustar00rootroot00000000000000Project Lombok makes java a spicier language by adding 'handlers' that know how to build and compile simple, boilerplate-free, not-quite-java code. See LICENSE for the Project Lombok license. To start, run: ant -projecthelp HINT: If you'd like to develop lombok in eclipse, run 'ant eclipse' first. It creates the necessary project infrastructure and downloads dependencies. Note that, in order to run "LombokizedEclipse.launch", you need to have "Eclipse SDK" installed. For a list of all authors, see the AUTHORS file. Project Lombok was started by: Reinier Zwitserloot twitter: @surial home: http://zwitserloot.com/ Roel Spilker lombok-1.16.18/build.xml000066400000000000000000001165751312655740700150250ustar00rootroot00000000000000 This buildfile is part of projectlombok.org. It is the main entry point that contains the common tasks and can be called on to run the main aspects of all the sub-scripts. A new version of ivyplusplus was required and has been downloaded. Rerun the script to continue. Lombok version: ${lombok.version} (${lombok.fullversion}) lombok.launch.AnnotationProcessorHider$AnnotationProcessor lombok.launch.AnnotationProcessorHider$ClaimingProcessor lombok.launch.AnnotationProcessorHider$AstModificationNotifier ${releaseTimestamp} To add your eclipse installation's own plugins as dependencies, the build script needs to know where your eclipse is installed. Please enter this now (it's saved for future executions of this task). For example: /Applications/eclipse C:\Program Files\eclipse Eclipse can't be found in this location; I expect that directory to contain a subdirectory called 'plugins'. You do not have the eclipse plugin '${pluginName}'. I expected it to be in your eclipse plugins directory (followed by an underscore and a version number). Added to project classpath from your eclipse installation: ${pluginName}. ${sourceWarning} WARNING: If you wish to test JDK8 features in eclipse, there must be a JDK8 installation configured in your eclipse, and it must be called 'JavaSE-1.8'. Tests will now run against OpenJDK6 Tests will now run against OpenJDK7 Tests will now run against Oracle JDK7 Tests will now run against Oracle JDK8 ERROR: No test environment set up. You need to set up a test environment, which consists of a version of javac, and a JRE runtime classpath ('rt.jar'). Eventually, this environment concept will be extended to also include an ecj and/or eclipse to test against. You can let this ant script set them up for you: * ant setupJavaOpenJDK6TestEnvironment * ant setupJavaOpenJDK7TestEnvironment * ant setupJavaOracle7TestEnvironment * ant setupJavaOracle8TestEnvironment These will set up test environments based on OpenJDK6 and OpenJDK7, and download all required files automatically. This will be a relatively large download. You can switch by running this command again; the downloads are cached so switching is fast. You can also create your own by writing a 'testenvironment.properties' file. The relevant properties are: * test.location.javac = /path/to/javac6.jar * test.location.ecj = /path/to/ecj6.jar * test.location.bootclasspath = /path/to/rt.jar * test.location.name = RandomUsefulNameToIdentifyThisSetup * test.javaversion = 6 All tests successful.
Lombok - ]]>v${lombok.version}
Copyright © 2011-2015 The Project Lombok Authors, licensed under the MIT licence.]]>
The artifact has been published to staging. Now go to https://oss.sonatype.org/ and log in as Reinier, then doublecheck if all is well and 'release' it. Aborted. org.projectlombok.testAp.TestAp Running in order: First Lombok, Then testAP Running in order: First TestAP, Then Lombok
lombok-1.16.18/buildScripts/000077500000000000000000000000001312655740700156345ustar00rootroot00000000000000lombok-1.16.18/buildScripts/eclipse-debug-target.template000066400000000000000000000073021312655740700233670ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/eclipse-run-tests.template000066400000000000000000000065521312655740700227670ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/000077500000000000000000000000001312655740700174065ustar00rootroot00000000000000lombok-1.16.18/buildScripts/ivy-repo/net.java.openjdk.custom-javac6-1.6.0.18.xml000066400000000000000000000012511312655740700266360ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/net.java.openjdk.custom-javac7-1.7.0.xml000066400000000000000000000012401312655740700264070ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/netbeans.org-boot-6.8beta.xml000066400000000000000000000007301312655740700246230ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/netbeans.org-modules.java.source-6.8beta.xml000066400000000000000000000010031312655740700275410ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/netbeans.org-openide.modules-6.8beta.xml000066400000000000000000000007621312655740700267570ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/netbeans.org-openide.util-6.8beta.xml000066400000000000000000000007541312655740700262650ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-core.jobs-3.5.200.xml000066400000000000000000000013171312655740700263420ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-core.jobs-3.5.300.xml000066400000000000000000000013171312655740700263430ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-core.resources-3.7.0.xml000066400000000000000000000013341312655740700272560ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-core.resources-3.8.100.xml000066400000000000000000000013361312655740700274220ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-core.runtime-3.6.0.xml000066400000000000000000000013101312655740700267200ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-core.runtime-3.9.0.xml000066400000000000000000000013221312655740700267260ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-ecj-3.6.2.xml000066400000000000000000000011741312655740700250610ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-ecj-4.3.1.xml000066400000000000000000000011741312655740700250560ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-ecj-I20140430.xml000066400000000000000000000012221312655740700254130ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-equinox.common-3.6.0.xml000066400000000000000000000013151312655740700272720ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-equinox.common-3.6.200.xml000066400000000000000000000013351312655740700274360ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-jdt.core-3.6.0.xml000066400000000000000000000012641312655740700260260ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-jdt.core-3.9.1.xml000066400000000000000000000013061312655740700260270ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-jdt.ui-3.6.0.xml000066400000000000000000000013001312655740700255020ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-jdt.ui-3.9.1.xml000066400000000000000000000013001312655740700255060ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-osgi-3.6.0.xml000066400000000000000000000012601312655740700252530ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.eclipse.custom-osgi-3.9.0.xml000066400000000000000000000012721312655740700252610ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/org.projectlombok-lombok.patcher-0.22.xml000066400000000000000000000011651312655740700270600ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/projectlombok.org-jsch-ant-fixed-0.1.42.xml000066400000000000000000000007341312655740700271160ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/projectlombok.org-markdownj-1.02b4.xml000066400000000000000000000006401312655740700263660ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/projectlombok.org-spi-0.2.4.xml000066400000000000000000000007411312655740700250220ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/projectlombok.org-spi-0.2.7.xml000066400000000000000000000007411312655740700250250ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy-repo/zwitserloot.com-cmdreader-1.2.xml000066400000000000000000000013571312655740700255420ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivy.xml000066400000000000000000000100471312655740700171670ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/ivysettings.xml000066400000000000000000000007041312655740700207470ustar00rootroot00000000000000 lombok-1.16.18/buildScripts/javadoc/000077500000000000000000000000001312655740700172435ustar00rootroot00000000000000lombok-1.16.18/buildScripts/javadoc/java6/000077500000000000000000000000001312655740700202525ustar00rootroot00000000000000lombok-1.16.18/buildScripts/javadoc/java6/package-list000066400000000000000000000100231312655740700225350ustar00rootroot00000000000000java.applet java.awt java.awt.color java.awt.datatransfer java.awt.dnd java.awt.event java.awt.font java.awt.geom java.awt.im java.awt.im.spi java.awt.image java.awt.image.renderable java.awt.print java.beans java.beans.beancontext java.io java.lang java.lang.annotation java.lang.instrument java.lang.management java.lang.ref java.lang.reflect java.math java.net java.nio java.nio.channels java.nio.channels.spi java.nio.charset java.nio.charset.spi java.rmi java.rmi.activation java.rmi.dgc java.rmi.registry java.rmi.server java.security java.security.acl java.security.cert java.security.interfaces java.security.spec java.sql java.text java.text.spi java.util java.util.concurrent java.util.concurrent.atomic java.util.concurrent.locks java.util.jar java.util.logging java.util.prefs java.util.regex java.util.spi java.util.zip javax.accessibility javax.activation javax.activity javax.annotation javax.annotation.processing javax.crypto javax.crypto.interfaces javax.crypto.spec javax.imageio javax.imageio.event javax.imageio.metadata javax.imageio.plugins.bmp javax.imageio.plugins.jpeg javax.imageio.spi javax.imageio.stream javax.jws javax.jws.soap javax.lang.model javax.lang.model.element javax.lang.model.type javax.lang.model.util javax.management javax.management.loading javax.management.modelmbean javax.management.monitor javax.management.openmbean javax.management.relation javax.management.remote javax.management.remote.rmi javax.management.timer javax.naming javax.naming.directory javax.naming.event javax.naming.ldap javax.naming.spi javax.net javax.net.ssl javax.print javax.print.attribute javax.print.attribute.standard javax.print.event javax.rmi javax.rmi.CORBA javax.rmi.ssl javax.script javax.security.auth javax.security.auth.callback javax.security.auth.kerberos javax.security.auth.login javax.security.auth.spi javax.security.auth.x500 javax.security.cert javax.security.sasl javax.sound.midi javax.sound.midi.spi javax.sound.sampled javax.sound.sampled.spi javax.sql javax.sql.rowset javax.sql.rowset.serial javax.sql.rowset.spi javax.swing javax.swing.border javax.swing.colorchooser javax.swing.event javax.swing.filechooser javax.swing.plaf javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi javax.swing.plaf.synth javax.swing.table javax.swing.text javax.swing.text.html javax.swing.text.html.parser javax.swing.text.rtf javax.swing.tree javax.swing.undo javax.tools javax.transaction javax.transaction.xa javax.xml javax.xml.bind javax.xml.bind.annotation javax.xml.bind.annotation.adapters javax.xml.bind.attachment javax.xml.bind.helpers javax.xml.bind.util javax.xml.crypto javax.xml.crypto.dom javax.xml.crypto.dsig javax.xml.crypto.dsig.dom javax.xml.crypto.dsig.keyinfo javax.xml.crypto.dsig.spec javax.xml.datatype javax.xml.namespace javax.xml.parsers javax.xml.soap javax.xml.stream javax.xml.stream.events javax.xml.stream.util javax.xml.transform javax.xml.transform.dom javax.xml.transform.sax javax.xml.transform.stax javax.xml.transform.stream javax.xml.validation javax.xml.ws javax.xml.ws.handler javax.xml.ws.handler.soap javax.xml.ws.http javax.xml.ws.soap javax.xml.ws.spi javax.xml.ws.wsaddressing javax.xml.xpath org.ietf.jgss org.omg.CORBA org.omg.CORBA.DynAnyPackage org.omg.CORBA.ORBPackage org.omg.CORBA.TypeCodePackage org.omg.CORBA.portable org.omg.CORBA_2_3 org.omg.CORBA_2_3.portable org.omg.CosNaming org.omg.CosNaming.NamingContextExtPackage org.omg.CosNaming.NamingContextPackage org.omg.Dynamic org.omg.DynamicAny org.omg.DynamicAny.DynAnyFactoryPackage org.omg.DynamicAny.DynAnyPackage org.omg.IOP org.omg.IOP.CodecFactoryPackage org.omg.IOP.CodecPackage org.omg.Messaging org.omg.PortableInterceptor org.omg.PortableInterceptor.ORBInitInfoPackage org.omg.PortableServer org.omg.PortableServer.CurrentPackage org.omg.PortableServer.POAManagerPackage org.omg.PortableServer.POAPackage org.omg.PortableServer.ServantLocatorPackage org.omg.PortableServer.portable org.omg.SendingContext org.omg.stub.java.rmi org.w3c.dom org.w3c.dom.bootstrap org.w3c.dom.events org.w3c.dom.ls org.xml.sax org.xml.sax.ext org.xml.sax.helpers lombok-1.16.18/buildScripts/website.ant.xml000066400000000000000000000201461312655740700206040ustar00rootroot00000000000000 This buildfile is part of projectlombok.org. It is responsible for building the website and all website-related aspects, such as applying the templates to produce the website, converting the changelog into HTML, and creating javadoc. Supply lombok.version Supply lombok.fullversion ssh.username and ssh.keyfile should be set. Welcome to the lombok javadoc. If you're just looking to learn more about using lombok You probably want to look at the feature documentation. Otherwise, check the lombok package. If you're trying to extend lombok or write your own plugins, the other packages are what you're looking for. ]]>
Lombok - ]]>v${lombok.version}
Copyright © 2009-2015 The Project Lombok Authors, licensed under the MIT licence.]]>
lombok-1.16.18/doc/000077500000000000000000000000001312655740700137325ustar00rootroot00000000000000lombok-1.16.18/doc/.gitignore000066400000000000000000000000051312655740700157150ustar00rootroot00000000000000api lombok-1.16.18/doc/PlannedExtensions.txt000066400000000000000000000222231312655740700201350ustar00rootroot00000000000000Planned lombok features ======================= ## more hooks The parse and compilation process looks roughly like this: * raw text * list of tokens * Abstract Syntax Tree * Bound AST (a.k.a. LST) * bytecode * file on disk Currently lombok hooks right after the AST is built. It would be nice if you can also hook post binding, for modifying how types work. That way you could for example add a 'sort' method to List, or some such. It would also be nice if lombok can hook right after the bytecode is built, so bytecode-level rewriters such as generators can have a go, as well as cleanup some of the work lombok did in an earlier phase (such as just replacing try { /* block */ } catch ( Throwable t ) { throw sneakyThow(t); } with just 'block' - on the JVM level it boils down to the same thing in faster and smaller code. It may even be interesting to hook into the parser right at the raw text phase, not to modify the raw text, but to add more tokens and tree building primitives to the parser, such as closures, but that would probably be extremely complicated. ## Package level annotations and world awareness Lombok cannot currently figure out where sibling source files are, and it cannot for example find package-info.java or module-info.java (looking ahead to java7). Package-level or module-level annotations to enable or disable certain behaviours would probably be nice to be able to do. Javac has the filer, and eclipse has the IProject, so we ought to be able to hack something together. To hook after bytecode generation in javac: com.sun.tools.javac.jvm.ClassWriter.writeClassFile(OutputStream out, ClassSymbol c) - hack the one line where out.write() is called. ## Netbeans support Netbeans uses a slightly modified version of javac internally. This version seems compatible with everything the lombok.javac package does, however it is started specifically without annotation processors which is why lombok can't hook into netbeans that way. Using an agent failed because somehow the agent stops getting called on to instrument class files. Possibly netbeans is starting a new JVM under the hood and we need to instrument THAT call to add our agent? We may have to look into how netbeans' classloading works and hook there to load modified classes. ## IDEA support It's not open source and I've heard that they don't use javac under the hood but some sort of ANTLR based parser. If that is true, IDEA will need a dedicated lombok/IDEA afficionado to write and maintain an IDEA version of lombok, because that's far too much effort for Roel or Reinier, who don't own an IDEA copy and weren't planning to switch IDEs. Planned transformations ======================= ## @Property Basic needs: - generate a getter and a setter. The setter needs to fire notification handlers. - bind 2 properties together, with an optional value mapper. The utility of binding with mapping is too low to consider that 'too complicated, just write it out' territory. Note that conversion is 2-way, the slew of Mapping interfaces in functionaljava and similar libraries are all one-way. - add/remove a property change listeners. - optional: Support an 'invalid' state. Any 'get' operation must first update (re-validate) the value. This way properties backed by expensive operations can be lazily queried. ### JSR295 and JGoodies binding JSR295 has a Property class that is capable of getting/setting/notifying for a wide range of string-based properties, which seems like needlessly dumb design (Never use (non-compile-time checked) string literals for this stuff!) Being compatible with it can be done if specifically asked for, but using that as the default seems like a bad idea. JSR295 seems like it won't make it into java7. String literals completely eliminate the ability to have some sort of static type checking for the actual type of object that you need to set/get, and for properties that only expose one value, this string is usually ignored, and ignored variables are an obvious indicator of bad API design. JGoodies binding has made the similar fatal mistake of using a string literal. ### JavaFX binding See [Hacking JavaFX Binding](http://today.java.net/pub/a/today/2009/06/02/hacking-javafx-binding.html) for source on this info. See also [FishEye browser for the JavaFX's com.sun.javafx.runtime.location package](http://fisheye4.atlassian.com/browse/openjfx-compiler/trunk/src/share/classes/com/sun/javafx/runtime/location) JavaFX actually uses `$foo` as a field that holds a Location object (JavaFX's take on properties). In JavaFX's internals, a property is called a Location, and it has the methods: * `isMutable()` * `isValid()` / `invalidate()` / `update()` * `addChangeListener()` / `removeChangeListener()` The actual set and get methods are implemented via dynamically generated subtypes, in order for the return/param type on the methods to be properly typed. These methods also have unique names; the `IntVariable` class has methods named `getAsInt()` and `setAsInt(int)` for example. Each type comes in `xxxConstant` and `xxxVariable` variants, for mutable and immutable. Having an immutable property in java seems overkill. Change ChangeListener just contains an onChange() method; the listener is evidently supposed to both hold a reference to the actual Location to get the change/interact, AND to be registered on only one Location as there's no way to differentiate the onChange() calls if you're listening to more than 1 property. There's also a getDependencyKind() method which seems more related to JavaFX's internal workings. There are generated unique subclasses per type which add more methods to do retrieval. Using this system directly also seems problematic: * All this auto-generation really isn't helping - lombok is a compile-time device. We'd have to roll specific subclasses. * There's quite a bit of javafx-specific stuff going on which we'd have to leave blank. * This is all in a com.sun.javafx.runtime.location package. However, we could use it as inspiration, and strive to be as API compatible with it as seems reasonable, without of course the package name. At some point we might introduce a module/package level annotation to state that all lombok properties need to be generated as JavaFX properties. ## @Generator There are bytecode rewriters out there, though technically it may be possible to do this on the source level. The idea behind @Generator is that all method local state is retained when you return, so this: @Generator public int return0Through9() { for ( int i = 0 ; i < 10 ; i++ ) return i; } would actually do what it says, instead of returning 0 every time you call it. The return type should probably be `Iterable` instead, which would work well with a source-level rewrite. bytecode rewrite based generators use a superclass type named 'Generator' and use this to support a method that returns X, but which when called from the outside returns Iterable. ## @Finalizer Creates a new unique (serializable?) anonymous inner class based object that has a finalizer which will call the annotated method. # Maybes: ## @RunInEDT Automatically wraps the method in a SwingUtilities.invoke(andWait/later). ## @SaneEquals Finds all instances of `a == b` where both a and b are non-primitive types, and replaces it with: `a == null ? b == null : a.equals(b)` - this is dangerous new territory where we change the semantics of legal java code into different java code, but it is admittedly a lot more useful than what `a == b` does now. ## List Comprehensions Something like: List lengths = build; for ( String s : list ) toInt().filter(s != null).select(s.length()); issues: Ugly; what happens if you use 'for' as an expression? Does the AST still contain a ForStatement, or does the parser just give up at that point? Can the toInt() bit be eliminated somehow, inferencing the type from the parameter in s.length()? Auto-formatters will screw this up. The biggest advantage of list comprehensions is that you can use them in-place as an expression instead of adding a bunch of code lines to first create a new list and then fill it. However, the above is only going to work when assigning to a new variable, which defeats a lot of the purpose! ## Dodge access restrictions (call method private stuff, recompile to reflection). An annotation on a local variable declaration or field that states that any method calls to non-accessible methods gets rewritten to reflective calls. Would require knowledge of the depedencies which lombok does not currently have. ## @ReturnThis Enforces that 'this' is returned, or if missing, adds 'return this' to the end of the method and any return statements. Figuring out where to put statements is _very_ hard, because sticking a 'return this;' at the end of a method that consists of an endless while loop is illegal java code (unreachable code), and without auto-generating the 'return this' statements, the utility of this annotation seems too low to bother with it. It would also be nice if extending classes automatically generated a new method with itself as return type - THAT would be worth it, but requires knowledge of the world and sets a precedent where annotations in a supertype have an effect on compilation, which is not java-esque. ## lombok-1.16.18/doc/changelog.markdown000066400000000000000000001637631312655740700174450ustar00rootroot00000000000000Lombok Changelog ---------------- ### v1.16.18 (July 3rd, 2017) * PLATFORM: JDK9 support much improved since v1.16.6; [Issue #985](https://github.com/rzwitserloot/lombok/issues/985) * BUGFIX: Lombok now works with [Bazel](https://bazel.build/) and [Error Prone](https://error-prone.info/). [Issue #1290](https://github.com/rzwitserloot/lombok/issues/1290) * FEATURE: Lombok has a new [website](https://projectlombok.org/)! A few very minor changes to the code to be more consistent with it have been added, mostly to the javadoc. ### v1.16.16 "Dancing Elephant" (March 23rd, 2017) * FEATURE: `@Builder.Default` lets you configure default values for your fields when using `@Builder`. See the [Builder feature page](https://projectlombok.org/features/Builder.html) for more information. [Issue #1201](https://github.com/rzwitserloot/lombok/issues/1201) * PLATFORM: JDK9 now supported for compilation (delomboking with java9 not yet possible). Note, you'll have to do some command line wrangling. See [Issue #985](https://github.com/rzwitserloot/lombok/issues/985) * BUGFIX: The `onX` feature (which lets you add annotations to generated methods) did not work if the annotation you added contained named parameters, and you are compiling with JDK8's javac. We can't fix this (it's a bug in javac), but we have provided an alternate, prettier way to do `onX` on javac8+. [Issue #778](https://github.com/rzwitserloot/lombok/issues/778) [onX documentation](https://projectlombok.org/features/experimental/onX.html) * BUGFIX: `@Data` and `@Value` now respect the configuration for field access when generating equals, hashCode and toString [Issue #1329](https://github.com/rzwitserloot/lombok/issues/1329) * BUGFIX: `@Builder` now marks generated builder 'setters' as `@Deprecated` if the source field is deprecated. [Issue #1342](https://github.com/rzwitserloot/lombok/issues/1342) * CHANGE: `@ConstructorProperties` will now also be generated for private and package private constructors. This is useful for Jackson [Issue #1180](https://github.com/rzwitserloot/lombok/issues/1180) ### v1.16.14 (February 10th, 2017) * FEATURE: Generated classes, methods and fields can now also annotated with `@lombok.Generated` [Issue #1014](https://github.com/rzwitserloot/lombok/issues/1014) * PLATFORM: Lombok can now be used together with other annotation processors that are looking for lombok-generated methods, but only if lombok is the first annotation processor executed. The most commonly used annotation processor affected by this change is [MapStruct](http://mapstruct.org/); we've worked with the mapstruct team specifically to allow any order. Other annotation processors might follow the framework we've built to make this possible; point the authors of any such processor to us and we'll get it sorted [MapStruct issue #510](https://github.com/mapstruct/mapstruct/issues/510) [Lombok issue #973](https://github.com/rzwitserloot/lombok/issues/973) * PLATFORM: Eclipse: Refactor script 'rename field' when lombok has also generated getters and/or setters for this field is nicer now [Issue #210](https://github.com/rzwitserloot/lombok/issues/210) * BUGFIX: Something you never encountered. [Issue #1274](https://github.com/rzwitserloot/lombok/issues/1274) ### v1.16.12 (December 5th, 2016) * FEATURE: `var` is the mutable sister of `val`. For now experimental, and opt-in using `ALLOW` in the flagUsage configuration key. Thanks for the contribution, Bulgakov Alexander. * CHANGE: `@Value` and `@FieldDefaults` no longer touch static fields [Issue #1254](https://github.com/rzwitserloot/lombok/issues/1254) * BUGFIX: `val` in lambda expressions now work as expected [Issue #911](https://github.com/rzwitserloot/lombok/issues/911) * BUGFIX: `Getter(lazy=true)` now emits an error message when used on a transient field [Issue #1236](https://github.com/rzwitserloot/lombok/issues/1236) * BUGFIX: Annotation Processors that use ecj internally (dagger) no longer give linkage errors [Issue #1218](https://github.com/rzwitserloot/lombok/issues/1218) * PLATFORM: Red Hat JBoss Developer Studio is now correctly identified by the installer [Issue #1164](https://github.com/rzwitserloot/lombok/issues/1164) * BUGFIX: delombok: for-loops with initializers that are not local variables would be generated incorrectly [Issue #1076](https://github.com/rzwitserloot/lombok/issues/1076) ### v1.16.10 (July 15th, 2016) * FEATURE: Added support for JBoss logger [Issue #1103](https://github.com/rzwitserloot/lombok/issues/1103) * ENHANCEMENT: Running `javac -Xlint:all` would generate a warning about unclaimed annotations [Issue #1117](https://github.com/rzwitserloot/lombok/issues/1117) * BUGFIX: Eclipse Mars would sometimes throw a NullPointerException when using `@Delegate` [Issue #913](https://github.com/rzwitserloot/lombok/issues/913) * ENHANCEMENT: Add support for older maven-compiler-plugin [Issue #1138](https://github.com/rzwitserloot/lombok/issues/1138) ### v1.16.8 (March 7th, 2016) * PLATFORM: Starting jdk9 support: No more error message regarding `pid` * FEATURE: `@Builder` updates: It now generates `clearFieldName()` methods if `@Singular` is used. [Issue #967](https://github.com/rzwitserloot/lombok/issues/967). * FEATURE: `@Builder` updates: The annotation can now be put on instance methods. [Issue #63](https://github.com/rzwitserloot/lombok/issues/63). * FEATURE: `@Builder` updates: `@Singular` now supports guava's ImmutableTable [Issue #937](https://github.com/rzwitserloot/lombok/issues/937). * FEATURE: A `lombok.config` key can now be used to make your fields `final` and/or `private`... __everywhere__. We'll be monitoring the performance impact of this for a while. We'll touch every source file if you turn these on, and even if you don't, we have to call into the lombok config system for every file. * FEATURE: A `lombok.config` key can now be used to set the default behaviour of `@EqualsAndHashCode` when generating methods for a class that extends something in regards to calling the superclass implementations of `equals` and `hashCode` or not. [Issue #965](https://github.com/rzwitserloot/lombok/issues/965). * FEATURE: Putting `@Wither` on abstract classes now generates something slightly more useful: An abstract wither method. [Issue #945](https://github.com/rzwitserloot/lombok/issues/945). * BUGFIX: `@Helper` used to only be be legal in pretty specific places; now it works just about everywhere. * BUGFIX: lambdas with 1 argument that has an explicit type did not pretty print correctly. [Issue #972](https://github.com/rzwitserloot/lombok/issues/972). * BUGFIX: When using delombok, a source file with only `@NonNull` annotations on parameters as lombok feature would not get properly delomboked. [Issue #950](https://github.com/rzwitserloot/lombok/issues/950). * BUGFIX: `@Delegate` in javac would generate arrays instead of varargs parameters. [Issue #932](https://github.com/rzwitserloot/lombok/issues/932). * BUGFIX: `@Value` and `@FieldDefaults` no longer make uninitialized static fields final. [Issue #928](https://github.com/rzwitserloot/lombok/issues/928). * ENHANCEMENT: `@Builder.ObtainVia` now has `@Retention(SOURCE)` [Issue #986](https://github.com/rzwitserloot/lombok/issues/986). * ENHANCEMENT: Putting `@NonNull` on a parameter of an abstract method no longer generates a warning, to allow you to use this annotation to document intended behaviour [Issue #807](https://github.com/rzwitserloot/lombok/issues/807). ### v1.16.6 (August 18th, 2015) * FEATURE: `@Helper` can be placed on method-local inner classes to make all methods in the class accessible to the rest of the method. [Full documentation](https://projectlombok.org/features/experimental/Helper.html). * FEATURE: `@Builder(toBuilder = true)` is now available. It produces an instance method that creates a new builder, initialized with all the values of that instance. For more, read the [Feature page on Builder](https://projectlombok.org/features/Builder.html). * FEATURE: the `hashCode()` method generated by lombok via `@EqualsAndHashCode`, `@Data`, and `@Value` is now smarter about nulls; they are treated as if they hash to a magic prime instead of 0, which reduces hash collisions. * FEATURE: `@NoArgsConstructor(force = true)` can be used to create no args constructors even if final fields are present. * BUGFIX: Parameterized static methods with `@Builder` would produce compiler errors in javac. [Issue #828](https://github.com/rzwitserloot/lombok/issues/828). * BUGFIX: The new annotations-on-types feature introduced in JDK8 did not delombok correctly. [Issue #855](https://github.com/rzwitserloot/lombok/issues/855). * PERFORMANCE: the config system caused significant slowdowns in eclipse if the filesystem is very slow (network file system) or has a slow authentication system. * BUGFIX: Various quickfixes in Eclipse Mars were broken. [Issue #861](https://github.com/rzwitserloot/lombok/issues/861) [Issue #866](https://github.com/rzwitserloot/lombok/issues/866) [Issue #870](https://github.com/rzwitserloot/lombok/issues/870). ### v1.16.4 (April 14th, 2015) * BUGFIX: Lombok now works with Eclipse Mars. * BUGFIX: @UtilityClass could result in uninitialized static variables if compiled with ecj/eclipse. [Issue #839](https://github.com/rzwitserloot/lombok/issues/839) * BUGFIX: This version of lombok has a refactored launcher (the one introduced in v1.16.0), which fixes various bugs related to errors in eclipse concerning loading classes, failure to find lombok classes, and errors on ClassLoaders. Probably impacts issues [Issue #767](https://github.com/rzwitserloot/lombok/issues/767) and [Issue #826](https://github.com/rzwitserloot/lombok/issues/826). ### v1.16.2 (February 10th, 2015) * FEATURE: The config key `lombok.extern.findbugs.addSuppressFBWarnings` can now be used to add findbugs suppress warnings annotations to all code lombok generates. This addresses feature request [Issue #737](https://github.com/rzwitserloot/lombok/issues/737). * FEATURE: New lombok annotation: `@UtilityClass`, for making utility classes (not instantiable, contains only static 'function' methods). See the [feature documentation](https://projectlombok.org/features/experimental/UtilityClass.html) for more information. * BUGFIX: The ant `delombok` task was broken starting with v1.16.0. Note that the task def class has been changed; taskdef `lombok.delombok.ant.Tasks$Delombok` instead of the old `lombok.delombok.ant.DelombokTask`. [Issue #810](https://github.com/rzwitserloot/lombok/issues/810). * BUGFIX: `val` in javac would occasionally fail if used inside inner classes. This is (probably) fixed. [Issue #729](https://github.com/rzwitserloot/lombok/issues/729) and [Issue #616](https://github.com/rzwitserloot/lombok/issues/616). * BUGFIX: Starting with v1.16.0, lombok would fail to execute as an executable jar if it was in a path with spaces in it. [Issue #812](https://github.com/rzwitserloot/lombok/issues/812). * BUGFIX: v1.16.0 did not work in old eclipse versions (such as eclipse indigo). [Issue #818](https://github.com/rzwitserloot/lombok/issues/818). ### v1.16.0 "Candid Duck" (January 26th, 2015) * BUGFIX: `@ExtensionMethod` was broken in Eclipse using java 8. [Issue #777](https://github.com/rzwitserloot/lombok/issues/777), [Issue #782](https://github.com/rzwitserloot/lombok/issues/782) * BUGFIX: delombok: Using exotic characters in your source files would overzealously backslash-u escape them. Now, all characters are printed unescaped, assuming your chosen encoding can support them. Otherwise, they are escaped. [Issue #794](https://github.com/rzwitserloot/lombok/issues/794) * PROMOTION: `@Builder` has graduated from experimental to the main package with a few changes (addition of `@Singular`, removal of the `fluent` and `chain` options). The old one still exists and has been deprecated. * FEATURE: `@Builder` now supports adding the `@Singular` annotation to any field/parameter that represents a collection, which results in a method in the generated builder that takes in one element of that collection and adds it. Lombok takes care of generating the appropriate code to produce a compacted immutable version of the appropriate type. In this version, java.util collections and guava's ImmutableCollections are supported. See the [feature documentation](https://projectlombok.org/features/Builder.html) for more information. * FEATURE: Added a launcher to the lombok boot process which removes the need for `-Xbootclasspath` to be in your `eclipse.ini` file, and removes all non-public API and third party dependencies (such as ASM) from the lombok jar, thus removing them from your IDE's auto complete offerings in any project that uses lombok. For those debugging lombok, the launcher enables hot code replace which makes debugging a lot easier, as previously one was required to shut down the IDE, rebuild the jar, and relaunch. Add `-Dshadow.override.lombok=/path/to/lombok/bin` to the launch target for hot code replace. ### v1.14.8 (September 15th, 2014) * PERFORMANCE: The configuration system typically hit the filesystem twice per read configuration key instead of hardly ever. This is a continuation of [Issue #717](https://github.com/rzwitserloot/lombok/issues/717). ### v1.14.6 (September 2nd, 2014) * BUGFIX: Usage of `val` would break starting with JDK8 release `1.8.0_20`. [Issue #766](https://github.com/rzwitserloot/lombok/issues/766) * BUGFIX: Depending on your eclipse project setup, releases v1.14.0 through v1.14.4 could noticably slow down your eclipse. [Issue #717](https://github.com/rzwitserloot/lombok/issues/717). ### v1.14.4 (July 1st, 2014) * BUGFIX: GWT produces errors in handlers on line 1 in any source files that use lombok; this has been fixed. [Issue #734](https://github.com/rzwitserloot/lombok/issues/734) * BUGFIX-IN-PROGRESS: Many pathfinder issues in eclipse (see the bugfix in progress in v1.14.2) have now been fixed. [Issue #717](https://github.com/rzwitserloot/lombok/issues/717) ### v1.14.2 (June 10th, 2014) * BUGFIX: syntax highlighting in eclipse will become weird and auto-complete may stop working amongst other eclipse features in v1.14.0 (regression from v1.12.6). [Issue #723](https://github.com/rzwitserloot/lombok/issues/723) * FEATURE: Added `@Tolerate`; put this annotation on any method or constructor and lombok will skip it when considering whether or not to generate a method or constructor. This is useful if the types of the parameters of your method do not clash with what lombok would generate. * FEATURE: Added config key `lombok.getter.noIsPrefix`, which lets you disable use and generation of `isFoo()`, instead going with `getFoo()`, for {@code boolean} fields. * BUGFIX: Errors in the eclipse log with `IndexOutOfBound: 2` in `ASTConverter.convertType`. [Issue #721](https://github.com/rzwitserloot/lombok/issues/721) * BUGFIX-IN-PROGRESS: As yet unknown conditions in eclipse result in lots of `IllegalArgumentException` in the log with message "Path must include project and resource name". Also, 'invalid URL' or 'URI not absolute' errors can occur when using exotic file system abstractions such as Jazz. These bugs haven't been fixed, but instead of catastrophic failure, warning logs will be emitted instead. [Issue #717](https://github.com/rzwitserloot/lombok/issues/717) * BUGFIX: mvn builds fail with a 'URI not absolute' exception. [Issue #718](https://github.com/rzwitserloot/lombok/issues/718) ### v1.14.0 "Branching Cobra" (May 27th, 2014) * FEATURE: You can now configure aspects of lombok project wide (or even workspace wide, or just for a single package) via the [configuration system](https://projectlombok.org/features/configuration.html). You can configure many things; run `java -jar lombok.jar config -gv` for the complete list. * DEPRECATION: `@Delegate` has been moved to `lombok.experimental.Delegate`, and corner cases such as recursive delegation (delegating a type that itself has fields or methods annotated with `@Delegate`) are now error conditions. See the [feature documentation](https://projectlombok.org/features/experimental/Delegate.html) for more information. * FEATURE: It is now possible to put annotations, such as `@Nullable`, on the one parameter of generated `equals()` methods by specifying the `onParam=` option on `@EqualsAndHashCode`, similar to how that feature already exists for `@Setter`. [Issue #709](https://github.com/rzwitserloot/lombok/issues/709) * CHANGE: suppressConstructorProperties should now be configured via lombok configuration. [Issue #694](https://github.com/rzwitserloot/lombok/issues/694) * CHANGE: The `canEqual` method generated by `@EqualsAndHashCode`, `@Value` and `@Data` is now `protected` instead of `public`. [Issue #695](https://github.com/rzwitserloot/lombok/issues/695) * BUGFIX: Major work on improving support for JDK8, both for javac and eclipse. * BUGFIX: Deadlocks would occasionally occur in eclipse when using lazy getters [Issue #625](https://github.com/rzwitserloot/lombok/issues/625) * BUGFIX: Usage of `@SneakyThrows` with a javac from JDK8 with `-target 1.8` would result in a post compiler error. [Issue #690](https://github.com/rzwitserloot/lombok/issues/690) * BUGFIX: Switching workspace on some versions of eclipse resulted in a 'duplicate field' error. [Issue #701](https://github.com/rzwitserloot/lombok/issues/701) ### v1.12.6 (March 6th, 2014) * BUGFIX: Deadlocks would occasionally occur in eclipse during project builds, especially if using the gradle plugin. [Issue #680](https://github.com/rzwitserloot/lombok/issues/680) * PLATFORM: Added support for Eclipse Luna. [Issue #644](https://github.com/rzwitserloot/lombok/issues/644) * PLATFORM: Initial JDK8 support for eclipse's alpha support in kepler. [Issue #632](https://github.com/rzwitserloot/lombok/issues/632) * FEATURE: The various `@Log` annotations now support the `topic` parameter, which sets the logger's name. The default remains the fully qualified type name of the class itself. [Issue #667](https://github.com/rzwitserloot/lombok/issues/667). * BUGFIX: Using lombok with IntelliJ and the IBM JDK would result in NPEs during initialization. [Issue #683](https://github.com/rzwitserloot/lombok/issues/683). * BUGFIX: Eclipse quickfix _Surround with try/catch block_ didn't work inside `@SneakyThrows` annotated methods [Issue #511](https://github.com/rzwitserloot/lombok/issues/511). * BUGFIX: Eclipse refactoring _Extract Local Variable_ didn't work inside `@SneakyThrows` annotated methods [Issue #668](https://github.com/rzwitserloot/lombok/issues/668). * BUGFIX: {Netbeans} @SneakyThrows would lead to unused import and break refactorings [Issue #544](https://github.com/rzwitserloot/lombok/issues/544). * BUGFIX: Eclipse Organize Imports would generate error: AST must not be null [Issue #666](https://github.com/rzwitserloot/lombok/issues/666). * BUGFIX: Copying javadoc to getters / setters / withers would copy non-relevant sections too. [Issue #620](https://github.com/rzwitserloot/lombok/issues/620). * ENHANCEMENT: Lombok used to ship with [JNA](http://en.wikipedia.org/wiki/Java_Native_Access). It added over 800k to the size of lombok.jar and could mess with usage of JNA in your local environment, especially in eclipse. [Issue #682](https://github.com/rzwitserloot/lombok/issues/682) * DETAIL: {Delombok} Inside enum bodies the delombok formatter didn't respect the emptyLines directive [Issue #664](https://github.com/rzwitserloot/lombok/issues/664). * DETAIL: Use smaller primes (<127) for generating hashcodes [Issue #660](https://github.com/rzwitserloot/lombok/issues/660) ### v1.12.4 (January 15th, 2014) * BUGFIX: v1.12.2's delombok turns all operator+assignments into just assignment. Fixed. [Issue #633](https://github.com/rzwitserloot/lombok/issues/633) * BUGFIX: {Netbeans} v1.12.2 doesn't well with netbeans. [Issue #626](https://github.com/rzwitserloot/lombok/issues/626) * ENHANCEMENT: Delombok now supports varied options for how it formats the resulting source files. This includes scanning the source for things like the preferred indent. Use option `--format-help` for more information. [Issue #643](https://github.com/rzwitserloot/lombok/issues/643) * DETAIL: The primes lombok generates for use in generated hashCode() methods used to be direct copies from Effective Java. It turns out these particular primes are used so much, they tend to be a bit more collision-prone, so we switched them. Now, '277' is used instead of '31'. The primes for booleans have also been changed. [Issue #660](https://github.com/rzwitserloot/lombok/issues/660) ### v1.12.2 (October 10th, 2013) * PLATFORM: Initial JDK8 support, without affecting existing support for JDK6 and 7. [Issue #524](https://github.com/rzwitserloot/lombok/issues/524). While lombok will now work on JDK8 / javac8, and netbeans 7.4 and up, lombok does not (yet) support new language features introduced with java8, such as lambda expressions. Support for these features will be added in a future version. * PLATFORM: Running javac on IBM J9 VM would cause NullPointerExceptions when compiling with lombok. These issues should be fixed. [Issue #589](https://github.com/rzwitserloot/lombok/issues/589). * CHANGE: [JDK8-related] The canonical way to write onMethod / onParameter / onConstructor annotation now uses a double underscore instead of a single underscore, so, now, the proper way to use this feature is `@RequiredArgsConstructor(onConstructor=@__(@Inject))`. The old way (single underscore) still works, but generates warnings on javac 8. * BUGFIX: Using `@NonNull` on an abstract method used to cause exceptions during compilation. [Issue #594](https://github.com/rzwitserloot/lombok/issues/594). * BUGFIX: Using `@NonNull` on methods that also have `@SneakyThrows` or `@Synchronized` caused arbitrary behaviour. [Issue #623](https://github.com/rzwitserloot/lombok/issues/623). * GERMANY: Major version bumped from 0 to 1, because allegedly this is important. Rest assured, this change is nevertheless backwards compatible. ### v0.12.0 "Angry Butterfly" (July 16th, 2013) * FEATURE: javadoc on fields will now be copied to generated getters / setters / withers. There are ways to specify separate javadoc for the field, the setter, and the getter, and `@param` and `@return` are handled appropriately. Addresses feature request [Issue #132](https://github.com/rzwitserloot/lombok/issues/132). [@Getter and @Setter documentation](https://projectlombok.org/features/GetterSetter.html). [@Wither documentation](https://projectlombok.org/features/experimental/Wither.html). * CHANGE: The desugaring of @Getter(lazy=true) is now less object creation intensive. Documentation has been updated to reflect what the new desugaring looks like. [@Getter(lazy=true) documentation](https://projectlombok.org/features/GetterLazy.html). * PROMOTION: `@Value` has been promoted from experimental to the main package with no changes. The 'old' experimental one is still around but is deprecated, and is an alias for the new main package one. [@Value documentation](https://projectlombok.org/features/Value.html). * FEATURE: {Experimental} `@Builder` support. One of our earliest feature request issues, [Issue #89](https://github.com/rzwitserloot/lombok/issues/89), has finally been addressed. [@Builder documentation](https://projectlombok.org/features/experimental/Builder.html). * FEATURE: `@NonNull` on a method or constructor parameter now generates a null-check statement at the start of your method. This nullcheck will throw a `NullPointerException` with the name of the parameter as the message. [Issue #549](https://github.com/rzwitserloot/lombok/issues/549) * BUGFIX: Usage of `Lombok.sneakyThrow()` or `@SneakyThrows` would sometimes result in invalid classes (classes which fail with `VerifyError`). [Issue #543](https://github.com/rzwitserloot/lombok/issues/543) * BUGFIX: Using `val` in try-with-resources did not work for javac. [Issue #555](https://github.com/rzwitserloot/lombok/issues/555) * BUGFIX: When using `@Data`, warnings are not generated if certain aspects are not generated because you wrote explicit versions of them. However, this gets confusing with `equals` / `hashCode` / `canEqual`, as nothing is generated if any one of those methods is present. Now, if one of `equals` or `hashCode` is present but not the other one (or `canEqual` is present but `equals` and/or `hashCode` is missing), a warning is emitted to explain that lombok will not generate any of the equals / hashCode methods, and that you should either write them all yourself or remove them all. [Issue #548](https://github.com/rzwitserloot/lombok/issues/548) * BUGFIX: Possibly fixed a race condition in patcher [Issue #566](https://github.com/rzwitserloot/lombok/issues/566). ### v0.11.8 (April 23rd, 2013) * FEATURE: Major performance improvements in eclipse by profiling the project clean process. * CHANGE: {Experimental} The experimental `@Value` feature no longer implies the also experimental `@Wither`. If you like your `@Value` classes to make withers, add `@Wither` to the class right next to `@Value`. * FEATURE: {Experimental} Reintroduced `onMethod`, `onConstructor` and `onParam` to `@Getter`, `@Setter`, `@Wither`, and `@XArgsConstructor`. These parameters allow you to add annotations to the methods/constructors that lombok will generate. This is a workaround feature: The stability of the feature on future versions of javac is not guaranteed, and if a better way to implement this feature is found, this feature's current incarnation will be removed without a reasonable period of deprecation. [Documentation on the onX feature](https://projectlombok.org/features/experimental/onX.html) * FEATURE: Added support for Log4j v2.0 via `@Log4j2` [Issue #505](https://github.com/rzwitserloot/lombok/issues/505) * ENHANCEMENT: The Lombok installer can now find and install lombok into [JBoss Developer Studio](http://www.redhat.com/products/jbossenterprisemiddleware/developer-studio/). The installer will now also look for eclipse and eclipse variants in your home directory. [Issue #507](https://github.com/rzwitserloot/lombok/issues/507) * BUGFIX: `@ExtensionMethods` no longer causes `VerifyError` exceptions when running eclipse-compiled code if extension methods are called on expressions which are method calls whose return type is a type variable. For example, `someList.get(i).extensionMethod()` would fail that way. [Issue #509](https://github.com/rzwitserloot/lombok/issues/509) * BUGFIX: java 7's try-with-resources statement did not delombok correctly. [Issue #532](https://github.com/rzwitserloot/lombok/issues/532) ### v0.11.6 (October 30th, 2012) * FEATURE: Lombok can be disabled entirely for any given compile run by using JVM switch `-Dlombok.disable`. This might be useful for code style checkers and such. * FEATURE: Added support for Slf4j extended logger [Issue #494](https://github.com/rzwitserloot/lombok/issues/494) * BUGFIX: {Delombok} Running delombok has been causing VerifyError errors when used with javac 1.7 since 0.11.0. [Issue #495](https://github.com/rzwitserloot/lombok/issues/495) * BUGFIX: A conflict between lombok and certain eclipse plugins would result in NullPointerExceptions in the log when using `@Delegate`. * BUGFIX: `NullPointerException in lombok.​javac.​handlers.​JavacHandlerUtil.​upToTypeNode​(JavacHandlerUtil.java:978)` when compiling with `@ExtensionMethod` in javac and generated constructors are involved. [Issue #496](https://github.com/rzwitserloot/lombok/issues/496) * BUGFIX: `@Deprecated` on a field that gets a generated setter in eclipse would result in `IllegalArgumentException`, which you wouldn't see unless you have the error log open. If you have save actions defined, you'd get a popup box with the exception. Now fixed. [Issue #481](https://github.com/rzwitserloot/lombok/issues/481) ### v0.11.4 (August 13th, 2012) * FEATURE: {Experimental} `@Value`, `@Wither` and `@FieldDefaults` are now available. These are a lot like `@Data` but geared towards immutable classes. [Documentation on @Value](https://projectlombok.org/features/experimental/Value.html), [Documentation on @Wither](https://projectlombok.org/features/experimental/Wither.html) and [Documentation on @FieldDefaults](https://projectlombok.org/features/experimental/FieldDefaults.html). * BUGFIX: Eclipse would throw an OOME if using `@ExtensionMethod`. [Issue #463](https://github.com/rzwitserloot/lombok/issues/463) * BUGFIX: {Netbeans} `@Cleanup` and `@Synchronized` cause far fewer issues in the netbeans editor. [Issue #466](https://github.com/rzwitserloot/lombok/issues/466) * BUGFIX: {Installer} Erroneous messages about the installer complaining about needing root access when installing or removing lombok from eclipse installs has been fixed. The installer edge of this problem was actually already fixed in v0.11.2. [Issue #436](https://github.com/rzwitserloot/lombok/issues/436) * BUGFIX: `@ExtensionMethod` had all sorts of issues in javac. [Issue #472](https://github.com/rzwitserloot/lombok/issues/472) * BUGFIX: Generating static constructors with javac when you have fields with generics, i.e. `Class`, caused errors. [Issue #469](https://github.com/rzwitserloot/lombok/issues/469) * BUGFIX: Minor `@ExtensionMethod` issues in eclipse, such as the ability to call extension methods on a `super` reference which is now no longer possible. [Issue #479](https://github.com/rzwitserloot/lombok/issues/479) ### v0.11.2 "Dashing Kakapo" (July 3rd, 2012) * FEATURE: {Experimental} `@ExtensionMethod` is now available to add extensions to any type in the form of static methods that take as first parameter an object of that type. [Documentation on @ExtensionMethod](https://projectlombok.org/features/experimental/ExtensionMethod.html) * FEATURE: ONGOING: Fix for using lombok together with gwt-designer. * ENHANCEMENT: Small performance enhancements in `equals` and `hashCode`. [Issue #439](https://github.com/rzwitserloot/lombok/issues/439) * BUGFIX: Eclipse would display an error message regarding an invalid super constructor in the wrong location. [Issue #409](https://github.com/rzwitserloot/lombok/issues/409) * BUGFIX: Eclipse refactor script 'rename method arguments' should work more often with lombok-affected methods. * BUGFIX: Using `val` in an enhanced for loop did not work if the iterable was a raw type. * BUGFIX: Using `@Getter(lazy=true)` when the data type is boolean, int, array, or some other type that requires special treatment for hashCode/equals, now works properly with `@Data`, `@EqualsHashCode` and `@ToString`. [Issue #449](https://github.com/rzwitserloot/lombok/issues/449) * BUGFIX: `SneakyThrows` in constructor should not wrap this/super call in try-block [Issue #454](https://github.com/rzwitserloot/lombok/issues/454) * BUGFIX: Setting breakpoints on code above the first generated method was not possible. [Issue #450](https://github.com/rzwitserloot/lombok/issues/450) ### v0.11.0 (March 26th, 2012) * FEATURE: {Experimental} 'fluent' getters and setters (using just `fieldName` as methodname instead of `getFieldName`), setters that return `this` instead of `void`, and support for fields with prefixes is introduced with this lombok version. Also, the number of parameters of any existing methods with the same name that lombok would generate are now taken into account; previously if you had any method named `setX` regardless of how many parameters it has, lombok would avoid generating a `setX` method. Now lombok generates the method if all present `setX` methods have a number of parameters other than 1. [documentation](https://projectlombok.org/features/experimental/Accessors.html). * FEATURE: The combination of `@Delegate` and `@Getter` or `@Data` will now delegate to the result of a generated getter. [Issue #401](https://github.com/rzwitserloot/lombok/issues/401) * FEATURE: Developing android apps on eclipse with lombok is now possible by running `java -jar lombok.jar publicApi` and including the generated jar in your project. [Documentation on using lombok for android development](https://projectlombok.org/setup/android.html). * BUGFIX: In NetBeans the generated default constructor would still be generated even if Lombok also generated constructors. [Issue #399](https://github.com/rzwitserloot/lombok/issues/399) * BUGFIX: Some classes that contain @SneakyThrows would not compile (throw ClassFormatError). [Issue #412](https://github.com/rzwitserloot/lombok/issues/412) * BUGFIX: delombok: When `@Delegate` would generate a method with type parameters of the type `T extends package.Class`, a dot would be prepended to the type name. [Issue #414](https://github.com/rzwitserloot/lombok/issues/414) * BUGFIX: @Getter and @Setter now generate deprecated methods for deprecated fields. Fixes [Issue #415](https://github.com/rzwitserloot/lombok/issues/415) * BUGFIX: @Delegate would not generate @Deprecated on methods marked deprecated in javadoc. Fixes [Issue #421](https://github.com/rzwitserloot/lombok/issues/421) * BUGFIX: Using `val` with a type like `Outer.Inner` now works. [Issue #416](https://github.com/rzwitserloot/lombok/issues/416) * BUGFIX: `@Getter(lazy=true)` where the variable type is a primitive and the initializing expression is of a different primitive type that would type coerce implicitly, i.e. ints can be assigned to longs without a cast, didn't work before. [Issue #418](https://github.com/rzwitserloot/lombok/issues/418) * BUGFIX: `val` is no longer legal inside basic for loops (the old kind, not the foreach kind). These variables should rarely be final, and in practice it wasn't possible to delombok this code properly. [Issue #419](https://github.com/rzwitserloot/lombok/issues/419) * BUGFIX: PrettyCommentsPrinter now prints default clause of annotation methods. Fixes [Issue #423](https://github.com/rzwitserloot/lombok/issues/423) ### v0.10.8 (January 19th, 2012) * FEATURE: `@Delegate` can now be used on a no-argument method, which works similarly to adding it to fields. See [documentation](https://projectlombok.org/features/Delegate.html). * BUGFIX: Eclipse refactoring Extract Interface was broken when using lombok annotation to generate methods. [Issue #159](https://github.com/rzwitserloot/lombok/issues/159) * BUGFIX: Eclipse action Sort Members was broken when using lombok annotations to generate methods or fields. [Issue #338](https://github.com/rzwitserloot/lombok/issues/338) * BUGFIX: Eclipse action Refactor/Rename on an inner type was broken when using lombok annotations. [Issue #389](https://github.com/rzwitserloot/lombok/issues/389) * BUGFIX: 0.10.6 causes ClassNotFoundErrors when using ecj (and thus, play framework, gwt, etc). [Issue #393](https://github.com/rzwitserloot/lombok/issues/393) * BUGFIX: Eclipse parsing was broken when using lombok annotations with parentheses. [Issue #398](https://github.com/rzwitserloot/lombok/issues/398) * ENHANCEMENT: Lombok now adds a line to the Eclipse About dialog about itself. ### v0.10.6 (December 19th, 2011) * PERFORMANCE: Performance issues (memory leaks) when using lombok in netbeans, introduced in 0.10, have been fixed. [Issue #315](https://github.com/rzwitserloot/lombok/issues/315) * BUGFIX: Eclipse quickfix "Add unimplemented methods" would sometimes insert the new method stubs in strange places, especially if `@Data` was present. [Issue #124](https://github.com/rzwitserloot/lombok/issues/124) * BUGFIX: Eclipse quickfix "Assign parameter to new field" would insert it outside the class body if `@Data` was present. [Issue #295](https://github.com/rzwitserloot/lombok/issues/295) * BUGFIX: Renaming a @Data-annotated class in eclipse using Alt+Shift+R no longer mangles the data annotation. [Issue #359](https://github.com/rzwitserloot/lombok/issues/359) * BUGFIX: Using save action 'Use this qualifier for field accesses, only if necessary' did not work together with `@Data` in certain cases. [Issue #374](https://github.com/rzwitserloot/lombok/issues/374) * BUGFIX: Organize imports, either run manually or as save action, would throw an exception. [Issue #381](https://github.com/rzwitserloot/lombok/issues/381) * BUGFIX: Extracted constants would be placed outside the class body when a logging annotation was present. [Issue #388](https://github.com/rzwitserloot/lombok/issues/388) ### v0.10.4 (November 21st, 2011) * BUGFIX: Using the `log` field from `@Log`, etc, now works in static initializers. [Issue #368](https://github.com/rzwitserloot/lombok/issues/368) * BUGFIX: Auto-formatting code containing lombok on eclipse, even via an auto-save action, now works. [Issue #163](https://github.com/rzwitserloot/lombok/issues/163) * BUGFIX: Letting eclipse generate various methods when a lombok annotation is present now works. [Issue #211](https://github.com/rzwitserloot/lombok/issues/211) * BUGFIX: Renaming a @Data-annotated class in eclipse no longer mangles the data annotation. [Issue #359](https://github.com/rzwitserloot/lombok/issues/359) * BUGFIX: Eclipse save action *Add final modifier to private fields* no longer adds final keyword to `@Setter` fields. [Issue #336](https://github.com/rzwitserloot/lombok/issues/336) * BUGFIX: Mixing labels and `lombok.val` would cause NPEs in javac. [Issue #372](https://github.com/rzwitserloot/lombok/issues/372) * BUGFIX: Writing `lombok.val` out in full (vs. using an import statement) did not work in eclipse. [Issue #373](https://github.com/rzwitserloot/lombok/issues/373) ### v0.10.2 (November 1st, 2011) * BUGFIX: Delombok will no longer jumble up comments from different files when using -sourcepath option. [Issue #357](https://github.com/rzwitserloot/lombok/issues/357) * BUGFIX: Turns out treating `@NotNull` as an annotation that indicates lombok should generate nullcheck guards causes all sorts of problems. This has been removed again, and documentation has been updated to reflect this. [Issue #360](https://github.com/rzwitserloot/lombok/issues/360) * BUGFIX: `@EqualsAndHashCode` or `@Data` did not work on non-static inner classes whose outer class has a type variable. It does now. [Issue #362](https://github.com/rzwitserloot/lombok/issues/362) ### v0.10.1 (October 3rd, 2011) * BUGFIX: `@Delegate` in eclipse could cause memory leaks in 0.10.0. [Issue #337](https://github.com/rzwitserloot/lombok/issues/337) * BUGFIX: Annotations on enum values were being deleted by delombok. [Issue #342](https://github.com/rzwitserloot/lombok/issues/342) * BUGFIX: `@AllArgsConstructor` was erroneously generating a parameter and an assignment for final variables already assigned in their declaration. [Issue #351](https://github.com/rzwitserloot/lombok/issues/351) * ENHANCEMENT: `@NotNull` is now also recognized as an annotation indicating that lombok should generate nullcheck guards in generated constructors and setters. [Issue #344](https://github.com/rzwitserloot/lombok/issues/344) ### v0.10.0 "Burning Emu" (August 19th, 2011) * FEATURE: New annotation: @Delegate. This annotation lets lombok generate delegation methods for a given field. [More…](https://projectlombok.org/features/Delegate.html) * FEATURE: Added support for 'val'. Val is an immutable variable that infers its type from the right hand side of the initializing expression. [More…](https://projectlombok.org/features/val.html) * FEATURE: Added support for several logging frameworks via the `@Log`, `@Slf4j`, etc. annotation. [More…](https://projectlombok.org/features/Log.html) * FEATURE: Lombok now supports post-compile transformers. [Issue #217](https://github.com/rzwitserloot/lombok/issues/217) * FEATURE: Using `@SneakyThrows` no longer requires a runtime dependency on lombok.jar. In fact, any call to `Lombok.sneakyThrows(ex)` is optimized at the bytecode level and no longer requires you to actually have lombok.jar or lombok-runtime.jar on the classpath. * FEATURE: @*X*ArgsConstructor, @Getter, and @ToString can now be used on enum declarations. Previously, behaviour of these annotations on enums was undefined. * FEATURE: @Getter/@Setter (and by extension, @Data) in v0.9.3 and earlier would generate getter and setter method names that did not conform to the beanspec, primarily when faced with boolean properties. This has been fixed. In practice this won't affect you unless you have properties named `isFoo` or `hasFoo`. Now the setter generated for this will be called `setFoo` (as the property name is `foo`) and not `setIsFoo`. Also, `hasFoo` is now no longer special; the names would be `isHasFoo` and `setHasFoo`. The java bean spec does not give `has` special meaning. * FEATURE: `@EqualsAndHashCode` (and by extension, `@Data`) now add a `canEqual` method which improves the sanity of equality amongst a hierarchy of classes. [More…](https://projectlombok.org/features/EqualsAndHashCode.html) * FEATURE: `@Getter` now supports a `lazy=true` attribute. [More…](https://projectlombok.org/features/GetterLazy.html) * ENHANCEMENT: The installer will now find Eclipse installations when they are located in a subdirectory of a directory containing the word 'eclipse' . [Issue #283](https://github.com/rzwitserloot/lombok/issues/283) * ENHANCEMENT: Add null check for `@Cleanup` [Issue #227](https://github.com/rzwitserloot/lombok/issues/227) * BUGFIX: Lombok is now compatible with javac 7. * BUGFIX: Hard to reproduce `NullPointerException` in Eclipse on the `getTypeBinding` method in the error log has been fixed. [Issue #237](https://github.com/rzwitserloot/lombok/issues/237) * BUGFIX: `@Setter` and `@Getter` can now be applied to static fields again (was broken in v0.9.3 only). [Issue #209](https://github.com/rzwitserloot/lombok/issues/209) * BUGFIX: delombok added type parameters to constructors that mirror the type's own type parameters. This resulted in delombok turning any generated constructor that takes at least 1 parameter of type 'T' into something that didn't compile, and to boot, a confusing error message ('T is not compatible with T'). This is now fixed. [Issue #213](https://github.com/rzwitserloot/lombok/issues/213) * BUGFIX: The Eclipse source generator would place the generated code outside the class [Issue #228](https://github.com/rzwitserloot/lombok/issues/228) * BUGFIX: When using m2eclipse, occasionally you'd see a ClassNotFoundError on JavacProcessingEnvironment. This has been fixed. [Issue #250](https://github.com/rzwitserloot/lombok/issues/250) * BUGFIX: Either all or none of `equals`, `hashCode` and `canEqual` will be generated. [Issue #313](https://github.com/rzwitserloot/lombok/issues/313) * BUGFIX: Delombok in output-to-directory mode was generating very long paths on mac and linux. [Issue #322](https://github.com/rzwitserloot/lombok/issues/322) * BUGFIX: Various refactor scripts and save actions bugs have been fixed in eclipse, though most remain. ### v0.9.3 "Burrowing Whale" (July 25th, 2010) * FEATURE: Adding `@Getter` or `@Setter` to a class is now legal and is like adding those annotations to every non-static field in it. [Issue #202](https://github.com/rzwitserloot/lombok/issues/202) * FEATURE: Three new annotations, `@NoArgsConstructor`, `@RequiredArgsConstructor` and `@AllArgsConstructor` have been added. These split off `@Data`'s ability to generate constructors, and also allow you to finetune what kind of constructor you want. In addition, by using these annotations, you can force generation of constructors even if you have your own. [Issue #152](https://github.com/rzwitserloot/lombok/issues/152) * FEATURE: Constructors generated by lombok now include a `@java.beans.ConstructorProperties` annotation. This does mean these constructors no longer work in java 1.5, as this is a java 1.6 feature. The annotation can be suppressed by setting `suppressConstructorProperties` to `true` in a `@RequiredArgsConstructor` or `@AllArgsConstructor` annotation. [Issue #195](https://github.com/rzwitserloot/lombok/issues/195) * FEATURE: generated `toString`, `equals` and `hashCode` methods will now use `this.getX()` and `other.getX()` instead of `this.x` and `other.x` if a suitable getter is available. This behaviour is useful for proxied classes, such as the POJOs that hibernate makes. Usage of the getters can be suppressed with `@ToString/@EqualsAndHashCode(doNotUseGetters = true)`. [Issue #183](https://github.com/rzwitserloot/lombok/issues/183) * ENHANCEMENT: FindBugs' `@CheckForNull` is now copied from a field to a setter's parameter and the getter method just like `@Nullable`. [Issue #201](https://github.com/rzwitserloot/lombok/issues/201) * ENHANCEMENT: plugins and `@SneakyThrows`: Resolving types in annotations now works better especially for classes that aren't in the core java libraries. [Issue #161](https://github.com/rzwitserloot/lombok/issues/161) * ENHANCEMENT: If `tools.jar` isn't found (required when running _delombok_), now a useful error message is generated. The search for `tools.jar` now also looks in `JAVA_HOME`. * ENHANCEMENT: toString() on inner classes now lists the class name as `Outer.Inner` instead of just `Inner`. [Issue #206](https://github.com/rzwitserloot/lombok/issues/206) * ENHANCEMENT: All field accesses generated by lombok are now qualified (like so: `this.fieldName`). For those who have a warning configured for unqualified field access, those should no longer occur. [Issue #121](https://github.com/rzwitserloot/lombok/issues/121) * ENHANCEMENT: All fields and methods generated by lombok now get `@SuppressWarnings("all")` attached to avoid such warnings as missing javadoc, for those of you who have that warning enabled. [Issue #120](https://github.com/rzwitserloot/lombok/issues/120) * PLATFORMS: Lombok should now run in stand-alone ecj (Eclipse Compiler for Java). This isn't just useful for the few souls actually using this compiler day to day, but various eclipse build tools such as the RCP builder run ecj internally as well. [Issue #145](https://github.com/rzwitserloot/lombok/issues/145) * BUGFIX: Eclipse: `@Data` and other annotations now don't throw errors when you include fields with bounded wildcard generics, such as `List`. [Issue #157](https://github.com/rzwitserloot/lombok/issues/157) * BUGFIX: complex enums didn't get delomboked properly. [Issue #169](https://github.com/rzwitserloot/lombok/issues/169) * BUGFIX: delombok now no longer forgets to remove `import lombok.AccessLevel;`. In netbeans, that import will no longer be flagged erroneously as being unused. [Issue #173](https://github.com/rzwitserloot/lombok/issues/173) and [Issue #176](https://github.com/rzwitserloot/lombok/issues/176) * BUGFIX: While its discouraged, `import lombok.*;` is supposed to work in the vast majority of cases. In eclipse, however, it didn't. Now it does. [Issue #175](https://github.com/rzwitserloot/lombok/issues/175) * BUGFIX: When `@Getter` or `@Setter` is applied to a multiple field declaration, such as `@Getter int x, y;`, the annotation now applies to all fields, not just the first. [Issue #127](https://github.com/rzwitserloot/lombok/issues/127) * BUGFIX: delombok on most javacs would quit with a NoSuchFieldError if it contains `` style wildcards anywhere in the source, as well as at least 1 lombok annotation. No longer. [Issue #207](https://github.com/rzwitserloot/lombok/issues/207) * BUILD: dependencies are now fetched automatically via ivy, and most dependencies now include sources by default, which is particularly handy for those working on the lombok sources themselves. ### v0.9.2 "Hailbunny" (December 15th, 2009) * preliminary support for lombok on NetBeans! - thanks go to Jan Lahoda from NetBeans. [Issue #93](https://github.com/rzwitserloot/lombok/issues/93) * lombok now ships with the delombok tool, which copies an entire directory filled with sources to a new directory, desugaring any java files to what it would look like without lombok's transformations. Compiling the sources in this new directory without lombok support should result in the same class files as compiling the original with lombok support. Great to double check on what lombok is doing, and for chaining the delombok-ed sources to source-based java tools such as Google Web Toolkit or javadoc. lombok.jar itself also provides an ant task for delombok. [Full documentation of delombok](https://projectlombok.org/features/delombok.html). * Lombok now works on openjdk7 (tested with JDK7m5)! For all the folks on the cutting edge, this should be very good news. [Issue #134](https://github.com/rzwitserloot/lombok/issues/134) - thanks go to Jan Lahoda from NetBeans. * lombok now has various command-line accessible utilities bundled with it. Run `java -jar lombok.jar --help` to see them. Included (aside from the already mentioned delombok): * Ability to create a tiny jar named lombok-runtime.jar with runtime dependencies. The lombok transformations that have a runtime dependency on this jar can be listed as well. Run `java -jar lombok.jar createRuntime --help` for more information. * Scriptable command line install and uninstall options. Run `java -jar lombok.jar install --help` (or `uninstall`, of course) for more information. Technically this support has been there in earlier versions, but the command line options are now much more lenient, not to mention more visible. * Lombok now works on Springsource Tool Suite. [Issue #95](https://github.com/rzwitserloot/lombok/issues/95) * Lombok now works on JDK 1.6.0_0, for those of us who have really old JDK1.6's installed on their system. [Issue #156](https://github.com/rzwitserloot/lombok/issues/156) * Erroneous use of lombok in Eclipse (adding it to a project as an annotation processor, which is not how lombok is to be used on Eclipse) now generates a useful warning message with helpful information, instead of a confusing error hidden in the logs. [Issue #126](https://github.com/rzwitserloot/lombok/issues/126) * FIXED: Regression bug where you would occasionally see errors with the gist 'loader constraint violation: when resolving...', such as when opening the help system, starting the diff editor, or, rarely, opening any java source file. [Issue #141](https://github.com/rzwitserloot/lombok/issues/141) * FIXED: @SneakyThrows without any parameters should default to `Throwable.class` but it didn't do anything in javac. [Issue #146](https://github.com/rzwitserloot/lombok/issues/146) * FIXED: Capitalization is now ignored when scanning for existing methods, so if `setURL` already exists, then a `@Data` annotation on a class with a field named `url` will no longer _also_ generate `setUrl`. [Issue #148](https://github.com/rzwitserloot/lombok/issues/148) ### v0.9.1 (November 9th, 2009) * The installer now works much better on linux, in that it auto-finds eclipse in most locations linux users tend to put their eclipse installs, and it can now handle apt-get installed eclipses, which previously didn't work well at all. There's also a hidden feature where the installer can work as a command-line only tool (`java -jar lombok.jar install eclipse path/to/eclipse`) which also supports `uninstall` of course. You can now also point at `eclipse.ini` in case you have a really odd eclipse install, which should always work. * For lombok developers, the eclipse launch target now works out-of-the-box on snow leopard. [Issue #139](https://github.com/rzwitserloot/lombok/issues/139) ### v0.9.0 (November 2nd, 2009) * The lombok class patching system has been completely revamped; the core business of patching class files has been offloaded in an independent project called 'lombok.patcher', which is now used to patch lombok into eclipse. * Many behind-the-scenes changes to improve lombok's stability and flexibility on eclipse. * Changes to the lombok core API which aren't backwards compatible with lombok series v0.8 but which were necessary to make writing third party processors for lombok a lot easier. * Minor version number bumped due to the above 3 issues. * Eclipse's "rename" refactor script, invoked by pressing CMD/CTRL+SHIFT+R, now works on `@Data` annotated classes. * The windows installer would fail on boot if you have unformatted drives. [Issue #138](https://github.com/rzwitserloot/lombok/issues/138) * The static constructor that `@Data` can make was being generated as package private when compiling with javac. [Issue #136](https://github.com/rzwitserloot/lombok/issues/136) ### v0.8.5 (September 3rd, 2009) * There's now an `AccessLevel.NONE` that you can use for your `@Getter` and `@Setter` annotations to suppress generating setters and getters when you're using the `@Data` annotation. Address [Issue #110](https://github.com/rzwitserloot/lombok/issues/110) * Both `@EqualsAndHashCode` and `@ToString` now support explicitly specifying the fields to use, via the new 'of' parameter. Fields that begin with a '$' are now also excluded by default from equals, hashCode, and toString generation, unless of course you explicitly mention them in the 'of' parameter. Addresses [Issue #105](https://github.com/rzwitserloot/lombok/issues/105) * There's a commonly used `@NotNull` annotation, from javax.validation (and in earlier versions of hibernate, which is the origin of javax.validation) which does not quite mean what we want it to mean: It is not legal on parameters, and it is checked at runtime after an explicit request for validation. As a workaround, we've removed checking for any annotation named `NotNull` from the nonnull support of lombok's generated Getters, Setters, and constructors. [Issue #116](https://github.com/rzwitserloot/lombok/issues/116) * Fixed yet another issue with `@SneakyThrows`. This was reported fixed in v0.8.4. but it still didn't work quite as it should. Still falls under the bailiwick of [Issue #103](https://github.com/rzwitserloot/lombok/issues/103) ### v0.8.4 (September 2nd, 2009) * Fixed many issues with `@SneakyThrows` - in previous versions, using it would sometimes confuse the syntax colouring, and various constructs in the annotated method would cause outright eclipse errors, such as beginning the method with a try block. This also fixes [Issue #103](https://github.com/rzwitserloot/lombok/issues/103) * Fixed the David Lynch bug - in eclipse, classes with lombok features used in them would sometimes appear invisible from other source files. It's described in more detail on [Issue #114](https://github.com/rzwitserloot/lombok/issues/114). If you suffered from it, you'll know what this is about. * Fixed the problem where eclipse's help system did not start up on lombokized eclipses. [Issue #99](https://github.com/rzwitserloot/lombok/issues/99) * All generated methods now make their parameters (if they have any) final. This should help avoid problems with the 'make all parameters final' save action in eclipse. [Issue #113](https://github.com/rzwitserloot/lombok/issues/113) * Okay, this time _really_ added support for @NonNull and @NotNull annotations. It was reported for v0.8.3 but it wasn't actually in that release. @Nullable annotations are now also copied over to the getter's return type and the setter and constructor's parameters (but, obviously, no check is added). Any @NonNull annotated non-final fields that are not initialized are now also added to the generated constructor by @Data in order to ensure via an explicit null check that they contain a legal value. * @ToString (and hence, @Data) now default to includeFieldNames=true. [Issue #108](https://github.com/rzwitserloot/lombok/issues/108) ### v0.8.3 (August 21st, 2009) * @EqualsAndHashCode (and, indirectly, @Data) generate a warning when overriding a class other than java.lang.Object but not setting EqualsAndHashCode's callSuper to true. There are, however, legitimate reasons to do this, so this warning is now no longer generated if you explicitly set callSuper to false. The warning text now also refers to this action if not calling super is intentional. * If your fields have @NonNull or @NotNull annotations, then generated setters are generated with a null check, and the annotation is copied to the setter's parameter, and the getter's method. * An annoying bug that usually showed up if you had package-info.java files has been fixed. It would cause a `NullPointerException` at lombok.javac.apt.Processor.toUnit(Processor.java:143) ### v0.8.2 (July 29th, 2009) * @EqualsAndHashCode and @ToString created; these are subsets of what @Data does (namely: generate toString(), and generate equals() and hashCode() implementations). @Data will still generate these methods, but you can now generate them separately if you wish. As part of this split off, you can now specify for toString generation to include the field names in the produced toString method, and for all 3 methods: You can choose to involve the implementation of the superclass, and you can choose to exclude certain fields. [Issue #81](https://github.com/rzwitserloot/lombok/issues/81) * when compiling with javac: warnings on specific entries of an annotation parameter (such as non-existent fields in a @EqualsAndHashCode exclude parameter) now show up on the problematic parameter and not on the entire annotation. [Issue #84](https://github.com/rzwitserloot/lombok/issues/84) ### v0.8.1 (July 26th, 2009) * Changelog tracking from this version on. * Using eclipse's 'find callers' on a @Data annotation will now find callers of the static constructor if you generated it. If not, it still finds callers to hashCode() as before (it's not possible to make eclipse find callers to the normal constructor, though you can just use 'find callers' on the class name, which works fine). [Issue #78](https://github.com/rzwitserloot/lombok/issues/78) * If your field is called 'hasFoo' and its a boolean, and you use @Getter or @Data to generate a getter for it, that getter will now be called 'hasFoo' and not 'isHasFoo' as before. This rule holds for any field prefixed with 'has', 'is', or 'get', AND the character following the prefix is not lowercase (so that 'hashCodeGenerated' is not erroneously identified as already having a prefix!). Similar logic has been added to not generate a getter at all for a field named 'foo' or 'hasFoo' if there is already a method named 'isFoo'. [Issue #77](https://github.com/rzwitserloot/lombok/issues/77) * Starting the lombok installer on mac os X using soylatte instead of apple's JVM now correctly detects being on a mac, and using mac-specific code for finding and installing eclipses. [Issue #80](https://github.com/rzwitserloot/lombok/issues/80) * For non-mac, non-windows installations, the jar file in the `-javaagent` parameter is now written as an absolute path in `eclipse.ini` instead of a relative one. For some reason, on at least 1 linux installation, an absolute path is required to make javaagent work. This 'fix' has the unfortunate side-effect of making it impossible to move your eclipse installation around without breaking the pointer to the lombok java agent, so this change has only been introduced for non-windows, non-mac. Thanks to WouterS for spotting this one and helping us out with some research on fixing it. [Issue #79](https://github.com/rzwitserloot/lombok/issues/79) ### v0.8 * Initial release before announcements * (note: There are a few different editions of lombok out there, all tagged with v0.8.) lombok-1.16.18/doc/experiences.txt000066400000000000000000000073071312655740700170140ustar00rootroot00000000000000## Fix HandleCleanup Consider requiring an initializer and warn when the varname gets reassigned, if the declaration wasn't already final. Think about this more. Right now exceptions thrown by the cleanup method will mask any exceptions thrown in the main body, which is not wanted. This does not appear to be doable without java 7 features or very extensive additions to the lombok framework. A lot has been tried: Tried tactics, and why they won't work: - Replace every 'return', 'break', and 'continue' statement (for the latter 2, only if they break/continue out of the try block) with a block that first sets a uniquely named flag before doing the operation. Then, check that flag in the finally block to see if the cleanup call should be guarded by a try/catchThrowable. This doesn't work, because its not possible to instrument the 4th way out of a try block: just running to the end of it. Putting a 'flag = true;' at the end isn't safe, because that might be unreachable code. - Put catch blocks in for all relevant exceptions (RuntimeException, Error, all exceptions declared as thrown by the method, and all types of exceptions of the catch blocks of encapsulating try blocks. This doesn't work, partly because it'll fail for sneakily thrown exceptions, but mostly because you can't just catch an exception listed in the 'throws' clause of the method body; catching an exception that no statement in the try block can throw is a compile time error, but it is perfectly allright to declare these as 'thrown'. - Put in a blanket catch Throwable to set the flag. Two problems with this: First, sneaky throw can't be done. Thread.stop invokes a security manager and triggers a warning, Calling a sneakyThrow method creates a runtime dependency on lombok, constructing a sneakyThrow in-class requires either lots of "$1" classes that clog up permgen, or are slow and require reflection tricks to load live off of a byte array literal. Secondly, this would mean that any statements in the try body that throw an exception aren't flagged to the user as needing to be handled. Unacceptable. The Cleanup annotation now also calls the cleanup method for you, and will call it at the END of the current scope. The following plans have been tried and abandoned: - Cleanup right after the final mention. This doesn't work, because the final mention may not be the final use-place. Example: @Cleanup InputStream in = new FileInputStream(someFile); InputStreamReader reader = new InputStreamReader(in); reader.read(); //oops - in is already closed by now. - Require an explicit var.cleanup() call and consider that the cue to close off the try block. This doesn't work either, because now variables set in between the @Cleanup declaration and the var.cleanup() call become invisible to following statements. Example: @Cleanup InputStream in = new FileInputStream(someFile); int i = in.read(); in.close(); System.out.println(i); //fail - i is inside the generated try block but this isn't, so 'i' is not visible from here. By running to the end of visible scope, all these problems are avoided. This does remove the flexibility of declaring where you want a close call to be executed, but there are two mitigating factors available: 1) Create an explicit scope block. You can just stick { code } in any place where you can legally write a statement, in java. This is relatively unknown, so I expect most users will go for: 2) Just call close explicitly. I've yet to see a cleanup method which isn't idempotent anyway (calling it multiple times is no different than calling it once). lombok-1.16.18/doc/git-workflow.txt000066400000000000000000000023531312655740700171310ustar00rootroot00000000000000# git workflow for Project Lombok public branch 'master' tracks major releases and should always be in an effectively working condition. It is updated only occasionally, and virtually always just points at a particularly stable point on the more dynamic 'develop' branch. public branch 'develop' is still intended to run more or less stable, but is less tested and is what developers check completed features into. Each version release is accompanied by a tag. To develop a new feature, no matter how trivial: git checkout develop # start from branch 'develop' git checkout -b fixFoobar # Create a new branch for yourself ..... # write and commit stuff git checkout develop # go back to develop to update it git pull # update develop git checkout fixFoobar git rebase develop # Rewrite fixFoobar's history as if it was written according to latest 'develop' state. git checkout develop git merge fixFoobar # Update your version of 'develop' to include your fixes. git branch -d fixFoobar # delete your branch name git push # push changes up to github repo Major features might be turned into public branches, and will be merged and not rebased. lombok-1.16.18/doc/maven-pom.xml000066400000000000000000000030421312655740700163520ustar00rootroot00000000000000 4.0.0 org.projectlombok lombok jar @VERSION@ Project Lombok https://projectlombok.org Spice up your java: Automatic Resource Management, automatic generation of getters, setters, equals, hashCode and toString, and more! The MIT License https://projectlombok.org/LICENSE repo scm:git:git://github.com/rzwitserloot/lombok.git http://github.com/rzwitserloot/lombok Google Code http://code.google.com/p/projectlombok/issues rzwitserloot Reinier Zwitserloot reinier@projectlombok.org http://zwitserloot.com +1 rspilker Roel Spilker roel@projectlombok.org +1 rgrootjans Robbert Jan Grootjans +1 lombok-1.16.18/doc/publishing.txt000066400000000000000000000014141312655740700166370ustar00rootroot00000000000000To publish: Step #1: Change src/core/lombok/core/Version.java and pick a nice version number. Example: "0.8.1" Step #2: commit everything to the git master branch. Step #3: tag this release with the version number. (Example: v0.8.1) - note the prefix v. Step #4: git push && git push --tags Step #5: ant publish-all Step #6: Follow the instructions that flew by when the maven-publish task ran, which involves going to http://oss.sonatype.org/ and logging in with the username/pass that are in your scroll log, to test and then 'release' the staged repo to maven central. Note that once you do this there's no turning back, and that version number is forever associated with this release. Step #6: Change src/core/lombok/core/Version.java to "0.8.2-EDGE", and commit this. lombok-1.16.18/doc/utils-maven-pom.xml000066400000000000000000000030501312655740700175070ustar00rootroot00000000000000 4.0.0 org.projectlombok lombok-utils jar @VERSION@ Project Lombok https://projectlombok.org Spice up your java: Automatic Resource Management, automatic generation of getters, setters, equals, hashCode and toString, and more! The MIT License https://projectlombok.org/LICENSE repo scm:git:git://github.com/rzwitserloot/lombok.git http://github.com/rzwitserloot/lombok Google Code http://code.google.com/p/projectlombok/issues rzwitserloot Reinier Zwitserloot reinier@projectlombok.org http://zwitserloot.com +1 rspilker Roel Spilker roel@projectlombok.org +1 rgrootjans Robbert Jan Grootjans +1 lombok-1.16.18/experimental/000077500000000000000000000000001312655740700156625ustar00rootroot00000000000000lombok-1.16.18/experimental/build.xml000066400000000000000000000041141312655740700175030ustar00rootroot00000000000000 This buildfile is part of projectlombok.org. It is the main entry point for experimental features. Does the build and packaging work on experimental features. Currently available: disableCheckedExceptions(-publish) lombok-1.16.18/experimental/buildScripts/000077500000000000000000000000001312655740700203315ustar00rootroot00000000000000lombok-1.16.18/experimental/buildScripts/disableCheckedExceptions.ant.xml000066400000000000000000000075141312655740700265570ustar00rootroot00000000000000 This buildfile is part of projectlombok.org. It controls building and packaging of the disableCheckedExceptions feature. lombok.javac.disableCheckedExceptions.DisableCheckedExceptionsAgent lombok-1.16.18/experimental/src/000077500000000000000000000000001312655740700164515ustar00rootroot00000000000000lombok-1.16.18/experimental/src/lombok/000077500000000000000000000000001312655740700177345ustar00rootroot00000000000000lombok-1.16.18/experimental/src/lombok/javac/000077500000000000000000000000001312655740700210205ustar00rootroot00000000000000lombok-1.16.18/experimental/src/lombok/javac/disableCheckedExceptions/000077500000000000000000000000001312655740700257345ustar00rootroot00000000000000DisableCheckedExceptionsAgent.java000066400000000000000000000110421312655740700343510ustar00rootroot00000000000000lombok-1.16.18/experimental/src/lombok/javac/disableCheckedExceptions/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.disableCheckedExceptions; import java.lang.instrument.Instrumentation; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic.Kind; import lombok.patcher.ClassRootFinder; import lombok.patcher.Hook; import lombok.patcher.MethodTarget; import lombok.patcher.ScriptManager; import lombok.patcher.inject.LiveInjector; import lombok.patcher.scripts.ScriptBuilder; @SupportedAnnotationTypes("*") @SupportedSourceVersion(SourceVersion.RELEASE_6) public class DisableCheckedExceptionsAgent extends AbstractProcessor { private String errorToShow; /** Inject an agent if we're on a sun-esque JVM. */ @Override public void init(ProcessingEnvironment procEnv) { super.init(procEnv); String className = procEnv.getClass().getName(); if (className.startsWith("org.eclipse.jdt.")) { errorToShow = "This version of disableCheckedExceptions is not compatible with eclipse. javac only; sorry."; procEnv.getMessager().printMessage(Kind.WARNING, errorToShow); } else if (!procEnv.getClass().getName().equals("com.sun.tools.javac.processing.JavacProcessingEnvironment")) { procEnv.getMessager().printMessage(Kind.WARNING, "You aren't using a compiler based around javac v1.6, so disableCheckedExceptions will not work.\n" + "Your processor class is: " + className); } else { new LiveInjector().inject(ClassRootFinder.findClassRootOfClass(DisableCheckedExceptionsAgent.class)); } } /** Does nothing - we just wanted the init method so we can inject an agent. */ @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { if (errorToShow != null) { if (errorToShow != null) { Set rootElements = roundEnv.getRootElements(); if (!rootElements.isEmpty()) { processingEnv.getMessager().printMessage(Kind.WARNING, errorToShow, rootElements.iterator().next()); errorToShow = null; } } } return false; } public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception { registerPatchScripts(instrumentation, true); } public static void premain(String agentArgs, Instrumentation instrumentation) throws Exception { registerPatchScripts(instrumentation, false); } private static void registerPatchScripts(Instrumentation instrumentation, boolean reloadExistingClasses) { ScriptManager sm = new ScriptManager(); sm.registerTransformer(instrumentation); patchExceptions(sm); if (reloadExistingClasses) sm.reloadClasses(instrumentation); } private static void patchExceptions(ScriptManager sm) { sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("com.sun.tools.javac.comp.Check", "isUnchecked", "boolean", "com.sun.tools.javac.code.Symbol$ClassSymbol")) .decisionMethod(new Hook("lombok.javac.disableCheckedExceptions.DisableCheckedExceptionsAgent", "retTrue", "boolean")) .valueMethod(new Hook("lombok.javac.disableCheckedExceptions.DisableCheckedExceptionsAgent", "retTrue", "boolean")) .insert().build()); } public static boolean retTrue() { return true; } } lombok-1.16.18/src/000077500000000000000000000000001312655740700137545ustar00rootroot00000000000000lombok-1.16.18/src/core/000077500000000000000000000000001312655740700147045ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/000077500000000000000000000000001312655740700161675ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/AccessLevel.java000066400000000000000000000026141312655740700212260ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; /** * Represents an AccessLevel. Used e.g. to specify the access level for generated methods and fields. */ public enum AccessLevel { PUBLIC, MODULE, PROTECTED, PACKAGE, PRIVATE, /** Represents not generating anything or the complete lack of a method. */ NONE; } lombok-1.16.18/src/core/lombok/AllArgsConstructor.java000066400000000000000000000065241312655740700226340ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Generates an all-args constructor. * An all-args constructor requires one argument for every field in the class. *

* Complete documentation is found at the project lombok features page for @Constructor. *

* Even though it is not listed, this annotation also has the {@code onConstructor} parameter. See the full documentation for more details. * * @see NoArgsConstructor * @see RequiredArgsConstructor */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface AllArgsConstructor { /** * If set, the generated constructor will be private, and an additional static 'constructor' * is generated with the same argument list that wraps the real constructor. * * Such a static 'constructor' is primarily useful as it infers type arguments. * * @return Name of static 'constructor' method to generate (blank = generate a normal constructor). */ String staticName() default ""; /** * Any annotations listed here are put on the generated constructor. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
* up to JDK7:
* {@code @AllArgsConstructor(onConstructor=@__({@AnnotationsGoHere}))}
* from JDK8:
* {@code @AllArgsConstructor(onConstructor_={@AnnotationsGohere})} // note the underscore after {@code onConstructor}. * * @return List of annotations to apply to the generated constructor. */ AnyAnnotation[] onConstructor() default {}; /** * Sets the access level of the constructor. By default, generated constructors are {@code public}. * * @return The constructor will be generated with this access modifier. */ AccessLevel access() default lombok.AccessLevel.PUBLIC; /** * Placeholder annotation to enable the placement of annotations on the generated code. * * @deprecated Don't use this annotation, ever - Read the documentation. */ @Deprecated @Retention(RetentionPolicy.SOURCE) @Target({}) @interface AnyAnnotation {} } lombok-1.16.18/src/core/lombok/Builder.java000066400000000000000000000150261312655740700204240ustar00rootroot00000000000000/* * Copyright (C) 2013-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * The builder annotation creates a so-called 'builder' aspect to the class that is annotated or the class * that contains a member which is annotated with {@code @Builder}. *

* If a member is annotated, it must be either a constructor or a method. If a class is annotated, * then a private constructor is generated with all fields as arguments * (as if {@code @AllArgsConstructor(AccessLevel.PRIVATE)} is present * on the class), and it is as if this constructor has been annotated with {@code @Builder} instead. *

* The effect of {@code @Builder} is that an inner class is generated named TBuilder, * with a private constructor. Instances of TBuilder are made with the * method named {@code builder()} which is also generated for you in the class itself (not in the builder class). *

* The TBuilder class contains 1 method for each parameter of the annotated * constructor / method (each field, when annotating a class), which returns the builder itself. * The builder also has a build() method which returns a completed instance of the original type, * created by passing all parameters as set via the various other methods in the builder to the constructor * or method that was annotated with {@code @Builder}. The return type of this method will be the same * as the relevant class, unless a method has been annotated, in which case it'll be equal to the * return type of that method. *

* Complete documentation is found at the project lombok features page for @Builder. *
*

* Before: * *

 * @Builder
 * class Example {
 * 	private int foo;
 * 	private final String bar;
 * }
 * 
* * After: * *
 * class Example<T> {
 * 	private T foo;
 * 	private final String bar;
 * 	
 * 	private Example(T foo, String bar) {
 * 		this.foo = foo;
 * 		this.bar = bar;
 * 	}
 * 	
 * 	public static <T> ExampleBuilder<T> builder() {
 * 		return new ExampleBuilder<T>();
 * 	}
 * 	
 * 	public static class ExampleBuilder<T> {
 * 		private T foo;
 * 		private String bar;
 * 		
 * 		private ExampleBuilder() {}
 * 		
 * 		public ExampleBuilder foo(T foo) {
 * 			this.foo = foo;
 * 			return this;
 * 		}
 * 		
 * 		public ExampleBuilder bar(String bar) {
 * 			this.bar = bar;
 * 			return this;
 * 		}
 * 		
 * 		@java.lang.Override public String toString() {
 * 			return "ExampleBuilder(foo = " + foo + ", bar = " + bar + ")";
 * 		}
 * 		
 * 		public Example build() {
 * 			return new Example(foo, bar);
 * 		}
 * 	}
 * }
 * 
*/ @Target({TYPE, METHOD, CONSTRUCTOR}) @Retention(SOURCE) public @interface Builder { /** * The field annotated with {@code @Default} must have an initializing expression; that expression is taken as the default to be used if not explicitly set during building. */ @Target(FIELD) @Retention(SOURCE) public @interface Default {} /** @return Name of the method that creates a new builder instance. Default: {@code builder}. */ String builderMethodName() default "builder"; /** @return Name of the method in the builder class that creates an instance of your {@code @Builder}-annotated class. */ String buildMethodName() default "build"; /** * Name of the builder class. * * Default for {@code @Builder} on types and constructors: {@code (TypeName)Builder}. *

* Default for {@code @Builder} on methods: {@code (ReturnTypeName)Builder}. * * @return Name of the builder class that will be generated (or if it already exists, will be filled with builder elements). */ String builderClassName() default ""; /** * If true, generate an instance method to obtain a builder that is initialized with the values of this instance. * Legal only if {@code @Builder} is used on a constructor, on the type itself, or on a static method that returns * an instance of the declaring type. * * @return Whether to generate a {@code toBuilder()} method. */ boolean toBuilder() default false; /** * Put on a field (in case of {@code @Builder} on a type) or a parameter (for {@code @Builder} on a constructor or static method) to * indicate how lombok should obtain a value for this field or parameter given an instance; this is only relevant if {@code toBuilder} is {@code true}. * * You do not need to supply an {@code @ObtainVia} annotation unless you wish to change the default behaviour: Use a field with the same name. *

* Note that one of {@code field} or {@code method} should be set, or an error is generated. *

* The default behaviour is to obtain a value by referencing the name of the parameter as a field on 'this'. */ @Target({FIELD, PARAMETER}) @Retention(SOURCE) public @interface ObtainVia { /** * @return Tells lombok to obtain a value with the expression {@code this.value}. */ String field() default ""; /** * @return Tells lombok to obtain a value with the expression {@code this.method()}. */ String method() default ""; /** * @return Tells lombok to obtain a value with the expression {@code SelfType.method(this)}; requires {@code method} to be set. */ boolean isStatic() default false; } } lombok-1.16.18/src/core/lombok/Cleanup.java000066400000000000000000000061071312655740700204250ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Ensures the variable declaration that you annotate will be cleaned up by calling its close method, regardless * of what happens. Implemented by wrapping all statements following the local variable declaration to the * end of your scope into a try block that, as a finally action, closes the resource. *

* Complete documentation is found at the project lombok features page for @Cleanup. *

* Example: *

 * public void copyFile(String in, String out) throws IOException {
 *     @Cleanup FileInputStream inStream = new FileInputStream(in);
 *     @Cleanup FileOutputStream outStream = new FileOutputStream(out);
 *     byte[] b = new byte[65536];
 *     while (true) {
 *         int r = inStream.read(b);
 *         if (r == -1) break;
 *         outStream.write(b, 0, r);
 *     }
 * }
 * 
* * Will generate: *
 * public void copyFile(String in, String out) throws IOException {
 *     @Cleanup FileInputStream inStream = new FileInputStream(in);
 *     try {
 *         @Cleanup FileOutputStream outStream = new FileOutputStream(out);
 *         try {
 *             byte[] b = new byte[65536];
 *             while (true) {
 *                 int r = inStream.read(b);
 *                 if (r == -1) break;
 *                 outStream.write(b, 0, r);
 *             }
 *         } finally {
 *             if (out != null) out.close();
 *         }
 *     } finally {
 *         if (in != null) in.close();
 *     }
 * }
 * 
*/ @Target(ElementType.LOCAL_VARIABLE) @Retention(RetentionPolicy.SOURCE) public @interface Cleanup { /** @return The name of the method that cleans up the resource. By default, 'close'. The method must not have any parameters. */ String value() default "close"; } lombok-1.16.18/src/core/lombok/ConfigurationKeys.java000066400000000000000000000706071312655740700225070ustar00rootroot00000000000000/* * Copyright (C) 2013-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.util.List; import lombok.core.configuration.CallSuperType; import lombok.core.configuration.ConfigurationKey; import lombok.core.configuration.FlagUsageType; import lombok.core.configuration.NullCheckExceptionType; /** * A container class containing all lombok configuration keys that do not belong to a specific annotation. */ public class ConfigurationKeys { private ConfigurationKeys() {} // ##### main package features ##### // ----- global ----- /** * lombok configuration: {@code lombok.addGeneratedAnnotation} = {@code true} | {@code false}. * * If unset or {@code true}, lombok generates {@code @javax.annotation.Generated("lombok")} on all fields, methods, and types that are generated, unless {@code lombok.addJavaxGeneratedAnnotation} is set. * * @see ConfigurationKeys#ADD_JAVAX_GENERATED_ANNOTATIONS * @see ConfigurationKeys#ADD_LOMBOK_GENERATED_ANNOTATIONS * @deprecated Since version 1.16.14, use {@link #ADD_JAVAX_GENERATED_ANNOTATIONS} instead. */ @Deprecated public static final ConfigurationKey ADD_GENERATED_ANNOTATIONS = new ConfigurationKey("lombok.addGeneratedAnnotation", "Generate @javax.annotation.Generated on all generated code (default: true). Deprecated, use 'lombok.addJavaxGeneratedAnnotation' instead.") {}; /** * lombok configuration: {@code lombok.addJavaxGeneratedAnnotation} = {@code true} | {@code false}. * * If unset or {@code true}, lombok generates {@code @javax.annotation.Generated("lombok")} on all fields, methods, and types that are generated, unless {@code lombok.addGeneratedAnnotation} is set to {@code false}. */ public static final ConfigurationKey ADD_JAVAX_GENERATED_ANNOTATIONS = new ConfigurationKey("lombok.addJavaxGeneratedAnnotation", "Generate @javax.annotation.Generated on all generated code (default: follow lombok.addGeneratedAnnotation).") {}; /** * lombok configuration: {@code lombok.addLombokGeneratedAnnotation} = {@code true} | {@code false}. * * If {@code true}, lombok generates {@code @lombok.Generated} on all fields, methods, and types that are generated. */ public static final ConfigurationKey ADD_LOMBOK_GENERATED_ANNOTATIONS = new ConfigurationKey("lombok.addLombokGeneratedAnnotation", "Generate @lombok.Generated on all generated code (default: false).") {}; /** * lombok configuration: {@code lombok.extern.findbugs.addSuppressFBWarnings} = {@code true} | {@code false}. * * If {@code true}, lombok generates {@code edu.umd.cs.findbugs.annotations.SuppressFBWarnings} on all fields, methods, and types that are generated. * * NB: If you enable this option, findbugs must be on the source or classpath, or you'll get errors that the type {@code SuppressFBWarnings} cannot be found. */ public static final ConfigurationKey ADD_FINDBUGS_SUPPRESSWARNINGS_ANNOTATIONS = new ConfigurationKey("lombok.extern.findbugs.addSuppressFBWarnings", "Generate @edu.umd.cs.findbugs.annotations.SuppressFBWArnings on all generated code (default: false).") {}; // ----- *ArgsConstructor ----- /** * lombok configuration: {@code lombok.anyConstructor.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @AllArgsConstructor}, {@code @RequiredArgsConstructor}, or {@code @NoArgsConstructor} results in a warning / error. */ public static final ConfigurationKey ANY_CONSTRUCTOR_FLAG_USAGE = new ConfigurationKey("lombok.anyConstructor.flagUsage", "Emit a warning or error if any of the XxxArgsConstructor annotations are used.") {}; /** * lombok configuration: {@code lombok.anyConstructor.suppressConstructorProperties} = {@code true} | {@code false}. * * If {@code false} or this configuration is omitted, all generated constructors with at least 1 argument get a {@code @ConstructorProperties}. * To suppress the generation of it, set this configuration to {@code true}. * * NB: GWT projects, and probably android projects, should explicitly set this key to {@code true} for the entire project. */ public static final ConfigurationKey ANY_CONSTRUCTOR_SUPPRESS_CONSTRUCTOR_PROPERTIES = new ConfigurationKey("lombok.anyConstructor.suppressConstructorProperties", "Suppress the generation of @ConstructorProperties for generated constructors (default: false).") {}; /** * lombok configuration: {@code lombok.allArgsConstructor.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @AllArgsConstructor} results in a warning / error. */ public static final ConfigurationKey ALL_ARGS_CONSTRUCTOR_FLAG_USAGE = new ConfigurationKey("lombok.allArgsConstructor.flagUsage", "Emit a warning or error if @AllArgsConstructor is used.") {}; /** * lombok configuration: {@code lombok.noArgsConstructor.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @NoArgsConstructor} results in a warning / error. */ public static final ConfigurationKey NO_ARGS_CONSTRUCTOR_FLAG_USAGE = new ConfigurationKey("lombok.noArgsConstructor.flagUsage", "Emit a warning or error if @NoArgsConstructor is used.") {}; /** * lombok configuration: {@code lombok.requiredArgsConstructor.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @RequiredArgsConstructor} results in a warning / error. */ public static final ConfigurationKey REQUIRED_ARGS_CONSTRUCTOR_FLAG_USAGE = new ConfigurationKey("lombok.requiredArgsConstructor.flagUsage", "Emit a warning or error if @RequiredArgsConstructor is used.") {}; // ##### Beanies ##### // ----- Data ----- /** * lombok configuration: {@code lombok.data.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Data} results in a warning / error. */ public static final ConfigurationKey DATA_FLAG_USAGE = new ConfigurationKey("lombok.data.flagUsage", "Emit a warning or error if @Data is used.") {}; // ----- Value ----- /** * lombok configuration: {@code lombok.value.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Value} results in a warning / error. */ public static final ConfigurationKey VALUE_FLAG_USAGE = new ConfigurationKey("lombok.value.flagUsage", "Emit a warning or error if @Value is used.") {}; // ----- Getter ----- /** * lombok configuration: {@code lombok.getter.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Getter} results in a warning / error. */ public static final ConfigurationKey GETTER_FLAG_USAGE = new ConfigurationKey("lombok.getter.flagUsage", "Emit a warning or error if @Getter is used.") {}; /** * lombok configuration: {@code lombok.getter.lazy.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Getter(lazy=true)} results in a warning / error. */ public static final ConfigurationKey GETTER_LAZY_FLAG_USAGE = new ConfigurationKey("lombok.getter.lazy.flagUsage", "Emit a warning or error if @Getter(lazy=true) is used.") {}; /** * lombok configuration: {@code lombok.getter.noIsPrefix} = {@code true} | {@code false}. * * If {@code true}, booleans getters are both referred to, and generated as {@code getFieldName()}. If {@code false} (the default), the javabean-standard {@code isFieldName()} is generated / used instead. * */ public static final ConfigurationKey GETTER_CONSEQUENT_BOOLEAN = new ConfigurationKey("lombok.getter.noIsPrefix", "If true, generate and use getFieldName() for boolean getters instead of isFieldName().") {}; // ----- Setter ----- /** * lombok configuration: {@code lombok.setter.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Setter} results in a warning / error. */ public static final ConfigurationKey SETTER_FLAG_USAGE = new ConfigurationKey("lombok.setter.flagUsage", "Emit a warning or error if @Setter is used.") {}; // ----- EqualsAndHashCode ----- /** * lombok configuration: {@code lombok.equalsAndHashCode.doNotUseGetters} = {@code true} | {@code false}. * * For any class without an {@code @EqualsAndHashCode} that explicitly defines the {@code doNotUseGetters} option, this value is used (default = false). */ public static final ConfigurationKey EQUALS_AND_HASH_CODE_DO_NOT_USE_GETTERS = new ConfigurationKey("lombok.equalsAndHashCode.doNotUseGetters", "Don't call the getters but use the fields directly in the generated equals and hashCode method (default = false).") {}; /** * lombok configuration: {@code lombok.equalsAndHashCode.callSuper} = {@code call} | {@code ignore} | {@code warn}. * * For any class with an {@code @EqualsAndHashCode} annotation which extends a class other than {@code java.lang.Object}, should a call to superclass's implementation of {@code equals} and {@code hashCode} be included in the generated methods? (Default = warn) */ public static final ConfigurationKey EQUALS_AND_HASH_CODE_CALL_SUPER = new ConfigurationKey("lombok.equalsAndHashCode.callSuper", "When generating equals and hashCode for classes that don't extend Object, either automatically take into account superclass implementation (call), or don't (skip), or warn and don't (warn). (default = warn).") {}; /** * lombok configuration: {@code lombok.equalsAndHashCode.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @EqualsAndHashCode} results in a warning / error. */ public static final ConfigurationKey EQUALS_AND_HASH_CODE_FLAG_USAGE = new ConfigurationKey("lombok.equalsAndHashCode.flagUsage", "Emit a warning or error if @EqualsAndHashCode is used.") {}; // ----- ToString ----- /** * lombok configuration: {@code lombok.toString.doNotUseGetters} = {@code true} | {@code false}. * * For any class without an {@code @ToString} that explicitly defines the {@code doNotUseGetters} option, this value is used (default = false). */ public static final ConfigurationKey TO_STRING_DO_NOT_USE_GETTERS = new ConfigurationKey("lombok.toString.doNotUseGetters", "Don't call the getters but use the fields directly in the generated toString method (default = false).") {}; /** * lombok configuration: {@code lombok.toString.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @ToString} results in a warning / error. */ public static final ConfigurationKey TO_STRING_FLAG_USAGE = new ConfigurationKey("lombok.toString.flagUsage", "Emit a warning or error if @ToString is used.") {}; /** * lombok configuration: {@code lombok.toString.includeFieldNames} = {@code true} | {@code false}. * * For any class without an {@code @ToString} that explicitly defines the {@code includeFieldNames} option, this value is used (default = true). */ public static final ConfigurationKey TO_STRING_INCLUDE_FIELD_NAMES = new ConfigurationKey("lombok.toString.includeFieldNames", "Include the field names in the generated toString method (default = true).") {}; // ----- Builder ----- /** * lombok configuration: {@code lombok.builder.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Builder} results in a warning / error. */ public static final ConfigurationKey BUILDER_FLAG_USAGE = new ConfigurationKey("lombok.builder.flagUsage", "Emit a warning or error if @Builder is used.") {}; // ----- Singular ----- /** * lombok configuration: {@code lombok.singular.useGuava} = {@code true} | {@code false}. * * If explicitly set to {@code true}, guava's {@code ImmutableList} etc are used to implement the immutable collection datatypes generated by @Singular @Builder for fields/parameters of type {@code java.util.List} and such. * By default, unmodifiable-wrapped versions of {@code java.util} types are used. */ public static final ConfigurationKey SINGULAR_USE_GUAVA = new ConfigurationKey("lombok.singular.useGuava", "Generate backing immutable implementations for @Singular on java.util.* types by using guava's ImmutableList, etc. Normally java.util's mutable types are used and wrapped to make them immutable.") {}; /** * lombok configuration: {@code lombok.singular.auto} = {@code true} | {@code false}. * * By default or if explicitly set to {@code true}, lombok will attempt to automatically singularize the name of your variable/parameter when using {@code @Singular}; the name is assumed to be written in english, and a plural. If explicitly to {@code false}, you must always specify the singular form; this is especially useful if your identifiers are in a foreign language. */ public static final ConfigurationKey SINGULAR_AUTO = new ConfigurationKey("lombok.singular.auto", "If true (default): Automatically singularize the assumed-to-be-plural name of your variable/parameter when using {@code @Singular}.") {}; // ##### Standalones ##### // ----- Cleanup ----- /** * lombok configuration: {@code lombok.cleanup.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Cleanup} results in a warning / error. */ public static final ConfigurationKey CLEANUP_FLAG_USAGE = new ConfigurationKey("lombok.cleanup.flagUsage", "Emit a warning or error if @Cleanup is used.") {}; // ----- Delegate ----- /** * lombok configuration: {@code lombok.delegate.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Delegate} results in a warning / error. */ public static final ConfigurationKey DELEGATE_FLAG_USAGE = new ConfigurationKey("lombok.delegate.flagUsage", "Emit a warning or error if @Delegate is used.") {}; // ----- NonNull ----- /** * lombok configuration: {@code lombok.nonNull.exceptionType} = <String: a java exception type; either [{@code IllegalArgumentException} or: {@code NullPointerException}]. * * Sets the exception to throw if {@code @NonNull} is applied to a method parameter, and a caller passes in {@code null}. */ public static final ConfigurationKey NON_NULL_EXCEPTION_TYPE = new ConfigurationKey("lombok.nonNull.exceptionType", "The type of the exception to throw if a passed-in argument is null (Default: NullPointerException).") {}; /** * lombok configuration: {@code lombok.nonNull.flagUsage} = {@code WARNING} | {@code ERROR}. * * Implementation note: This field is supposed to be lombok.NonNull itself, but jdk6 and 7 have bugs where fields in annotations don't work well. * * If set, any usage of {@code @NonNull} results in a warning / error. */ public static final ConfigurationKey NON_NULL_FLAG_USAGE = new ConfigurationKey("lombok.nonNull.flagUsage", "Emit a warning or error if @NonNull is used.") {}; // ----- SneakyThrows ----- /** * lombok configuration: {@code lombok.sneakyThrows.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @SneakyThrows} results in a warning / error. */ public static final ConfigurationKey SNEAKY_THROWS_FLAG_USAGE = new ConfigurationKey("lombok.sneakyThrows.flagUsage", "Emit a warning or error if @SneakyThrows is used.") {}; // ----- Synchronized ----- /** * lombok configuration: {@code lombok.synchronized.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Synchronized} results in a warning / error. */ public static final ConfigurationKey SYNCHRONIZED_FLAG_USAGE = new ConfigurationKey("lombok.synchronized.flagUsage", "Emit a warning or error if @Synchronized is used.") {}; // ----- val ----- /** * lombok configuration: {@code lombok.val.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code val} results in a warning / error. */ public static final ConfigurationKey VAL_FLAG_USAGE = new ConfigurationKey("lombok.val.flagUsage", "Emit a warning or error if 'val' is used.") {}; public static final ConfigurationKey VAR_FLAG_USAGE = new ConfigurationKey("lombok.var.flagUsage", "Emit a warning or error if 'var' is used.") {}; // ##### Extern ##### // ----- Logging ----- /** * lombok configuration: {@code lombok.log.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of any of the log annotations in {@code lombok.extern}{@code @Slf4j} results in a warning / error. */ public static final ConfigurationKey LOG_ANY_FLAG_USAGE = new ConfigurationKey("lombok.log.flagUsage", "Emit a warning or error if any of the log annotations is used.") {}; /** * lombok configuration: {@code lombok.log.apacheCommons.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @CommonsLog} results in a warning / error. */ public static final ConfigurationKey LOG_COMMONS_FLAG_USAGE = new ConfigurationKey("lombok.log.apacheCommons.flagUsage", "Emit a warning or error if @CommonsLog is used.") {}; /** * lombok configuration: {@code lombok.log.javaUtilLogging.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Log} results in a warning / error. */ public static final ConfigurationKey LOG_JUL_FLAG_USAGE = new ConfigurationKey("lombok.log.javaUtilLogging.flagUsage", "Emit a warning or error if @Log is used.") {}; /** * lombok configuration: {@code lombok.log.log4j.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Log4j} results in a warning / error. */ public static final ConfigurationKey LOG_LOG4J_FLAG_USAGE = new ConfigurationKey("lombok.log.log4j.flagUsage", "Emit a warning or error if @Log4j is used.") {}; /** * lombok configuration: {@code lombok.log.log4j2.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Log4j2} results in a warning / error. */ public static final ConfigurationKey LOG_LOG4J2_FLAG_USAGE = new ConfigurationKey("lombok.log.log4j2.flagUsage", "Emit a warning or error if @Log4j2 is used.") {}; /** * lombok configuration: {@code lombok.log.slf4j.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Slf4j} results in a warning / error. */ public static final ConfigurationKey LOG_SLF4J_FLAG_USAGE = new ConfigurationKey("lombok.log.slf4j.flagUsage", "Emit a warning or error if @Slf4j is used.") {}; /** * lombok configuration: {@code lombok.log.xslf4j.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @XSlf4j} results in a warning / error. */ public static final ConfigurationKey LOG_XSLF4J_FLAG_USAGE = new ConfigurationKey("lombok.log.xslf4j.flagUsage", "Emit a warning or error if @XSlf4j is used.") {}; /** * lombok configuration: {@code lombok.log.jbosslog.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @JBossLog} results in a warning / error. */ public static final ConfigurationKey LOG_JBOSSLOG_FLAG_USAGE = new ConfigurationKey("lombok.log.jbosslog.flagUsage", "Emit a warning or error if @JBossLog is used.") {}; /** * lombok configuration: {@code lombok.log.fieldName} = <String: aJavaIdentifier> (Default: {@code log}). * * If set the various log annotations (which make a log field) will use the stated identifier instead of {@code log} as a name. */ public static final ConfigurationKey LOG_ANY_FIELD_NAME = new ConfigurationKey("lombok.log.fieldName", "Use this name for the generated logger fields (default: 'log').") {}; /** * lombok configuration: {@code lombok.log.fieldIsStatic} = {@code true} | {@code false}. * * If not set, or set to {@code true}, the log field generated by the various log annotations will be {@code static}. * * If set to {@code false}, these will be generated as instance fields instead. */ public static final ConfigurationKey LOG_ANY_FIELD_IS_STATIC = new ConfigurationKey("lombok.log.fieldIsStatic", "Make the generated logger fields static (default: true).") {}; // ##### Experimental ##### /** * lombok configuration: {@code lombok.experimental.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of any experimental features (from package {@code lombok.experimental}) that haven't been * promoted to a main feature results in a warning / error. */ public static final ConfigurationKey EXPERIMENTAL_FLAG_USAGE = new ConfigurationKey("lombok.experimental.flagUsage", "Emit a warning or error if an experimental feature is used.") {}; // ----- Accessors ----- /** * lombok configuration: {@code lombok.accessors.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Accessors} results in a warning / error. */ public static final ConfigurationKey ACCESSORS_FLAG_USAGE = new ConfigurationKey("lombok.accessors.flagUsage", "Emit a warning or error if @Accessors is used.") {}; /** * lombok configuration: {@code lombok.accessors.prefix} += <String: prefix>. * * For any class without an {@code @Accessors} that explicitly defines the {@code prefix} option, this list of prefixes is used. */ public static final ConfigurationKey> ACCESSORS_PREFIX = new ConfigurationKey>("lombok.accessors.prefix", "Strip this field prefix, like 'f' or 'm_', from the names of generated getters and setters.") {}; /** * lombok configuration: {@code lombok.accessors.chain} = {@code true} | {@code false}. * * For any class without an {@code @Accessors} that explicitly defines the {@code chain} option, this value is used (default = false). */ public static final ConfigurationKey ACCESSORS_CHAIN = new ConfigurationKey("lombok.accessors.chain", "Generate setters that return 'this' instead of 'void' (default: false).") {}; /** * lombok configuration: {@code lombok.accessors.fluent} = {@code true} | {@code false}. * * For any class without an {@code @Accessors} that explicitly defines the {@code fluent} option, this value is used (default = false). */ public static final ConfigurationKey ACCESSORS_FLUENT = new ConfigurationKey("lombok.accessors.fluent", "Generate getters and setters using only the field name (no get/set prefix) (default: false).") {}; // ----- ExtensionMethod ----- /** * lombok configuration: {@code lombok.extensionMethod.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @ExtensionMethod} results in a warning / error. */ public static final ConfigurationKey EXTENSION_METHOD_FLAG_USAGE = new ConfigurationKey("lombok.extensionMethod.flagUsage", "Emit a warning or error if @ExtensionMethod is used.") {}; // ----- FieldDefaults ----- /** * lombok configuration: {@code lombok.fieldDefaults.defaultPrivate} = {@code true} | {@code false}. * * If set to true any field without an access modifier or {@code @PackagePrivate} is marked as {@code private} by lombok, in all source files compiled. */ public static final ConfigurationKey FIELD_DEFAULTS_PRIVATE_EVERYWHERE = new ConfigurationKey("lombok.fieldDefaults.defaultPrivate", "If true, fields without any access modifier, in any file (lombok annotated or not) are marked as private. Use @PackagePrivate or an explicit modifier to override this.") {}; /** * lombok configuration: {@code lombok.fieldDefaults.defaultFinal} = {@code true} | {@code false}. * * If set to true any field without {@code @NonFinal} is marked as {@code final} by lombok, in all source files compiled. */ public static final ConfigurationKey FIELD_DEFAULTS_FINAL_EVERYWHERE = new ConfigurationKey("lombok.fieldDefaults.defaultFinal", "If true, fields, in any file (lombok annotated or not) are marked as final. Use @NonFinal to override this.") {}; /** * lombok configuration: {@code lombok.fieldDefaults.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @FieldDefaults} results in a warning / error. */ public static final ConfigurationKey FIELD_DEFAULTS_FLAG_USAGE = new ConfigurationKey("lombok.fieldDefaults.flagUsage", "Emit a warning or error if @FieldDefaults is used.") {}; // ----- Helper ----- /** * lombok configuration: {@code lombok.helper.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Helper} results in a warning / error. */ public static final ConfigurationKey HELPER_FLAG_USAGE = new ConfigurationKey("lombok.helper.flagUsage", "Emit a warning or error if @Helper is used.") {}; // ----- onX ----- /** * lombok configuration: {@code lombok.onX.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code onX} results in a warning / error. *
* Specifically, this flags usage of {@code @Getter(onMethod=...)}, {@code @Setter(onParam=...)}, {@code @Setter(onMethod=...)}, {@code @XArgsConstructor(onConstructor=...)}. */ public static final ConfigurationKey ON_X_FLAG_USAGE = new ConfigurationKey("lombok.onX.flagUsage", "Emit a warning or error if onX is used.") {}; // ----- UtilityClass ----- /** * lombok configuration: {@code lombok.utilityClass.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @UtilityClass} results in a warning / error. */ public static final ConfigurationKey UTILITY_CLASS_FLAG_USAGE = new ConfigurationKey("lombok.utilityClass.flagUsage", "Emit a warning or error if @UtilityClass is used.") {}; // ----- Wither ----- /** * lombok configuration: {@code lombok.wither.flagUsage} = {@code WARNING} | {@code ERROR}. * * If set, any usage of {@code @Wither} results in a warning / error. */ public static final ConfigurationKey WITHER_FLAG_USAGE = new ConfigurationKey("lombok.wither.flagUsage", "Emit a warning or error if @Wither is used.") {}; // ----- Configuration System ----- /** * lombok configuration: {@code config.stopBubbling} = {@code true} | {@code false}. * * If not set, or set to {@code false}, the configuration system will look for {@code lombok.config} files in the parent directory. * * If set to {@code true}, no further {@code lombok.config} files will be checked. */ public static final ConfigurationKey STOP_BUBBLING = new ConfigurationKey("config.stopBubbling", "Tell the configuration system it should stop looking for other configuration files (default: false).") {}; } lombok-1.16.18/src/core/lombok/Data.java000066400000000000000000000050421312655740700177040ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Generates getters for all fields, a useful toString method, and hashCode and equals implementations that check * all non-transient fields. Will also generate setters for all non-final fields, as well as a constructor. *

* Equivalent to {@code @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode}. *

* Complete documentation is found at the project lombok features page for @Data. * * @see Getter * @see Setter * @see RequiredArgsConstructor * @see ToString * @see EqualsAndHashCode * @see lombok.Value */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface Data { /** * If you specify a static constructor name, then the generated constructor will be private, and * instead a static factory method is created that other classes can use to create instances. * We suggest the name: "of", like so: * *

	 *     public @Data(staticConstructor = "of") class Point { final int x, y; }
	 * 
* * Default: No static constructor, instead the normal constructor is public. * * @return Name of static 'constructor' method to generate (blank = generate a normal constructor). */ String staticConstructor() default ""; } lombok-1.16.18/src/core/lombok/Delegate.java000066400000000000000000000053441312655740700205520ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @deprecated Use {@link lombok.experimental.Delegate} instead. */ @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.SOURCE) @Deprecated public @interface Delegate { /** * Normally the type of the field is used as delegate type. However, to choose a different type to delegate, you can list one (or more) types here. Note that types with * type arguments can only be done as a field type. A solution for this is to create a private inner interface/class with the appropriate types extended, and possibly * with all methods you'd like to delegate listed, and then supply that class here. The field does not actually have to implement the type you're delegating; the * type listed here is used only to determine which delegate methods to generate. * * NB: All methods in {@code Object}, as well as {@code canEqual(Object other)} will never be delegated. * * @return For each method (not already in {@code java.lang.Object}) in these types, generate a delegate method. */ Class[] types() default {}; /** * Each method in any of the types listed here (include supertypes) will not be delegated. * * NB: All methods in {@code Object}, as well as {@code canEqual(Object other)} will never be delegated. * * @return For each method (not already in {@code java.lang.Object}) in these types, skip generating a delegate method (overrides {@code types()}). */ Class[] excludes() default {}; } lombok-1.16.18/src/core/lombok/EqualsAndHashCode.java000066400000000000000000000075511312655740700223160ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Generates implementations for the {@code equals} and {@code hashCode} methods inherited by all objects, based on relevant fields. *

* Complete documentation is found at the project lombok features page for @EqualsAndHashCode. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface EqualsAndHashCode { /** * Any fields listed here will not be taken into account in the generated {@code equals} and {@code hashCode} implementations. * Mutually exclusive with {@link #of()}. * * @return A list of fields to exclude. */ String[] exclude() default {}; /** * If present, explicitly lists the fields that are to be used for identity. * Normally, all non-static, non-transient fields are used for identity. *

* Mutually exclusive with {@link #exclude()}. * * @return A list of fields to use (default: all of them). */ String[] of() default {}; /** * Call on the superclass's implementations of {@code equals} and {@code hashCode} before calculating for the fields in this class. * default: false * * @return Whether to call the superclass's {@code equals} implementation as part of the generated equals algorithm. */ boolean callSuper() default false; /** * Normally, if getters are available, those are called. To suppress this and let the generated code use the fields directly, set this to {@code true}. * default: false * * @return If {@code true}, always use direct field access instead of calling the getter method. */ boolean doNotUseGetters() default false; /** * Any annotations listed here are put on the generated parameter of {@code equals} and {@code canEqual}. * This is useful to add for example a {@code Nullable} annotation.
* The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
* up to JDK7:
* {@code @EqualsAndHashCode(onParam=@__({@AnnotationsGoHere}))}
* from JDK8:
* {@code @EqualsAndHashCode(onParam_={@AnnotationsGohere})} // note the underscore after {@code onParam}. * * @return List of annotations to apply to the generated parameter in the {@code equals()} method. */ AnyAnnotation[] onParam() default {}; /** * Placeholder annotation to enable the placement of annotations on the generated code. * @deprecated Don't use this annotation, ever - Read the documentation. */ @Deprecated @Retention(RetentionPolicy.SOURCE) @Target({}) @interface AnyAnnotation {} } lombok-1.16.18/src/core/lombok/Generated.java000066400000000000000000000036501312655740700207340ustar00rootroot00000000000000/* * Copyright (C) 2015-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Lombok will eventually automatically add this annotation to all generated constructors, methods, fields, and types. * * You can mark the presence of this annotation as 'ignore it' for all code style and bug finding tools. *

* NB: As of v1.16.2 which introduces this annotation, lombok doesn't actually add this annotation; we're setting * it up so that lombok jars in widespread use start having this, which will make it easier to actually apply it * later on. */ @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.CLASS) public @interface Generated { } lombok-1.16.18/src/core/lombok/Getter.java000066400000000000000000000062611312655740700202710ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Put on any field to make lombok build a standard getter. *

* Complete documentation is found at the project lombok features page for @Getter and @Setter. *

* Even though it is not listed, this annotation also has the {@code onMethod} parameter. See the full documentation for more details. *

* Example: *

 *     private @Getter int foo;
 * 
* * will generate: * *
 *     public int getFoo() {
 *         return this.foo;
 *     }
 * 
*

* This annotation can also be applied to a class, in which case it'll be as if all non-static fields that don't already have * a {@code @Getter} annotation have the annotation. */ @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.SOURCE) public @interface Getter { /** * If you want your getter to be non-public, you can specify an alternate access level here. * * @return The getter method will be generated with this access modifier. */ lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC; /** * Any annotations listed here are put on the generated method. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
* up to JDK7:
* {@code @Getter(onMethod=@__({@AnnotationsGoHere}))}
* from JDK8:
* {@code @Getter(onMethod_={@AnnotationsGohere})} // note the underscore after {@code onMethod}. * * @return List of annotations to apply to the generated getter method. */ AnyAnnotation[] onMethod() default {}; boolean lazy() default false; /** * Placeholder annotation to enable the placement of annotations on the generated code. * @deprecated Don't use this annotation, ever - Read the documentation. */ @Deprecated @Retention(RetentionPolicy.SOURCE) @Target({}) @interface AnyAnnotation {} } lombok-1.16.18/src/core/lombok/Lombok.java000066400000000000000000000070211312655740700202550ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; /** * Useful utility methods to manipulate lombok-generated code. */ public class Lombok { /** * Throws any throwable 'sneakily' - you don't need to catch it, nor declare that you throw it onwards. * The exception is still thrown - javac will just stop whining about it. *

* Example usage: *

public void run() {
	 *     throw sneakyThrow(new IOException("You don't need to catch me!"));
	 * }
*

* NB: The exception is not wrapped, ignored, swallowed, or redefined. The JVM actually does not know or care * about the concept of a 'checked exception'. All this method does is hide the act of throwing a checked exception * from the java compiler. *

* Note that this method has a return type of {@code RuntimeException}; it is advised you always call this * method as argument to the {@code throw} statement to avoid compiler errors regarding no return * statement and similar problems. This method won't of course return an actual {@code RuntimeException} - * it never returns, it always throws the provided exception. * * @param t The throwable to throw without requiring you to catch its type. * @return A dummy RuntimeException; this method never returns normally, it always throws an exception! */ public static RuntimeException sneakyThrow(Throwable t) { if (t == null) throw new NullPointerException("t"); Lombok.sneakyThrow0(t); return null; } @SuppressWarnings("unchecked") private static void sneakyThrow0(Throwable t) throws T { throw (T)t; } /** * Returns the parameter directly. * * This method can be used to prevent a static analyzer to determine the nullness of the passed parameter. * * @param the type of the parameter. * @param value the value to return. * @return value (this method just returns the parameter). */ public static T preventNullAnalysis(T value) { return value; } /** * Ensures that the {@code value} is not {@code null}. * * @param Type of the parameter. * @param value the value to test for null. * @param message the message of the {@link NullPointerException}. * @return the value if it is not null. * @throws NullPointerException with the {@code message} if the value is null. */ public static T checkNotNull(T value, String message) { if (value == null) throw new NullPointerException(message); return value; } } lombok-1.16.18/src/core/lombok/NoArgsConstructor.java000066400000000000000000000074511312655740700225000ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Generates a no-args constructor. * Will generate an error message if such a constructor cannot be written due to the existence of final fields. *

* Complete documentation is found at the project lombok features page for @Constructor. *

* Even though it is not listed, this annotation also has the {@code onConstructor} parameter. See the full documentation for more details. *

* NB: Fields with constraints such as {@code @NonNull} will NOT be checked in a {@code @NoArgsConstructor} constructor, of course! * * @see RequiredArgsConstructor * @see AllArgsConstructor */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface NoArgsConstructor { /** * If set, the generated constructor will be private, and an additional static 'constructor' * is generated with the same argument list that wraps the real constructor. * * Such a static 'constructor' is primarily useful as it infers type arguments. * * @return Name of static 'constructor' method to generate (blank = generate a normal constructor). */ String staticName() default ""; /** * Any annotations listed here are put on the generated constructor. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
* up to JDK7:
* {@code @NoArgsConstructor(onConstructor=@__({@AnnotationsGoHere}))}
* from JDK8:
* {@code @NoArgsConstructor(onConstructor_={@AnnotationsGohere})} // note the underscore after {@code onConstructor}. * * @return List of annotations to apply to the generated constructor. */ AnyAnnotation[] onConstructor() default {}; /** * Sets the access level of the constructor. By default, generated constructors are {@code public}. * * @return The constructor will be generated with this access modifier. */ AccessLevel access() default lombok.AccessLevel.PUBLIC; /** * If {@code true}, initializes all final fields to 0 / null / false. * Otherwise, a compile time error occurs. * * @return Return {@code} true to force generation of a no-args constructor, picking defaults if necessary to assign required fields. */ boolean force() default false; /** * Placeholder annotation to enable the placement of annotations on the generated code. * @deprecated Don't use this annotation, ever - Read the documentation. */ @Deprecated @Retention(RetentionPolicy.SOURCE) @Target({}) @interface AnyAnnotation {} } lombok-1.16.18/src/core/lombok/NonNull.java000066400000000000000000000050351312655740700204220ustar00rootroot00000000000000/* * Copyright (C) 2009-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * If put on a parameter, lombok will insert a null-check at the start of the method / constructor's body, throwing a * {@code NullPointerException} with the parameter's name as message. If put on a field, any generated method assigning * a value to this field will also produce these nullchecks. *

* Note that any annotation named {@code NonNull} with any casing and any package will result in nullchecks produced for * generated methods (and the annotation will be copied to the getter return type and any parameters of generated methods), * but only this annotation, if present on a parameter, will result in a null check inserted into your otherwise * handwritten method. * * WARNING: If the java community ever does decide on supporting a single {@code @NonNull} annotation (for example via JSR305), then * this annotation will be deleted from the lombok package. If the need to update an import statement scares * you, you should use your own annotation named {@code @NonNull} instead of this one. */ @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) @Retention(RetentionPolicy.CLASS) @Documented public @interface NonNull { } lombok-1.16.18/src/core/lombok/RequiredArgsConstructor.java000066400000000000000000000065631312655740700237070ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Generates a constructor with required arguments. * Required arguments are final fields and fields with constraints such as {@code @NonNull}. *

* Complete documentation is found at the project lombok features page for @Constructor. *

* Even though it is not listed, this annotation also has the {@code onConstructor} parameter. See the full documentation for more details. * * @see NoArgsConstructor * @see AllArgsConstructor */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface RequiredArgsConstructor { /** * If set, the generated constructor will be private, and an additional static 'constructor' * is generated with the same argument list that wraps the real constructor. * * Such a static 'constructor' is primarily useful as it infers type arguments. * * @return Name of static 'constructor' method to generate (blank = generate a normal constructor). */ String staticName() default ""; /** * Any annotations listed here are put on the generated constructor. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
* up to JDK7:
* {@code @RequiredArgsConstructor(onConstructor=@__({@AnnotationsGoHere}))}
* from JDK8:
* {@code @RequiredArgsConstructor(onConstructor_={@AnnotationsGohere})} // note the underscore after {@code onConstructor}. * * @return List of annotations to apply to the generated constructor. */ AnyAnnotation[] onConstructor() default {}; /** * Sets the access level of the constructor. By default, generated constructors are {@code public}. * * @return The constructor will be generated with this access modifier. */ AccessLevel access() default lombok.AccessLevel.PUBLIC; /** * Placeholder annotation to enable the placement of annotations on the generated code. * @deprecated Don't use this annotation, ever - Read the documentation. */ @Deprecated @Retention(RetentionPolicy.SOURCE) @Target({}) @interface AnyAnnotation {} } lombok-1.16.18/src/core/lombok/Setter.java000066400000000000000000000073201312655740700203020ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Put on any field to make lombok build a standard setter. *

* Complete documentation is found at the project lombok features page for @Getter and @Setter. *

* Even though it is not listed, this annotation also has the {@code onParam} and {@code onMethod} parameter. See the full documentation for more details. *

* Example: *

 *     private @Setter int foo;
 * 
* * will generate: * *
 *     public void setFoo(int foo) {
 *         this.foo = foo;
 *     }
 * 
* *

* This annotation can also be applied to a class, in which case it'll be as if all non-static fields that don't already have * a {@code Setter} annotation have the annotation. */ @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.SOURCE) public @interface Setter { /** * If you want your setter to be non-public, you can specify an alternate access level here. * * @return The setter method will be generated with this access modifier. */ lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC; /** * Any annotations listed here are put on the generated method. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
* up to JDK7:
* {@code @Setter(onMethod=@__({@AnnotationsGoHere}))}
* from JDK8:
* {@code @Setter(onMethod_={@AnnotationsGohere})} // note the underscore after {@code onMethod}. * * @return List of annotations to apply to the generated setter method. */ AnyAnnotation[] onMethod() default {}; /** * Any annotations listed here are put on the generated method's parameter. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
* up to JDK7:
* {@code @Setter(onParam=@__({@AnnotationsGoHere}))}
* from JDK8:
* {@code @Setter(onParam_={@AnnotationsGohere})} // note the underscore after {@code onParam}. * * @return List of annotations to apply to the generated parameter in the setter method. */ AnyAnnotation[] onParam() default {}; /** * Placeholder annotation to enable the placement of annotations on the generated code. * @deprecated Don't use this annotation, ever - Read the documentation. */ @Deprecated @Retention(RetentionPolicy.SOURCE) @Target({}) @interface AnyAnnotation {} }lombok-1.16.18/src/core/lombok/Singular.java000066400000000000000000000033301312655740700206150ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * The singular annotation is used together with {@code @Builder} to create single element 'add' methods in the builder for collections. */ @Target({FIELD, PARAMETER}) @Retention(SOURCE) public @interface Singular { /** @return The singular name of this field. If it's a normal english plural, lombok will figure it out automatically. Otherwise, this parameter is mandatory. */ String value() default ""; } lombok-1.16.18/src/core/lombok/SneakyThrows.java000066400000000000000000000060161312655740700214760ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @SneakyThrow will avoid javac's insistence that you either catch or throw onward any checked exceptions that * statements in your method body declare they generate. *

* @SneakyThrow does not silently swallow, wrap into RuntimeException, or otherwise modify any exceptions of the listed * checked exception types. The JVM does not check for the consistency of the checked exception system; javac does, * and this annotation lets you opt out of its mechanism. *

* Complete documentation is found at the project lombok features page for @SneakyThrows. *

* Example: *

 * @SneakyThrows(UnsupportedEncodingException.class)
 * public void utf8ToString(byte[] bytes) {
 *     return new String(bytes, "UTF-8");
 * }
 * 
* * Becomes: *
 * public void utf8ToString(byte[] bytes) {
 *     try {
 *         return new String(bytes, "UTF-8");
 *     } catch (UnsupportedEncodingException $uniqueName) {
 *         throw useMagicTrickeryToHideThisFromTheCompiler($uniqueName);
 *         // This trickery involves a bytecode transformer run automatically during the final stages of compilation;
 *         // there is no runtime dependency on lombok.
 *     }
 * 
*/ @Target({ElementType.METHOD, ElementType.CONSTRUCTOR}) @Retention(RetentionPolicy.SOURCE) public @interface SneakyThrows { /** @return The exception type(s) you want to sneakily throw onward. */ Class[] value() default java.lang.Throwable.class; //The fully qualified name is used for java.lang.Throwable in the parameter only. This works around a bug in javac: // presence of an annotation processor throws off the type resolver for some reason. } lombok-1.16.18/src/core/lombok/Synchronized.java000066400000000000000000000045421312655740700215160ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Almost exactly like putting the 'synchronized' keyword on a method, except will synchronize on a private internal * Object, so that other code not under your control doesn't meddle with your thread management by locking on * your own instance. *

* For non-static methods, a field named {@code $lock} is used, and for static methods, * {@code $LOCK} is used. These will be generated if needed and if they aren't already present. The contents * of the fields will be serializable. *

* Complete documentation is found at the project lombok features page for @Synchronized. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface Synchronized { /** * Optional: specify the name of a different field to lock on. It is a compile time error if this field * doesn't already exist (the fields are automatically generated only if you don't specify a specific name. * * @return Name of the field to lock on (blank = generate one). */ String value() default ""; } lombok-1.16.18/src/core/lombok/ToString.java000066400000000000000000000061071312655740700206070ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Generates an implementation for the {@code toString} method inherited by all objects, consisting of printing the values of relevant fields. *

* Complete documentation is found at the project lombok features page for @ToString. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface ToString { /** * Include the name of each field when printing it. * default: true * * @return Whether or not to include the names of fields in the string produced by the generated {@code toString()}. */ boolean includeFieldNames() default true; /** * Any fields listed here will not be printed in the generated {@code toString} implementation. * Mutually exclusive with {@link #of()}. * * @return A list of fields to exclude. */ String[] exclude() default {}; /** * If present, explicitly lists the fields that are to be printed. * Normally, all non-static fields are printed. *

* Mutually exclusive with {@link #exclude()}. * * @return A list of fields to use (default: all of them). */ String[] of() default {}; /** * Include the result of the superclass's implementation of {@code toString} in the output. * default: false * * @return Whether to call the superclass's {@code equals} implementation as part of the generated equals algorithm. */ boolean callSuper() default false; /** * Normally, if getters are available, those are called. To suppress this and let the generated code use the fields directly, set this to {@code true}. * default: false * * @return If {@code true}, always use direct field access instead of calling the getter method. */ boolean doNotUseGetters() default false; } lombok-1.16.18/src/core/lombok/Value.java000066400000000000000000000050121312655740700201040ustar00rootroot00000000000000/* * Copyright (C) 2012-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Generates a lot of code which fits with a class that is a representation of an immutable entity. *

* Equivalent to {@code @Getter @FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE) @AllArgsConstructor @ToString @EqualsAndHashCode}. *

* Complete documentation is found at the project lombok features page for @Value. * * @see lombok.Getter * @see lombok.experimental.FieldDefaults * @see lombok.AllArgsConstructor * @see lombok.ToString * @see lombok.EqualsAndHashCode * @see lombok.Data */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface Value { /** * If you specify a static constructor name, then the generated constructor will be private, and * instead a static factory method is created that other classes can use to create instances. * We suggest the name: "of", like so: * *

	 *     public @Value(staticConstructor = "of") class Point { final int x, y; }
	 * 
* * Default: No static constructor, instead the normal constructor is public. * * @return Name of static 'constructor' method to generate (blank = generate a normal constructor). */ String staticConstructor() default ""; } lombok-1.16.18/src/core/lombok/bytecode/000077500000000000000000000000001312655740700177655ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/bytecode/AsmUtil.java000066400000000000000000000040151312655740700222060ustar00rootroot00000000000000/* * Copyright (C) 2010-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.commons.JSRInlinerAdapter; class AsmUtil { private AsmUtil() { throw new UnsupportedOperationException(); } static byte[] fixJSRInlining(byte[] byteCode) { ClassReader reader = new ClassReader(byteCode); ClassWriter writer = new FixedClassWriter(reader, 0); ClassVisitor visitor = new ClassVisitor(Opcodes.ASM5, writer) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new JSRInlinerAdapter(super.visitMethod(access, name, desc, signature, exceptions), access, name, desc, signature, exceptions); } }; reader.accept(visitor, 0); return writer.toByteArray(); } } lombok-1.16.18/src/core/lombok/bytecode/ClassFileMetaData.java000066400000000000000000000336721312655740700241110ustar00rootroot00000000000000/* * Copyright (C) 2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Utility to read the constant pool, header, and inheritance information of any class file. */ public class ClassFileMetaData { private static final byte UTF8 = 1; private static final byte INTEGER = 3; private static final byte FLOAT = 4; private static final byte LONG = 5; private static final byte DOUBLE = 6; private static final byte CLASS = 7; private static final byte STRING = 8; private static final byte FIELD = 9; private static final byte METHOD = 10; private static final byte INTERFACE_METHOD = 11; private static final byte NAME_TYPE = 12; // New in java7: support for methodhandles and invokedynamic private static final byte METHOD_HANDLE = 15; private static final byte METHOD_TYPE = 16; private static final byte INVOKE_DYNAMIC = 18; private static final int NOT_FOUND = -1; private static final int START_OF_CONSTANT_POOL = 8; private final byte[] byteCode; private final int maxPoolSize; private final int[] offsets; private final byte[] types; private final String[] utf8s; private final int endOfPool; public ClassFileMetaData(byte[] byteCode) { this.byteCode = byteCode; maxPoolSize = readValue(START_OF_CONSTANT_POOL); offsets = new int[maxPoolSize]; types = new byte[maxPoolSize]; utf8s = new String[maxPoolSize]; int position = 10; for (int i = 1; i < maxPoolSize; i++) { byte type = byteCode[position]; types[i] = type; position++; offsets[i] = position; switch (type) { case UTF8: int length = readValue(position); position += 2; utf8s[i] = decodeString(position, length); position += length; break; case CLASS: case STRING: case METHOD_TYPE: position += 2; break; case METHOD_HANDLE: position += 3; break; case INTEGER: case FLOAT: case FIELD: case METHOD: case INTERFACE_METHOD: case NAME_TYPE: case INVOKE_DYNAMIC: position += 4; break; case LONG: case DOUBLE: position += 8; i++; break; case 0: break; default: throw new AssertionError("Unknown constant pool type " + type); } } endOfPool = position; } private String decodeString(int pos, int size) { int end = pos + size; // the resulting string might be smaller StringBuilder result = new StringBuilder(size); while (pos < end) { int first = (byteCode[pos++] & 0xFF); if (first < 0x80) { result.append((char)first); } else if ((first & 0xE0) == 0xC0) { int x = (first & 0x1F) << 6; int y = (byteCode[pos++] & 0x3F); result.append((char)(x | y)); } else { int x = (first & 0x0F) << 12; int y = (byteCode[pos++] & 0x3F) << 6; int z = (byteCode[pos++] & 0x3F); result.append((char)(x | y | z)); } } return result.toString(); } /** * Checks if the constant pool contains the provided 'raw' string. These are used as source material for further JVM types, such as string constants, type references, etcetera. */ public boolean containsUtf8(String value) { return findUtf8(value) != NOT_FOUND; } /** * Checks if the constant pool contains a reference to the provided class. * * NB: Most uses of a type do NOT show up as a class in the constant pool. * For example, the parameter types and return type of any method you invoke or declare, are stored as signatures and not as type references, * but the type to which any method you invoke belongs, is. Read the JVM Specification for more information. * * @param className must be provided JVM-style, such as {@code java/lang/String} */ public boolean usesClass(String className) { return findClass(className) != NOT_FOUND; } /** * Checks if the constant pool contains a reference to a given field, either for writing or reading. * * @param className must be provided JVM-style, such as {@code java/lang/String} */ public boolean usesField(String className, String fieldName) { int classIndex = findClass(className); if (classIndex == NOT_FOUND) return false; int fieldNameIndex = findUtf8(fieldName); if (fieldNameIndex == NOT_FOUND) return false; for (int i = 1; i < maxPoolSize; i++) { if (types[i] == FIELD && readValue(offsets[i]) == classIndex) { int nameAndTypeIndex = readValue(offsets[i] + 2); if (readValue(offsets[nameAndTypeIndex]) == fieldNameIndex) return true; } } return false; } /** * Checks if the constant pool contains a reference to a given method, with any signature (return type and parameter types). * * @param className must be provided JVM-style, such as {@code java/lang/String} */ public boolean usesMethod(String className, String methodName) { int classIndex = findClass(className); if (classIndex == NOT_FOUND) return false; int methodNameIndex = findUtf8(methodName); if (methodNameIndex == NOT_FOUND) return false; for (int i = 1; i < maxPoolSize; i++) { if (isMethod(i) && readValue(offsets[i]) == classIndex) { int nameAndTypeIndex = readValue(offsets[i] + 2); if (readValue(offsets[nameAndTypeIndex]) == methodNameIndex) return true; } } return false; } /** * Checks if the constant pool contains a reference to a given method. * * @param className must be provided JVM-style, such as {@code java/lang/String} * @param descriptor must be provided JVM-style, such as {@code (IZ)Ljava/lang/String;} */ public boolean usesMethod(String className, String methodName, String descriptor) { int classIndex = findClass(className); if (classIndex == NOT_FOUND) return false; int nameAndTypeIndex = findNameAndType(methodName, descriptor); if (nameAndTypeIndex == NOT_FOUND) return false; for (int i = 1; i < maxPoolSize; i++) { if (isMethod(i) && readValue(offsets[i]) == classIndex && readValue(offsets[i] + 2) == nameAndTypeIndex) return true; } return false; } /** * Checks if the constant pool contains the provided string constant, which implies the constant is used somewhere in the code. * * NB: String literals get concatenated by the compiler. * NB2: This method does NOT do any kind of normalization. */ public boolean containsStringConstant(String value) { int index = findUtf8(value); if (index == NOT_FOUND) return false; for (int i = 1; i < maxPoolSize; i++) { if (types[i] == STRING && readValue(offsets[i]) == index) return true; } return false; } /** * Checks if the constant pool contains the provided long constant, which implies the constant is used somewhere in the code. * * NB: compile-time constant expressions are evaluated at compile time. */ public boolean containsLong(long value) { for (int i = 1; i < maxPoolSize; i++) { if (types[i] == LONG && readLong(i) == value) return true; } return false; } /** * Checks if the constant pool contains the provided double constant, which implies the constant is used somewhere in the code. * * NB: compile-time constant expressions are evaluated at compile time. */ public boolean containsDouble(double value) { boolean isNan = Double.isNaN(value); for (int i = 1; i < maxPoolSize; i++) { if (types[i] == DOUBLE) { double d = readDouble(i); if (d == value || (isNan && Double.isNaN(d))) return true; } } return false; } /** * Checks if the constant pool contains the provided int constant, which implies the constant is used somewhere in the code. * * NB: compile-time constant expressions are evaluated at compile time. */ public boolean containsInteger(int value) { for (int i = 1; i < maxPoolSize; i++) { if (types[i] == INTEGER && readInteger(i) == value) return true; } return false; } /** * Checks if the constant pool contains the provided float constant, which implies the constant is used somewhere in the code. * * NB: compile-time constant expressions are evaluated at compile time. */ public boolean containsFloat(float value) { boolean isNan = Float.isNaN(value); for (int i = 1; i < maxPoolSize; i++) { if (types[i] == FLOAT) { float f = readFloat(i); if (f == value || (isNan && Float.isNaN(f))) return true; } } return false; } private long readLong(int index) { int pos = offsets[index]; return ((long)read32(pos)) << 32 | (read32(pos + 4) & 0x00000000FFFFFFFFL); } private double readDouble(int index) { return Double.longBitsToDouble(readLong(index)); } private int readInteger(int index) { return read32(offsets[index]); } private float readFloat(int index) { return Float.intBitsToFloat(readInteger(index)); } private int read32(int pos) { return (byteCode[pos] & 0xFF) << 24 | (byteCode[pos + 1] & 0xFF) << 16 | (byteCode[pos + 2] & 0xFF) << 8 | (byteCode[pos + 3] & 0xFF); } /** * Returns the name of the class in JVM format, such as {@code java/lang/String} */ public String getClassName() { return getClassName(readValue(endOfPool + 2)); } /** * Returns the name of the superclass in JVM format, such as {@code java/lang/Object} * * NB: If you try this on Object itself, you'll get {@code null}.
* NB2: For interfaces and annotation interfaces, you'll always get {@code java/lang/Object} */ public String getSuperClassName() { return getClassName(readValue(endOfPool + 4)); } /** * Returns the name of all implemented interfaces. */ public List getInterfaces() { int size = readValue(endOfPool + 6); if (size == 0) return Collections.emptyList(); List result = new ArrayList(); for (int i = 0; i < size; i++) { result.add(getClassName(readValue(endOfPool + 8 + (i * 2)))); } return result; } /** * A {@code toString()} like utility to dump all contents of the constant pool into a string. * * NB: No guarantees are made about the exact layout of this string. It is for informational purposes only, don't try to parse it.
* NB2: After a double or long, there's a JVM spec-mandated gap, which is listed as {@code (cont.)} in the returned string. */ public String poolContent() { StringBuilder result = new StringBuilder(); for (int i = 1; i < maxPoolSize; i++) { result.append(String.format("#%02x: ", i)); int pos = offsets[i]; switch(types[i]) { case UTF8: result.append("Utf8 ").append(utf8s[i]); break; case CLASS: result.append("Class ").append(getClassName(i)); break; case STRING: result.append("String \"").append(utf8s[readValue(pos)]).append("\""); break; case INTEGER: result.append("int ").append(readInteger(i)); break; case FLOAT: result.append("float ").append(readFloat(i)); break; case FIELD: appendAccess(result.append("Field "), i); break; case METHOD: case INTERFACE_METHOD: appendAccess(result.append("Method "), i); break; case NAME_TYPE: appendNameAndType(result.append("Name&Type "), i); break; case LONG: result.append("long ").append(readLong(i)); break; case DOUBLE: result.append("double ").append(readDouble(i)); break; case METHOD_HANDLE: result.append("MethodHandle..."); break; case METHOD_TYPE: result.append("MethodType..."); break; case INVOKE_DYNAMIC: result.append("InvokeDynamic..."); break; case 0: result.append("(cont.)"); break; } result.append("\n"); } return result.toString(); } private void appendAccess(StringBuilder result, int index) { int pos = offsets[index]; result.append(getClassName(readValue(pos))).append("."); appendNameAndType(result, readValue(pos + 2)); } private void appendNameAndType(StringBuilder result, int index) { int pos = offsets[index]; result.append(utf8s[readValue(pos)]).append(":").append(utf8s[readValue(pos + 2)]); } private String getClassName(int classIndex) { if (classIndex < 1) return null; return utf8s[readValue(offsets[classIndex])]; } private boolean isMethod(int i) { byte type = types[i]; return type == METHOD || type == INTERFACE_METHOD; } private int findNameAndType(String name, String descriptor) { int nameIndex = findUtf8(name); if (nameIndex == NOT_FOUND) return NOT_FOUND; int descriptorIndex = findUtf8(descriptor); if (descriptorIndex == NOT_FOUND) return NOT_FOUND; for (int i = 1; i < maxPoolSize; i++) { if (types[i] == NAME_TYPE && readValue(offsets[i]) == nameIndex && readValue(offsets[i] + 2) == descriptorIndex) return i; } return NOT_FOUND; } private int findUtf8(String value) { for (int i = 1; i < maxPoolSize; i++) { if (value.equals(utf8s[i])) { return i; } } return NOT_FOUND; } private int findClass(String className) { int index = findUtf8(className); if (index == -1) return NOT_FOUND; for (int i = 1; i < maxPoolSize; i++) { if (types[i] == CLASS && readValue(offsets[i]) == index) return i; } return NOT_FOUND; } private int readValue(int position) { return ((byteCode[position] & 0xFF) << 8) | (byteCode[position + 1] & 0xFF); } } lombok-1.16.18/src/core/lombok/bytecode/FixedClassWriter.java000066400000000000000000000034761312655740700240640ustar00rootroot00000000000000/* * Copyright (C) 2010-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; class FixedClassWriter extends ClassWriter { FixedClassWriter(ClassReader classReader, int flags) { super(classReader, flags); } @Override protected String getCommonSuperClass(String type1, String type2) { //By default, ASM will attempt to live-load the class types, which will fail if meddling with classes in an //environment with custom classloaders, such as Equinox. It's just an optimization; returning Object is always legal. try { return super.getCommonSuperClass(type1, type2); } catch (OutOfMemoryError e) { throw e; } catch (Throwable t) { return "java/lang/Object"; } } }lombok-1.16.18/src/core/lombok/bytecode/PoolConstantsApp.java000066400000000000000000000065741312655740700241130ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import java.io.File; import java.util.ArrayList; import java.util.List; import lombok.core.LombokApp; import org.mangosdk.spi.ProviderFor; import com.zwitserloot.cmdreader.CmdReader; import com.zwitserloot.cmdreader.Description; import com.zwitserloot.cmdreader.InvalidCommandLineException; import com.zwitserloot.cmdreader.Mandatory; import com.zwitserloot.cmdreader.Sequential; import com.zwitserloot.cmdreader.Shorthand; @ProviderFor(LombokApp.class) public class PoolConstantsApp extends LombokApp { @Override public String getAppName() { return "Xprintpool"; } @Override public String getAppDescription() { return "Prints the content of the constant pool to standard out."; } @Override public boolean isDebugTool() { return true; } public static class CmdArgs { @Sequential @Mandatory @Description("paths to class files to be printed. If a directory is named, all files (recursively) in that directory will be printed.") private List classFiles = new ArrayList(); @Shorthand({"h", "?"}) @Description("Shows this help text") boolean help = false; } @Override public int runApp(List raw) throws Exception { CmdReader reader = CmdReader.of(CmdArgs.class); CmdArgs args; try { args = reader.make(raw.toArray(new String[0])); if (args.help) { System.out.println(reader.generateCommandLineHelp("java -jar lombok.jar -printpool")); return 0; } } catch (InvalidCommandLineException e) { System.err.println(e.getMessage()); System.err.println(reader.generateCommandLineHelp("java -jar lombok.jar -printpool")); return 1; } List filesToProcess = PostCompilerApp.cmdArgsToFiles(args.classFiles); int filesVisited = 0; boolean moreThanOne = filesToProcess.size() > 1; for (File file : filesToProcess) { if (!file.exists() || !file.isFile()) { System.out.printf("Cannot find file '%s'\n", file.getAbsolutePath()); continue; } filesVisited++; if (moreThanOne) System.out.printf("Processing '%s'\n", file.getAbsolutePath()); System.out.println(new ClassFileMetaData(PostCompilerApp.readFile(file)).poolContent()); } if (moreThanOne) System.out.printf("Total files visited: %d\n", filesVisited); return filesVisited == 0 ? 1 : 0; } } lombok-1.16.18/src/core/lombok/bytecode/PostCompilerApp.java000066400000000000000000000124501312655740700237130ustar00rootroot00000000000000/* * Copyright (C) 2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.core.DiagnosticsReceiver; import lombok.core.LombokApp; import lombok.core.PostCompiler; import org.mangosdk.spi.ProviderFor; import com.zwitserloot.cmdreader.CmdReader; import com.zwitserloot.cmdreader.Description; import com.zwitserloot.cmdreader.InvalidCommandLineException; import com.zwitserloot.cmdreader.Mandatory; import com.zwitserloot.cmdreader.Sequential; import com.zwitserloot.cmdreader.Shorthand; @ProviderFor(LombokApp.class) public class PostCompilerApp extends LombokApp { @Override public List getAppAliases() { return Arrays.asList("post", "postcompile"); } @Override public String getAppDescription() { return "Runs registered post compiler handlers to against existing class files, modifying them in the process."; } @Override public String getAppName() { return "post-compile"; } public static class CmdArgs { @Sequential @Mandatory @Description("paths to class files to be converted. If a directory is named, all files (recursively) in that directory will be converted.") private List classFiles = new ArrayList(); @Shorthand("v") @Description("Prints lots of status information as the post compiler runs") boolean verbose = false; @Shorthand({"h", "?"}) @Description("Shows this help text") boolean help = false; } @Override public int runApp(List raw) throws Exception { CmdReader reader = CmdReader.of(CmdArgs.class); CmdArgs args; try { args = reader.make(raw.toArray(new String[0])); if (args.help) { System.out.println(reader.generateCommandLineHelp("java -jar lombok.jar post-compile")); return 0; } } catch (InvalidCommandLineException e) { System.err.println(e.getMessage()); System.err.println(reader.generateCommandLineHelp("java -jar lombok.jar post-compile")); return 1; } int filesVisited = 0, filesTouched = 0; for (File file : cmdArgsToFiles(args.classFiles)) { if (!file.exists() || !file.isFile()) { System.out.printf("Cannot find file '%s'\n", file); continue; } filesVisited++; if (args.verbose) System.out.println("Processing " + file.getAbsolutePath()); byte[] original = readFile(file); byte[] clone = original.clone(); byte[] transformed = PostCompiler.applyTransformations(clone, file.toString(), DiagnosticsReceiver.CONSOLE); if (clone != transformed && !Arrays.equals(original, transformed)) { filesTouched++; if (args.verbose) System.out.println("Rewriting " + file.getAbsolutePath()); writeFile(file, transformed); } } if (args.verbose) { System.out.printf("Total files visited: %d total files changed: %d\n", filesVisited, filesTouched); } return filesVisited == 0 ? 1 : 0; } static List cmdArgsToFiles(List fileNames) { List filesToProcess = new ArrayList(); for (String f : fileNames) addFiles(filesToProcess, f); return filesToProcess; } static void addFiles(List filesToProcess, String f) { File file = new File(f); if (file.isDirectory()) { addRecursively(filesToProcess, file); } else { filesToProcess.add(file); } } static void addRecursively(List filesToProcess, File file) { for (File f : file.listFiles()) { if (f.isDirectory()) addRecursively(filesToProcess, f); else if (f.getName().endsWith(".class")) filesToProcess.add(f); } } static byte[] readFile(File file) throws IOException { byte[] buffer = new byte[1024]; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); FileInputStream fileInputStream = new FileInputStream(file); try { while (true) { int read = fileInputStream.read(buffer); if (read == -1) break; bytes.write(buffer, 0, read); } } finally { fileInputStream.close(); } return bytes.toByteArray(); } static void writeFile(File file, byte[] transformed) throws IOException { FileOutputStream out = new FileOutputStream(file); try { out.write(transformed); } finally { out.close(); } } } lombok-1.16.18/src/core/lombok/bytecode/PreventNullAnalysisRemover.java000066400000000000000000000064201312655740700261540ustar00rootroot00000000000000/* * Copyright (C) 2010-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import static lombok.bytecode.AsmUtil.*; import java.util.concurrent.atomic.AtomicBoolean; import lombok.core.DiagnosticsReceiver; import lombok.core.PostCompilerTransformation; import org.mangosdk.spi.ProviderFor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; @ProviderFor(PostCompilerTransformation.class) public class PreventNullAnalysisRemover implements PostCompilerTransformation { @Override public byte[] applyTransformations(byte[] original, String fileName, DiagnosticsReceiver diagnostics) { if (!new ClassFileMetaData(original).usesMethod("lombok/Lombok", "preventNullAnalysis")) return null; byte[] fixedByteCode = fixJSRInlining(original); ClassReader reader = new ClassReader(fixedByteCode); ClassWriter writer = new FixedClassWriter(reader, 0); final AtomicBoolean changesMade = new AtomicBoolean(); class PreventNullAnalysisVisitor extends MethodVisitor { PreventNullAnalysisVisitor(MethodVisitor mv) { super(Opcodes.ASM5, mv); } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { boolean hit = true; if (hit && opcode != Opcodes.INVOKESTATIC) hit = false; if (hit && !"preventNullAnalysis".equals(name)) hit = false; if (hit && !"lombok/Lombok".equals(owner)) hit = false; if (hit && !"(Ljava/lang/Object;)Ljava/lang/Object;".equals(desc)) hit = false; if (hit) { changesMade.set(true); if (System.getProperty("lombok.debugAsmOnly", null) != null) super.visitMethodInsn(opcode, owner, name, desc, itf); // DEBUG for issue 470! } else { super.visitMethodInsn(opcode, owner, name, desc, itf); } } } reader.accept(new ClassVisitor(Opcodes.ASM5, writer) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new PreventNullAnalysisVisitor(super.visitMethod(access, name, desc, signature, exceptions)); } }, 0); return changesMade.get() ? writer.toByteArray() : null; } } lombok-1.16.18/src/core/lombok/bytecode/SneakyThrowsRemover.java000066400000000000000000000150021312655740700246270ustar00rootroot00000000000000/* * Copyright (C) 2010-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import static lombok.bytecode.AsmUtil.*; import java.util.concurrent.atomic.AtomicBoolean; import lombok.core.DiagnosticsReceiver; import lombok.core.PostCompilerTransformation; import org.mangosdk.spi.ProviderFor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; @ProviderFor(PostCompilerTransformation.class) public class SneakyThrowsRemover implements PostCompilerTransformation { @Override public byte[] applyTransformations(byte[] original, String fileName, final DiagnosticsReceiver diagnostics) { if (!new ClassFileMetaData(original).usesMethod("lombok/Lombok", "sneakyThrow")) return null; byte[] fixedByteCode = fixJSRInlining(original); ClassReader reader = new ClassReader(fixedByteCode); ClassWriter writer = new ClassWriter(reader, 0); final AtomicBoolean changesMade = new AtomicBoolean(); class SneakyThrowsRemoverVisitor extends MethodVisitor { SneakyThrowsRemoverVisitor(MethodVisitor mv) { super(Opcodes.ASM5, mv); } private boolean methodInsnQueued = false; @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if ( opcode == Opcodes.INVOKESTATIC && "sneakyThrow".equals(name) && "lombok/Lombok".equals(owner) && "(Ljava/lang/Throwable;)Ljava/lang/RuntimeException;".equals(desc)) { if (System.getProperty("lombok.debugAsmOnly", null) != null) { super.visitMethodInsn(opcode, owner, name, desc, itf); // DEBUG for issue 470! } else { methodInsnQueued = true; } } else { super.visitMethodInsn(opcode, owner, name, desc, itf); } } private void handleQueue() { if (!methodInsnQueued) return; super.visitMethodInsn(Opcodes.INVOKESTATIC, "lombok/Lombok", "sneakyThrow", "(Ljava/lang/Throwable;)Ljava/lang/RuntimeException;", false); methodInsnQueued = false; diagnostics.addWarning("Proper usage is: throw lombok.Lombok.sneakyThrow(someException);. You did not 'throw' it. Because of this, the call to sneakyThrow " + "remains in your classfile and you will need lombok.jar on the classpath at runtime."); } @Override public void visitInsn(int arg0) { if (methodInsnQueued && arg0 == Opcodes.ATHROW) { changesMade.set(true); // As expected, the required ATHROW. We can now safely 'eat' the previous call. methodInsnQueued = false; } handleQueue(); super.visitInsn(arg0); } @Override public void visitFrame(int arg0, int arg1, Object[] arg2, int arg3, Object[] arg4) { handleQueue(); super.visitFrame(arg0, arg1, arg2, arg3, arg4); } @Override public void visitIincInsn(int arg0, int arg1) { handleQueue(); super.visitIincInsn(arg0, arg1); } @Override public void visitFieldInsn(int arg0, String arg1, String arg2, String arg3) { handleQueue(); super.visitFieldInsn(arg0, arg1, arg2, arg3); } @Override public void visitIntInsn(int arg0, int arg1) { handleQueue(); super.visitIntInsn(arg0, arg1); } @Override public void visitEnd() { handleQueue(); super.visitEnd(); } @Override public void visitInvokeDynamicInsn(String arg0, String arg1, Handle arg2, Object... arg3) { handleQueue(); super.visitInvokeDynamicInsn(arg0, arg1, arg2, arg3); } @Override public void visitLabel(Label arg0) { handleQueue(); super.visitLabel(arg0); } @Override public void visitJumpInsn(int arg0, Label arg1) { handleQueue(); super.visitJumpInsn(arg0, arg1); } @Override public void visitLdcInsn(Object arg0) { handleQueue(); super.visitLdcInsn(arg0); } @Override public void visitLocalVariable(String arg0, String arg1, String arg2, Label arg3, Label arg4, int arg5) { handleQueue(); super.visitLocalVariable(arg0, arg1, arg2, arg3, arg4, arg5); } @Override public void visitMaxs(int arg0, int arg1) { handleQueue(); super.visitMaxs(arg0, arg1); } @Override public void visitLookupSwitchInsn(Label arg0, int[] arg1, Label[] arg2) { handleQueue(); super.visitLookupSwitchInsn(arg0, arg1, arg2); } @Override public void visitMultiANewArrayInsn(String arg0, int arg1) { handleQueue(); super.visitMultiANewArrayInsn(arg0, arg1); } @Override public void visitVarInsn(int arg0, int arg1) { handleQueue(); super.visitVarInsn(arg0, arg1); } @Override public void visitTryCatchBlock(Label arg0, Label arg1, Label arg2, String arg3) { handleQueue(); super.visitTryCatchBlock(arg0, arg1, arg2, arg3); } @Override public void visitTableSwitchInsn(int arg0, int arg1, Label arg2, Label... arg3) { handleQueue(); super.visitTableSwitchInsn(arg0, arg1, arg2, arg3); } @Override public void visitTypeInsn(int arg0, String arg1) { handleQueue(); super.visitTypeInsn(arg0, arg1); } } reader.accept(new ClassVisitor(Opcodes.ASM5, writer) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new SneakyThrowsRemoverVisitor(super.visitMethod(access, name, desc, signature, exceptions)); } }, 0); return changesMade.get() ? writer.toByteArray() : null; } } lombok-1.16.18/src/core/lombok/bytecode/package-info.java000066400000000000000000000030051312655740700231520ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * This package contains utilities and handlers for the 'post-process class files' aspect of * lombok. Lombok's class file post processing capabilities are based on Objectweb's ASM library. * * NB: This package is not public API in the sense that contents of this package, * even public classes / methods / etc, may change in point releases. */ package lombok.bytecode; lombok-1.16.18/src/core/lombok/core/000077500000000000000000000000001312655740700171175ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/core/AST.java000066400000000000000000000342301312655740700204130ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import static lombok.Lombok.sneakyThrow; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import lombok.core.configuration.ConfigurationKey; import lombok.core.debug.HistogramTracker; /** * Lombok wraps the AST produced by a target platform into its own AST system, mostly because both Eclipse and javac * do not allow upward traversal (from a method to its owning type, for example). * * @param A Self-type. * @param L type of all LombokNodes. * @param N The common type of all AST nodes in the internal representation of the target platform. * For example, JCTree for javac, and ASTNode for Eclipse. */ public abstract class AST, L extends LombokNode, N> { /** The kind of node represented by a given AST.Node object. */ public enum Kind { COMPILATION_UNIT, TYPE, FIELD, INITIALIZER, METHOD, ANNOTATION, ARGUMENT, LOCAL, STATEMENT; } private L top; private final String fileName; private final String packageDeclaration; private final ImportList imports; Map identityDetector = new IdentityHashMap(); private Map nodeMap = new IdentityHashMap(); private boolean changed = false; // The supertypes which are considered AST Node children. Usually, the Statement, and the Expression, // though some platforms (such as Eclipse) group these under one common supertype. private final Collection> statementTypes; private static final HistogramTracker configTracker = System.getProperty("lombok.timeConfig") == null ? null : new HistogramTracker("lombok.config"); protected AST(String fileName, String packageDeclaration, ImportList imports, Collection> statementTypes) { this.fileName = fileName == null ? "(unknown).java" : fileName; this.packageDeclaration = packageDeclaration; this.imports = imports; this.statementTypes = statementTypes; } /** * Attempts to find the absolute path (in URI form) to the source file represented by this AST. * * May return {@code null} if this cannot be done. We don't yet know under which conditions this will happen. */ public abstract URI getAbsoluteFileLocation(); public void setChanged() { this.changed = true; } protected void clearChanged() { this.changed = false; } public boolean isChanged() { return changed; } /** Set the node object that wraps the internal Compilation Unit node. */ protected void setTop(L top) { this.top = top; } /** * Return the content of the package declaration on this AST's top (Compilation Unit) node. * * Example: "java.util". */ public final String getPackageDeclaration() { return packageDeclaration; } /** * Return the contents of each non-static import statement on this AST's top (Compilation Unit) node. * * Example: "java.util.IOException". */ public final ImportList getImportList() { return imports; } /** * Puts the given node in the map so that javac/Eclipse's own internal AST object can be translated to * an AST.Node object. Also registers the object as visited to avoid endless loops. */ protected L putInMap(L node) { nodeMap.put(node.get(), node); identityDetector.put(node.get(), node.get()); return node; } /** Returns the node map, that can map javac/Eclipse internal AST objects to AST.Node objects. */ protected Map getNodeMap() { return nodeMap; } /** Clears the registry that avoids endless loops, and empties the node map. The existing node map * object is left untouched, and instead a new map is created. */ protected void clearState() { identityDetector = new IdentityHashMap(); nodeMap = new IdentityHashMap(); } /** * Marks the stated node as handled (to avoid endless loops if 2 nodes refer to each other, or a node * refers to itself). Will then return true if it was already set as handled before this call - in which * case you should do nothing lest the AST build process loops endlessly. */ protected boolean setAndGetAsHandled(N node) { return identityDetector.put(node, node) != null; } public String getFileName() { return fileName; } /** The AST.Node object representing the Compilation Unit. */ public L top() { return top; } /** Maps a javac/Eclipse internal AST Node to the appropriate AST.Node object. */ public L get(N node) { return nodeMap.get(node); } /** * Returns the JLS spec version that the compiler uses to parse and compile this AST. * For example, if -source 1.6 is on the command line, this will return {@code 6}. */ public int getSourceVersion() { return 6; } /** * Returns the latest version of the java language specification supported by the host compiler. * For example, if compiling with javac v1.7, this returns {@code 7}. * * NB: Even if -source (lower than maximum) is specified, this method still returns the maximum supported number. */ public int getLatestJavaSpecSupported() { return 6; } @SuppressWarnings({"unchecked", "rawtypes"}) L replaceNewWithExistingOld(Map oldNodes, L newNode) { L oldNode = oldNodes.get(newNode.get()); L targetNode = oldNode == null ? newNode : oldNode; List children = new ArrayList(); for (L child : newNode.children) { L oldChild = replaceNewWithExistingOld(oldNodes, child); children.add(oldChild); oldChild.parent = targetNode; } targetNode.children = LombokImmutableList.copyOf(children); return targetNode; } /** Build an AST.Node object for the stated internal (javac/Eclipse) AST Node object. */ protected abstract L buildTree(N item, Kind kind); /** * Represents a field that contains AST children. */ protected static class FieldAccess { /** The actual field. */ public final Field field; /** Dimensions of the field. Works for arrays, or for java.util.collections. */ public final int dim; FieldAccess(Field field, int dim) { this.field = field; this.dim = dim; } } private static final ConcurrentMap, Collection> fieldsOfASTClasses = new ConcurrentHashMap, Collection>(); /** Returns FieldAccess objects for the stated class. Each field that contains objects of the kind returned by * {@link #getStatementTypes()}, either directly or inside of an array or java.util.collection (or array-of-arrays, * or collection-of-collections, et cetera), is returned. */ protected Collection fieldsOf(Class c) { Collection fields = fieldsOfASTClasses.get(c); if (fields != null) return fields; fields = new ArrayList(); getFields(c, fields); fieldsOfASTClasses.putIfAbsent(c, fields); return fieldsOfASTClasses.get(c); } private void getFields(Class c, Collection fields) { if (c == Object.class || c == null) return; for (Field f : c.getDeclaredFields()) { if (Modifier.isStatic(f.getModifiers())) continue; Class t = f.getType(); int dim = 0; if (t.isArray()) { while (t.isArray()) { dim++; t = t.getComponentType(); } } else { while (Collection.class.isAssignableFrom(t)) { dim++; t = getComponentType(f.getGenericType()); } } if (shouldDrill(c, t, f.getName())) { f.setAccessible(true); fields.add(new FieldAccess(f, dim)); } } getFields(c.getSuperclass(), fields); } private Class getComponentType(Type type) { if (type instanceof ParameterizedType) { Type component = ((ParameterizedType)type).getActualTypeArguments()[0]; return component instanceof Class ? (Class)component : Object.class; } return Object.class; } private boolean shouldDrill(Class parentType, Class childType, String fieldName) { for (Class statementType : statementTypes) { if (statementType.isAssignableFrom(childType)) return true; } return false; } /** * buildTree implementation that uses reflection to find all child nodes by way of inspecting * the fields. */ protected Collection buildWithField(Class nodeType, N statement, FieldAccess fa) { List list = new ArrayList(); buildWithField0(nodeType, statement, fa, list); return list; } /** * Uses reflection to find the given direct child on the given statement, and replace it with a new child. */ protected boolean replaceStatementInNode(N statement, N oldN, N newN) { for (FieldAccess fa : fieldsOf(statement.getClass())) { if (replaceStatementInField(fa, statement, oldN, newN)) return true; } return false; } private boolean replaceStatementInField(FieldAccess fa, N statement, N oldN, N newN) { try { Object o = fa.field.get(statement); if (o == null) return false; if (o == oldN) { fa.field.set(statement, newN); return true; } if (fa.dim > 0) { if (o.getClass().isArray()) { return replaceStatementInArray(o, oldN, newN); } else if (Collection.class.isInstance(o)) { return replaceStatementInCollection(fa.field, statement, new ArrayList>(), (Collection)o, oldN, newN); } } return false; } catch (IllegalAccessException e) { throw sneakyThrow(e); } } private boolean replaceStatementInCollection(Field field, Object fieldRef, List> chain, Collection collection, N oldN, N newN) throws IllegalAccessException { if (collection == null) return false; int idx = -1; for (Object o : collection) { idx++; if (o == null) continue; if (Collection.class.isInstance(o)) { Collection newC = (Collection)o; List> newChain = new ArrayList>(chain); newChain.add(newC); if (replaceStatementInCollection(field, fieldRef, newChain, newC, oldN, newN)) return true; } if (o == oldN) { setElementInASTCollection(field, fieldRef, chain, collection, idx, newN); return true; } } return false; } /** * Override if your AST collection does not support the set method. Javac's for example, does not. * * @param field The field that contains the array or list of AST nodes. * @param fieldRef The object that you can supply to the field's {@code get} method. * @param chain If the collection is immutable, you need to update the pointer to the collection in each element in the chain. * * @throws IllegalAccessException This exception won't happen, but we allow you to throw it so you can avoid having to catch it. */ @SuppressWarnings({"rawtypes", "unchecked"}) protected void setElementInASTCollection(Field field, Object fieldRef, List> chain, Collection collection, int idx, N newN) throws IllegalAccessException { if (collection instanceof List) { ((List)collection).set(idx, newN); } } private boolean replaceStatementInArray(Object array, N oldN, N newN) { if (array == null) return false; int len = Array.getLength(array); for (int i = 0; i < len; i++) { Object o = Array.get(array, i); if (o == null) continue; if (o.getClass().isArray()) { if (replaceStatementInArray(o, oldN, newN)) return true; } else if (o == oldN) { Array.set(array, i, newN); return true; } } return false; } @SuppressWarnings("unchecked") private void buildWithField0(Class nodeType, N child, FieldAccess fa, Collection list) { try { Object o = fa.field.get(child); if (o == null) return; if (fa.dim == 0) { L node = buildTree((N)o, Kind.STATEMENT); if (node != null) list.add(nodeType.cast(node)); } else if (o.getClass().isArray()) { buildWithArray(nodeType, o, list, fa.dim); } else if (Collection.class.isInstance(o)) { buildWithCollection(nodeType, o, list, fa.dim); } } catch (IllegalAccessException e) { throw sneakyThrow(e); } } @SuppressWarnings("unchecked") private void buildWithArray(Class nodeType, Object array, Collection list, int dim) { if (dim == 1) { for (Object v : (Object[])array) { if (v == null) continue; L node = buildTree((N)v, Kind.STATEMENT); if (node != null) list.add(nodeType.cast(node)); } } else for (Object v : (Object[])array) { if (v == null) return; buildWithArray(nodeType, v, list, dim -1); } } @SuppressWarnings("unchecked") private void buildWithCollection(Class nodeType, Object collection, Collection list, int dim) { if (dim == 1) { for (Object v : (Collection)collection) { if (v == null) continue; L node = buildTree((N)v, Kind.STATEMENT); if (node != null) list.add(nodeType.cast(node)); } } else for (Object v : (Collection)collection) { buildWithCollection(nodeType, v, list, dim-1); } } public final T readConfiguration(ConfigurationKey key) { long start = configTracker == null ? 0L : configTracker.start(); try { return LombokConfiguration.read(key, this); } finally { if (configTracker != null) configTracker.end(start); } } } lombok-1.16.18/src/core/lombok/core/AgentLauncher.java000066400000000000000000000063351312655740700225110ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.lang.instrument.Instrumentation; import java.util.Arrays; import java.util.Collections; import java.util.List; public class AgentLauncher { public interface AgentLaunchable { void runAgent(String agentArgs, Instrumentation instrumentation, boolean injected, Class launchingContext) throws Exception; } public static void runAgents(String agentArgs, Instrumentation instrumentation, boolean injected, Class launchingContext) throws Throwable { for (AgentInfo info : AGENTS) { try { Class agentClass = Class.forName(info.className()); AgentLaunchable agent = (AgentLaunchable) agentClass.newInstance(); agent.runAgent(agentArgs, instrumentation, injected, launchingContext); } catch (Throwable t) { info.problem(t, instrumentation); } } } private static final List AGENTS = Collections.unmodifiableList(Arrays.asList( new EclipsePatcherInfo() )); private static abstract class AgentInfo { abstract String className(); /** * Called if an exception occurs while loading the agent represented by this AgentInfo object. * * @param t The throwable. * @param instrumentation In case you want to take an alternative action. */ void problem(Throwable t, Instrumentation instrumentation) throws Throwable { if (t instanceof ClassNotFoundException) { //That's okay - this lombok evidently is a version with support for something stripped out. return; } if (t instanceof ClassCastException) { throw new InternalError("Lombok bug. Class: " + className() + " is not an implementation of lombok.core.Agent"); } if (t instanceof IllegalAccessError) { throw new InternalError("Lombok bug. Class: " + className() + " is not public"); } if (t instanceof InstantiationException) { throw new InternalError("Lombok bug. Class: " + className() + " is not concrete or has no public no-args constructor"); } throw t; } } private static class EclipsePatcherInfo extends AgentInfo { @Override String className() { return "lombok.eclipse.agent.EclipsePatcher"; } } } lombok-1.16.18/src/core/lombok/core/AnnotationProcessor.java000066400000000000000000000164541312655740700240060ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import static lombok.core.Augments.ClassLoader_lombokAlreadyAddedTo; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic.Kind; import lombok.patcher.ClassRootFinder; @SupportedAnnotationTypes("*") public class AnnotationProcessor extends AbstractProcessor { private static String trace(Throwable t) { StringWriter w = new StringWriter(); t.printStackTrace(new PrintWriter(w, true)); return w.toString(); } static abstract class ProcessorDescriptor { abstract boolean want(ProcessingEnvironment procEnv, List delayedWarnings); abstract String getName(); abstract boolean process(Set annotations, RoundEnvironment roundEnv); } private final List registered = Arrays.asList(new JavacDescriptor(), new EcjDescriptor()); private final List active = new ArrayList(); private final List delayedWarnings = new ArrayList(); static class JavacDescriptor extends ProcessorDescriptor { private Processor processor; @Override String getName() { return "sun/apple javac 1.6"; } @Override boolean want(ProcessingEnvironment procEnv, List delayedWarnings) { if (!procEnv.getClass().getName().equals("com.sun.tools.javac.processing.JavacProcessingEnvironment")) return false; try { ClassLoader classLoader = findAndPatchClassLoader(procEnv); processor = (Processor) Class.forName("lombok.javac.apt.LombokProcessor", false, classLoader).newInstance(); } catch (Exception e) { delayedWarnings.add("You found a bug in lombok; lombok.javac.apt.LombokProcessor is not available. Lombok will not run during this compilation: " + trace(e)); return false; } catch (NoClassDefFoundError e) { delayedWarnings.add("Can't load javac processor due to (most likely) a class loader problem: " + trace(e)); return false; } try { processor.init(procEnv); } catch (Exception e) { delayedWarnings.add("lombok.javac.apt.LombokProcessor could not be initialized. Lombok will not run during this compilation: " + trace(e)); return false; } catch (NoClassDefFoundError e) { delayedWarnings.add("Can't initialize javac processor due to (most likely) a class loader problem: " + trace(e)); return false; } return true; } private ClassLoader findAndPatchClassLoader(ProcessingEnvironment procEnv) throws Exception { ClassLoader environmentClassLoader = procEnv.getClass().getClassLoader(); if (environmentClassLoader != null && environmentClassLoader.getClass().getCanonicalName().equals("org.codehaus.plexus.compiler.javac.IsolatedClassLoader")) { if (!ClassLoader_lombokAlreadyAddedTo.getAndSet(environmentClassLoader, true)) { Method m = environmentClassLoader.getClass().getDeclaredMethod("addURL", URL.class); URL selfUrl = new File(ClassRootFinder.findClassRootOfClass(AnnotationProcessor.class)).toURI().toURL(); m.invoke(environmentClassLoader, selfUrl); } } ClassLoader ourClassLoader = JavacDescriptor.class.getClassLoader(); if (ourClassLoader == null) return ClassLoader.getSystemClassLoader(); return ourClassLoader; } @Override boolean process(Set annotations, RoundEnvironment roundEnv) { return processor.process(annotations, roundEnv); } } static class EcjDescriptor extends ProcessorDescriptor { @Override String getName() { return "ECJ"; } @Override boolean want(ProcessingEnvironment procEnv, List delayedWarnings) { if (!procEnv.getClass().getName().startsWith("org.eclipse.jdt.")) return false; // Lombok used to work as annotation processor to ecj but that never actually worked properly, so we disabled the feature in 0.10.0. // Because loading lombok as an agent in any ECJ-based non-interactive tool works just fine, we're not going to generate any warnings, as we'll // likely generate more false positives than be helpful. return true; } @Override boolean process(Set annotations, RoundEnvironment roundEnv) { return false; } } @Override public void init(ProcessingEnvironment procEnv) { super.init(procEnv); for (ProcessorDescriptor proc : registered) { if (proc.want(procEnv, delayedWarnings)) active.add(proc); } if (active.isEmpty() && delayedWarnings.isEmpty()) { StringBuilder supported = new StringBuilder(); for (ProcessorDescriptor proc : registered) { if (supported.length() > 0) supported.append(", "); supported.append(proc.getName()); } procEnv.getMessager().printMessage(Kind.WARNING, String.format("You aren't using a compiler supported by lombok, so lombok will not work and has been disabled.\n" + "Your processor is: %s\nLombok supports: %s", procEnv.getClass().getName(), supported)); } } @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { if (!delayedWarnings.isEmpty()) { Set rootElements = roundEnv.getRootElements(); if (!rootElements.isEmpty()) { Element firstRoot = rootElements.iterator().next(); for (String warning : delayedWarnings) processingEnv.getMessager().printMessage(Kind.WARNING, warning, firstRoot); delayedWarnings.clear(); } } for (ProcessorDescriptor proc : active) proc.process(annotations, roundEnv); return false; } /** * We just return the latest version of whatever JDK we run on. Stupid? Yeah, but it's either that or warnings on all versions but 1. Blame Joe. */ @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.values()[SourceVersion.values().length - 1]; } } lombok-1.16.18/src/core/lombok/core/AnnotationValues.java000066400000000000000000000442471312655740700232670ustar00rootroot00000000000000/* * Copyright (C) 2009-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import lombok.core.AST.Kind; /** * Represents a single annotation in a source file and can be used to query the parameters present on it. * * @param A The annotation that this class represents, such as {@code lombok.Getter} */ public class AnnotationValues { private final Class type; private final Map values; private final LombokNode ast; /** * Represents a single method on the annotation class. For example, the value() method on the Getter annotation. */ public static class AnnotationValue { /** A list of the raw expressions. List is size 1 unless an array is provided. */ public final List raws; /** Guesses for each raw expression. If the raw expression is a literal expression, the guess will * likely be right. If not, it'll be wrong. */ public final List valueGuesses; /** A list of the actual expressions. List is size 1 unless an array is provided. */ public final List expressions; private final LombokNode node; private final boolean isExplicit; /** * Like the other constructor, but used for when the annotation method is initialized with an array value. */ public AnnotationValue(LombokNode node, List raws, List expressions, List valueGuesses, boolean isExplicit) { this.node = node; this.raws = raws; this.expressions = expressions; this.valueGuesses = valueGuesses; this.isExplicit = isExplicit; } /** * Override this if you want more specific behaviour (to get the source position just right). * * @param message English message with the problem. * @param valueIdx The index into the values for this annotation key that caused the problem. * -1 for a problem that applies to all values, otherwise the 0-based index into an array of values. * If there is no array for this value (e.g. value=1 instead of value={1,2}), then always -1 or 0. */ public void setError(String message, int valueIdx) { node.addError(message); } /** * Override this if you want more specific behaviour (to get the source position just right). * * @param message English message with the problem. * @param valueIdx The index into the values for this annotation key that caused the problem. * -1 for a problem that applies to all values, otherwise the 0-based index into an array of values. * If there is no array for this value (e.g. value=1 instead of value={1,2}), then always -1 or 0. */ public void setWarning(String message, int valueIdx) { node.addError(message); } /** {@inheritDoc} */ @Override public String toString() { return "raws: " + raws + " valueGuesses: " + valueGuesses; } public boolean isExplicit() { return isExplicit; } } /** * Creates a new AnnotationValues. * * @param type The annotation type. For example, "Getter.class" * @param values a Map of method names to AnnotationValue instances, for example 'value -> annotationValue instance'. * @param ast The Annotation node. */ public AnnotationValues(Class type, Map values, LombokNode ast) { this.type = type; this.values = values; this.ast = ast; } public static AnnotationValues of(Class type) { return new AnnotationValues(type, Collections.emptyMap(), null); } /** * Creates a new annotation wrapper with all default values, and using the provided ast as lookup anchor for * class literals. */ public static AnnotationValues of(Class type, LombokNode ast) { return new AnnotationValues(type, Collections.emptyMap(), ast); } /** * Thrown on the fly if an actual annotation instance procured via the {@link #getInstance()} method is queried * for a method for which this AnnotationValues instance either doesn't have a guess or can't manage to fit * the guess into the required data type. */ public static class AnnotationValueDecodeFail extends RuntimeException { private static final long serialVersionUID = 1L; /** The index into an array initializer (e.g. if the second value in an array initializer is * an integer constant expression like '5+SomeOtherClass.CONSTANT', this exception will be thrown, * and you'll get a '1' for idx. */ public final int idx; /** The AnnotationValue object that goes with the annotation method for which the failure occurred. */ public final AnnotationValue owner; public AnnotationValueDecodeFail(AnnotationValue owner, String msg, int idx) { super(msg); this.idx = idx; this.owner = owner; } } private static AnnotationValueDecodeFail makeNoDefaultFail(AnnotationValue owner, Method method) { return new AnnotationValueDecodeFail(owner, "No value supplied but " + method.getName() + " has no default either.", -1); } private A cachedInstance = null; /** * Creates an actual annotation instance. You can use this to query any annotation methods, except for * those annotation methods with class literals, as those can most likely not be turned into Class objects. * * If some of the methods cannot be implemented, this method still works; it's only when you call a method * that has a problematic value that an AnnotationValueDecodeFail exception occurs. */ @SuppressWarnings("unchecked") public A getInstance() { if (cachedInstance != null) return cachedInstance; InvocationHandler invocations = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { AnnotationValue v = values.get(method.getName()); if (v == null) { Object defaultValue = method.getDefaultValue(); if (defaultValue != null) return defaultValue; throw makeNoDefaultFail(v, method); } boolean isArray = false; Class expected = method.getReturnType(); Object array = null; if (expected.isArray()) { isArray = true; expected = expected.getComponentType(); array = Array.newInstance(expected, v.valueGuesses.size()); } if (!isArray && v.valueGuesses.size() > 1) { throw new AnnotationValueDecodeFail(v, "Expected a single value, but " + method.getName() + " has an array of values", -1); } if (v.valueGuesses.size() == 0 && !isArray) { Object defaultValue = method.getDefaultValue(); if (defaultValue == null) throw makeNoDefaultFail(v, method); return defaultValue; } int idx = 0; for (Object guess : v.valueGuesses) { Object result = guess == null ? null : guessToType(guess, expected, v, idx); if (!isArray) { if (result == null) { Object defaultValue = method.getDefaultValue(); if (defaultValue == null) throw makeNoDefaultFail(v, method); return defaultValue; } return result; } if (result == null) { if (v.valueGuesses.size() == 1) { Object defaultValue = method.getDefaultValue(); if (defaultValue == null) throw makeNoDefaultFail(v, method); return defaultValue; } throw new AnnotationValueDecodeFail(v, "I can't make sense of this annotation value. Try using a fully qualified literal.", idx); } Array.set(array, idx++, result); } return array; } }; return cachedInstance = (A) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, invocations); } private Object guessToType(Object guess, Class expected, AnnotationValue v, int pos) { if (expected == int.class) { if (guess instanceof Integer || guess instanceof Short || guess instanceof Byte) { return ((Number)guess).intValue(); } } if (expected == long.class) { if (guess instanceof Long || guess instanceof Integer || guess instanceof Short || guess instanceof Byte) { return ((Number)guess).longValue(); } } if (expected == short.class) { if (guess instanceof Integer || guess instanceof Short || guess instanceof Byte) { int intVal = ((Number)guess).intValue(); int shortVal = ((Number)guess).shortValue(); if (shortVal == intVal) return shortVal; } } if (expected == byte.class) { if (guess instanceof Integer || guess instanceof Short || guess instanceof Byte) { int intVal = ((Number)guess).intValue(); int byteVal = ((Number)guess).byteValue(); if (byteVal == intVal) return byteVal; } } if (expected == double.class) { if (guess instanceof Number) return ((Number)guess).doubleValue(); } if (expected == float.class) { if (guess instanceof Number) return ((Number)guess).floatValue(); } if (expected == boolean.class) { if (guess instanceof Boolean) return ((Boolean)guess).booleanValue(); } if (expected == char.class) { if (guess instanceof Character) return ((Character)guess).charValue(); } if (expected == String.class) { if (guess instanceof String) return guess; } if (Enum.class.isAssignableFrom(expected) ) { if (guess instanceof String) { for (Object enumConstant : expected.getEnumConstants()) { String target = ((Enum)enumConstant).name(); if (target.equals(guess)) return enumConstant; } throw new AnnotationValueDecodeFail(v, "Can't translate " + guess + " to an enum of type " + expected, pos); } } if (Class.class == expected) { if (guess instanceof String) try { return Class.forName(toFQ((String)guess)); } catch (ClassNotFoundException e) { throw new AnnotationValueDecodeFail(v, "Can't translate " + guess + " to a class object.", pos); } } throw new AnnotationValueDecodeFail(v, "Can't translate a " + guess.getClass() + " to the expected " + expected, pos); } /** * Returns the raw expressions used for the provided {@code annotationMethodName}. * * You should use this method for annotation methods that return {@code Class} objects. Remember that * class literals end in ".class" which you probably want to strip off. */ public List getRawExpressions(String annotationMethodName) { AnnotationValue v = values.get(annotationMethodName); return v == null ? Collections.emptyList() : v.raws; } /** * Returns the actual expressions used for the provided {@code annotationMethodName}. */ public List getActualExpressions(String annotationMethodName) { AnnotationValue v = values.get(annotationMethodName); return v == null ? Collections.emptyList() : v.expressions; } public boolean isExplicit(String annotationMethodName) { AnnotationValue annotationValue = values.get(annotationMethodName); return annotationValue != null && annotationValue.isExplicit(); } /** * Convenience method to return the first result in a {@link #getRawExpressions(String)} call. * * You should use this method if the annotation method is not an array type. */ public String getRawExpression(String annotationMethodName) { List l = getRawExpressions(annotationMethodName); return l.isEmpty() ? null : l.get(0); } /** * Convenience method to return the first result in a {@link #getActualExpressions(String)} call. * * You should use this method if the annotation method is not an array type. */ public Object getActualExpression(String annotationMethodName) { List l = getActualExpressions(annotationMethodName); return l.isEmpty() ? null : l.get(0); } /** Generates an error message on the stated annotation value (you should only call this method if you know it's there!) */ public void setError(String annotationMethodName, String message) { setError(annotationMethodName, message, -1); } /** Generates a warning message on the stated annotation value (you should only call this method if you know it's there!) */ public void setWarning(String annotationMethodName, String message) { setWarning(annotationMethodName, message, -1); } /** Generates an error message on the stated annotation value, which must have an array initializer. * The index-th item in the initializer will carry the error (you should only call this method if you know it's there!) */ public void setError(String annotationMethodName, String message, int index) { AnnotationValue v = values.get(annotationMethodName); if (v == null) return; v.setError(message, index); } /** Generates a warning message on the stated annotation value, which must have an array initializer. * The index-th item in the initializer will carry the error (you should only call this method if you know it's there!) */ public void setWarning(String annotationMethodName, String message, int index) { AnnotationValue v = values.get(annotationMethodName); if (v == null) return; v.setWarning(message, index); } /** * Attempts to translate class literals to their fully qualified names, such as 'Throwable.class' to 'java.lang.Throwable'. * * This process is at best a guess, but it will take into account import statements. */ public List getProbableFQTypes(String annotationMethodName) { List result = new ArrayList(); AnnotationValue v = values.get(annotationMethodName); if (v == null) return Collections.emptyList(); for (Object o : v.valueGuesses) result.add(o == null ? null : toFQ(o.toString())); return result; } /** * Convenience method to return the first result in a {@link #getProbableFQType(String)} call. * * You should use this method if the annotation method is not an array type. */ public String getProbableFQType(String annotationMethodName) { List l = getProbableFQTypes(annotationMethodName); return l.isEmpty() ? null : l.get(0); } /* * Credit goes to Petr Jiricka of Sun for highlighting the problems with the earlier version of this method. */ private String toFQ(String typeName) { String prefix = typeName.indexOf('.') > -1 ? typeName.substring(0, typeName.indexOf('.')) : typeName; /* 1. Walk through type names in this source file at this level. */ { LombokNode n = ast; walkThroughCU: while (n != null) { if (n.getKind() == Kind.TYPE) { String simpleName = n.getName(); if (prefix.equals(simpleName)) { //We found a matching type name in the local hierarchy! List outerNames = new ArrayList(); while (true) { n = n.up(); if (n == null || n.getKind() == Kind.COMPILATION_UNIT) break; if (n.getKind() == Kind.TYPE) outerNames.add(n.getName()); //If our type has a parent that isn't either the CompilationUnit or another type, then we are //a method-local class or an anonymous inner class literal. These technically do have FQNs //and we may, with a lot of effort, figure out their name, but, that's some fairly horrible code //style and these methods have 'probable' in their name for a reason. break walkThroughCU; } StringBuilder result = new StringBuilder(); if (ast.getPackageDeclaration() != null) result.append(ast.getPackageDeclaration()); if (result.length() > 0) result.append('.'); Collections.reverse(outerNames); for (String outerName : outerNames) result.append(outerName).append('.'); result.append(typeName); return result.toString(); } } n = n.up(); } } /* 2. Walk through non-star imports and search for a match. */ { if (prefix.equals(typeName)) { String fqn = ast.getImportList().getFullyQualifiedNameForSimpleName(typeName); if (fqn != null) return fqn; } } /* 3. Walk through star imports and, if they start with "java.", use Class.forName based resolution. */ { for (String potential : ast.getImportList().applyNameToStarImports("java", typeName)) { try { Class c = Class.forName(potential); if (c != null) return c.getName(); } catch (Throwable t) { //Class.forName failed for whatever reason - it most likely does not exist, continue. } } } /* 4. If the type name is a simple name, then our last guess is that it's another class in this package. */ { if (typeName.indexOf('.') == -1) return inLocalPackage(ast, typeName); } /* 5. It's either an FQN or a nested class in another class in our package. Use code conventions to guess. */ { char firstChar = typeName.charAt(0); if (Character.isTitleCase(firstChar) || Character.isUpperCase(firstChar)) { //Class names start with uppercase letters, so presume it's a nested class in another class in our package. return inLocalPackage(ast, typeName); } //Presume it's fully qualified. return typeName; } } private static String inLocalPackage(LombokNode node, String typeName) { StringBuilder result = new StringBuilder(); if (node != null && node.getPackageDeclaration() != null) result.append(node.getPackageDeclaration()); if (result.length() > 0) result.append('.'); result.append(typeName); return result.toString(); } } lombok-1.16.18/src/core/lombok/core/Augments.java000066400000000000000000000026071312655740700215520ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; public final class Augments { private Augments() { // prevent instantiation } public static final FieldAugment ClassLoader_lombokAlreadyAddedTo = FieldAugment.augment(ClassLoader.class, boolean.class, "lombok$alreadyAddedTo"); } lombok-1.16.18/src/core/lombok/core/DiagnosticsReceiver.java000066400000000000000000000031471312655740700237230ustar00rootroot00000000000000/* * Copyright (C) 2009-2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; public interface DiagnosticsReceiver { DiagnosticsReceiver CONSOLE = new DiagnosticsReceiver() { @Override public void addError(String message) { System.err.println("Error: " + message); } @Override public void addWarning(String message) { System.out.println("Warning: " + message); } }; /** Generate a compiler error on this node. */ void addError(String message); /** Generate a compiler warning on this node. */ void addWarning(String message); } lombok-1.16.18/src/core/lombok/core/GuavaTypeMap.java000066400000000000000000000051071312655740700223300ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.util.Collections; import java.util.HashMap; import java.util.Map; public final class GuavaTypeMap { private static final Map TYPE_TO_GUAVA_TYPE; static { Map m = new HashMap(); m.put("java.util.NavigableSet", "ImmutableSortedSet"); m.put("java.util.NavigableMap", "ImmutableSortedMap"); m.put("java.util.SortedSet", "ImmutableSortedSet"); m.put("java.util.SortedMap", "ImmutableSortedMap"); m.put("java.util.Set", "ImmutableSet"); m.put("java.util.Map", "ImmutableMap"); m.put("java.util.Collection", "ImmutableList"); m.put("java.util.List", "ImmutableList"); m.put("com.google.common.collect.ImmutableSet", "ImmutableSet"); m.put("com.google.common.collect.ImmutableSortedSet", "ImmutableSortedSet"); m.put("com.google.common.collect.ImmutableMap", "ImmutableMap"); m.put("com.google.common.collect.ImmutableBiMap", "ImmutableBiMap"); m.put("com.google.common.collect.ImmutableSortedMap", "ImmutableSortedMap"); m.put("com.google.common.collect.ImmutableList", "ImmutableList"); m.put("com.google.common.collect.ImmutableCollection", "ImmutableList"); m.put("com.google.common.collect.ImmutableTable", "ImmutableTable"); TYPE_TO_GUAVA_TYPE = Collections.unmodifiableMap(m); } public static String getGuavaTypeName(String fqn) { String target = TYPE_TO_GUAVA_TYPE.get(fqn); return target != null ? target : "ImmutableList"; } private GuavaTypeMap() {} } lombok-1.16.18/src/core/lombok/core/HandlerPriority.java000066400000000000000000000050041312655740700231000ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to order the way handlers are run. Handlers with a lower priority value are run before handlers with higher priority values. * For example, {@code @Value} can cause the class to be marked final, and this affects the behaviour of {@code @EqualsAndHashCode}. By ensuring that * the handler for {@code @Value} always runs before the handler for {@code @EqualsAndHashCode}, the code is simpler: The {@code @EqualsAndHashCode} handler * does not have to check for the presence of a {@code @Value} annotation to determine whether to generate the {@code canEqual} method or not. *

* A new priority level can also be used to force a reset of the resolved model, i.e. to add generated methods to the symbol tables. Each platform implementation (javac, ecj, etc) * may have additional marker annotations required to indicate the need for the reset. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface HandlerPriority { int value(); /** * This can be used to differentiate 2 handlers with the same value to be at a different handler priority anyway. * DO NOT USE THIS unless someone has been crowding out the numbers and there's no room left. */ int subValue() default 0; } lombok-1.16.18/src/core/lombok/core/ImportList.java000066400000000000000000000036231312655740700220740ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.util.Collection; public interface ImportList { /** * If there is an explicit import of the stated unqualified type name, return that. Otherwise, return null. */ String getFullyQualifiedNameForSimpleName(String unqualified); /** * Returns true if the package name is explicitly star-imported, OR the packageName refers to this source file's own package name, OR packageName is 'java.lang'. */ boolean hasStarImport(String packageName); /** * Takes all explicit non-static star imports whose first element is equal to {@code startsWith}, replaces the star with {@code unqualified}, and returns these. */ Collection applyNameToStarImports(String startsWith, String unqualified); String applyUnqualifiedNameToPackage(String unqualified); } lombok-1.16.18/src/core/lombok/core/LombokApp.java000066400000000000000000000043511312655740700216510ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.util.Collections; import java.util.List; /** * Implement this class, and add yourself as a provider for it, to become an app runnable by running lombok.jar as a jar. * * @see lombok.core.Main.VersionApp */ public abstract class LombokApp { /** * @param args The arguments; analogous to what's passed to {@code public static void main(String[] args)} methods. * @return The return value. Don't call {@code System.exit} yourself. */ public abstract int runApp(List args) throws Exception; /** * @return Your app name. For example {@code delombok}. */ public abstract String getAppName(); /** * @return Description of this app, for the command line. */ public abstract String getAppDescription(); /** * @return When lombok.jar is executed with any of these strings as first argument, your app will be started. */ public List getAppAliases() { return Collections.emptyList(); } /** * @return {@code true} if this app is an internal debugging tool and won't be listed by the default help message. */ public boolean isDebugTool() { return false; } } lombok-1.16.18/src/core/lombok/core/LombokConfiguration.java000066400000000000000000000060751312655740700237450ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.util.Collections; import lombok.core.configuration.BubblingConfigurationResolver; import lombok.core.configuration.ConfigurationKey; import lombok.core.configuration.ConfigurationProblemReporter; import lombok.core.configuration.ConfigurationResolver; import lombok.core.configuration.ConfigurationResolverFactory; import lombok.core.configuration.FileSystemSourceCache; public class LombokConfiguration { private static final ConfigurationResolver NULL_RESOLVER = new ConfigurationResolver() { @SuppressWarnings("unchecked") @Override public T resolve(ConfigurationKey key) { if (key.getType().isList()) return (T) Collections.emptyList(); return null; } }; private static FileSystemSourceCache cache = new FileSystemSourceCache(); private static ConfigurationResolverFactory configurationResolverFactory; static { if (System.getProperty("lombok.disableConfig") != null) { configurationResolverFactory = new ConfigurationResolverFactory() { @Override public ConfigurationResolver createResolver(AST ast) { return NULL_RESOLVER; } }; } else { configurationResolverFactory = createFileSystemBubblingResolverFactory(); } } private LombokConfiguration() { // prevent instantiation } public static void overrideConfigurationResolverFactory(ConfigurationResolverFactory crf) { configurationResolverFactory = crf == null ? createFileSystemBubblingResolverFactory() : crf; } static T read(ConfigurationKey key, AST ast) { return configurationResolverFactory.createResolver(ast).resolve(key); } private static ConfigurationResolverFactory createFileSystemBubblingResolverFactory() { return new ConfigurationResolverFactory() { @Override public ConfigurationResolver createResolver(AST ast) { return new BubblingConfigurationResolver(cache.sourcesForJavaFile(ast.getAbsoluteFileLocation(), ConfigurationProblemReporter.CONSOLE)); } }; } } lombok-1.16.18/src/core/lombok/core/LombokInternalAliasing.java000066400000000000000000000047001312655740700243530ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class LombokInternalAliasing { /** Maps a package name to a space separated list of packages. If the key package is star-imported, assume all packages in the 'value' part of the MapEntry are too. */ public static final Map> IMPLIED_EXTRA_STAR_IMPORTS; public static final Map ALIASES; /** * Provide a fully qualified name (FQN), and the canonical version of this is returned. */ public static String processAliases(String in) { if (in == null) return null; for (Map.Entry e : ALIASES.entrySet()) { if (in.equals(e.getKey())) return e.getValue(); } return in; } static { Map> m1 = new HashMap>(); m1.put("lombok.experimental", Collections.singleton("lombok")); m1.put("lombok", Collections.singleton("lombok.experimental")); IMPLIED_EXTRA_STAR_IMPORTS = Collections.unmodifiableMap(m1); Map m2 = new HashMap(); m2.put("lombok.experimental.Value", "lombok.Value"); m2.put("lombok.experimental.Builder", "lombok.Builder"); m2.put("lombok.Delegate", "lombok.experimental.Delegate"); ALIASES = Collections.unmodifiableMap(m2); } } lombok-1.16.18/src/core/lombok/core/LombokNode.java000066400000000000000000000211721312655740700220160ustar00rootroot00000000000000/* * Copyright (C) 2009-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import lombok.core.AST.Kind; /** * An instance of this class wraps an Eclipse/javac internal node object. * * @param A Type of our owning AST. * @param L self-type. * @param N The common type of all AST nodes in the internal representation of the target platform. * For example, JCTree for javac, and ASTNode for Eclipse. */ public abstract class LombokNode, L extends LombokNode, N> implements DiagnosticsReceiver { protected final A ast; protected final Kind kind; protected final N node; protected LombokImmutableList children; protected L parent; /** structurally significant are those nodes that can be annotated in java 1.6 or are method-like toplevels, * so fields, local declarations, method arguments, methods, types, the Compilation Unit itself, and initializers. */ protected boolean isStructurallySignificant; /** * Creates a new Node object that represents the provided node. * * @param ast The owning AST - this node is part of this AST's tree of nodes. * @param node The AST object in the target parser's own internal AST tree that this node object will represent. * @param children A list of child nodes. Passing in null results in the children list being empty, not null. * @param kind The kind of node represented by this object. */ @SuppressWarnings("unchecked") protected LombokNode(A ast, N node, List children, Kind kind) { this.ast = ast; this.kind = kind; this.node = node; this.children = children != null ? LombokImmutableList.copyOf(children) : LombokImmutableList.of(); for (L child : this.children) { child.parent = (L) this; if (!child.isStructurallySignificant) child.isStructurallySignificant = calculateIsStructurallySignificant(node); } this.isStructurallySignificant = calculateIsStructurallySignificant(null); } public A getAst() { return ast; } /** {@inheritDoc} */ @Override public String toString() { return String.format("NODE %s (%s) %s", kind, node == null ? "(NULL)" : node.getClass(), node == null ? "" : node); } /** * Convenient shortcut to the owning ast object's {@code getPackageDeclaration} method. * * @see AST#getPackageDeclaration() */ public String getPackageDeclaration() { return ast.getPackageDeclaration(); } /** * Convenient shortcut to the owning ast object's {@code getImportList} method. * * @see AST#getImportList() */ public ImportList getImportList() { return ast.getImportList(); } /** * See {@link #isStructurallySignificant}. */ protected abstract boolean calculateIsStructurallySignificant(N parent); /** * Convenient shortcut to the owning ast object's get method. * * @see AST#get(Object) */ public L getNodeFor(N obj) { return ast.get(obj); } /** * @return The javac/Eclipse internal AST object wrapped by this LombokNode object. */ public N get() { return node; } public Kind getKind() { return kind; } /** * Return the name of your type (simple name), method, field, or local variable. Return null if this * node doesn't really have a name, such as initializers, while statements, etc. */ public abstract String getName(); /** Returns the structurally significant node that encloses this one. * * @see #isStructurallySignificant() */ public L up() { L result = parent; while (result != null && !result.isStructurallySignificant) result = result.parent; return result; } /** * {@code @Foo int x, y;} is stored in both javac and ecj as 2 FieldDeclarations, both with the same annotation as child. * The normal {@code up()} method can't handle having multiple parents, but this one can. */ public Collection upFromAnnotationToFields() { if (getKind() != Kind.ANNOTATION) return Collections.emptyList(); L field = up(); if (field == null || field.getKind() != Kind.FIELD) return Collections.emptyList(); L type = field.up(); if (type == null || type.getKind() != Kind.TYPE) return Collections.emptyList(); List fields = new ArrayList(); for (L potentialField : type.down()) { if (potentialField.getKind() != Kind.FIELD) continue; if (fieldContainsAnnotation(potentialField.get(), get())) fields.add(potentialField); } return fields; } /** * Return {@code true} if the annotation is attached to the field. */ protected abstract boolean fieldContainsAnnotation(N field, N annotation); /** * Returns the direct parent node in the AST tree of this node. For example, a local variable declaration's * direct parent can be e.g. an If block, but its {@code up()} {@code LombokNode} is the {@code Method} that contains it. */ public L directUp() { return parent; } /** * Returns all children nodes. */ public LombokImmutableList down() { return children; } /** * Convenient shortcut to the owning ast object's getLatestJavaSpecSupported method. * * @see AST#getLatestJavaSpecSupported() */ public int getLatestJavaSpecSupported() { return ast.getLatestJavaSpecSupported(); } /** * Convenient shortcut to the owning ast object's getSourceVersion method. * * @see AST#getSourceVersion() */ public int getSourceVersion() { return ast.getSourceVersion(); } /** * Convenient shortcut to the owning ast object's top method. * * @see AST#top() */ public L top() { return ast.top(); } /** * Convenient shortcut to the owning ast object's getFileName method. * * @see AST#getFileName() */ public String getFileName() { return ast.getFileName(); } /** * Adds the stated node as a direct child of this node. * * Does not change the underlying (javac/Eclipse) AST, only the wrapped view. */ @SuppressWarnings({"unchecked"}) public L add(N newChild, Kind newChildKind) { ast.setChanged(); L n = ast.buildTree(newChild, newChildKind); if (n == null) return null; n.parent = (L) this; children = children.append(n); return n; } /** * Reparses the AST node represented by this node. Any existing nodes that occupy a different space in the AST are rehomed, any * nodes that no longer exist are removed, and new nodes are created. * * Careful - the node you call this on must not itself have been removed or rehomed - it rebuilds all children. */ public void rebuild() { Map oldNodes = new IdentityHashMap(); gatherAndRemoveChildren(oldNodes); L newNode = ast.buildTree(get(), kind); ast.setChanged(); ast.replaceNewWithExistingOld(oldNodes, newNode); } @SuppressWarnings({"unchecked", "rawtypes"}) private void gatherAndRemoveChildren(Map map) { for (LombokNode child : children) child.gatherAndRemoveChildren(map); ast.identityDetector.remove(get()); map.put(get(), (L) this); children = LombokImmutableList.of(); ast.getNodeMap().remove(get()); } /** * Removes the stated node, which must be a direct child of this node, from the AST. * * Does not change the underlying (javac/Eclipse) AST, only the wrapped view. */ public void removeChild(L child) { ast.setChanged(); children = children.removeElement(child); } /** * Structurally significant means: LocalDeclaration, TypeDeclaration, MethodDeclaration, ConstructorDeclaration, * FieldDeclaration, Initializer, and CompilationUnitDeclaration. * The rest is e.g. if statements, while loops, etc. */ public boolean isStructurallySignificant() { return isStructurallySignificant; } } lombok-1.16.18/src/core/lombok/core/Main.java000066400000000000000000000120751312655740700206530ustar00rootroot00000000000000/* * Copyright (C) 2009-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.mangosdk.spi.ProviderFor; public class Main { private static final Collection HELP_SWITCHES = Collections.unmodifiableList(Arrays.asList( "/?", "/h", "/help", "-h", "-help", "--help", "help", "h" )); public static void main(String[] args) throws IOException { Thread.currentThread().setContextClassLoader(Main.class.getClassLoader()); int err = new Main(SpiLoadUtil.readAllFromIterator( SpiLoadUtil.findServices(LombokApp.class)), Arrays.asList(args)).go(); System.exit(err); } @ProviderFor(LombokApp.class) public static class VersionApp extends LombokApp { @Override public String getAppName() { return "version"; } @Override public String getAppDescription() { return "prints lombok's version."; } @Override public List getAppAliases() { return Arrays.asList("-version", "--version"); } @Override public int runApp(List args) { System.out.println(Version.getFullVersion()); return 0; } } @ProviderFor(LombokApp.class) public static class LicenseApp extends LombokApp { @Override public String getAppName() { return "license"; } @Override public String getAppDescription() { return "prints license information."; } @Override public List getAppAliases() { return Arrays.asList("licence", "copyright", "copyleft", "gpl"); } @Override public int runApp(List args) { try { InputStream in = Main.class.getResourceAsStream("/LICENSE"); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] b = new byte[65536]; while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } System.out.println(new String(out.toByteArray())); return 0; } finally { in.close(); } } catch (Exception e) { System.err.println("License file not found. Check https://projectlombok.org/LICENSE"); return 1; } } } private final List apps; private final List args; public Main(List apps, List args) { this.apps = apps; this.args = args; } public int go() { if (!args.isEmpty() && HELP_SWITCHES.contains(args.get(0))) { printHelp(null, System.out); return 0; } String command = args.isEmpty() ? "" : args.get(0).trim(); if (command.startsWith("--")) command = command.substring(2); else if (command.startsWith("-")) command = command.substring(1); List subArgs = args.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList( args.subList(1, args.size())); for (LombokApp app : apps) { if (app.getAppName().equals(command) || app.getAppAliases().contains(command)) { try { return app.runApp(subArgs); } catch (Exception e) { e.printStackTrace(); return 5; } } } printHelp("Unknown command: " + command, System.err); return 1; } public void printHelp(String message, PrintStream out) { if (message != null) { out.println(message); out.println("------------------------------"); } out.println("projectlombok.org " + Version.getFullVersion()); out.println("Copyright (C) 2009-2015 The Project Lombok Authors."); out.println("Run 'lombok license' to see the lombok license agreement."); out.println(); out.println("Run lombok without any parameters to start the graphical installer."); out.println("Other available commands:"); for (LombokApp app : apps) { if (app.isDebugTool()) continue; String[] desc = app.getAppDescription().split("\n"); for (int i = 0; i < desc.length; i++) { out.printf(" %15s %s\n", i == 0 ? app.getAppName() : "", desc[i]); } } out.println(); out.println("Run lombok commandName --help for more info on each command."); } } lombok-1.16.18/src/core/lombok/core/PostCompiler.java000066400000000000000000000071241312655740700224060ustar00rootroot00000000000000/* * Copyright (C) 2010-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.List; public final class PostCompiler { private PostCompiler() {/* prevent instantiation*/}; private static List transformations; public static byte[] applyTransformations(byte[] original, String fileName, DiagnosticsReceiver diagnostics) { if (System.getProperty("lombok.disablePostCompiler", null) != null) return original; init(diagnostics); byte[] previous = original; for (PostCompilerTransformation transformation : transformations) { try { byte[] next = transformation.applyTransformations(previous, fileName, diagnostics); if (next != null) { previous = next; } } catch (Exception e) { diagnostics.addWarning(String.format("Error during the transformation of '%s'; post-compiler '%s' caused an exception: %s", fileName, transformation.getClass().getName(), e)); } } return previous; } private static synchronized void init(DiagnosticsReceiver diagnostics) { if (transformations != null) return; try { transformations = SpiLoadUtil.readAllFromIterator(SpiLoadUtil.findServices(PostCompilerTransformation.class, PostCompilerTransformation.class.getClassLoader())); } catch (IOException e) { transformations = Collections.emptyList(); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw, true)); diagnostics.addWarning("Could not load post-compile transformers: " + e.getMessage() + "\n" + sw.toString()); } } public static OutputStream wrapOutputStream(final OutputStream originalStream, final String fileName, final DiagnosticsReceiver diagnostics) throws IOException { if (System.getProperty("lombok.disablePostCompiler", null) != null) return originalStream; return new ByteArrayOutputStream() { @Override public void close() throws IOException { // no need to call super byte[] original = toByteArray(); byte[] copy = null; try { copy = applyTransformations(original, fileName, diagnostics); } catch (Exception e) { diagnostics.addWarning(String.format("Error during the transformation of '%s'; no post-compilation has been applied", fileName)); } if (copy == null) { copy = original; } // Exceptions below should bubble originalStream.write(copy); originalStream.close(); } }; } } lombok-1.16.18/src/core/lombok/core/PostCompilerTransformation.java000066400000000000000000000024261312655740700253350ustar00rootroot00000000000000/* * Copyright (C) 2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; public interface PostCompilerTransformation { byte[] applyTransformations(byte[] original, String fileName, DiagnosticsReceiver diagnostics); } lombok-1.16.18/src/core/lombok/core/PrintAST.java000066400000000000000000000047131312655740700214330ustar00rootroot00000000000000/* * Copyright (C) 2009-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Will print the tree structure of annotated node and all its children. * * This annotation is useful only for those working on Lombok, for example to test if a Lombok handlers is doing its * job correctly, or to see what the imagined endresult of a transformation is supposed to look like. */ @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.SOURCE) public @interface PrintAST { /** * Normally, the AST is printed to standard out, but you can pick a filename instead. Useful for many IDEs * which don't have a console unless you start them from the command line. */ String outfile() default ""; /** * Sets whether to print node structure (false) or generated java code (true). * * By setting printContent to true, the annotated element's java code representation is printed. If false, * its node structure (e.g. node classname) is printed, and this process is repeated for all children. */ boolean printContent() default false; /** * if {@code true} prints the start and end position of each node. */ boolean printPositions() default false; } lombok-1.16.18/src/core/lombok/core/PublicApiCreatorApp.java000066400000000000000000000131531312655740700236160ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import lombok.Lombok; import lombok.patcher.ClassRootFinder; import org.mangosdk.spi.ProviderFor; @ProviderFor(LombokApp.class) public class PublicApiCreatorApp extends LombokApp { @Override public String getAppName() { return "publicApi"; } @Override public String getAppDescription() { return "Creates a small lombok-api.jar with the annotations and other public API\n" + "classes of all lombok features. This is primarily useful to include in your\n" + "android projects."; } @Override public int runApp(List rawArgs) throws Exception { String loc = "."; switch (rawArgs.size()) { case 0: break; case 1: loc = rawArgs.get(0); break; default: System.err.println("Supply 1 path to specify the directory where lombok-api.jar will be created. No path means the current directory is used."); return 1; } File out = new File(loc, "lombok-api.jar"); int errCode = 0; try { errCode = writeApiJar(out); } catch (Exception e) { System.err.println("ERROR: Creating " + canonical(out) + " failed: "); e.printStackTrace(); return 1; } return errCode; } /** * Returns a File object pointing to our own jar file. Will obviously fail if the installer was started via * a jar that wasn't accessed via the file-system, or if its started via e.g. unpacking the jar. */ private static File findOurJar() { return new File(ClassRootFinder.findClassRootOfClass(PublicApiCreatorApp.class)); } private int writeApiJar(File outFile) throws Exception { File selfRaw = findOurJar(); if (selfRaw == null) { System.err.println("The publicApi option only works if lombok is a jar."); return 2; } List toCopy = new ArrayList(); JarFile self = new JarFile(selfRaw); try { Enumeration entries = self.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (!name.startsWith("lombok/")) continue; if (name.endsWith("/package-info.class")) continue; if (!name.endsWith(".class")) continue; String subName = name.substring(7, name.length() - 6); int firstSlash = subName.indexOf('/'); if (firstSlash == -1) { // direct member of the lombok package. if (!subName.startsWith("ConfigurationKeys")) toCopy.add(name); continue; } String topPkg = subName.substring(0, firstSlash); if ("extern".equals(topPkg) || "experimental".equals(topPkg)) { toCopy.add(name); } } } finally { self.close(); } if (toCopy.isEmpty()) { System.out.println("Not generating lombok-api.jar: No lombok api classes required!"); return 1; } OutputStream out = new FileOutputStream(outFile); boolean success = false; try { JarOutputStream jar = new JarOutputStream(out); for (String resourceName : toCopy) { InputStream in = Lombok.class.getResourceAsStream("/" + resourceName); try { if (in == null) { throw new Fail(String.format("api class %s cannot be found", resourceName)); } writeIntoJar(jar, resourceName, in); } finally { if (in != null) in.close(); } } jar.close(); out.close(); System.out.println("Successfully created: " + canonical(outFile)); return 0; } catch (Throwable t) { try { out.close();} catch (Throwable ignore) {} if (!success) outFile.delete(); if (t instanceof Fail) { System.err.println(t.getMessage()); return 1; } else if (t instanceof Exception) { throw (Exception)t; } else if (t instanceof Error) { throw (Error)t; } else { throw new Exception(t); } } } private void writeIntoJar(JarOutputStream jar, String resourceName, InputStream in) throws IOException { jar.putNextEntry(new ZipEntry(resourceName)); byte[] b = new byte[65536]; while (true) { int r = in.read(b); if (r == -1) break; jar.write(b, 0, r); } jar.closeEntry(); in.close(); } private static class Fail extends Exception { Fail(String message) { super(message); } } private static String canonical(File out) { try { return out.getCanonicalPath(); } catch (Exception e) { return out.getAbsolutePath(); } } } lombok-1.16.18/src/core/lombok/core/TypeLibrary.java000066400000000000000000000114641312655740700222360ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.util.HashMap; import java.util.Map; /** * Library of types, which can be used to look up potential matching types. * * For example, if you put {@code foo.Spork} and {@code bar.Spork} into the library, and then ask for * all compatible types given the type {@code Spork}, you'll get both of them, but you'll only * get the one if you ask for compatible types given {@code foo.Spork}. *

* When adding {@code foo.Spork}, that FQN (Fully Qualified Name) will be returned as an option for any of these queries: *

*/ public class TypeLibrary { private final Map unqualifiedToQualifiedMap; private final String unqualified, qualified; private boolean locked; public TypeLibrary() { unqualifiedToQualifiedMap = new HashMap(); unqualified = null; qualified = null; } public void lock() { this.locked = true; } private TypeLibrary(String fqnSingleton) { if (fqnSingleton.indexOf("$") != -1) { unqualifiedToQualifiedMap = new HashMap(); unqualified = null; qualified = null; addType(fqnSingleton); } else { unqualifiedToQualifiedMap = null; qualified = fqnSingleton; int idx = fqnSingleton.lastIndexOf('.'); if (idx == -1) { unqualified = fqnSingleton; } else { unqualified = fqnSingleton.substring(idx + 1); } } locked = true; } public static TypeLibrary createLibraryForSingleType(String fqnSingleton) { return new TypeLibrary(fqnSingleton); } /** * Add a type to the library. * * @param fullyQualifiedTypeName the FQN type name, such as 'java.lang.String'. */ public void addType(String fullyQualifiedTypeName) { String dotBased = fullyQualifiedTypeName.replace("$", "."); if (locked) throw new IllegalStateException("locked"); int idx = fullyQualifiedTypeName.lastIndexOf('.'); if (idx == -1) throw new IllegalArgumentException( "Only fully qualified types are allowed (and stuff in the default package is not palatable to us either!)"); String unqualified = fullyQualifiedTypeName.substring(idx + 1); if (unqualifiedToQualifiedMap == null) throw new IllegalStateException("SingleType library"); unqualifiedToQualifiedMap.put(unqualified.replace("$", "."), dotBased); unqualifiedToQualifiedMap.put(unqualified, dotBased); unqualifiedToQualifiedMap.put(fullyQualifiedTypeName, dotBased); unqualifiedToQualifiedMap.put(dotBased, dotBased); for (Map.Entry e : LombokInternalAliasing.ALIASES.entrySet()) { if (fullyQualifiedTypeName.equals(e.getValue())) unqualifiedToQualifiedMap.put(e.getKey(), dotBased); } int idx2 = fullyQualifiedTypeName.indexOf('$', idx + 1); while (idx2 != -1) { String unq = fullyQualifiedTypeName.substring(idx2 + 1); unqualifiedToQualifiedMap.put(unq.replace("$", "."), dotBased); unqualifiedToQualifiedMap.put(unq, dotBased); idx2 = fullyQualifiedTypeName.indexOf('$', idx2 + 1); } } /** * Translates an unqualified name such as 'String' to 'java.lang.String', _if_ you added 'java.lang.String' to the library via the {@code addType} method. * Also returns the input if it is equal to a fully qualified name added to this type library. * * Returns null if it does not match any type in this type library. */ public String toQualified(String typeReference) { if (unqualifiedToQualifiedMap == null) { if (typeReference.equals(unqualified) || typeReference.equals(qualified)) return qualified; for (Map.Entry e : LombokInternalAliasing.ALIASES.entrySet()) { if (e.getKey().equals(typeReference)) return e.getValue(); } return null; } return unqualifiedToQualifiedMap.get(typeReference); } } lombok-1.16.18/src/core/lombok/core/TypeResolver.java000066400000000000000000000116171312655740700224330ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import lombok.core.AST.Kind; /** * Capable of resolving a simple type name such as 'String' into 'java.lang.String'. *

* NB: This resolver gives wrong answers when there's a class in the local package with the same name as a class in a star-import, * and this importer also can't find inner types from superclasses/interfaces. */ public class TypeResolver { private ImportList imports; /** * Creates a new TypeResolver that can be used to resolve types in a source file with the given package and import statements. */ public TypeResolver(ImportList importList) { this.imports = importList; } public boolean typeMatches(LombokNode context, String fqn, String typeRef) { return typeRefToFullyQualifiedName(context, TypeLibrary.createLibraryForSingleType(fqn), typeRef) != null; } public String typeRefToFullyQualifiedName(LombokNode context, TypeLibrary library, String typeRef) { typeRef = LombokInternalAliasing.processAliases(typeRef); // When asking if 'Foo' could possibly be referring to 'bar.Baz', the answer is obviously no. String qualified = library.toQualified(typeRef); if (qualified == null) return null; // When asking if 'lombok.Getter' could possibly be referring to 'lombok.Getter', the answer is obviously yes. if (typeRef.equals(qualified)) return typeRef; // When asking if 'Getter' could possibly be referring to 'lombok.Getter' if 'import lombok.Getter;' is in the source file, the answer is yes. int firstDot = typeRef.indexOf('.'); if (firstDot == -1) firstDot = typeRef.length(); String firstTypeRef = typeRef.substring(0, firstDot); String fromExplicitImport = imports.getFullyQualifiedNameForSimpleName(firstTypeRef); if (fromExplicitImport != null) { // ... and if 'import foobar.Getter;' is in the source file, the answer is no. return (fromExplicitImport + typeRef.substring(firstDot)).equals(qualified) ? qualified : null; } // When asking if 'Getter' could possibly be referring to 'lombok.Getter' and 'import lombok.*; / package lombok;' isn't in the source file. the answer is no. String pkgName = qualified.substring(0, qualified.length() - typeRef.length() - 1); if (!imports.hasStarImport(pkgName)) return null; // Now the hard part: Given that there is a star import, 'Getter' most likely refers to 'lombok.Getter', but type shadowing may occur in which case it doesn't. LombokNode n = context; mainLoop: while (n != null) { if (n.getKind() == Kind.TYPE && firstTypeRef.equals(n.getName())) { // Our own class or one of our outer classes is named 'typeRef' so that's what 'typeRef' is referring to, not one of our type library classes. return null; } if (n.getKind() == Kind.STATEMENT || n.getKind() == Kind.LOCAL) { LombokNode newN = n.directUp(); if (newN == null) break mainLoop; if (newN.getKind() == Kind.STATEMENT || newN.getKind() == Kind.INITIALIZER || newN.getKind() == Kind.METHOD) { for (LombokNode child : newN.down()) { // We found a method local with the same name above our code. That's the one 'typeRef' is referring to, not // anything in the type library we're trying to find, so, no matches. if (child.getKind() == Kind.TYPE && firstTypeRef.equals(child.getName())) return null; if (child == n) break; } } n = newN; continue mainLoop; } if (n.getKind() == Kind.TYPE || n.getKind() == Kind.COMPILATION_UNIT) { for (LombokNode child : n.down()) { // Inner class that's visible to us has 'typeRef' as name, so that's the one being referred to, not one of our type library classes. if (child.getKind() == Kind.TYPE && firstTypeRef.equals(child.getName())) return null; } } n = n.directUp(); } return qualified; } } lombok-1.16.18/src/core/lombok/core/Version.java000066400000000000000000000072451312655740700214170ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.io.InputStream; /** * This class just holds lombok's current version. */ public class Version { // ** CAREFUL ** - this class must always compile with 0 dependencies (it must not refer to any other sources or libraries). // Note: In 'X.Y.Z', if Z is odd, its a snapshot build built from the repository, so many different 0.10.3 versions can exist, for example. // Official builds always end in an even number. (Since 0.10.2). private static final String VERSION = "1.16.18"; // private static final String RELEASE_NAME = "Edgy Guinea Pig"; private static final String RELEASE_NAME = "Dancing Elephant"; // Named version history: // Angry Butterfly // Branching Cobra // Candid Duck // Dancing Elephant private Version() { //Prevent instantiation } /** * Prints the version followed by a newline, and exits. */ public static void main(String[] args) { if (args.length > 0) { System.out.printf("%s\n", getFullVersion()); } else { System.out.println(VERSION); } } /** * Get the current Lombok version. */ public static String getVersion() { return VERSION; } /** * Get the current release name. * * The release name is a string (not numbers). Every time a new release has a significantly improved feature set, a new release name is given. * Thus, many versions can carry the same release name. Version bumps and release names are not related; if a new version of lombok is entirely * backwards compatible with a previous one, but also adds many new features, it will get only a minor version bump, but also a new release name. */ public static String getReleaseName() { return RELEASE_NAME; } public static String getFullVersion() { String version = String.format("v%s \"%s\"", VERSION, RELEASE_NAME); if (!isEdgeRelease()) return version; InputStream in = Version.class.getResourceAsStream("/release-timestamp.txt"); if (in == null) return version; try { byte[] data = new byte[65536]; int p = 0; while (p < data.length) { int r = in.read(data, p, data.length - p); if (r == -1) break; p += r; } String timestamp = new String(data, "UTF-8").trim(); return version + " - " + timestamp; } catch (Exception e) { try { in.close(); } catch (Exception ignore) {} } return version; } public static boolean isEdgeRelease() { int lastIdx = VERSION.lastIndexOf('.'); if (lastIdx == -1) return false; try { return Integer.parseInt(VERSION.substring(lastIdx + 1)) % 2 == 1; } catch (Exception e) { return false; } } } lombok-1.16.18/src/core/lombok/core/configuration/000077500000000000000000000000001312655740700217665ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/core/configuration/AllowHelper.java000066400000000000000000000030641312655740700250520ustar00rootroot00000000000000/* * Copyright (C) 2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import java.util.Collection; import java.util.Collections; import lombok.ConfigurationKeys; public final class AllowHelper { private final static Collection> ALLOWABLE = Collections.singleton(ConfigurationKeys.VAR_FLAG_USAGE); private AllowHelper() { // Prevent instantiation } public static boolean isAllowable(ConfigurationKey key) { return ALLOWABLE.contains(key); } } lombok-1.16.18/src/core/lombok/core/configuration/BubblingConfigurationResolver.java000066400000000000000000000053331312655740700306330ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import lombok.core.configuration.ConfigurationSource.ListModification; import lombok.core.configuration.ConfigurationSource.Result; public class BubblingConfigurationResolver implements ConfigurationResolver { private final Iterable sources; public BubblingConfigurationResolver(Iterable sources) { this.sources = sources; } @SuppressWarnings("unchecked") @Override public T resolve(ConfigurationKey key) { boolean isList = key.getType().isList(); List> listModificationsList = null; for (ConfigurationSource source : sources) { Result result = source.resolve(key); if (result == null) continue; if (isList) { if (listModificationsList == null) listModificationsList = new ArrayList>(); listModificationsList.add((List)result.getValue()); } if (result.isAuthoritative()) { if (isList) break; return (T) result.getValue(); } } if (!isList) return null; if (listModificationsList == null) return (T) Collections.emptyList(); List listValues = new ArrayList(); Collections.reverse(listModificationsList); for (List listModifications : listModificationsList) { if (listModifications != null) for (ListModification modification : listModifications) { listValues.remove(modification.getValue()); if (modification.isAdded()) listValues.add(modification.getValue()); } } return (T) listValues; } } lombok-1.16.18/src/core/lombok/core/configuration/CallSuperType.java000066400000000000000000000025071312655740700253710ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; /** Used for lombok configuration for configuration whether or not to call the super implementation for certain lombok feature. */ public enum CallSuperType { CALL, SKIP, WARN; } lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationApp.java000066400000000000000000000324661312655740700261140ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import static lombok.core.configuration.FileSystemSourceCache.fileToString; import java.io.File; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import lombok.ConfigurationKeys; import lombok.core.LombokApp; import lombok.core.configuration.ConfigurationParser.Collector; import org.mangosdk.spi.ProviderFor; import com.zwitserloot.cmdreader.CmdReader; import com.zwitserloot.cmdreader.Description; import com.zwitserloot.cmdreader.Excludes; import com.zwitserloot.cmdreader.InvalidCommandLineException; import com.zwitserloot.cmdreader.Mandatory; import com.zwitserloot.cmdreader.Sequential; import com.zwitserloot.cmdreader.Shorthand; @ProviderFor(LombokApp.class) public class ConfigurationApp extends LombokApp { private static final URI NO_CONFIG = URI.create(""); private PrintStream out = System.out; private PrintStream err = System.err; @Override public String getAppName() { return "config"; } @Override public String getAppDescription() { return "Prints the configurations for the provided paths to standard out."; } @Override public List getAppAliases() { return Arrays.asList("configuration", "config", "conf", "settings"); } public static class CmdArgs { @Sequential @Mandatory(onlyIfNot={"help", "generate"}) @Description("Paths to java files or directories the configuration is to be printed for.") private List paths = new ArrayList(); @Shorthand("g") @Excludes("paths") @Description("Generates a list containing all the available configuration parameters. Add --verbose to print more information.") boolean generate = false; @Shorthand("v") @Description("Displays more information.") boolean verbose = false; @Shorthand("k") @Description("Limit the result to these keys.") private List key = new ArrayList(); @Shorthand({"h", "?"}) @Description("Shows this help text.") boolean help = false; } @Override public int runApp(List raw) throws Exception { CmdReader reader = CmdReader.of(CmdArgs.class); CmdArgs args; try { args = reader.make(raw.toArray(new String[0])); if (args.help) { out.println(reader.generateCommandLineHelp("java -jar lombok.jar configuration")); return 0; } } catch (InvalidCommandLineException e) { err.println(e.getMessage()); err.println(reader.generateCommandLineHelp("java -jar lombok.jar configuration")); return 1; } ConfigurationKeysLoader.LoaderLoader.loadAllConfigurationKeys(); Collection> keys = checkKeys(args.key); if (keys == null) return 1; boolean verbose = args.verbose; if (args.generate) { return generate(keys, verbose); } return display(keys, verbose, args.paths, !args.key.isEmpty()); } public ConfigurationApp redirectOutput(PrintStream out, PrintStream err) { if (out != null) this.out = out; if (err != null) this.err = err; return this; } public int generate(Collection> keys, boolean verbose) { for (ConfigurationKey key : keys) { String keyName = key.getKeyName(); ConfigurationDataType type = key.getType(); String description = key.getDescription(); boolean hasDescription = description != null && !description.isEmpty(); if (!verbose) { out.println(keyName); if (hasDescription) { out.print(" "); out.println(description); } out.println(); continue; } out.printf("##%n## Key : %s%n## Type: %s%n", keyName, type); if (hasDescription) { out.printf("##%n## %s%n", description); } out.printf("##%n## Examples:%n#%n"); out.printf("# clear %s%n", keyName); String exampleValue = type.getParser().exampleValue(); if (type.isList()) { out.printf("# %s += %s%n", keyName, exampleValue); out.printf("# %s -= %s%n", keyName, exampleValue); } else { out.printf("# %s = %s%n", keyName, exampleValue); } out.printf("#%n%n"); } if (!verbose) { out.println("Use --verbose for more information."); } return 0; } public int display(Collection> keys, boolean verbose, Collection argsPaths, boolean explicitKeys) throws Exception { TreeMap> sharedDirectories = findSharedDirectories(argsPaths); if (sharedDirectories == null) return 1; Set none = sharedDirectories.remove(NO_CONFIG); if (none != null) { if (none.size() == 1) { out.printf("No 'lombok.config' found for '%s'.%n", none.iterator().next()); } else { out.println("No 'lombok.config' found for: "); for (String path : none) out.printf("- %s%n", path); } } final List problems = new ArrayList(); ConfigurationProblemReporter reporter = new ConfigurationProblemReporter() { @Override public void report(String sourceDescription, String problem, int lineNumber, CharSequence line) { problems.add(String.format("%s: %s (%s:%d)", problem, line, sourceDescription, lineNumber)); } }; FileSystemSourceCache cache = new FileSystemSourceCache(); boolean first = true; for (Entry> entry : sharedDirectories.entrySet()) { if (!first) { out.printf("%n%n"); } Set paths = entry.getValue(); if (paths.size() == 1) { if (!(argsPaths.size() == 1)) out.printf("Configuration for '%s'.%n%n", paths.iterator().next()); } else { out.printf("Configuration for:%n"); for (String path : paths) out.printf("- %s%n", path); out.println(); } URI directory = entry.getKey(); ConfigurationResolver resolver = new BubblingConfigurationResolver(cache.sourcesForDirectory(directory, reporter)); Map, ? extends Collection> traces = trace(keys, directory); boolean printed = false; for (ConfigurationKey key : keys) { Object value = resolver.resolve(key); Collection modifications = traces.get(key); if (!modifications.isEmpty() || explicitKeys) { if (printed && verbose) out.println(); printValue(key, value, verbose, modifications); printed = true; } } if (!printed) out.println(""); first = false; } if (!problems.isEmpty()) { out.printf("%nProblems in the configuration files: %n"); for (String problem : problems) out.printf("- %s%n", problem); } return 0; } private void printValue(ConfigurationKey key, Object value, boolean verbose, Collection history) { if (verbose) out.printf("# %s%n", key.getDescription()); if (value == null) { out.printf("clear %s%n", key.getKeyName()); } else if (value instanceof List) { List list = (List)value; if (list.isEmpty()) out.printf("clear %s%n", key.getKeyName()); for (Object element : list) out.printf("%s += %s%n", key.getKeyName(), element); } else { out.printf("%s = %s%n", key.getKeyName(), value); } if (!verbose) return; for (String modification : history) out.printf("# %s%n", modification); } private static final ConfigurationProblemReporter VOID = new ConfigurationProblemReporter() { @Override public void report(String sourceDescription, String problem, int lineNumber, CharSequence line) {} }; private Map, ? extends Collection> trace(Collection> keys, URI directory) throws Exception { Map, List> result = new HashMap, List>(); for (ConfigurationKey key : keys) result.put(key, new ArrayList()); Set> used = new HashSet>(); boolean stopBubbling = false; String previousFileName = null; for (File currentDirectory = new File(directory); currentDirectory != null && !stopBubbling; currentDirectory = currentDirectory.getParentFile()) { File configFile = new File(currentDirectory, "lombok.config"); if (!configFile.exists() || !configFile.isFile()) continue; Map, List> traces = trace(fileToString(configFile), configFile.getAbsolutePath(), keys); stopBubbling = stopBubbling(traces.get(ConfigurationKeys.STOP_BUBBLING)); for (ConfigurationKey key : keys) { List modifications = traces.get(key); if (modifications == null) { modifications = new ArrayList(); modifications.add(" <'" + key.getKeyName() + "' not mentioned>"); } else { used.add(key); } if (previousFileName != null) { modifications.add(""); modifications.add(previousFileName + ":"); } result.get(key).addAll(0, modifications); } previousFileName = configFile.getAbsolutePath(); } for (ConfigurationKey key : keys) { if (used.contains(key)) { result.get(key).add(0, previousFileName + (stopBubbling ? " (stopped bubbling):" : ":")); } else { result.put(key, Collections.emptyList()); } } return result; } private Map, List> trace(String content, String contentDescription, final Collection> keys) { final Map, List> result = new HashMap, List>(); Collector collector = new Collector() { @Override public void clear(ConfigurationKey key, String contentDescription, int lineNumber) { trace(key, "clear " + key.getKeyName(), lineNumber); } @Override public void set(ConfigurationKey key, Object value, String contentDescription, int lineNumber) { trace(key, key.getKeyName() + " = " + value, lineNumber); } @Override public void add(ConfigurationKey key, Object value, String contentDescription, int lineNumber) { trace(key, key.getKeyName() + " += " + value, lineNumber); } @Override public void remove(ConfigurationKey key, Object value, String contentDescription, int lineNumber) { trace(key, key.getKeyName() + " -= " + value, lineNumber); } private void trace(ConfigurationKey key, String message, int lineNumber) { if (!keys.contains(key)) return; List traces = result.get(key); if (traces == null) { traces = new ArrayList(); result.put(key, traces); } traces.add(String.format("%4d: %s", lineNumber, message)); } }; new ConfigurationParser(VOID).parse(content, contentDescription, collector); return result; } private boolean stopBubbling(List stops) { return stops != null && !stops.isEmpty() && stops.get(stops.size() -1).endsWith("true"); } private Collection> checkKeys(List keyList) { Map> registeredKeys = ConfigurationKey.registeredKeys(); if (keyList.isEmpty()) return registeredKeys.values(); Collection> keys = new ArrayList>(); for (String keyName : keyList) { ConfigurationKey key = registeredKeys.get(keyName); if (key == null) { err.printf("Unknown key '%s'%n", keyName); return null; } keys.remove(key); keys.add(key); } return keys; } private TreeMap> findSharedDirectories(Collection paths) { TreeMap> sharedDirectories = new TreeMap>(new Comparator() { @Override public int compare(URI o1, URI o2) { return o1.toString().compareTo(o2.toString()); } }); for (String path : paths) { File file = new File(path); if (!file.exists()) { err.printf("File not found: '%s'%n", path); return null; } URI first = findFirstLombokDirectory(file); Set sharedBy = sharedDirectories.get(first); if (sharedBy == null) { sharedBy = new TreeSet(); sharedDirectories.put(first, sharedBy); } sharedBy.add(path); } return sharedDirectories; } private URI findFirstLombokDirectory(File file) { File current = new File(file.toURI().normalize()); if (file.isFile()) current = current.getParentFile(); while (current != null) { if (new File(current, "lombok.config").exists()) return current.toURI(); current = current.getParentFile(); } return NO_CONFIG; } } lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationDataType.java000066400000000000000000000141501312655740700270750ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public final class ConfigurationDataType { private static final Map, ConfigurationValueParser> SIMPLE_TYPES; static { Map, ConfigurationValueParser> map = new HashMap, ConfigurationValueParser>(); map.put(String.class, new ConfigurationValueParser() { @Override public Object parse(String value) { return value; } @Override public String description() { return "string"; } @Override public String exampleValue() { return ""; } }); map.put(Integer.class, new ConfigurationValueParser() { @Override public Object parse(String value) { return Integer.parseInt(value); } @Override public String description() { return "int"; } @Override public String exampleValue() { return ""; } }); map.put(Long.class, new ConfigurationValueParser() { @Override public Object parse(String value) { return Long.parseLong(value); } @Override public String description() { return "long"; } @Override public String exampleValue() { return ""; } }); map.put(Double.class, new ConfigurationValueParser() { @Override public Object parse(String value) { return Double.parseDouble(value); } @Override public String description() { return "double"; } @Override public String exampleValue() { return ""; } }); map.put(Boolean.class, new ConfigurationValueParser() { @Override public Object parse(String value) { return Boolean.parseBoolean(value); } @Override public String description() { return "boolean"; } @Override public String exampleValue() { return "[false | true]"; } }); map.put(TypeName.class, new ConfigurationValueParser() { @Override public Object parse(String value) { return TypeName.valueOf(value); } @Override public String description() { return "type-name"; } @Override public String exampleValue() { return ""; } }); SIMPLE_TYPES = map; } private static ConfigurationValueParser enumParser(Object enumType) { final Class type = (Class) enumType; @SuppressWarnings("rawtypes") final Class rawType = type; return new ConfigurationValueParser() { @SuppressWarnings("unchecked") @Override public Object parse(String value) { try { return Enum.valueOf(rawType, value); } catch (Exception e) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (Character.isUpperCase(c) && i > 0) sb.append("_"); sb.append(Character.toUpperCase(c)); } return Enum.valueOf(rawType, sb.toString()); } } @Override public String description() { return "enum (" + type.getName() + ")"; } @Override public String exampleValue() { ExampleValueString evs = type.getAnnotation(ExampleValueString.class); if (evs != null) return evs.value(); return Arrays.toString(type.getEnumConstants()).replace(",", " |"); } }; } private final boolean isList; private final ConfigurationValueParser parser; public static ConfigurationDataType toDataType(Class> keyClass) { if (keyClass.getSuperclass() != ConfigurationKey.class) { throw new IllegalArgumentException("No direct subclass of ConfigurationKey: " + keyClass.getName()); } Type type = keyClass.getGenericSuperclass(); if (!(type instanceof ParameterizedType)) { throw new IllegalArgumentException("Missing type parameter in "+ type); } ParameterizedType parameterized = (ParameterizedType) type; Type argumentType = parameterized.getActualTypeArguments()[0]; boolean isList = false; if (argumentType instanceof ParameterizedType) { ParameterizedType parameterizedArgument = (ParameterizedType) argumentType; if (parameterizedArgument.getRawType() == List.class) { isList = true; argumentType = parameterizedArgument.getActualTypeArguments()[0]; } } if (SIMPLE_TYPES.containsKey(argumentType)) { return new ConfigurationDataType(isList, SIMPLE_TYPES.get(argumentType)); } if (isEnum(argumentType)) { return new ConfigurationDataType(isList, enumParser(argumentType)); } throw new IllegalArgumentException("Unsupported type parameter in " + type); } private ConfigurationDataType(boolean isList, ConfigurationValueParser parser) { this.isList = isList; this.parser = parser; } public boolean isList() { return isList; } ConfigurationValueParser getParser() { return parser; } @Override public String toString() { if (isList) return "list of " + parser.description(); return parser.description(); } private static boolean isEnum(Type argumentType) { return argumentType instanceof Class && ((Class) argumentType).isEnum(); } }lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationKey.java000066400000000000000000000066631312655740700261240ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import java.util.regex.Pattern; /** * Describes a configuration key and its type. *

* The recommended usage is to create a type token: *

 *    private static ConfigurationKey<String> KEY = new ConfigurationKey<String>("keyName", "description") {};
 * 
*/ public abstract class ConfigurationKey { private static final Pattern VALID_NAMES = Pattern.compile("[-_a-zA-Z][-.\\w]*(?> registeredKeys = new TreeMap>(String.CASE_INSENSITIVE_ORDER); private static Map> copy; private final String keyName; private final String description; private final ConfigurationDataType type; public ConfigurationKey(String keyName, String description) { this.keyName = checkName(keyName); @SuppressWarnings("unchecked") ConfigurationDataType type = ConfigurationDataType.toDataType((Class>)getClass()); this.type = type; this.description = description; registerKey(keyName, this); } public final String getKeyName() { return keyName; } public final String getDescription() { return description; } public final ConfigurationDataType getType() { return type; } @Override public String toString() { return keyName + " (" + type + "): " + description; } private static String checkName(String keyName) { if (keyName == null) throw new NullPointerException("keyName"); if (!VALID_NAMES.matcher(keyName).matches()) throw new IllegalArgumentException("Invalid keyName: " + keyName); return keyName; } /** * Returns a copy of the currently registered keys. */ @SuppressWarnings("unchecked") public static Map> registeredKeys() { synchronized (registeredKeys) { if (copy == null) copy = Collections.unmodifiableMap((Map>) registeredKeys.clone()); return copy; } } private static void registerKey(String keyName, ConfigurationKey key) { synchronized (registeredKeys) { if (registeredKeys.containsKey(keyName)) throw new IllegalArgumentException("Key '" + keyName + "' already registered"); registeredKeys.put(keyName, key); copy = null; } } }lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationKeysLoader.java000066400000000000000000000041671312655740700274330ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import java.io.IOException; import java.util.Iterator; import java.util.concurrent.atomic.AtomicBoolean; import lombok.ConfigurationKeys; import lombok.core.SpiLoadUtil; public interface ConfigurationKeysLoader { public class LoaderLoader { private static final AtomicBoolean alreadyLoaded = new AtomicBoolean(false); private LoaderLoader() {} public static void loadAllConfigurationKeys() { if (alreadyLoaded.get()) return; try { Class.forName(ConfigurationKeys.class.getName()); } catch (Throwable ignore) {} try { Iterator iterator = SpiLoadUtil.findServices(ConfigurationKeysLoader.class, ConfigurationKeysLoader.class.getClassLoader()).iterator(); while (iterator.hasNext()) { try { iterator.next(); } catch (Exception ignore) {} } } catch (IOException e) { throw new RuntimeException("Can't load config keys; services file issue.", e); } finally { alreadyLoaded.set(true); } } } } lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationParser.java000066400000000000000000000107131312655740700266170ustar00rootroot00000000000000/* * Copyright (C) 2014-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConfigurationParser { private static final Pattern LINE = Pattern.compile("(?:clear\\s+([^=]+))|(?:(\\S*?)\\s*([-+]?=)\\s*(.*?))"); private static final Pattern NEWLINE_FINDER = Pattern.compile("^[\t ]*(.*?)[\t\r ]*$", Pattern.MULTILINE); private ConfigurationProblemReporter reporter; public ConfigurationParser(ConfigurationProblemReporter reporter) { if (reporter == null) throw new NullPointerException("reporter"); this.reporter = reporter; } public void parse(CharSequence content, String contentDescription, Collector collector) { Map> registeredKeys = ConfigurationKey.registeredKeys(); int lineNumber = 0; Matcher lineMatcher = NEWLINE_FINDER.matcher(content); while (lineMatcher.find()) { CharSequence line = content.subSequence(lineMatcher.start(1), lineMatcher.end(1)); lineNumber++; if (line.length() == 0 || line.charAt(0) == '#') continue; Matcher matcher = LINE.matcher(line); if (!matcher.matches()) { reporter.report(contentDescription, "Invalid line", lineNumber, line); continue; } String operator = null; String keyName = null; String stringValue; if (matcher.group(1) == null) { keyName = matcher.group(2); operator = matcher.group(3); stringValue = matcher.group(4); } else { keyName = matcher.group(1); operator = "clear"; stringValue = null; } ConfigurationKey key = registeredKeys.get(keyName); if (key == null) { reporter.report(contentDescription, "Unknown key '" + keyName + "'", lineNumber, line); continue; } ConfigurationDataType type = key.getType(); boolean listOperator = operator.equals("+=") || operator.equals("-="); if (listOperator && !type.isList()) { reporter.report(contentDescription, "'" + keyName + "' is not a list and doesn't support " + operator + " (only = and clear)", lineNumber, line); continue; } if (operator.equals("=") && type.isList()) { reporter.report(contentDescription, "'" + keyName + "' is a list and cannot be assigned to (use +=, -= and clear instead)", lineNumber, line); continue; } Object value = null; if (stringValue != null) try { value = type.getParser().parse(stringValue); } catch (Exception e) { reporter.report(contentDescription, "Error while parsing the value for '" + keyName + "' value '" + stringValue + "' (should be " + type.getParser().exampleValue() + ")", lineNumber, line); continue; } if (operator.equals("clear")) { collector.clear(key, contentDescription, lineNumber); } else if (operator.equals("=")) { collector.set(key, value, contentDescription, lineNumber); } else if (operator.equals("+=")) { collector.add(key, value, contentDescription, lineNumber); } else { collector.remove(key, value, contentDescription, lineNumber); } } } public interface Collector { void clear(ConfigurationKey key, String contentDescription, int lineNumber); void set(ConfigurationKey key, Object value, String contentDescription, int lineNumber); void add(ConfigurationKey key, Object value, String contentDescription, int lineNumber); void remove(ConfigurationKey key, Object value, String contentDescription, int lineNumber); } } lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationProblemReporter.java000066400000000000000000000041601312655740700305050ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import lombok.eclipse.handlers.EclipseHandlerUtil; public interface ConfigurationProblemReporter { void report(String sourceDescription, String problem, int lineNumber, CharSequence line); ConfigurationProblemReporter CONSOLE = new ConfigurationProblemReporter() { @Override public void report(String sourceDescription, String problem, int lineNumber, CharSequence line) { try { // The console (System.err) is non-existent in eclipse environments, so we should try to // log into at least the error log. This isn't really the appropriate place (should go in the // relevant file instead, most people never see anything in the error log either!), but at least // there is a way to see it, vs. System.err, which is completely invisible. EclipseHandlerUtil.warning(String.format("%s (%s:%d)", problem, sourceDescription, lineNumber), null); } catch (Throwable ignore) {} System.err.printf("%s (%s:%d)\n", problem, sourceDescription, lineNumber); } }; } lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationResolver.java000066400000000000000000000023471312655740700271700ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; public interface ConfigurationResolver { T resolve(ConfigurationKey key); } lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationResolverFactory.java000066400000000000000000000024271312655740700305170ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import lombok.core.AST; public interface ConfigurationResolverFactory { ConfigurationResolver createResolver(AST ast); } lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationSource.java000066400000000000000000000040061312655740700266210ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; public interface ConfigurationSource { Result resolve(ConfigurationKey key); public static final class Result { private final Object value; private final boolean authoritative; public Result(Object value, boolean authoritative) { this.value = value; this.authoritative = authoritative; } public Object getValue() { return value; } public boolean isAuthoritative() { return authoritative; } @Override public String toString() { return String.valueOf(value) + (authoritative ? " (set)" : " (delta)"); } } public static class ListModification { private final Object value; private final boolean added; public ListModification(Object value, boolean added) { this.value = value; this.added = added; } public Object getValue() { return value; } public boolean isAdded() { return added; } } }lombok-1.16.18/src/core/lombok/core/configuration/ConfigurationValueParser.java000066400000000000000000000024051312655740700276130ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; interface ConfigurationValueParser { Object parse(String value); String description(); String exampleValue(); }lombok-1.16.18/src/core/lombok/core/configuration/ExampleValueString.java000066400000000000000000000032301312655740700264060ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * If a configuration key has an enum type, then the 'example values' string is built up by just joining all enum keys together with a bar separator, but you * can add this annotation to the enum type to override this string. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ExampleValueString { String value(); } lombok-1.16.18/src/core/lombok/core/configuration/FileSystemSourceCache.java000066400000000000000000000215241312655740700270260ustar00rootroot00000000000000/* * Copyright (C) 2014-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.URI; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import lombok.ConfigurationKeys; import lombok.core.configuration.ConfigurationSource.Result; import lombok.core.debug.ProblemReporter; public class FileSystemSourceCache { private static final String LOMBOK_CONFIG_FILENAME = "lombok.config"; private static final long FULL_CACHE_CLEAR_INTERVAL = TimeUnit.MINUTES.toMillis(30); private static final long RECHECK_FILESYSTEM = TimeUnit.SECONDS.toMillis(2); private static final long NEVER_CHECKED = -1; private static final long MISSING = -88; // Magic value; any lombok.config with this exact epochmillis last modified will never be read, so, let's ensure nobody accidentally has one with that exact last modified stamp. private final ConcurrentMap dirCache = new ConcurrentHashMap(); // caches files (representing dirs) to the content object that tracks content. private final ConcurrentMap uriCache = new ConcurrentHashMap(); // caches URIs of java source files to the dir that contains it. private volatile long lastCacheClear = System.currentTimeMillis(); private void cacheClear() { // We never clear the caches, generally because it'd be weird if a compile run would continually create an endless stream of new java files. // Still, eventually that's going to cause a bit of a memory leak, so lets just completely clear them out every many minutes. long now = System.currentTimeMillis(); long delta = now - lastCacheClear; if (delta > FULL_CACHE_CLEAR_INTERVAL) { lastCacheClear = now; dirCache.clear(); uriCache.clear(); } } public Iterable sourcesForJavaFile(URI javaFile, ConfigurationProblemReporter reporter) { if (javaFile == null) return Collections.emptyList(); cacheClear(); File dir = uriCache.get(javaFile); if (dir == null) { URI uri = javaFile.normalize(); if (!uri.isAbsolute()) uri = URI.create("file:" + uri.toString()); try { File file = new File(uri); if (!file.exists()) throw new IllegalArgumentException("File does not exist: " + uri); dir = file.isDirectory() ? file : file.getParentFile(); if (dir != null) uriCache.put(javaFile, dir); } catch (IllegalArgumentException e) { // This means that the file as passed is not actually a file at all, and some exotic path system is involved. // examples: sourcecontrol://jazz stuff, or an actual relative path (uri.isAbsolute() is completely different, that checks presence of schema!), // or it's eclipse trying to parse a snippet, which has "/Foo.java" as uri. // At some point it might be worth investigating abstracting away the notion of "I can read lombok.config if present in // current context, and I can give you may parent context", using ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(javaFile) as basis. // For now, we just carry on as if there is no lombok.config. (intentional fallthrough) } catch (Exception e) { // Especially for eclipse's sake, exceptions here make eclipse borderline unusable, so let's play nice. ProblemReporter.error("Can't find absolute path of file being compiled: " + javaFile, e); } } if (dir != null) { try { return sourcesForDirectory(dir, reporter); } catch (Exception e) { // Especially for eclipse's sake, exceptions here make eclipse borderline unusable, so let's play nice. ProblemReporter.error("Can't resolve config stack for dir: " + dir.getAbsolutePath(), e); } } return Collections.emptyList(); } public Iterable sourcesForDirectory(URI directory, ConfigurationProblemReporter reporter) { return sourcesForJavaFile(directory, reporter); } private Iterable sourcesForDirectory(final File directory, final ConfigurationProblemReporter reporter) { return new Iterable() { @Override public Iterator iterator() { return new Iterator() { File currentDirectory = directory; ConfigurationSource next; boolean stopBubbling = false; @Override public boolean hasNext() { if (next != null) return true; if (stopBubbling) return false; next = findNext(); return next != null; } @Override public ConfigurationSource next() { if (!hasNext()) throw new NoSuchElementException(); ConfigurationSource result = next; next = null; return result; } private ConfigurationSource findNext() { while (currentDirectory != null && next == null) { next = getSourceForDirectory(currentDirectory, reporter); currentDirectory = currentDirectory.getParentFile(); } if (next != null) { Result stop = next.resolve(ConfigurationKeys.STOP_BUBBLING); stopBubbling = (stop != null && Boolean.TRUE.equals(stop.getValue())); } return next; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } ConfigurationSource getSourceForDirectory(File directory, ConfigurationProblemReporter reporter) { long now = System.currentTimeMillis(); File configFile = new File(directory, LOMBOK_CONFIG_FILENAME); Content content = ensureContent(directory); synchronized (content) { if (content.lastChecked != NEVER_CHECKED && now - content.lastChecked < RECHECK_FILESYSTEM) { return content.source; } content.lastChecked = now; long previouslyModified = content.lastModified; content.lastModified = getLastModifiedOrMissing(configFile); if (content.lastModified != previouslyModified) content.source = content.lastModified == MISSING ? null : parse(configFile, reporter); return content.source; } } private Content ensureContent(File directory) { Content content = dirCache.get(directory); if (content != null) { return content; } dirCache.putIfAbsent(directory, Content.empty()); return dirCache.get(directory); } private ConfigurationSource parse(File configFile, ConfigurationProblemReporter reporter) { String contentDescription = configFile.getAbsolutePath(); try { return StringConfigurationSource.forString(fileToString(configFile), reporter, contentDescription); } catch (Exception e) { reporter.report(contentDescription, "Exception while reading file: " + e.getMessage(), 0, null); return null; } } private static final ThreadLocal buffers = new ThreadLocal() { protected byte[] initialValue() { return new byte[65536]; } }; static String fileToString(File configFile) throws Exception { byte[] b = buffers.get(); FileInputStream fis = new FileInputStream(configFile); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); while (true) { int r = fis.read(b); if (r == -1) break; out.write(b, 0, r); } return new String(out.toByteArray(), "UTF-8"); } finally { fis.close(); } } private static final long getLastModifiedOrMissing(File file) { if (!file.exists() || !file.isFile()) return MISSING; return file.lastModified(); } private static class Content { ConfigurationSource source; long lastModified; long lastChecked; private Content(ConfigurationSource source, long lastModified, long lastChecked) { this.source = source; this.lastModified = lastModified; this.lastChecked = lastChecked; } static Content empty() { return new Content(null, MISSING, NEVER_CHECKED); } } }lombok-1.16.18/src/core/lombok/core/configuration/FlagUsageType.java000066400000000000000000000024301312655740700253300ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; /** Used for lombok configuration to flag usages of certain lombok feature. */ public enum FlagUsageType { WARNING, ERROR, ALLOW; } lombok-1.16.18/src/core/lombok/core/configuration/NullCheckExceptionType.java000066400000000000000000000034451312655740700272300ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; @ExampleValueString("[NullPointerException | IllegalArgumentException]") public enum NullCheckExceptionType { ILLEGAL_ARGUMENT_EXCEPTION { public String toExceptionMessage(String fieldName) { return fieldName + " is null"; } @Override public String getExceptionType() { return "java.lang.IllegalArgumentException"; } }, NULL_POINTER_EXCEPTION { @Override public String toExceptionMessage(String fieldName) { return fieldName; } public String getExceptionType() { return "java.lang.NullPointerException"; } }; public abstract String toExceptionMessage(String fieldName); public abstract String getExceptionType(); } lombok-1.16.18/src/core/lombok/core/configuration/StringConfigurationSource.java000066400000000000000000000070571312655740700300210ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import lombok.core.configuration.ConfigurationParser.Collector; public class StringConfigurationSource implements ConfigurationSource { private final Map, Result> values; public static ConfigurationSource forString(CharSequence content, ConfigurationProblemReporter reporter, String contentDescription) { final Map, Result> values = new HashMap, Result>(); new ConfigurationParser(reporter).parse(content, contentDescription, new Collector() { @Override public void clear(ConfigurationKey key, String contentDescription, int lineNumber) { values.put(key, new Result(null, true)); } @Override public void set(ConfigurationKey key, Object value, String contentDescription, int lineNumber) { values.put(key, new Result(value, true)); } @Override public void add(ConfigurationKey key, Object value, String contentDescription, int lineNumber) { modifyList(key, value, true); } @Override public void remove(ConfigurationKey key, Object value, String contentDescription, int lineNumber) { modifyList(key, value, false); } @SuppressWarnings("unchecked") private void modifyList(ConfigurationKey key, Object value, boolean add) { Result result = values.get(key); List list; if (result == null || result.getValue() == null) { list = new ArrayList(); values.put(key, new Result(list, result != null)); } else { list = (List) result.getValue(); } list.add(new ListModification(value, add)); } }); return new StringConfigurationSource(values); } private StringConfigurationSource(Map, Result> values) { this.values = new HashMap, Result>(); for (Entry, Result> entry : values.entrySet()) { Result result = entry.getValue(); if (result.getValue() instanceof List) { this.values.put(entry.getKey(), new Result(Collections.unmodifiableList((List) result.getValue()), result.isAuthoritative())); } else { this.values.put(entry.getKey(), result); } } } @Override public Result resolve(ConfigurationKey key) { return values.get(key); } } lombok-1.16.18/src/core/lombok/core/configuration/TypeName.java000066400000000000000000000031471312655740700243600ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; public final class TypeName { private final String name; private TypeName(String name) { this.name = name; } public static TypeName valueOf(String name) { return new TypeName(name); } @Override public boolean equals(Object obj) { if (!(obj instanceof TypeName)) return false; return name.equals(((TypeName) obj).name); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return name; } } lombok-1.16.18/src/core/lombok/core/debug/000077500000000000000000000000001312655740700202055ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/core/debug/AssertionLogger.java000066400000000000000000000077741312655740700241760ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.debug; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import lombok.core.Version; /** * We make a number of assumptions in lombok code, and if these assumptions fail, we try to fall back to a 'least bad' scenario. However, we would prefer to * just know about these cases, without confronting our users with error messages. The 'fix' is to log such assertion failures to this logger, which promptly * ignores them, _unless_ you specifically enable logging them to a file. If you'd like to help out or want to assist in debugging, turn this on. */ public class AssertionLogger { private static final String LOG_PATH; static { String log = System.getProperty("lombok.assertion.log", null); if (log != null) { LOG_PATH = log.isEmpty() ? null : log; } else { try { log = System.getenv("LOMBOK_ASSERTION_LOG"); } catch (Exception e) { log = null; } LOG_PATH = (log == null || log.isEmpty()) ? null : log; } } private static final AtomicBoolean loggedIntro = new AtomicBoolean(false); private static final String PROCESS_ID = generateProcessId(); private static final String ID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private static String generateProcessId() { char[] ID = new char[4]; Random r = new Random(); for (int i = 0; i < ID.length; i++) ID[i] = ID_CHARS.charAt(r.nextInt(ID_CHARS.length())); return new String(ID); } private static synchronized void logToFile(String msg) { if (msg == null) return; try { OutputStream out = new FileOutputStream(LOG_PATH, true); out.write(msg.getBytes("UTF-8")); out.close(); } catch (Exception e) { throw new RuntimeException("assertion logging can't write to log file", e); } } private static void logIntro() { if (loggedIntro.getAndSet(true)) return; String version; try { version = Version.getFullVersion(); } catch (Exception e) { version = Version.getVersion(); } logToFile(String.format("{%s} [%s -- START %s]\n", PROCESS_ID, new Date(), version)); } public static T assertLog(String message, T throwable) { if (LOG_PATH == null) return throwable; logIntro(); if (message == null) message = "(No message)"; String stackMsg = ""; if (throwable != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); pw.close(); stackMsg = "\n " + sw.toString().replace("\r", "").replace("\n", "\n ").trim(); } logToFile(String.format("{%s} [%ty% { private static AtomicLong counter = new AtomicLong(); private final long when, id = counter.getAndIncrement(); private final long bits; private final List trace; private final String threadName; private final String message; private final Object[] params; private final WeakReference owner; public DebugSnapshot(CompilationUnitDeclaration owner, int stackHiding, String message, Object... params) { this.when = System.currentTimeMillis(); this.bits = owner.bits; if (stackHiding < 0) { this.trace = null; } else { StackTraceElement[] stackTrace = new Throwable().getStackTrace(); this.trace = new ArrayList(Math.max(0, stackTrace.length - stackHiding - 1)); for (int i = 1 + stackHiding; i < stackTrace.length; i++) trace.add(stackTrace[i]); } this.threadName = Thread.currentThread().getName(); this.message = message; this.params = params == null ? new Object[0] : params; this.owner = new WeakReference(owner); } private String ownerName() { CompilationUnitDeclaration node = owner.get(); if (node == null) return "--GCed--"; char[] tn = node.getMainTypeName(); char[] fs = node.getFileName(); if (tn == null || tn.length == 0) { return (fs == null || fs.length == 0) ? "--UNKNOWN--" : new String(fs); } return new String(tn); } public String shortToString() { StringBuilder out = new StringBuilder(); out.append(String.format("WHEN: %14d THREAD: %s AST: %s HAMB: %b -- ", when, threadName, ownerName(), 0 != (bits & ASTNode.HasAllMethodBodies))); if (message != null) out.append(" ").append(String.format(message, params)); return out.toString(); } @Override public String toString() { StringBuilder out = new StringBuilder(); out.append(shortToString()).append("\n"); if (trace == null) { out.append(" Stack Omitted"); } else { for (StackTraceElement elem : trace) { out.append(" ").append(elem.toString()).append("\n"); } } return out.toString(); } @Override public int compareTo(DebugSnapshot o) { return Long.valueOf(id).compareTo(o.id); } } lombok-1.16.18/src/core/lombok/core/debug/DebugSnapshotStore.java000066400000000000000000000103301312655740700246300ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.debug; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; public class DebugSnapshotStore { public static final DebugSnapshotStore INSTANCE = new DebugSnapshotStore(); public static final boolean GLOBAL_DSS_DISABLE_SWITCH = true; // All access should synchronize on the map private final Map> map = new WeakHashMap>(); public void snapshot(CompilationUnitDeclaration owner, String message, Object... params) { if (GLOBAL_DSS_DISABLE_SWITCH) return; DebugSnapshot snapshot = new DebugSnapshot(owner, 1, message, params); List list; synchronized (map) { list = map.get(owner); if (list == null) { list = new ArrayList(); map.put(owner, list); list.add(snapshot); } else if (!list.isEmpty()) { list.add(snapshot); } else { // An empty list is an indicator that we no longer care about that particular CUD. } } } public void log(CompilationUnitDeclaration owner, String message, Object... params) { if (GLOBAL_DSS_DISABLE_SWITCH) return; DebugSnapshot snapshot = new DebugSnapshot(owner, -1, message, params); List list; synchronized (map) { list = map.get(owner); if (list == null) { list = new ArrayList(); map.put(owner, list); list.add(snapshot); } else if (!list.isEmpty()) { list.add(snapshot); } else { // An empty list is an indicator that we no longer care about that particular CUD. } } } public String print(CompilationUnitDeclaration owner, String message, Object... params) { if (GLOBAL_DSS_DISABLE_SWITCH) return null; List list; synchronized (map) { snapshot(owner, message == null ? "Printing" : message, params); list = new ArrayList(); list.addAll(map.get(owner)); if (list.isEmpty()) return null; // An empty list is an indicator that we no longer care about that particular CUD. map.get(owner).clear(); } Collections.sort(list); int idx = 1; StringBuilder out = new StringBuilder(); out.append("---------------------------\n"); for (DebugSnapshot snapshot : list) { out.append(String.format("%3d: %s\n", idx++, snapshot.shortToString())); } out.append("******\n"); idx = 1; for (DebugSnapshot snapshot : list) { out.append(String.format("%3d: %s", idx++, snapshot.toString())); } try { File logFile = new File(System.getProperty("user.home", "."), String.format("lombokdss-%d.err", System.currentTimeMillis())); OutputStream stream = new FileOutputStream(logFile); try { stream.write(out.toString().getBytes("UTF-8")); } finally { stream.close(); } return logFile.getAbsolutePath(); } catch (Exception e) { System.err.println(out); return "(can't write log file - emitted to system err)"; } } } lombok-1.16.18/src/core/lombok/core/debug/HistogramTracker.java000066400000000000000000000101311312655740700243150ustar00rootroot00000000000000package lombok.core.debug; import java.io.PrintStream; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicStampedReference; /** * Create one of these and call .report() on it a lot to emit histogram data about the times taken by some process. * Currently the results are broken down into 10 buckets, from 0 millis to a quarter of a second, and a report is emitted * to the ProblemReporter every minute. If there are 0 entries for a given minute, it is not reported. Reports aren't * emitted until you call report(). */ public class HistogramTracker { private static final long[] RANGES = { 250001L, 500001L, 1000001L, 2000001L, 4000001L, 8000001L, 16000001L, 32000001L, 64000001L, 128000001L, 256000001L, 512000001L, 1024000001L, 2048000001L, 10000000001L}; private static final long REPORT_WINDOW = 1000 * 60; private final String category; private final AtomicStampedReference bars = new AtomicStampedReference(new long[RANGES.length + 2], 0); private final AtomicBoolean addedSysHook = new AtomicBoolean(false); private final PrintStream out; public HistogramTracker(String category) { this.category = category; this.out = null; printInit(); } public HistogramTracker(String category, PrintStream out) { this.category = category; this.out = out; printInit(); } private void printInit() { if (category == null) { if (out == null) ProblemReporter.info("Initialized histogram", null); else out.println("Initialized histogram"); } else { if (out == null) ProblemReporter.info(String.format("Initialized histogram tracker for '%s'", category), null); else out.printf("Initialized histogram tracker for '%s'%n", category); } } public long start() { return System.nanoTime(); } public void end(long startToken) { if (!addedSysHook.getAndSet(true)) Runtime.getRuntime().addShutdownHook(new Thread("Histogram Printer") { @Override public void run() { int[] currentInterval = {0}; long[] b = bars.get(currentInterval); printReport(currentInterval[0], b); } }); long end = System.nanoTime(); long now = System.currentTimeMillis(); long delta = end - startToken; if (delta < 0L) delta = 0L; int interval = (int) (now / REPORT_WINDOW); int[] currentInterval = {0}; long[] bars = this.bars.get(currentInterval); long[] newBars; if (currentInterval[0] != interval) { printReport(currentInterval[0], bars); newBars = new long[RANGES.length + 2]; if (!this.bars.compareAndSet(bars, newBars, currentInterval[0], interval)) { newBars = this.bars.get(currentInterval); } } else { newBars = bars; } newBars[RANGES.length + 1] += delta; for (int i = 0; i < RANGES.length; i++) { if (delta < RANGES[i]) { newBars[i]++; return; } } newBars[RANGES.length]++; } private void printReport(int interval, long[] bars) { StringBuilder sb = new StringBuilder(); if (category != null) sb.append(category).append(" "); sb.append("["); GregorianCalendar gc = new GregorianCalendar(); gc.setTimeInMillis(interval * REPORT_WINDOW); int hour = gc.get(Calendar.HOUR_OF_DAY); int minute = gc.get(Calendar.MINUTE); if (hour < 10) sb.append('0'); sb.append(hour).append(":"); if (minute < 10) sb.append('0'); sb.append(minute).append("] {"); long sum = bars[RANGES.length]; int count = 0; int lastZeroPos = sb.length(); for (int i = 0; i < RANGES.length; i++) { sum += bars[i]; sb.append(bars[i]); if (bars[i] != 0) lastZeroPos = sb.length(); sb.append(" "); count++; if (count == 3) sb.append("-- "); if (count == 9) sb.append("-- "); } if (sum == 0) return; sb.setLength(lastZeroPos); double millis = bars[RANGES.length + 1] / 1000000.0; long over = bars[RANGES.length]; if (over > 0L) { sb.append(" -- ").append(bars[RANGES.length]); } sb.append("} total calls: ").append(sum).append(" total time (millis): ").append((int)(millis + 0.5)); if (out == null) ProblemReporter.info(sb.toString(), null); else out.println(sb.toString()); } } lombok-1.16.18/src/core/lombok/core/debug/ProblemReporter.java000066400000000000000000000113311312655740700241720ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.debug; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.core.runtime.ILog; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.osgi.framework.Bundle; public class ProblemReporter { public static void info(String msg, Throwable ex) { init(); try { logger.info(msg, ex); } catch (Throwable t) { logger = new TerminalLogger(); logger.info(msg, ex); } } public static void warning(String msg, Throwable ex) { init(); try { logger.warning(msg, ex); } catch (Throwable t) { logger = new TerminalLogger(); logger.warning(msg, ex); } } public static void error(String msg, Throwable ex) { init(); try { logger.error(msg, ex); } catch (Throwable t) { logger = new TerminalLogger(); logger.error(msg, ex); } } private static void init() { if (logger != null) return; try { logger = new EclipseWorkspaceLogger(); } catch (Throwable t) { logger = new TerminalLogger(); } } private static ErrorLogger logger; private interface ErrorLogger { void info(String message, Throwable ex); void warning(String message, Throwable ex); void error(String message, Throwable ex); } private static class TerminalLogger implements ErrorLogger { @Override public void info(String message, Throwable ex) { System.err.println(message); if (ex != null) ex.printStackTrace(); } @Override public void warning(String message, Throwable ex) { System.err.println(message); if (ex != null) ex.printStackTrace(); } @Override public void error(String message, Throwable ex) { System.err.println(message); if (ex != null) ex.printStackTrace(); } } private static class EclipseWorkspaceLogger implements ErrorLogger { private static final String DEFAULT_BUNDLE_NAME = "org.eclipse.jdt.core"; private static final Bundle bundle; private static final int MAX_LOG = 200; private static final long SQUELCH_TIMEOUT = TimeUnit.HOURS.toMillis(1); private static final AtomicInteger counter = new AtomicInteger(); private static volatile long squelchTimeout = 0L; static { bundle = Platform.getBundle(DEFAULT_BUNDLE_NAME); if (bundle == null) throw new NoClassDefFoundError(); // this means some weird RCP build or possible ecj. At any rate, we can't report this way so act as if this isn't an eclipse. } @Override public void info(String message, Throwable error) { msg(IStatus.INFO, message, error); } @Override public void warning(String message, Throwable error) { msg(IStatus.WARNING, message, error); } @Override public void error(String message, Throwable error) { msg(IStatus.ERROR, message, error); } private void msg(int msgType, String message, Throwable error) { int ct = squelchTimeout != 0L ? 0 : counter.incrementAndGet(); boolean printSquelchWarning = false; if (squelchTimeout != 0L) { long now = System.currentTimeMillis(); if (squelchTimeout > now) return; squelchTimeout = now + SQUELCH_TIMEOUT; printSquelchWarning = true; } else if (ct >= MAX_LOG) { squelchTimeout = System.currentTimeMillis() + SQUELCH_TIMEOUT; printSquelchWarning = true; } ILog log = Platform.getLog(bundle); log.log(new Status(msgType, DEFAULT_BUNDLE_NAME, message, error)); if (printSquelchWarning) { log.log(new Status(IStatus.WARNING, DEFAULT_BUNDLE_NAME, "Lombok has logged too many messages; to avoid memory issues, further lombok logs will be squelched for a while. Restart eclipse to start over.")); } } } } lombok-1.16.18/src/core/lombok/core/debug/package-info.java000066400000000000000000000031521312655740700233750ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * This package contains tooling used only to debug issues that cannot be found with research but * which require releasing a production or edge release with extra introspective facilities in * an attempt to add clarity to the exceptions or other messages that result when the bug occurs. * * NB: This package is not public API in the sense that contents of this package, * even public classes / methods / etc, may change in point releases. */ package lombok.core.debug;lombok-1.16.18/src/core/lombok/core/handlers/000077500000000000000000000000001312655740700207175ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/core/handlers/HandlerUtil.java000066400000000000000000000507541312655740700240100ustar00rootroot00000000000000/* * Copyright (C) 2013-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.handlers; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import lombok.AllArgsConstructor; import lombok.ConfigurationKeys; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.Value; import lombok.core.AST; import lombok.core.AnnotationValues; import lombok.core.JavaIdentifiers; import lombok.core.LombokNode; import lombok.core.configuration.AllowHelper; import lombok.core.configuration.ConfigurationKey; import lombok.core.configuration.FlagUsageType; import lombok.experimental.Accessors; import lombok.experimental.FieldDefaults; import lombok.experimental.Wither; /** * Container for static utility methods useful for some of the standard lombok handlers, regardless of * target platform (e.g. useful for both javac and Eclipse lombok implementations). */ public class HandlerUtil { private HandlerUtil() {} public static int primeForHashcode() { return 59; } public static int primeForTrue() { return 79; } public static int primeForFalse() { return 97; } public static int primeForNull() { return 43; } /** Checks if the given name is a valid identifier. * * If it is, this returns {@code true} and does nothing else. * If it isn't, this returns {@code false} and adds an error message to the supplied node. */ public static boolean checkName(String nameSpec, String identifier, LombokNode errorNode) { if (identifier.isEmpty()) { errorNode.addError(nameSpec + " cannot be the empty string."); return false; } if (!JavaIdentifiers.isValidJavaIdentifier(identifier)) { errorNode.addError(nameSpec + " must be a valid java identifier."); return false; } return true; } public static String autoSingularize(String plural) { return Singulars.autoSingularize(plural); } public static void handleFlagUsage(LombokNode node, ConfigurationKey key, String featureName) { FlagUsageType fut = node.getAst().readConfiguration(key); if (fut == null && AllowHelper.isAllowable(key)) { node.addError("Use of " + featureName + " is disabled by default. Please add '" + key.getKeyName() + " = " + FlagUsageType.ALLOW + "' to 'lombok.config' if you want to enable is."); } if (fut != null) { String msg = "Use of " + featureName + " is flagged according to lombok configuration."; if (fut == FlagUsageType.WARNING) node.addWarning(msg); else if (fut == FlagUsageType.ERROR) node.addError(msg); } } @SuppressWarnings("deprecation") public static boolean shouldAddGenerated(LombokNode node) { Boolean add = node.getAst().readConfiguration(ConfigurationKeys.ADD_JAVAX_GENERATED_ANNOTATIONS); if (add != null) return add; return !Boolean.FALSE.equals(node.getAst().readConfiguration(ConfigurationKeys.ADD_GENERATED_ANNOTATIONS)); } public static void handleExperimentalFlagUsage(LombokNode node, ConfigurationKey key, String featureName) { handleFlagUsage(node, key, featureName, ConfigurationKeys.EXPERIMENTAL_FLAG_USAGE, "any lombok.experimental feature"); } public static void handleFlagUsage(LombokNode node, ConfigurationKey key1, String featureName1, ConfigurationKey key2, String featureName2) { FlagUsageType fut1 = node.getAst().readConfiguration(key1); FlagUsageType fut2 = node.getAst().readConfiguration(key2); FlagUsageType fut = null; String featureName = null; if (fut1 == FlagUsageType.ERROR) { fut = fut1; featureName = featureName1; } else if (fut2 == FlagUsageType.ERROR) { fut = fut2; featureName = featureName2; } else if (fut1 == FlagUsageType.WARNING) { fut = fut1; featureName = featureName1; } else { fut = fut2; featureName = featureName2; } if (fut != null) { String msg = "Use of " + featureName + " is flagged according to lombok configuration."; if (fut == FlagUsageType.WARNING) node.addWarning(msg); else node.addError(msg); } } public static boolean shouldReturnThis0(AnnotationValues accessors, AST ast) { boolean chainForced = accessors.isExplicit("chain"); boolean fluentForced = accessors.isExplicit("fluent"); Accessors instance = accessors.getInstance(); boolean chain = instance.chain(); boolean fluent = instance.fluent(); if (chainForced) return chain; if (!chainForced) { Boolean chainConfig = ast.readConfiguration(ConfigurationKeys.ACCESSORS_CHAIN); if (chainConfig != null) return chainConfig; } if (!fluentForced) { Boolean fluentConfig = ast.readConfiguration(ConfigurationKeys.ACCESSORS_FLUENT); if (fluentConfig != null) fluent = fluentConfig; } return chain || fluent; } @SuppressWarnings({"all", "unchecked", "deprecation"}) public static final List> INVALID_ON_BUILDERS = Collections.unmodifiableList( Arrays.>asList( Getter.class, Setter.class, Wither.class, ToString.class, EqualsAndHashCode.class, RequiredArgsConstructor.class, AllArgsConstructor.class, NoArgsConstructor.class, Data.class, Value.class, lombok.experimental.Value.class, FieldDefaults.class)); /** * Given the name of a field, return the 'base name' of that field. For example, {@code fFoobar} becomes {@code foobar} if {@code f} is in the prefix list. * For prefixes that end in a letter character, the next character must be a non-lowercase character (i.e. {@code hashCode} is not {@code ashCode} even if * {@code h} is in the prefix list, but {@code hAshcode} would become {@code ashCode}). The first prefix that matches is used. If the prefix list is empty, * or the empty string is in the prefix list and no prefix before it matches, the fieldName will be returned verbatim. * * If no prefix matches and the empty string is not in the prefix list and the prefix list is not empty, {@code null} is returned. * * @param fieldName The full name of a field. * @param prefixes A list of prefixes, usually provided by the {@code Accessors} settings annotation, listing field prefixes. * @return The base name of the field. */ public static CharSequence removePrefix(CharSequence fieldName, List prefixes) { if (prefixes == null || prefixes.isEmpty()) return fieldName; fieldName = fieldName.toString(); outer: for (String prefix : prefixes) { if (prefix.length() == 0) return fieldName; if (fieldName.length() <= prefix.length()) continue outer; for (int i = 0; i < prefix.length(); i++) { if (fieldName.charAt(i) != prefix.charAt(i)) continue outer; } char followupChar = fieldName.charAt(prefix.length()); // if prefix is a letter then follow up letter needs to not be lowercase, i.e. 'foo' is not a match // as field named 'oo' with prefix 'f', but 'fOo' would be. if (Character.isLetter(prefix.charAt(prefix.length() - 1)) && Character.isLowerCase(followupChar)) continue outer; return "" + Character.toLowerCase(followupChar) + fieldName.subSequence(prefix.length() + 1, fieldName.length()); } return null; } /* NB: 'notnull' is not part of the pattern because there are lots of @NotNull annotations out there that are crappily named and actually mean something else, such as 'this field must not be null _when saved to the db_ but its perfectly okay to start out as such, and a no-args constructor and the implied starts-out-as-null state that goes with it is in fact mandatory' which happens with javax.validation.constraints.NotNull. Various problems with spring have also been reported. See issue #287, issue #271, and issue #43. */ /** Matches the simple part of any annotation that lombok considers as indicative of NonNull status. */ public static final Pattern NON_NULL_PATTERN = Pattern.compile("^(?:nonnull)$", Pattern.CASE_INSENSITIVE); /** Matches the simple part of any annotation that lombok considers as indicative of Nullable status. */ public static final Pattern NULLABLE_PATTERN = Pattern.compile("^(?:nullable|checkfornull)$", Pattern.CASE_INSENSITIVE); public static final String DEFAULT_EXCEPTION_FOR_NON_NULL = "java.lang.NullPointerException"; /** * Generates a getter name from a given field name. * * Strategy: *
    *
  • Reduce the field's name to its base name by stripping off any prefix (from {@code Accessors}). If the field name does not fit * the prefix list, this method immediately returns {@code null}.
  • *
  • If {@code Accessors} has {@code fluent=true}, then return the basename.
  • *
  • Pick a prefix. 'get' normally, but 'is' if {@code isBoolean} is true.
  • *
  • Only if {@code isBoolean} is true: Check if the field starts with {@code is} followed by a non-lowercase character. If so, return the field name verbatim.
  • *
  • Check if the first character of the field is lowercase. If so, check if the second character * exists and is title or upper case. If so, uppercase the first character. If not, titlecase the first character.
  • *
  • Return the prefix plus the possibly title/uppercased first character, and the rest of the field name.
  • *
* * @param accessors Accessors configuration. * @param fieldName the name of the field. * @param isBoolean if the field is of type 'boolean'. For fields of type {@code java.lang.Boolean}, you should provide {@code false}. * @return The getter name for this field, or {@code null} if this field does not fit expected patterns and therefore cannot be turned into a getter name. */ public static String toGetterName(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { return toAccessorName(ast, accessors, fieldName, isBoolean, "is", "get", true); } /** * Generates a setter name from a given field name. * * Strategy: *
    *
  • Reduce the field's name to its base name by stripping off any prefix (from {@code Accessors}). If the field name does not fit * the prefix list, this method immediately returns {@code null}.
  • *
  • If {@code Accessors} has {@code fluent=true}, then return the basename.
  • *
  • Only if {@code isBoolean} is true: Check if the field starts with {@code is} followed by a non-lowercase character. * If so, replace {@code is} with {@code set} and return that.
  • *
  • Check if the first character of the field is lowercase. If so, check if the second character * exists and is title or upper case. If so, uppercase the first character. If not, titlecase the first character.
  • *
  • Return {@code "set"} plus the possibly title/uppercased first character, and the rest of the field name.
  • *
* * @param accessors Accessors configuration. * @param fieldName the name of the field. * @param isBoolean if the field is of type 'boolean'. For fields of type {@code java.lang.Boolean}, you should provide {@code false}. * @return The setter name for this field, or {@code null} if this field does not fit expected patterns and therefore cannot be turned into a getter name. */ public static String toSetterName(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { return toAccessorName(ast, accessors, fieldName, isBoolean, "set", "set", true); } /** * Generates a wither name from a given field name. * * Strategy: *
    *
  • Reduce the field's name to its base name by stripping off any prefix (from {@code Accessors}). If the field name does not fit * the prefix list, this method immediately returns {@code null}.
  • *
  • Only if {@code isBoolean} is true: Check if the field starts with {@code is} followed by a non-lowercase character. * If so, replace {@code is} with {@code with} and return that.
  • *
  • Check if the first character of the field is lowercase. If so, check if the second character * exists and is title or upper case. If so, uppercase the first character. If not, titlecase the first character.
  • *
  • Return {@code "with"} plus the possibly title/uppercased first character, and the rest of the field name.
  • *
* * @param accessors Accessors configuration. * @param fieldName the name of the field. * @param isBoolean if the field is of type 'boolean'. For fields of type {@code java.lang.Boolean}, you should provide {@code false}. * @return The wither name for this field, or {@code null} if this field does not fit expected patterns and therefore cannot be turned into a getter name. */ public static String toWitherName(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { return toAccessorName(ast, accessors, fieldName, isBoolean, "with", "with", false); } private static String toAccessorName(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean, String booleanPrefix, String normalPrefix, boolean adhereToFluent) { fieldName = fieldName.toString(); if (fieldName.length() == 0) return null; if (Boolean.TRUE.equals(ast.readConfiguration(ConfigurationKeys.GETTER_CONSEQUENT_BOOLEAN))) isBoolean = false; boolean explicitPrefix = accessors != null && accessors.isExplicit("prefix"); boolean explicitFluent = accessors != null && accessors.isExplicit("fluent"); Accessors ac = (explicitPrefix || explicitFluent) ? accessors.getInstance() : null; List prefix = explicitPrefix ? Arrays.asList(ac.prefix()) : ast.readConfiguration(ConfigurationKeys.ACCESSORS_PREFIX); boolean fluent = explicitFluent ? ac.fluent() : Boolean.TRUE.equals(ast.readConfiguration(ConfigurationKeys.ACCESSORS_FLUENT)); fieldName = removePrefix(fieldName, prefix); if (fieldName == null) return null; String fName = fieldName.toString(); if (adhereToFluent && fluent) return fName; if (isBoolean && fName.startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { // The field is for example named 'isRunning'. return booleanPrefix + fName.substring(2); } return buildAccessorName(isBoolean ? booleanPrefix : normalPrefix, fName); } /** * Returns all names of methods that would represent the getter for a field with the provided name. * * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:
* {@code [isRunning, getRunning, isIsRunning, getIsRunning]} * * @param accessors Accessors configuration. * @param fieldName the name of the field. * @param isBoolean if the field is of type 'boolean'. For fields of type 'java.lang.Boolean', you should provide {@code false}. */ public static List toAllGetterNames(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { return toAllAccessorNames(ast, accessors, fieldName, isBoolean, "is", "get", true); } /** * Returns all names of methods that would represent the setter for a field with the provided name. * * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:
* {@code [setRunning, setIsRunning]} * * @param accessors Accessors configuration. * @param fieldName the name of the field. * @param isBoolean if the field is of type 'boolean'. For fields of type 'java.lang.Boolean', you should provide {@code false}. */ public static List toAllSetterNames(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { return toAllAccessorNames(ast, accessors, fieldName, isBoolean, "set", "set", true); } /** * Returns all names of methods that would represent the wither for a field with the provided name. * * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:
* {@code [withRunning, withIsRunning]} * * @param accessors Accessors configuration. * @param fieldName the name of the field. * @param isBoolean if the field is of type 'boolean'. For fields of type 'java.lang.Boolean', you should provide {@code false}. */ public static List toAllWitherNames(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { return toAllAccessorNames(ast, accessors, fieldName, isBoolean, "with", "with", false); } private static List toAllAccessorNames(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean, String booleanPrefix, String normalPrefix, boolean adhereToFluent) { if (Boolean.TRUE.equals(ast.readConfiguration(ConfigurationKeys.GETTER_CONSEQUENT_BOOLEAN))) isBoolean = false; if (!isBoolean) { String accessorName = toAccessorName(ast, accessors, fieldName, false, booleanPrefix, normalPrefix, adhereToFluent); return (accessorName == null) ? Collections.emptyList() : Collections.singletonList(accessorName); } boolean explicitPrefix = accessors != null && accessors.isExplicit("prefix"); boolean explicitFluent = accessors != null && accessors.isExplicit("fluent"); Accessors ac = (explicitPrefix || explicitFluent) ? accessors.getInstance() : null; List prefix = explicitPrefix ? Arrays.asList(ac.prefix()) : ast.readConfiguration(ConfigurationKeys.ACCESSORS_PREFIX); boolean fluent = explicitFluent ? ac.fluent() : Boolean.TRUE.equals(ast.readConfiguration(ConfigurationKeys.ACCESSORS_FLUENT)); fieldName = removePrefix(fieldName, prefix); if (fieldName == null) return Collections.emptyList(); List baseNames = toBaseNames(fieldName, isBoolean, fluent); Set names = new HashSet(); for (String baseName : baseNames) { if (adhereToFluent && fluent) { names.add(baseName); } else { names.add(buildAccessorName(normalPrefix, baseName)); if (!normalPrefix.equals(booleanPrefix)) names.add(buildAccessorName(booleanPrefix, baseName)); } } return new ArrayList(names); } private static List toBaseNames(CharSequence fieldName, boolean isBoolean, boolean fluent) { List baseNames = new ArrayList(); baseNames.add(fieldName.toString()); // isPrefix = field is called something like 'isRunning', so 'running' could also be the fieldname. String fName = fieldName.toString(); if (fName.startsWith("is") && fName.length() > 2 && !Character.isLowerCase(fName.charAt(2))) { String baseName = fName.substring(2); if (fluent) { baseNames.add("" + Character.toLowerCase(baseName.charAt(0)) + baseName.substring(1)); } else { baseNames.add(baseName); } } return baseNames; } /** * @param prefix Something like {@code get} or {@code set} or {@code is}. * @param suffix Something like {@code running}. * @return prefix + smartly title-cased suffix. For example, {@code setRunning}. */ public static String buildAccessorName(String prefix, String suffix) { if (suffix.length() == 0) return prefix; if (prefix.length() == 0) return suffix; char first = suffix.charAt(0); if (Character.isLowerCase(first)) { boolean useUpperCase = suffix.length() > 2 && (Character.isTitleCase(suffix.charAt(1)) || Character.isUpperCase(suffix.charAt(1))); suffix = String.format("%s%s", useUpperCase ? Character.toUpperCase(first) : Character.toTitleCase(first), suffix.subSequence(1, suffix.length())); } return String.format("%s%s", prefix, suffix); } } lombok-1.16.18/src/core/lombok/core/handlers/Singulars.java000066400000000000000000000063631312655740700235410ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.handlers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Singulars { private static final List SINGULAR_STORE; // intended to be immutable. static { SINGULAR_STORE = new ArrayList(); try { InputStream in = Singulars.class.getResourceAsStream("singulars.txt"); try { BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); for (String line = br.readLine(); line != null; line = br.readLine()) { line = line.trim(); if (line.startsWith("#") || line.isEmpty()) continue; if (line.endsWith(" =")) { SINGULAR_STORE.add(line.substring(0, line.length() - 2)); SINGULAR_STORE.add(""); continue; } int idx = line.indexOf(" = "); SINGULAR_STORE.add(line.substring(0, idx)); SINGULAR_STORE.add(line.substring(idx + 3)); } } finally { try { in.close(); } catch (Throwable ignore) {} } } catch (IOException e) { SINGULAR_STORE.clear(); } } public static String autoSingularize(String in) { final int inLen = in.length(); for (int i = 0; i < SINGULAR_STORE.size(); i+= 2) { final String lastPart = SINGULAR_STORE.get(i); final boolean wholeWord = Character.isUpperCase(lastPart.charAt(0)); final int endingOnly = lastPart.charAt(0) == '-' ? 1 : 0; final int len = lastPart.length(); if (inLen < len) continue; if (!in.regionMatches(true, inLen - len + endingOnly, lastPart, endingOnly, len - endingOnly)) continue; if (wholeWord && inLen != len && !Character.isUpperCase(in.charAt(inLen - len))) continue; String replacement = SINGULAR_STORE.get(i + 1); if (replacement.equals("!")) return null; boolean capitalizeFirst = !replacement.isEmpty() && Character.isUpperCase(in.charAt(inLen - len + endingOnly)); String pre = in.substring(0, inLen - len + endingOnly); String post = capitalizeFirst ? Character.toUpperCase(replacement.charAt(0)) + replacement.substring(1) : replacement; return pre + post; } return null; } } lombok-1.16.18/src/core/lombok/core/handlers/SneakyThrowsAndCleanupDependencyInfo.java000066400000000000000000000036471312655740700310030ustar00rootroot00000000000000/* * Copyright (C) 2009-2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.handlers; import java.util.Arrays; import java.util.List; import lombok.core.runtimeDependencies.RuntimeDependencyInfo; import org.mangosdk.spi.ProviderFor; @ProviderFor(RuntimeDependencyInfo.class) public class SneakyThrowsAndCleanupDependencyInfo implements RuntimeDependencyInfo { @Override public List getRuntimeDependencies() { return Arrays.asList( "lombok/Lombok.class" ); } @Override public List getRuntimeDependentsDescriptions() { return Arrays.asList( "@SneakyThrows (only when delomboking - using @SneakyThrows in code that is compiled with lombok on the classpath does not create the dependency)", "@Cleanup (only when delomboking - using @Cleanup in code that is compiled with lombok on the classpath does not create the dependency)" ); } } lombok-1.16.18/src/core/lombok/core/handlers/package-info.java000066400000000000000000000027471312655740700241200ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * This package contains utility methods and classes shared between javac-specific feature implementations * and eclipse-specific feature implementations. * * NB: This package is not public API in the sense that contents of this package, * even public classes / methods / etc, may change in point releases. */ package lombok.core.handlers; lombok-1.16.18/src/core/lombok/core/handlers/singulars.txt000066400000000000000000000021601312655740700234660ustar00rootroot00000000000000#Based on https://github.com/rails/rails/blob/efff6c1fd4b9e2e4c9f705a45879373cb34a5b0e/activesupport/lib/active_support/inflections.rb quizzes = quiz matrices = matrix indices = index vertices = vertex statuses = status aliases = alias alias = ! species = ! Axes = ! -axes = axe sexes = sex Testes = testis movies = movie octopodes = octopus buses = bus Mice = mouse Lice = louse News = ! # We could add more detail (axemen, boatsmen, boogymen, cavemen, gentlemen, etc, but (A) there's stuff like 'cerumen', and (B) the 'men' ending is common in singulars and other languages.) # Therefore, the odds of a mistake are too high, so other than these 2 well known cases, force the explicit singular. Men = man Women = woman minutiae = minutia shoes = shoe synopses = synopsis prognoses = prognosis theses = thesis diagnoses = diagnosis bases = base analyses = analysis Crises = crisis children = child moves = move zombies = zombie -quies = quy -us = ! -is = ! series = ! -ies = y -oes = o hives = hive -tives = tive -sses = ss -ches = ch -xes = x -shes = sh -lves = lf -rves = rf saves = save Leaves = leaf -ves = ! -ss = ! -us = ! -s = lombok-1.16.18/src/core/lombok/core/package-info.java000066400000000000000000000032421312655740700223070ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Contains the platform-agnostic core of lombok. * Includes the lombok AST superclasses, annotation introspection support, * an implementation of SPI service loader (to avoid being dependent on a v1.6 JVM), * lombok's version, and annotations and support classes for your normal java code * that's primarily useful for developing and debugging lombok. * * NB: This package is not public API in the sense that contents of this package, * even public classes / methods / etc, may change in point releases. */ package lombok.core; lombok-1.16.18/src/core/lombok/core/runtimeDependencies/000077500000000000000000000000001312655740700231115ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/core/runtimeDependencies/CreateLombokRuntimeApp.java000066400000000000000000000161711312655740700303360ustar00rootroot00000000000000/* * Copyright (C) 2009-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.runtimeDependencies; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import lombok.core.LombokApp; import lombok.core.SpiLoadUtil; import org.mangosdk.spi.ProviderFor; import com.zwitserloot.cmdreader.CmdReader; import com.zwitserloot.cmdreader.Description; import com.zwitserloot.cmdreader.InvalidCommandLineException; import com.zwitserloot.cmdreader.Mandatory; import com.zwitserloot.cmdreader.Requires; import com.zwitserloot.cmdreader.Shorthand; @ProviderFor(LombokApp.class) public class CreateLombokRuntimeApp extends LombokApp { private List infoObjects; @Override public String getAppName() { return "createRuntime"; } @Override public String getAppDescription() { return "Creates a small lombok-runtime.jar with the runtime\n" + "dependencies of all lombok transformations that have them,\n" + "and prints the names of each lombok transformation that\n" + "requires the lombok-runtime.jar at runtime."; } @Override public List getAppAliases() { return Arrays.asList("runtime"); } private static class CmdArgs { @Shorthand("p") @Description("Prints those lombok transformations that require lombok-runtime.jar.") @Mandatory(onlyIfNot="create") boolean print; @Shorthand("c") @Description("Creates the lombok-runtime.jar.") @Mandatory(onlyIfNot="print") boolean create; @Shorthand("o") @Description("Where to write the lombok-runtime.jar. Defaults to the current working directory.") @Requires("create") String output; @Description("Shows this help text") boolean help; } @Override public int runApp(List rawArgs) throws Exception { CmdReader reader = CmdReader.of(CmdArgs.class); CmdArgs args; try { args = reader.make(rawArgs.toArray(new String[0])); } catch (InvalidCommandLineException e) { printHelp(reader, e.getMessage(), System.err); return 1; } if (args.help) { printHelp(reader, null, System.out); return 0; } initializeInfoObjects(); if (args.print) { printRuntimeDependents(); } int errCode = 0; if (args.create) { File out = new File("./lombok-runtime.jar"); if (args.output != null) { out = new File(args.output); if (out.isDirectory()) out = new File(out, "lombok-runtime.jar"); } try { errCode = writeRuntimeJar(out); } catch (Exception e) { System.err.println("ERROR: Creating " + canonical(out) + " failed: "); e.printStackTrace(); return 1; } } return errCode; } private void printRuntimeDependents() { List descriptions = new ArrayList(); for (RuntimeDependencyInfo info : infoObjects) descriptions.addAll(info.getRuntimeDependentsDescriptions()); if (descriptions.isEmpty()) { System.out.println("Not printing dependents: No lombok transformations currently have any runtime dependencies!"); } else { System.out.println("Using any of these lombok features means your app will need lombok-runtime.jar:"); for (String desc : descriptions) { System.out.println(desc); } } } private int writeRuntimeJar(File outFile) throws Exception { Map> deps = new LinkedHashMap>(); for (RuntimeDependencyInfo info : infoObjects) { List depNames = info.getRuntimeDependencies(); if (depNames != null) for (String depName : depNames) { if (!deps.containsKey(depName)) deps.put(depName, info.getClass()); } } if (deps.isEmpty()) { System.out.println("Not generating lombok-runtime.jar: No lombok transformations currently have any runtime dependencies!"); return 1; } OutputStream out = new FileOutputStream(outFile); boolean success = false; try { JarOutputStream jar = new JarOutputStream(out); deps.put("LICENSE", CreateLombokRuntimeApp.class); deps.put("AUTHORS", CreateLombokRuntimeApp.class); for (Entry> dep : deps.entrySet()) { InputStream in = dep.getValue().getResourceAsStream("/" + dep.getKey()); try { if (in == null) { throw new Fail(String.format("Dependency %s contributed by %s cannot be found", dep.getKey(), dep.getValue())); } writeIntoJar(jar, dep.getKey(), in); } finally { if (in != null) in.close(); } } jar.close(); out.close(); System.out.println("Successfully created: " + canonical(outFile)); return 0; } catch (Throwable t) { try { out.close();} catch (Throwable ignore) {} if (!success) outFile.delete(); if (t instanceof Fail) { System.err.println(t.getMessage()); return 1; } else if (t instanceof Exception) { throw (Exception)t; } else if (t instanceof Error) { throw (Error)t; } else { throw new Exception(t); } } } private void writeIntoJar(JarOutputStream jar, String depName, InputStream in) throws IOException { jar.putNextEntry(new ZipEntry(depName)); byte[] b = new byte[65536]; while (true) { int r = in.read(b); if (r == -1) break; jar.write(b, 0, r); } jar.closeEntry(); in.close(); } private static class Fail extends Exception { Fail(String message) { super(message); } } private void initializeInfoObjects() throws IOException { infoObjects = SpiLoadUtil.readAllFromIterator( SpiLoadUtil.findServices(RuntimeDependencyInfo.class)); } private static String canonical(File out) { try { return out.getCanonicalPath(); } catch (Exception e) { return out.getAbsolutePath(); } } private void printHelp(CmdReader reader, String message, PrintStream out) { if (message != null) { out.println(message); out.println("----------------------------"); } out.println(reader.generateCommandLineHelp("java -jar lombok.jar createRuntime")); } } lombok-1.16.18/src/core/lombok/core/runtimeDependencies/RuntimeDependencyInfo.java000066400000000000000000000034561312655740700302220ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.runtimeDependencies; import java.util.List; /** * Implement and provide this interface to specify which transformations have a runtime dependency on * {@code lombok-runtime.jar}, as well as which files of your transformation must be in {@code lombok-runtime.jar}. */ public interface RuntimeDependencyInfo { /** * @return A list of strings describing each lombok transformation that has a runtime dependency. */ public List getRuntimeDependentsDescriptions(); /** * @return A list of files (findable via {@code yourClass.getResourceAsStream("/" + NAME)}) to include in * {@code lombok-runtime.jar}. */ public List getRuntimeDependencies(); } lombok-1.16.18/src/core/lombok/core/runtimeDependencies/package-info.java000066400000000000000000000034021312655740700262770ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * This package is the basis for lombok's (the jar, run as an application) ability to spin off * a clone of itself that only contains files required as a runtime dependency. * * This feature was used for a short while to support {@code @SneakyThrows}, but this is no longer * necessary. Currently no lombok features have any such dependencies though at some point we may * reintroduce the concept, for example to support properties. * * It is possible we'll use a different mechanism at that point; use the infrastructure in this package * with knowledge that it may be eliminated at any time. */ package lombok.core.runtimeDependencies; lombok-1.16.18/src/core/lombok/eclipse/000077500000000000000000000000001312655740700176135ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/eclipse/DeferUntilPostDiet.java000066400000000000000000000034101312655740700241710ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Mark a handler class with this annotation to indicate that this handler should not be run in the diet parse phase. * 'diet parse' is where method bodies aren't filled in yet. If you have a method-level annotation that modifies the contents of that method, * you need to put this annotation on your handler. Otherwise, do not put this annotation on your handler. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DeferUntilPostDiet { } lombok-1.16.18/src/core/lombok/eclipse/EclipseAST.java000066400000000000000000000543651312655740700224270ustar00rootroot00000000000000/* * Copyright (C) 2009-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.Lombok; import lombok.core.AST; import lombok.core.LombokImmutableList; import lombok.eclipse.handlers.EclipseHandlerUtil; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.ImportReference; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; /** * Wraps around Eclipse's internal AST view to add useful features as well as the ability to visit parents from children, * something Eclipse own AST system does not offer. */ public class EclipseAST extends AST { /** * Creates a new EclipseAST of the provided Compilation Unit. * * @param ast The compilation unit, which serves as the top level node in the tree to be built. */ public EclipseAST(CompilationUnitDeclaration ast) { super(toFileName(ast), packageDeclaration(ast), new EclipseImportList(ast), statementTypes()); this.compilationUnitDeclaration = ast; setTop(buildCompilationUnit(ast)); this.completeParse = isComplete(ast); clearChanged(); } private static volatile boolean skipEclipseWorkspaceBasedFileResolver = false; private static final URI NOT_CALCULATED_MARKER = URI.create("https://projectlombok.org/not/calculated"); private URI memoizedAbsoluteFileLocation = NOT_CALCULATED_MARKER; public URI getAbsoluteFileLocation() { if (memoizedAbsoluteFileLocation != NOT_CALCULATED_MARKER) return memoizedAbsoluteFileLocation; memoizedAbsoluteFileLocation = getAbsoluteFileLocation0(); return memoizedAbsoluteFileLocation; } /** This is the call, but we wrapped it to memoize this. */ private URI getAbsoluteFileLocation0() { String fileName = getFileName(); if (fileName != null && (fileName.startsWith("file:") || fileName.startsWith("sourcecontrol:"))) { // Some exotic build systems get real fancy with filenames. Known culprits: // The 'jazz' source control system _probably_ (not confirmed yet) uses sourcecontrol://jazz: urls. // GWT puts file:/D:/etc/etc/etc/Foo.java in here. return URI.create(fileName); } // state of the research in this: // * We need an abstraction of a 'directory level'. This abstraction needs 'read()' which returns a string (content of lombok.config) and 'getParent()'. // * sometimes, cud.compilationResult.compilationUnit is an 'openable', you can chase this down to end up with a path, you can jigger this into being the sibling 'lombok.config', and then use: // InputStream in = ResourcesPlugin.getWorkspace().getRoot().getFile(ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(x)).getFullPath()).getContents(true); // to read out this data. Our theory is that this will work even with very crazy virtual filesystems such as sourcecontrol://jazz/blabla. // * With jazz and other creative file backed systems, is there even a 'project root' concept? Surely there won't be a 'workspace root' concept so how do we abstract the idea that, from jazz://whatever/projectroot, the parent is c:\myWorkspace? // * Check the .getAlternateAbsolutePath() impl which has the research done so far. // * VIRTUAL FILES: Sometimes virtual files are created; their location tends to be /FileName.java which cannot be resolved. Optimally speaking we should find the 'source' of the virtual code and use IT for determining lombok.config, but that may not be feasible. If not, can we get at project or at least workspace? // * Either way there are sufficiently many WTF situations, that in case of error, as painful as this is, we should just carry on and not apply lombok.config, though at least if we don't recognize the scenario we should write a log file imploring the user to send us a bunch of feedback on the situation. // Relevant issues: Comment 2 on #683, all of #682 if (!skipEclipseWorkspaceBasedFileResolver) { // if (Boolean.FALSE) throw new IllegalArgumentException("Here's the alt strat result: " + getAlternativeAbsolutePathDEBUG()); try { /*if (fileName.startsWith("/") && fileName.indexOf('/', 1) > -1) */ try { return EclipseWorkspaceBasedFileResolver.resolve(fileName); } catch (IllegalArgumentException e) { EclipseHandlerUtil.warning("Finding 'lombok.config' file failed for '" + fileName + "'", e); // String msg = e.getMessage(); // if (msg != null && msg.startsWith("Path must include project and resource name")) { // // We shouldn't throw an exception at all, but we can't reproduce this so we need help from our users to figure this out. // // Let's bother them with an error that slows their eclipse down to a crawl and makes it unusable. // throw new IllegalArgumentException("Path resolution for lombok.config failed. Path: " + fileName + " -- package of this class: " + this.getPackageDeclaration()); // } else throw e; } } catch (NoClassDefFoundError e) { skipEclipseWorkspaceBasedFileResolver = true; } } // Our fancy workspace based source file to absolute disk location algorithm only works in a fully fledged eclipse. // This fallback works when using 'ecj', which has a much simpler project/path system. For example, no 'linked' resources. try { return new File(fileName).getAbsoluteFile().toURI(); } catch (Exception e) { // This is a temporary workaround while we try and gather all the various exotic shenanigans where lombok.config resolution is not going to work! return null; } } // /** This is ongoing research for issues with lombok.config resolution. */ // @SuppressWarnings("unused") private String getAlternativeAbsolutePathDEBUG() { // try { // ICompilationUnit cu = this.compilationUnitDeclaration.compilationResult.compilationUnit; // // if (cu instanceof Openable) { // String x = ((Openable) cu).getResource().getFullPath().makeAbsolute().toString(); // int lastLoc = x.lastIndexOf('/'); // x = x.substring(0, lastLoc + 1) + "lombok.config"; // URI lombokConfigLoc = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(x)).getLocationURI(); // InputStream in = ResourcesPlugin.getWorkspace().getRoot().getFile(ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(x)).getFullPath()).getContents(true); // byte[] b = new byte[100000]; // int p = 0; // while (true) { // int r = in.read(b, p, b.length - p); // if (r == -1) break; // p += r; // } // in.close(); // return "(Contents of lombok.config: " + new String(b, 0, p, "UTF-8"); // //// return "(alt strategy result C: '" + ((Openable) cu).getResource().getFullPath().makeAbsolute().toString() + "'): resolved: " + EclipseWorkspaceBasedFileResolver.resolve(((Openable) cu).getResource().getFullPath().makeAbsolute().toString()); // } // if (cu instanceof SourceFile) { // String cuFileName = new String(((SourceFile) cu).getFileName()); // String cuIFilePath = ((SourceFile) cu).resource.getFullPath().toString(); // return "(alt strategy result A: \"" + cuFileName + "\" B: \"" + cuIFilePath + "\")"; // } // return "(alt strategy failed: cu isn't a SourceFile or Openable but a " + cu.getClass() + ")"; // } catch (Exception e) { // return "(alt strategy failed: " + e + ")"; // } // } private static class EclipseWorkspaceBasedFileResolver { public static URI resolve(String path) { /* eclipse issue: When creating snippets, for example to calculate 'find callers', refactor scripts, save actions, etc, * eclipse creates a psuedo-file whose path is simply "/SimpleName.java", which cannot be turned back into a real location. * What we really need to do is find out which file is the source of this script job and use its directory instead. For now, * we just go with all defaults; these operations are often not sensitive to proper lomboking or aren't even lomboked at all. * * Reliable way to reproduce this (Kepler, possibly with JDK8 beta support): * * Have a method, called once by some code in another class. * * Refactor it with the 'change method signature' refactor script, and add a parameter and hit 'ok'. */ if (path == null || path.indexOf('/', 1) == -1) { return null; } try { return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path)).getLocationURI(); } catch (Exception e) { // One of the exceptions that can occur is IllegalStateException (during getWorkspace()) // if you try to run this while eclipse is shutting down. return null; } } } private static String packageDeclaration(CompilationUnitDeclaration cud) { ImportReference pkg = cud.currentPackage; return pkg == null ? null : Eclipse.toQualifiedName(pkg.getImportName()); } @Override public int getSourceVersion() { long sl = compilationUnitDeclaration.problemReporter.options.sourceLevel; long cl = compilationUnitDeclaration.problemReporter.options.complianceLevel; sl >>= 16; cl >>= 16; if (sl == 0) sl = cl; if (cl == 0) cl = sl; return Math.min((int)(sl - 44), (int)(cl - 44)); } @Override public int getLatestJavaSpecSupported() { return Eclipse.getEcjCompilerVersion(); } /** * Runs through the entire AST, starting at the compilation unit, calling the provided visitor's visit methods * for each node, depth first. */ public void traverse(EclipseASTVisitor visitor) { top().traverse(visitor); } void traverseChildren(EclipseASTVisitor visitor, EclipseNode node) { LombokImmutableList children = node.down(); int len = children.size(); for (int i = 0; i < len; i++) { children.get(i).traverse(visitor); } } /** * Eclipse starts off with a 'diet' parse which leaves method bodies blank, amongst other shortcuts. * * For such diet parses, this method returns false, otherwise it returns true. Any lombok processor * that needs the contents of methods should just do nothing (and return false so it gets another shot later!) * when this is false. */ public boolean isCompleteParse() { return completeParse; } class ParseProblem { final boolean isWarning; final String message; final int sourceStart; final int sourceEnd; ParseProblem(boolean isWarning, String message, int sourceStart, int sourceEnd) { this.isWarning = isWarning; this.message = message; this.sourceStart = sourceStart; this.sourceEnd = sourceEnd; } void addToCompilationResult() { CompilationUnitDeclaration cud = (CompilationUnitDeclaration) top().get(); addProblemToCompilationResult(cud.getFileName(), cud.compilationResult, isWarning, message, sourceStart, sourceEnd); } } private void propagateProblems() { if (queuedProblems.isEmpty()) return; CompilationUnitDeclaration cud = (CompilationUnitDeclaration) top().get(); if (cud.compilationResult == null) return; for (ParseProblem problem : queuedProblems) problem.addToCompilationResult(); queuedProblems.clear(); } private final List queuedProblems = new ArrayList(); void addProblem(ParseProblem problem) { queuedProblems.add(problem); propagateProblems(); } /** * Adds a problem to the provided CompilationResult object so that it will show up * in the Problems/Warnings view. */ public static void addProblemToCompilationResult(char[] fileNameArray, CompilationResult result, boolean isWarning, String message, int sourceStart, int sourceEnd) { try { EcjReflectionCheck.addProblemToCompilationResult.invoke(null, fileNameArray, result, isWarning, message, sourceStart, sourceEnd); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(EcjReflectionCheck.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } } private final CompilationUnitDeclaration compilationUnitDeclaration; private boolean completeParse; private static String toFileName(CompilationUnitDeclaration ast) { return ast.compilationResult.fileName == null ? null : new String(ast.compilationResult.fileName); } /** * Call this method to move an EclipseAST generated for a diet parse to rebuild itself for the full parse - * with filled in method bodies and such. Also propagates problems and errors, which in diet parse * mode can't be reliably added to the problems/warnings view. */ public void rebuild(boolean force) { propagateProblems(); if (completeParse && !force) return; boolean changed = isChanged(); boolean newCompleteParse = isComplete(compilationUnitDeclaration); if (!newCompleteParse && !force) return; top().rebuild(); this.completeParse = newCompleteParse; if (!changed) clearChanged(); } private static boolean isComplete(CompilationUnitDeclaration unit) { return (unit.bits & ASTNode.HasAllMethodBodies) != 0; } /** {@inheritDoc} */ @Override protected EclipseNode buildTree(ASTNode node, Kind kind) { switch (kind) { case COMPILATION_UNIT: return buildCompilationUnit((CompilationUnitDeclaration) node); case TYPE: return buildType((TypeDeclaration) node); case FIELD: return buildField((FieldDeclaration) node); case INITIALIZER: return buildInitializer((Initializer) node); case METHOD: return buildMethod((AbstractMethodDeclaration) node); case ARGUMENT: return buildLocal((Argument) node, kind); case LOCAL: return buildLocal((LocalDeclaration) node, kind); case STATEMENT: return buildStatement((Statement) node); case ANNOTATION: return buildAnnotation((Annotation) node, false); default: throw new AssertionError("Did not expect to arrive here: " + kind); } } private EclipseNode buildCompilationUnit(CompilationUnitDeclaration top) { if (setAndGetAsHandled(top)) return null; List children = buildTypes(top.types); return putInMap(new EclipseNode(this, top, children, Kind.COMPILATION_UNIT)); } private void addIfNotNull(Collection collection, EclipseNode n) { if (n != null) collection.add(n); } private List buildTypes(TypeDeclaration[] children) { List childNodes = new ArrayList(); if (children != null) for (TypeDeclaration type : children) addIfNotNull(childNodes, buildType(type)); return childNodes; } private EclipseNode buildType(TypeDeclaration type) { if (setAndGetAsHandled(type)) return null; List childNodes = new ArrayList(); childNodes.addAll(buildFields(type.fields)); childNodes.addAll(buildTypes(type.memberTypes)); childNodes.addAll(buildMethods(type.methods)); childNodes.addAll(buildAnnotations(type.annotations, false)); return putInMap(new EclipseNode(this, type, childNodes, Kind.TYPE)); } private Collection buildFields(FieldDeclaration[] children) { List childNodes = new ArrayList(); if (children != null) for (FieldDeclaration child : children) addIfNotNull(childNodes, buildField(child)); return childNodes; } private static List singleton(T item) { List list = new ArrayList(); if (item != null) list.add(item); return list; } private EclipseNode buildField(FieldDeclaration field) { if (field instanceof Initializer) return buildInitializer((Initializer)field); if (setAndGetAsHandled(field)) return null; List childNodes = new ArrayList(); addIfNotNull(childNodes, buildStatement(field.initialization)); childNodes.addAll(buildAnnotations(field.annotations, true)); return putInMap(new EclipseNode(this, field, childNodes, Kind.FIELD)); } private EclipseNode buildInitializer(Initializer initializer) { if (setAndGetAsHandled(initializer)) return null; return putInMap(new EclipseNode(this, initializer, singleton(buildStatement(initializer.block)), Kind.INITIALIZER)); } private Collection buildMethods(AbstractMethodDeclaration[] children) { List childNodes = new ArrayList(); if (children != null) for (AbstractMethodDeclaration method : children) addIfNotNull(childNodes, buildMethod(method)); return childNodes; } private EclipseNode buildMethod(AbstractMethodDeclaration method) { if (setAndGetAsHandled(method)) return null; List childNodes = new ArrayList(); childNodes.addAll(buildArguments(method.arguments)); if (method instanceof ConstructorDeclaration) { ConstructorDeclaration constructor = (ConstructorDeclaration) method; addIfNotNull(childNodes, buildStatement(constructor.constructorCall)); } childNodes.addAll(buildStatements(method.statements)); childNodes.addAll(buildAnnotations(method.annotations, false)); return putInMap(new EclipseNode(this, method, childNodes, Kind.METHOD)); } //Arguments are a kind of LocalDeclaration. They can definitely contain lombok annotations, so we care about them. private Collection buildArguments(Argument[] children) { List childNodes = new ArrayList(); if (children != null) for (LocalDeclaration local : children) { addIfNotNull(childNodes, buildLocal(local, Kind.ARGUMENT)); } return childNodes; } private EclipseNode buildLocal(LocalDeclaration local, Kind kind) { if (setAndGetAsHandled(local)) return null; List childNodes = new ArrayList(); addIfNotNull(childNodes, buildStatement(local.initialization)); childNodes.addAll(buildAnnotations(local.annotations, true)); return putInMap(new EclipseNode(this, local, childNodes, kind)); } private Collection buildAnnotations(Annotation[] annotations, boolean varDecl) { List elements = new ArrayList(); if (annotations != null) for (Annotation an : annotations) addIfNotNull(elements, buildAnnotation(an, varDecl)); return elements; } private EclipseNode buildAnnotation(Annotation annotation, boolean field) { if (annotation == null) return null; boolean handled = setAndGetAsHandled(annotation); if (!field && handled) { // @Foo int x, y; is handled in eclipse by putting the same annotation node on 2 FieldDeclarations. return null; } return putInMap(new EclipseNode(this, annotation, null, Kind.ANNOTATION)); } private Collection buildStatements(Statement[] children) { List childNodes = new ArrayList(); if (children != null) for (Statement child : children) addIfNotNull(childNodes, buildStatement(child)); return childNodes; } private EclipseNode buildStatement(Statement child) { if (child == null) return null; if (child instanceof TypeDeclaration) return buildType((TypeDeclaration)child); if (child instanceof LocalDeclaration) return buildLocal((LocalDeclaration)child, Kind.LOCAL); if (setAndGetAsHandled(child)) return null; return drill(child); } private EclipseNode drill(Statement statement) { List childNodes = new ArrayList(); for (FieldAccess fa : fieldsOf(statement.getClass())) childNodes.addAll(buildWithField(EclipseNode.class, statement, fa)); return putInMap(new EclipseNode(this, statement, childNodes, Kind.STATEMENT)); } /* For Eclipse, only Statement counts, as Expression is a subclass of it, even though this isn't * entirely correct according to the JLS spec (only some expressions can be used as statements, not all of them). */ private static Collection> statementTypes() { return Collections.>singleton(Statement.class); } private static class EcjReflectionCheck { private static final String COMPILATIONRESULT_TYPE = "org.eclipse.jdt.internal.compiler.CompilationResult"; public static Method addProblemToCompilationResult; public static final Throwable problem; static { Throwable problem_ = null; Method m = null; try { m = EclipseAstProblemView.class.getMethod("addProblemToCompilationResult", char[].class, Class.forName(COMPILATIONRESULT_TYPE), boolean.class, String.class, int.class, int.class); } catch (Throwable t) { // That's problematic, but as long as no local classes are used we don't actually need it. // Better fail on local classes than crash altogether. problem_ = t; } addProblemToCompilationResult = m; problem = problem_; } } } lombok-1.16.18/src/core/lombok/eclipse/EclipseASTAdapter.java000066400000000000000000000105271312655740700237200ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; /** * Standard adapter for the {@link EclipseASTVisitor} interface. Every method on that interface * has been implemented with an empty body. Override whichever methods you need. */ public abstract class EclipseASTAdapter implements EclipseASTVisitor { /** {@inheritDoc} */ public void visitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit) {} /** {@inheritDoc} */ public void endVisitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit) {} /** {@inheritDoc} */ public void visitType(EclipseNode typeNode, TypeDeclaration type) {} /** {@inheritDoc} */ public void visitAnnotationOnType(TypeDeclaration type, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitType(EclipseNode typeNode, TypeDeclaration type) {} /** {@inheritDoc} */ public void visitInitializer(EclipseNode initializerNode, Initializer initializer) {} /** {@inheritDoc} */ public void endVisitInitializer(EclipseNode initializerNode, Initializer initializer) {} /** {@inheritDoc} */ public void visitField(EclipseNode fieldNode, FieldDeclaration field) {} /** {@inheritDoc} */ public void visitAnnotationOnField(FieldDeclaration field, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitField(EclipseNode fieldNode, FieldDeclaration field) {} /** {@inheritDoc} */ public void visitMethod(EclipseNode methodNode, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitMethod(EclipseNode methodNode, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ public void visitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ public void visitLocal(EclipseNode localNode, LocalDeclaration local) {} /** {@inheritDoc} */ public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ public void endVisitLocal(EclipseNode localNode, LocalDeclaration local) {} /** {@inheritDoc} */ public void visitStatement(EclipseNode statementNode, Statement statement) {} /** {@inheritDoc} */ public void endVisitStatement(EclipseNode statementNode, Statement statement) {} } lombok-1.16.18/src/core/lombok/eclipse/EclipseASTVisitor.java000066400000000000000000000316231312655740700237770ustar00rootroot00000000000000/* * Copyright (C) 2009-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.io.PrintStream; import java.lang.reflect.Modifier; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; /** * Implement so you can ask any EclipseAST.Node to traverse depth-first through all children, * calling the appropriate visit and endVisit methods. */ public interface EclipseASTVisitor { /** * Called at the very beginning and end. */ void visitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit); void endVisitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit); /** * Called when visiting a type (a class, interface, annotation, enum, etcetera). */ void visitType(EclipseNode typeNode, TypeDeclaration type); void visitAnnotationOnType(TypeDeclaration type, EclipseNode annotationNode, Annotation annotation); void endVisitType(EclipseNode typeNode, TypeDeclaration type); /** * Called when visiting a field of a class. * Even though in Eclipse initializers (both instance and static) are represented as Initializer objects, * which are a subclass of FieldDeclaration, those do NOT result in a call to this method. They result * in a call to the visitInitializer method. */ void visitField(EclipseNode fieldNode, FieldDeclaration field); void visitAnnotationOnField(FieldDeclaration field, EclipseNode annotationNode, Annotation annotation); void endVisitField(EclipseNode fieldNode, FieldDeclaration field); /** * Called for static and instance initializers. You can tell the difference via the modifier flag on the * ASTNode (8 for static, 0 for not static). The content is in the 'block', not in the 'initialization', * which would always be null for an initializer instance. */ void visitInitializer(EclipseNode initializerNode, Initializer initializer); void endVisitInitializer(EclipseNode initializerNode, Initializer initializer); /** * Called for both methods (MethodDeclaration) and constructors (ConstructorDeclaration), but not for * Clinit objects, which are a vestigial Eclipse thing that never contain anything. Static initializers * show up as 'Initializer', in the visitInitializer method, with modifier bit STATIC set. */ void visitMethod(EclipseNode methodNode, AbstractMethodDeclaration method); void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation); void endVisitMethod(EclipseNode methodNode, AbstractMethodDeclaration method); /** * Visits a method argument */ void visitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method); void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation); void endVisitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method); /** * Visits a local declaration - that is, something like 'int x = 10;' on the method level. */ void visitLocal(EclipseNode localNode, LocalDeclaration local); void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode annotationNode, Annotation annotation); void endVisitLocal(EclipseNode localNode, LocalDeclaration local); /** * Visits a statement that isn't any of the other visit methods (e.g. TypeDeclaration). */ void visitStatement(EclipseNode statementNode, Statement statement); void endVisitStatement(EclipseNode statementNode, Statement statement); /** * Prints the structure of an AST. */ public static class Printer implements EclipseASTVisitor { private final PrintStream out; private final boolean printContent; private int disablePrinting = 0; private int indent = 0; private boolean printClassNames = false; private final boolean printPositions; public boolean deferUntilPostDiet() { return false; } /** * @param printContent if true, bodies are printed directly, as java code, * instead of a tree listing of every AST node inside it. */ public Printer(boolean printContent) { this(printContent, System.out, false); } /** * @param printContent if true, bodies are printed directly, as java code, * instead of a tree listing of every AST node inside it. * @param out write output to this stream. You must close it yourself. flush() is called after every line. * * @see java.io.PrintStream#flush() */ public Printer(boolean printContent, PrintStream out, boolean printPositions) { this.printContent = printContent; this.out = out; this.printPositions = printPositions; } private void forcePrint(String text, Object... params) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; i++) sb.append(" "); sb.append(text); Object[] t; if (printClassNames && params.length > 0) { sb.append(" ["); for (int i = 0; i < params.length; i++) { if (i > 0) sb.append(", "); sb.append("%s"); } sb.append("]"); t = new Object[params.length + params.length]; for (int i = 0; i < params.length; i++) { t[i] = params[i]; t[i + params.length] = (params[i] == null) ? "NULL " : params[i].getClass(); } } else { t = params; } sb.append("\n"); out.printf(sb.toString(), t); out.flush(); } private void print(String text, Object... params) { if (disablePrinting == 0) forcePrint(text, params); } private String str(char[] c) { if (c == null) return "(NULL)"; return new String(c); } private String str(TypeReference type) { if (type == null) return "(NULL)"; char[][] c = type.getTypeName(); StringBuilder sb = new StringBuilder(); boolean first = true; for (char[] d : c) { sb.append(first ? "" : ".").append(new String(d)); first = false; } return sb.toString(); } public void visitCompilationUnit(EclipseNode node, CompilationUnitDeclaration unit) { out.println("---------------------------------------------------------"); out.println(node.isCompleteParse() ? "COMPLETE" : "incomplete"); print("", node.getFileName(), isGenerated(unit) ? " (GENERATED)" : "", position(node)); indent++; } public void endVisitCompilationUnit(EclipseNode node, CompilationUnitDeclaration unit) { indent--; print(""); } public void visitType(EclipseNode node, TypeDeclaration type) { print("", str(type.name), isGenerated(type) ? " (GENERATED)" : "", position(node)); indent++; if (printContent) { print("%s", type); disablePrinting++; } } public void visitAnnotationOnType(TypeDeclaration type, EclipseNode node, Annotation annotation) { forcePrint("", isGenerated(annotation) ? " (GENERATED)" : "", annotation, position(node)); } public void endVisitType(EclipseNode node, TypeDeclaration type) { if (printContent) disablePrinting--; indent--; print("", str(type.name)); } public void visitInitializer(EclipseNode node, Initializer initializer) { Block block = initializer.block; boolean s = (block != null && block.statements != null); print("<%s INITIALIZER: %s%s%s>", (initializer.modifiers & Modifier.STATIC) != 0 ? "static" : "instance", s ? "filled" : "blank", isGenerated(initializer) ? " (GENERATED)" : "", position(node)); indent++; if (printContent) { if (initializer.block != null) print("%s", initializer.block); disablePrinting++; } } public void endVisitInitializer(EclipseNode node, Initializer initializer) { if (printContent) disablePrinting--; indent--; print("", (initializer.modifiers & Modifier.STATIC) != 0 ? "static" : "instance"); } public void visitField(EclipseNode node, FieldDeclaration field) { print("", isGenerated(field) ? " (GENERATED)" : "", str(field.type), str(field.name), field.initialization, position(node)); indent++; if (printContent) { if (field.initialization != null) print("%s", field.initialization); disablePrinting++; } } public void visitAnnotationOnField(FieldDeclaration field, EclipseNode node, Annotation annotation) { forcePrint("", isGenerated(annotation) ? " (GENERATED)" : "", annotation, position(node)); } public void endVisitField(EclipseNode node, FieldDeclaration field) { if (printContent) disablePrinting--; indent--; print("", str(field.type), str(field.name)); } public void visitMethod(EclipseNode node, AbstractMethodDeclaration method) { String type = method instanceof ConstructorDeclaration ? "CONSTRUCTOR" : "METHOD"; print("<%s %s: %s%s%s>", type, str(method.selector), method.statements != null ? "filled" : "blank", isGenerated(method) ? " (GENERATED)" : "", position(node)); indent++; if (printContent) { if (method.statements != null) print("%s", method); disablePrinting++; } } public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode node, Annotation annotation) { forcePrint("", isGenerated(method) ? " (GENERATED)" : "", annotation, position(node)); } public void endVisitMethod(EclipseNode node, AbstractMethodDeclaration method) { if (printContent) disablePrinting--; String type = method instanceof ConstructorDeclaration ? "CONSTRUCTOR" : "METHOD"; indent--; print("", type, str(method.selector)); } public void visitMethodArgument(EclipseNode node, Argument arg, AbstractMethodDeclaration method) { print("", isGenerated(arg) ? " (GENERATED)" : "", str(arg.type), str(arg.name), arg.initialization, position(node)); indent++; } public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode node, Annotation annotation) { print("", isGenerated(annotation) ? " (GENERATED)" : "", annotation, position(node)); } public void endVisitMethodArgument(EclipseNode node, Argument arg, AbstractMethodDeclaration method) { indent--; print("", str(arg.type), str(arg.name)); } public void visitLocal(EclipseNode node, LocalDeclaration local) { print("", isGenerated(local) ? " (GENERATED)" : "", str(local.type), str(local.name), local.initialization, position(node)); indent++; } public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode node, Annotation annotation) { print("", isGenerated(annotation) ? " (GENERATED)" : "", annotation); } public void endVisitLocal(EclipseNode node, LocalDeclaration local) { indent--; print("", str(local.type), str(local.name)); } public void visitStatement(EclipseNode node, Statement statement) { print("<%s%s%s>", statement.getClass(), isGenerated(statement) ? " (GENERATED)" : "", position(node)); indent++; print("%s", statement); } public void endVisitStatement(EclipseNode node, Statement statement) { indent--; print("", statement.getClass()); } String position(EclipseNode node) { if (!printPositions) return ""; int start = node.get().sourceStart(); int end = node.get().sourceEnd(); return String.format(" [%d, %d]", start, end); } } } lombok-1.16.18/src/core/lombok/eclipse/EclipseAnnotationHandler.java000066400000000000000000000075211312655740700254000ustar00rootroot00000000000000/* * Copyright (C) 2009-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import lombok.core.AnnotationValues; import lombok.core.SpiLoadUtil; /** * Implement this interface if you want to be triggered for a specific annotation. * * You MUST replace 'T' with a specific annotation type, such as: * * {@code public class HandleGetter extends EclipseAnnotationHandler} * * Because this generics parameter is inspected to figure out which class you're interested in. * * You also need to register yourself via SPI discovery as being an implementation of {@code EclipseAnnotationHandler}. */ public abstract class EclipseAnnotationHandler { /** * Called when an annotation is found that is likely to match the annotation you're interested in. * * Be aware that you'll be called for ANY annotation node in the source that looks like a match. There is, * for example, no guarantee that the annotation node belongs to a method, even if you set your * TargetType in the annotation to methods only. * * @param annotation The actual annotation - use this object to retrieve the annotation parameters. * @param ast The Eclipse AST node representing the annotation. * @param annotationNode The Lombok AST wrapper around the 'ast' parameter. You can use this object * to travel back up the chain (something javac AST can't do) to the parent of the annotation, as well * as access useful methods such as generating warnings or errors focused on the annotation. */ public abstract void handle(AnnotationValues annotation, org.eclipse.jdt.internal.compiler.ast.Annotation ast, EclipseNode annotationNode); /** * Called when you want to defer until post diet, and we're still in pre-diet. May be called not at all or multiple times, so make sure * this method is idempotent if run more than once, and whatever you do here should also be done in the main 'handle' method. * * NB: This method exists because in certain cases, within eclipse, you have to create i.e. a field before referencing it in generated code. You still * have to create the field, if its not already there, in 'handle', because for example preHandle would never even be called in ecj mode. */ public void preHandle(AnnotationValues annotation, org.eclipse.jdt.internal.compiler.ast.Annotation ast, EclipseNode annotationNode) { } /** * This handler is a handler for the given annotation; you don't normally need to override this class * as the annotation type is extracted from your {@code extends EclipseAnnotationHandler} * signature. */ @SuppressWarnings("unchecked") public Class getAnnotationHandledByThisHandler() { return (Class) SpiLoadUtil.findAnnotationClass(getClass(), EclipseAnnotationHandler.class); } } lombok-1.16.18/src/core/lombok/eclipse/EclipseAstProblemView.java000066400000000000000000000037361312655740700246770ustar00rootroot00000000000000package lombok.eclipse; import org.eclipse.jdt.core.compiler.CategorizedProblem; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.problem.DefaultProblem; import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities; import org.eclipse.jdt.internal.compiler.util.Util; public class EclipseAstProblemView { /** * Adds a problem to the provided CompilationResult object so that it will show up * in the Problems/Warnings view. */ public static void addProblemToCompilationResult(char[] fileNameArray, CompilationResult result, boolean isWarning, String message, int sourceStart, int sourceEnd) { if (result == null) return; if (fileNameArray == null) fileNameArray = "(unknown).java".toCharArray(); int lineNumber = 0; int columnNumber = 1; int[] lineEnds = null; lineNumber = sourceStart >= 0 ? Util.getLineNumber(sourceStart, lineEnds = result.getLineSeparatorPositions(), 0, lineEnds.length-1) : 0; columnNumber = sourceStart >= 0 ? Util.searchColumnNumber(result.getLineSeparatorPositions(), lineNumber,sourceStart) : 0; CategorizedProblem ecProblem = new LombokProblem( fileNameArray, message, 0, new String[0], isWarning ? ProblemSeverities.Warning : ProblemSeverities.Error, sourceStart, sourceEnd, lineNumber, columnNumber); result.record(ecProblem, null); } private static class LombokProblem extends DefaultProblem { private static final String MARKER_ID = "org.eclipse.jdt.apt.pluggable.core.compileProblem"; //$NON-NLS-1$ public LombokProblem(char[] originatingFileName, String message, int id, String[] stringArguments, int severity, int startPosition, int endPosition, int line, int column) { super(originatingFileName, message, id, stringArguments, severity, startPosition, endPosition, line, column); } @Override public int getCategoryID() { return CAT_UNSPECIFIED; } @Override public String getMarkerType() { return MARKER_ID; } } } lombok-1.16.18/src/core/lombok/eclipse/EclipseAugments.java000066400000000000000000000040471312655740700235530ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import lombok.core.FieldAugment; public final class EclipseAugments { private EclipseAugments() { // Prevent instantiation } public static final FieldAugment FieldDeclaration_booleanLazyGetter = FieldAugment.augment(FieldDeclaration.class, boolean.class, "lombok$booleanLazyGetter"); public static final FieldAugment ASTNode_handled = FieldAugment.augment(ASTNode.class, boolean.class, "lombok$handled"); public static final FieldAugment ASTNode_generatedBy = FieldAugment.augment(ASTNode.class, ASTNode.class, "$generatedBy"); public static final FieldAugment Annotation_applied = FieldAugment.augment(Annotation.class, boolean.class, "lombok$applied"); } lombok-1.16.18/src/core/lombok/eclipse/EclipseImportList.java000066400000000000000000000124741312655740700241010ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import static lombok.eclipse.Eclipse.toQualifiedName; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import lombok.core.ImportList; import lombok.core.LombokInternalAliasing; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ImportReference; public class EclipseImportList implements ImportList { private ImportReference[] imports; private ImportReference pkg; public EclipseImportList(CompilationUnitDeclaration cud) { this.pkg = cud.currentPackage; this.imports = cud.imports; } @Override public String getFullyQualifiedNameForSimpleName(String unqualified) { if (imports != null) { outer: for (ImportReference imp : imports) { if ((imp.bits & ASTNode.OnDemand) != 0) continue; char[][] tokens = imp.tokens; char[] token = tokens.length == 0 ? new char[0] : tokens[tokens.length - 1]; int len = token.length; if (len != unqualified.length()) continue; for (int i = 0; i < len; i++) if (token[i] != unqualified.charAt(i)) continue outer; return LombokInternalAliasing.processAliases(toQualifiedName(tokens)); } } return null; } @Override public boolean hasStarImport(String packageName) { if (isEqual(packageName, pkg)) return true; if ("java.lang".equals(packageName)) return true; if (pkg != null && pkg.tokens != null && pkg.tokens.length == 0) { for (Map.Entry> e : LombokInternalAliasing.IMPLIED_EXTRA_STAR_IMPORTS.entrySet()) { if (isEqual(e.getKey(), pkg) && e.getValue().contains(packageName)) return true; } } if (imports != null) for (ImportReference imp : imports) { if ((imp.bits & ASTNode.OnDemand) == 0) continue; if (imp.isStatic()) continue; if (isEqual(packageName, imp)) return true; for (Map.Entry> e : LombokInternalAliasing.IMPLIED_EXTRA_STAR_IMPORTS.entrySet()) { if (isEqual(e.getKey(), imp) && e.getValue().contains(packageName)) return true; } } return false; } private static boolean isEqual(String packageName, ImportReference pkgOrStarImport) { if (pkgOrStarImport == null || pkgOrStarImport.tokens == null || pkgOrStarImport.tokens.length == 0) return packageName.isEmpty(); int pos = 0; int len = packageName.length(); for (int i = 0; i < pkgOrStarImport.tokens.length; i++) { if (i != 0) { if (pos >= len) return false; if (packageName.charAt(pos++) != '.') return false; } for (int j = 0; j < pkgOrStarImport.tokens[i].length; j++) { if (pos >= len) return false; if (packageName.charAt(pos++) != pkgOrStarImport.tokens[i][j]) return false; } } return true; } @Override public Collection applyNameToStarImports(String startsWith, String name) { List out = Collections.emptyList(); if (pkg != null && pkg.tokens != null && pkg.tokens.length != 0) { char[] first = pkg.tokens[0]; int len = first.length; boolean match = true; if (startsWith.length() == len) { for (int i = 0; match && i < len; i++) { if (startsWith.charAt(i) != first[i]) match = false; } if (match) out.add(toQualifiedName(pkg.tokens) + "." + name); } } if (imports != null) { outer: for (ImportReference imp : imports) { if ((imp.bits & ASTNode.OnDemand) == 0) continue; if (imp.isStatic()) continue; if (imp.tokens == null || imp.tokens.length == 0) continue; char[] firstToken = imp.tokens[0]; if (firstToken.length != startsWith.length()) continue; for (int i = 0; i < firstToken.length; i++) if (startsWith.charAt(i) != firstToken[i]) continue outer; String fqn = toQualifiedName(imp.tokens) + "." + name; if (out.isEmpty()) out = Collections.singletonList(fqn); else if (out.size() == 1) { out = new ArrayList(out); out.add(fqn); } else { out.add(fqn); } } } return out; } @Override public String applyUnqualifiedNameToPackage(String unqualified) { if (pkg == null || pkg.tokens == null || pkg.tokens.length == 0) return unqualified; return toQualifiedName(pkg.tokens) + "." + unqualified; } } lombok-1.16.18/src/core/lombok/eclipse/EclipseNode.java000066400000000000000000000162671312655740700226640ustar00rootroot00000000000000/* * Copyright (C) 2009-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import java.util.List; import lombok.core.AST.Kind; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Clinit; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; /** * Eclipse specific version of the LombokNode class. */ public class EclipseNode extends lombok.core.LombokNode { /** {@inheritDoc} */ EclipseNode(EclipseAST ast, ASTNode node, List children, Kind kind) { super(ast, node, children, kind); } /** * Visits this node and all child nodes depth-first, calling the provided visitor's visit methods. */ public void traverse(EclipseASTVisitor visitor) { if (!this.isCompleteParse() && visitor.getClass().isAnnotationPresent(DeferUntilPostDiet.class)) return; switch (getKind()) { case COMPILATION_UNIT: visitor.visitCompilationUnit(this, (CompilationUnitDeclaration) get()); ast.traverseChildren(visitor, this); visitor.endVisitCompilationUnit(this, (CompilationUnitDeclaration) get()); break; case TYPE: visitor.visitType(this, (TypeDeclaration) get()); ast.traverseChildren(visitor, this); visitor.endVisitType(this, (TypeDeclaration) get()); break; case FIELD: visitor.visitField(this, (FieldDeclaration) get()); ast.traverseChildren(visitor, this); visitor.endVisitField(this, (FieldDeclaration) get()); break; case INITIALIZER: visitor.visitInitializer(this, (Initializer) get()); ast.traverseChildren(visitor, this); visitor.endVisitInitializer(this, (Initializer) get()); break; case METHOD: if (get() instanceof Clinit) return; visitor.visitMethod(this, (AbstractMethodDeclaration) get()); ast.traverseChildren(visitor, this); visitor.endVisitMethod(this, (AbstractMethodDeclaration) get()); break; case ARGUMENT: AbstractMethodDeclaration method = (AbstractMethodDeclaration) up().get(); visitor.visitMethodArgument(this, (Argument) get(), method); ast.traverseChildren(visitor, this); visitor.endVisitMethodArgument(this, (Argument) get(), method); break; case LOCAL: visitor.visitLocal(this, (LocalDeclaration) get()); ast.traverseChildren(visitor, this); visitor.endVisitLocal(this, (LocalDeclaration) get()); break; case ANNOTATION: switch (up().getKind()) { case TYPE: visitor.visitAnnotationOnType((TypeDeclaration) up().get(), this, (Annotation) get()); break; case FIELD: visitor.visitAnnotationOnField((FieldDeclaration) up().get(), this, (Annotation) get()); break; case METHOD: visitor.visitAnnotationOnMethod((AbstractMethodDeclaration) up().get(), this, (Annotation) get()); break; case ARGUMENT: visitor.visitAnnotationOnMethodArgument( (Argument) parent.get(), (AbstractMethodDeclaration) parent.directUp().get(), this, (Annotation) get()); break; case LOCAL: visitor.visitAnnotationOnLocal((LocalDeclaration) parent.get(), this, (Annotation) get()); break; default: throw new AssertionError("Annotation not expected as child of a " + up().getKind()); } break; case STATEMENT: visitor.visitStatement(this, (Statement) get()); ast.traverseChildren(visitor, this); visitor.endVisitStatement(this, (Statement) get()); break; default: throw new AssertionError("Unexpected kind during node traversal: " + getKind()); } } @Override protected boolean fieldContainsAnnotation(ASTNode field, ASTNode annotation) { if (!(field instanceof FieldDeclaration)) return false; FieldDeclaration f = (FieldDeclaration) field; if (f.annotations == null) return false; for (Annotation childAnnotation : f.annotations) { if (childAnnotation == annotation) return true; } return false; } /** {@inheritDoc} */ @Override public String getName() { final char[] n; if (node instanceof TypeDeclaration) n = ((TypeDeclaration)node).name; else if (node instanceof FieldDeclaration) n = ((FieldDeclaration)node).name; else if (node instanceof AbstractMethodDeclaration) n = ((AbstractMethodDeclaration)node).selector; else if (node instanceof LocalDeclaration) n = ((LocalDeclaration)node).name; else n = null; return n == null ? null : new String(n); } /** {@inheritDoc} */ @Override public void addError(String message) { this.addError(message, this.get().sourceStart, this.get().sourceEnd); } /** Generate a compiler error that shows the wavy underline from-to the stated character positions. */ public void addError(String message, int sourceStart, int sourceEnd) { ast.addProblem(ast.new ParseProblem(false, message, sourceStart, sourceEnd)); } /** {@inheritDoc} */ @Override public void addWarning(String message) { this.addWarning(message, this.get().sourceStart, this.get().sourceEnd); } /** Generate a compiler warning that shows the wavy underline from-to the stated character positions. */ public void addWarning(String message, int sourceStart, int sourceEnd) { ast.addProblem(ast.new ParseProblem(true, message, sourceStart, sourceEnd)); } /** {@inheritDoc} */ @Override protected boolean calculateIsStructurallySignificant(ASTNode parent) { if (node instanceof TypeDeclaration) return true; if (node instanceof AbstractMethodDeclaration) return true; if (node instanceof FieldDeclaration) return true; if (node instanceof LocalDeclaration) return true; if (node instanceof CompilationUnitDeclaration) return true; return false; } /** * Convenient shortcut to the owning EclipseAST object's isCompleteParse method. * * @see EclipseAST#isCompleteParse() */ public boolean isCompleteParse() { return ast.isCompleteParse(); } } lombok-1.16.18/src/core/lombok/eclipse/HandlerLibrary.java000066400000000000000000000237141312655740700233670ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import static lombok.eclipse.EclipseAugments.ASTNode_handled; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import lombok.Lombok; import lombok.core.AnnotationValues; import lombok.core.AnnotationValues.AnnotationValueDecodeFail; import lombok.core.configuration.ConfigurationKeysLoader; import lombok.core.HandlerPriority; import lombok.core.SpiLoadUtil; import lombok.core.TypeLibrary; import lombok.core.TypeResolver; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; /** * This class tracks 'handlers' and knows how to invoke them for any given AST node. * * This class can find the handlers (via SPI discovery) and will set up the given AST node, such as * building an AnnotationValues instance. */ public class HandlerLibrary { /** * Creates a new HandlerLibrary. Errors will be reported to the Eclipse Error log. * You probably want to use {@link #load()} instead. */ public HandlerLibrary() { ConfigurationKeysLoader.LoaderLoader.loadAllConfigurationKeys(); } private TypeLibrary typeLibrary = new TypeLibrary(); private static class VisitorContainer { private final EclipseASTVisitor visitor; private final long priority; private final boolean deferUntilPostDiet; VisitorContainer(EclipseASTVisitor visitor) { this.visitor = visitor; this.deferUntilPostDiet = visitor.getClass().isAnnotationPresent(DeferUntilPostDiet.class); HandlerPriority hp = visitor.getClass().getAnnotation(HandlerPriority.class); this.priority = hp == null ? 0L : (((long)hp.value()) << 32) + hp.subValue(); } public boolean deferUntilPostDiet() { return deferUntilPostDiet; } public long getPriority() { return priority; } } private static class AnnotationHandlerContainer { private final EclipseAnnotationHandler handler; private final Class annotationClass; private final long priority; private final boolean deferUntilPostDiet; AnnotationHandlerContainer(EclipseAnnotationHandler handler, Class annotationClass) { this.handler = handler; this.annotationClass = annotationClass; this.deferUntilPostDiet = handler.getClass().isAnnotationPresent(DeferUntilPostDiet.class); HandlerPriority hp = handler.getClass().getAnnotation(HandlerPriority.class); this.priority = hp == null ? 0L : (((long)hp.value()) << 32) + hp.subValue(); } public void handle(org.eclipse.jdt.internal.compiler.ast.Annotation annotation, final EclipseNode annotationNode) { AnnotationValues annValues = createAnnotation(annotationClass, annotationNode); handler.handle(annValues, annotation, annotationNode); } public void preHandle(org.eclipse.jdt.internal.compiler.ast.Annotation annotation, final EclipseNode annotationNode) { AnnotationValues annValues = createAnnotation(annotationClass, annotationNode); handler.preHandle(annValues, annotation, annotationNode); } public boolean deferUntilPostDiet() { return deferUntilPostDiet; } public long getPriority() { return priority; } } private Map> annotationHandlers = new HashMap>(); private Collection visitorHandlers = new ArrayList(); /** * Creates a new HandlerLibrary. Errors will be reported to the Eclipse Error log. * then uses SPI discovery to load all annotation and visitor based handlers so that future calls * to the handle methods will defer to these handlers. */ public static HandlerLibrary load() { HandlerLibrary lib = new HandlerLibrary(); loadAnnotationHandlers(lib); loadVisitorHandlers(lib); lib.calculatePriorities(); return lib; } private SortedSet priorities; public SortedSet getPriorities() { return priorities; } private void calculatePriorities() { SortedSet set = new TreeSet(); for (AnnotationHandlerContainer container : annotationHandlers.values()) set.add(container.getPriority()); for (VisitorContainer container : visitorHandlers) set.add(container.getPriority()); this.priorities = Collections.unmodifiableSortedSet(set); } /** Uses SPI Discovery to find implementations of {@link EclipseAnnotationHandler}. */ @SuppressWarnings({"rawtypes", "unchecked"}) private static void loadAnnotationHandlers(HandlerLibrary lib) { try { for (EclipseAnnotationHandler handler : SpiLoadUtil.findServices(EclipseAnnotationHandler.class, EclipseAnnotationHandler.class.getClassLoader())) { try { Class annotationClass = handler.getAnnotationHandledByThisHandler(); AnnotationHandlerContainer container = new AnnotationHandlerContainer(handler, annotationClass); String annotationClassName = container.annotationClass.getName().replace("$", "."); if (lib.annotationHandlers.put(annotationClassName, container) != null) { error(null, "Duplicate handlers for annotation type: " + annotationClassName, null); } lib.typeLibrary.addType(container.annotationClass.getName()); } catch (Throwable t) { error(null, "Can't load Lombok annotation handler for Eclipse: ", t); } } } catch (IOException e) { throw Lombok.sneakyThrow(e); } } /** Uses SPI Discovery to find implementations of {@link EclipseASTVisitor}. */ private static void loadVisitorHandlers(HandlerLibrary lib) { try { for (EclipseASTVisitor visitor : SpiLoadUtil.findServices(EclipseASTVisitor.class, EclipseASTVisitor.class.getClassLoader())) { lib.visitorHandlers.add(new VisitorContainer(visitor)); } } catch (Throwable t) { throw Lombok.sneakyThrow(t); } } private boolean checkAndSetHandled(ASTNode node) { return !ASTNode_handled.getAndSet(node, true); } private boolean needsHandling(ASTNode node) { return !ASTNode_handled.get(node); } /** * Handles the provided annotation node by first finding a qualifying instance of * {@link EclipseAnnotationHandler} and if one exists, calling it with a freshly cooked up * instance of {@link AnnotationValues}. * * Note that depending on the printASTOnly flag, the {@link lombok.core.PrintAST} annotation * will either be silently skipped, or everything that isn't {@code PrintAST} will be skipped. * * The HandlerLibrary will attempt to guess if the given annotation node represents a lombok annotation. * For example, if {@code lombok.*} is in the import list, then this method will guess that * {@code Getter} refers to {@code lombok.Getter}, presuming that {@link lombok.eclipse.handlers.HandleGetter} * has been loaded. * * @param ast The Compilation Unit that contains the Annotation AST Node. * @param annotationNode The Lombok AST Node representing the Annotation AST Node. * @param annotation 'node.get()' - convenience parameter. */ public void handleAnnotation(CompilationUnitDeclaration ast, EclipseNode annotationNode, org.eclipse.jdt.internal.compiler.ast.Annotation annotation, long priority) { TypeResolver resolver = new TypeResolver(annotationNode.getImportList()); TypeReference rawType = annotation.type; if (rawType == null) return; String fqn = resolver.typeRefToFullyQualifiedName(annotationNode, typeLibrary, toQualifiedName(annotation.type.getTypeName())); if (fqn == null) return; AnnotationHandlerContainer container = annotationHandlers.get(fqn); if (container == null) return; if (priority != container.getPriority()) return; if (!annotationNode.isCompleteParse() && container.deferUntilPostDiet()) { if (needsHandling(annotation)) container.preHandle(annotation, annotationNode); return; } try { if (checkAndSetHandled(annotation)) container.handle(annotation, annotationNode); } catch (AnnotationValueDecodeFail fail) { fail.owner.setError(fail.getMessage(), fail.idx); } catch (Throwable t) { error(ast, String.format("Lombok annotation handler %s failed", container.handler.getClass()), t); } } /** * Will call all registered {@link EclipseASTVisitor} instances. */ public void callASTVisitors(EclipseAST ast, long priority, boolean isCompleteParse) { for (VisitorContainer container : visitorHandlers) { if (!isCompleteParse && container.deferUntilPostDiet()) continue; if (priority != container.getPriority()) continue; try { ast.traverse(container.visitor); } catch (Throwable t) { error((CompilationUnitDeclaration) ast.top().get(), String.format("Lombok visitor handler %s failed", container.visitor.getClass()), t); } } } } lombok-1.16.18/src/core/lombok/eclipse/TransformEclipseAST.java000066400000000000000000000215321312655740700243110ustar00rootroot00000000000000/* * Copyright (C) 2009-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.lang.reflect.Field; import lombok.core.debug.DebugSnapshotStore; import lombok.core.debug.HistogramTracker; import lombok.patcher.Symbols; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.parser.Parser; /** * Entry point for the Eclipse Parser patch that lets lombok modify the Abstract Syntax Tree as generated by * Eclipse's parser implementations. This class is injected into the appropriate OSGi ClassLoader and can thus * use any classes that belong to org.eclipse.jdt.(apt.)core. * * Note that, for any Method body, if Bit24 is set, the Eclipse parser has been patched to never attempt to * (re)parse it. You should set Bit24 on any MethodDeclaration object you inject into the AST: * * {@code methodDeclaration.bits |= ASTNode.Bit24; //0x800000} * * @author rzwitserloot * @author rspilker */ public class TransformEclipseAST { private final EclipseAST ast; //The patcher hacks this field onto CUD. It's public. private static final Field astCacheField; private static final HandlerLibrary handlers; public static boolean disableLombok = false; private static final HistogramTracker lombokTracker; static { String v = System.getProperty("lombok.histogram"); if (v == null) lombokTracker = null; else if (v.toLowerCase().equals("sysout")) lombokTracker = new HistogramTracker("lombok.histogram", System.out); else lombokTracker = new HistogramTracker("lombok.histogram"); } static { Field f = null; HandlerLibrary h = null; if (System.getProperty("lombok.disable") != null) { disableLombok = true; astCacheField = null; handlers = null; } else { try { h = HandlerLibrary.load(); } catch (Throwable t) { try { error(null, "Problem initializing lombok", t); } catch (Throwable t2) { System.err.println("Problem initializing lombok"); t.printStackTrace(); } disableLombok = true; } try { f = CompilationUnitDeclaration.class.getDeclaredField("$lombokAST"); } catch (Throwable t) { //I guess we're in an ecj environment; we'll just not cache stuff then. } astCacheField = f; handlers = h; } } public static void transform_swapped(CompilationUnitDeclaration ast, Parser parser) { transform(parser, ast); } public static EclipseAST getAST(CompilationUnitDeclaration ast, boolean forceRebuild) { EclipseAST existing = null; if (astCacheField != null) { try { existing = (EclipseAST) astCacheField.get(ast); } catch (Exception e) { // existing remains null } } if (existing == null) { existing = new EclipseAST(ast); if (astCacheField != null) try { astCacheField.set(ast, existing); } catch (Exception ignore) { } } else { existing.rebuild(forceRebuild); } return existing; } /** * This method is called immediately after Eclipse finishes building a CompilationUnitDeclaration, which is * the top-level AST node when Eclipse parses a source file. The signature is 'magic' - you should not * change it! * * Eclipse's parsers often operate in diet mode, which means many parts of the AST have been left blank. * Be ready to deal with just about anything being null, such as the Statement[] arrays of the Method AST nodes. * * @param parser The Eclipse parser object that generated the AST. Not actually used; mostly there to satisfy parameter rules for lombok.patcher scripts. * @param ast The AST node belonging to the compilation unit (java speak for a single source file). */ public static void transform(Parser parser, CompilationUnitDeclaration ast) { if (disableLombok) return; if (Symbols.hasSymbol("lombok.disable")) return; // Do NOT abort if (ast.bits & ASTNode.HasAllMethodBodies) != 0 - that doesn't work. try { DebugSnapshotStore.INSTANCE.snapshot(ast, "transform entry"); long histoToken = lombokTracker == null ? 0L : lombokTracker.start(); EclipseAST existing = getAST(ast, false); new TransformEclipseAST(existing).go(); if (lombokTracker != null) lombokTracker.end(histoToken); DebugSnapshotStore.INSTANCE.snapshot(ast, "transform exit"); } catch (Throwable t) { DebugSnapshotStore.INSTANCE.snapshot(ast, "transform error: %s", t.getClass().getSimpleName()); try { String message = "Lombok can't parse this source: " + t.toString(); EclipseAST.addProblemToCompilationResult(ast.getFileName(), ast.compilationResult, false, message, 0, 0); t.printStackTrace(); } catch (Throwable t2) { try { error(ast, "Can't create an error in the problems dialog while adding: " + t.toString(), t2); } catch (Throwable t3) { //This seems risky to just silently turn off lombok, but if we get this far, something pretty //drastic went wrong. For example, the eclipse help system's JSP compiler will trigger a lombok call, //but due to class loader shenanigans we'll actually get here due to a cascade of //ClassNotFoundErrors. This is the right action for the help system (no lombok needed for that JSP compiler, //of course). 'disableLombok' is static, but each context classloader (e.g. each eclipse OSGi plugin) has //it's own edition of this class, so this won't turn off lombok everywhere. disableLombok = true; } } } } public TransformEclipseAST(EclipseAST ast) { this.ast = ast; } /** * First handles all lombok annotations except PrintAST, then calls all non-annotation based handlers. * then handles any PrintASTs. */ public void go() { for (Long d : handlers.getPriorities()) { ast.traverse(new AnnotationVisitor(d)); handlers.callASTVisitors(ast, d, ast.isCompleteParse()); } } private static class AnnotationVisitor extends EclipseASTAdapter { private final long priority; public AnnotationVisitor(long priority) { this.priority = priority; } @Override public void visitAnnotationOnField(FieldDeclaration field, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnType(TypeDeclaration type, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/000077500000000000000000000000001312655740700214135ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java000066400000000000000000002076641312655740700260150ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.EclipseAugments.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.Data; import lombok.Getter; import lombok.Lombok; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.AnnotationValues.AnnotationValue; import lombok.core.TypeResolver; import lombok.core.configuration.NullCheckExceptionType; import lombok.core.debug.ProblemReporter; import lombok.core.handlers.HandlerUtil; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAST; import lombok.eclipse.EclipseNode; import lombok.experimental.Accessors; import lombok.experimental.Tolerate; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.CastExpression; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; import org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NameReference; import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.ThrowStatement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.Binding; import org.eclipse.jdt.internal.compiler.lookup.CaptureBinding; import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; /** * Container for static utility methods useful to handlers written for eclipse. */ public class EclipseHandlerUtil { private EclipseHandlerUtil() { //Prevent instantiation } /** * Generates an error in the Eclipse error log. Note that most people never look at it! * * @param cud The {@code CompilationUnitDeclaration} where the error occurred. * An error will be generated on line 0 linking to the error log entry. Can be {@code null}. * @param message Human readable description of the problem. * @param ex The associated exception. Can be {@code null}. */ public static void error(CompilationUnitDeclaration cud, String message, Throwable ex) { ProblemReporter.error(message, ex); if (cud != null) EclipseAST.addProblemToCompilationResult(cud.getFileName(), cud.compilationResult, false, message + " - See error log.", 0, 0); } /** * Generates a warning in the Eclipse error log. Note that most people never look at it! * * @param message Human readable description of the problem. * @param ex The associated exception. Can be {@code null}. */ public static void warning(String message, Throwable ex) { ProblemReporter.warning(message, ex); } public static ASTNode getGeneratedBy(ASTNode node) { return ASTNode_generatedBy.get(node); } public static boolean isGenerated(ASTNode node) { return getGeneratedBy(node) != null; } public static T setGeneratedBy(T node, ASTNode source) { ASTNode_generatedBy.set(node, source); return node; } public static MarkerAnnotation generateDeprecatedAnnotation(ASTNode source) { QualifiedTypeReference qtr = new QualifiedTypeReference(new char[][] { {'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'D', 'e', 'p', 'r', 'e', 'c', 'a', 't', 'e', 'd'}}, poss(source, 3)); setGeneratedBy(qtr, source); MarkerAnnotation ma = new MarkerAnnotation(qtr, source.sourceStart); // No matter what value you input for sourceEnd, the AST->DOM converter of eclipse will reparse to find the end, and will fail as // it can't find code that isn't really there. This results in the end position being set to 2 or 0 or some weird magic value, and thus, // length, as calculated by end-start, is all screwed up, resulting in IllegalArgumentException during a setSourceRange call MUCH later in the process. // We solve it by going with a voodoo magic source start value such that the calculated length so happens to exactly be 0. 0 lengths are accepted // by eclipse. For some reason. // TL;DR: Don't change 1. 1 is sacred. Trust the 1. // issue: #408. ma.sourceStart = 1; setGeneratedBy(ma, source); return ma; } public static boolean isFieldDeprecated(EclipseNode fieldNode) { if (!(fieldNode.get() instanceof FieldDeclaration)) return false; FieldDeclaration field = (FieldDeclaration) fieldNode.get(); if ((field.modifiers & ClassFileConstants.AccDeprecated) != 0) { return true; } if (field.annotations == null) return false; for (Annotation annotation : field.annotations) { if (typeMatches(Deprecated.class, fieldNode, annotation.type)) { return true; } } return false; } /** * Checks if the given TypeReference node is likely to be a reference to the provided class. * * @param type An actual type. This method checks if {@code typeNode} is likely to be a reference to this type. * @param node A Lombok AST node. Any node in the appropriate compilation unit will do (used to get access to import statements). * @param typeRef A type reference to check. */ public static boolean typeMatches(Class type, EclipseNode node, TypeReference typeRef) { if (typeRef == null || typeRef.getTypeName() == null || typeRef.getTypeName().length == 0) return false; String lastPartA = new String(typeRef.getTypeName()[typeRef.getTypeName().length -1]); String lastPartB = type.getSimpleName(); if (!lastPartA.equals(lastPartB)) return false; String typeName = toQualifiedName(typeRef.getTypeName()); TypeResolver resolver = new TypeResolver(node.getImportList()); return resolver.typeMatches(node, type.getName(), typeName); } public static void sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(EclipseNode typeNode, EclipseNode errorNode) { List disallowed = null; for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.ANNOTATION) continue; for (Class annType : INVALID_ON_BUILDERS) { if (annotationTypeMatches(annType, child)) { if (disallowed == null) disallowed = new ArrayList(); disallowed.add(annType.getSimpleName()); } } } int size = disallowed == null ? 0 : disallowed.size(); if (size == 0) return; if (size == 1) { errorNode.addError("@" + disallowed.get(0) + " is not allowed on builder classes."); return; } StringBuilder out = new StringBuilder(); for (String a : disallowed) out.append("@").append(a).append(", "); out.setLength(out.length() - 2); errorNode.addError(out.append(" are not allowed on builder classes.").toString()); } public static Annotation copyAnnotation(Annotation annotation, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; if (annotation instanceof MarkerAnnotation) { MarkerAnnotation ann = new MarkerAnnotation(copyType(annotation.type, source), pS); setGeneratedBy(ann, source); ann.declarationSourceEnd = ann.sourceEnd = ann.statementEnd = pE; return ann; } if (annotation instanceof SingleMemberAnnotation) { SingleMemberAnnotation ann = new SingleMemberAnnotation(copyType(annotation.type, source), pS); setGeneratedBy(ann, source); ann.declarationSourceEnd = ann.sourceEnd = ann.statementEnd = pE; //TODO memberValue(s) need to be copied as well (same for copying a NormalAnnotation as below). ann.memberValue = ((SingleMemberAnnotation)annotation).memberValue; return ann; } if (annotation instanceof NormalAnnotation) { NormalAnnotation ann = new NormalAnnotation(copyType(annotation.type, source), pS); setGeneratedBy(ann, source); ann.declarationSourceEnd = ann.statementEnd = ann.sourceEnd = pE; ann.memberValuePairs = ((NormalAnnotation)annotation).memberValuePairs; return ann; } return annotation; } /** * You can't share TypeParameter objects or bad things happen; for example, one 'T' resolves differently * from another 'T', even for the same T in a single class file. Unfortunately the TypeParameter type hierarchy * is complicated and there's no clone method on TypeParameter itself. This method can clone them. */ public static TypeParameter[] copyTypeParams(TypeParameter[] params, ASTNode source) { if (params == null) return null; TypeParameter[] out = new TypeParameter[params.length]; int idx = 0; for (TypeParameter param : params) { TypeParameter o = new TypeParameter(); setGeneratedBy(o, source); o.annotations = param.annotations; o.bits = param.bits; o.modifiers = param.modifiers; o.name = param.name; o.type = copyType(param.type, source); o.sourceStart = param.sourceStart; o.sourceEnd = param.sourceEnd; o.declarationEnd = param.declarationEnd; o.declarationSourceStart = param.declarationSourceStart; o.declarationSourceEnd = param.declarationSourceEnd; if (param.bounds != null) { TypeReference[] b = new TypeReference[param.bounds.length]; int idx2 = 0; for (TypeReference ref : param.bounds) b[idx2++] = copyType(ref, source); o.bounds = b; } out[idx++] = o; } return out; } public static TypeReference namePlusTypeParamsToTypeReference(char[] typeName, TypeParameter[] params, long p) { if (params != null && params.length > 0) { TypeReference[] refs = new TypeReference[params.length]; int idx = 0; for (TypeParameter param : params) { TypeReference typeRef = new SingleTypeReference(param.name, p); refs[idx++] = typeRef; } return new ParameterizedSingleTypeReference(typeName, refs, 0, p); } return new SingleTypeReference(typeName, p); } public static TypeReference[] copyTypes(TypeReference[] refs) { return copyTypes(refs, null); } /** * Convenience method that creates a new array and copies each TypeReference in the source array via * {@link #copyType(TypeReference, ASTNode)}. */ public static TypeReference[] copyTypes(TypeReference[] refs, ASTNode source) { if (refs == null) return null; TypeReference[] outs = new TypeReference[refs.length]; int idx = 0; for (TypeReference ref : refs) { outs[idx++] = copyType(ref, source); } return outs; } public static TypeReference copyType(TypeReference ref) { return copyType(ref, null); } /** * You can't share TypeReference objects or subtle errors start happening. * Unfortunately the TypeReference type hierarchy is complicated and there's no clone * method on TypeReference itself. This method can clone them. */ public static TypeReference copyType(TypeReference ref, ASTNode source) { if (ref instanceof ParameterizedQualifiedTypeReference) { ParameterizedQualifiedTypeReference iRef = (ParameterizedQualifiedTypeReference) ref; TypeReference[][] args = null; if (iRef.typeArguments != null) { args = new TypeReference[iRef.typeArguments.length][]; int idx = 0; for (TypeReference[] inRefArray : iRef.typeArguments) { if (inRefArray == null) args[idx++] = null; else { TypeReference[] outRefArray = new TypeReference[inRefArray.length]; int idx2 = 0; for (TypeReference inRef : inRefArray) { outRefArray[idx2++] = copyType(inRef, source); } args[idx++] = outRefArray; } } } TypeReference typeRef = new ParameterizedQualifiedTypeReference(iRef.tokens, args, iRef.dimensions(), copy(iRef.sourcePositions)); if (source != null) setGeneratedBy(typeRef, source); return typeRef; } if (ref instanceof ArrayQualifiedTypeReference) { ArrayQualifiedTypeReference iRef = (ArrayQualifiedTypeReference) ref; TypeReference typeRef = new ArrayQualifiedTypeReference(iRef.tokens, iRef.dimensions(), copy(iRef.sourcePositions)); if (source != null) setGeneratedBy(typeRef, source); return typeRef; } if (ref instanceof QualifiedTypeReference) { QualifiedTypeReference iRef = (QualifiedTypeReference) ref; TypeReference typeRef = new QualifiedTypeReference(iRef.tokens, copy(iRef.sourcePositions)); if (source != null) setGeneratedBy(typeRef, source); return typeRef; } if (ref instanceof ParameterizedSingleTypeReference) { ParameterizedSingleTypeReference iRef = (ParameterizedSingleTypeReference) ref; TypeReference[] args = null; if (iRef.typeArguments != null) { args = new TypeReference[iRef.typeArguments.length]; int idx = 0; for (TypeReference inRef : iRef.typeArguments) { if (inRef == null) args[idx++] = null; else args[idx++] = copyType(inRef, source); } } TypeReference typeRef = new ParameterizedSingleTypeReference(iRef.token, args, iRef.dimensions(), (long)iRef.sourceStart << 32 | iRef.sourceEnd); if (source != null) setGeneratedBy(typeRef, source); return typeRef; } if (ref instanceof ArrayTypeReference) { ArrayTypeReference iRef = (ArrayTypeReference) ref; TypeReference typeRef = new ArrayTypeReference(iRef.token, iRef.dimensions(), (long)iRef.sourceStart << 32 | iRef.sourceEnd); if (source != null) setGeneratedBy(typeRef, source); return typeRef; } if (ref instanceof Wildcard) { Wildcard original = (Wildcard)ref; Wildcard wildcard = new Wildcard(original.kind); wildcard.sourceStart = original.sourceStart; wildcard.sourceEnd = original.sourceEnd; if (original.bound != null) wildcard.bound = copyType(original.bound, source); if (source != null) setGeneratedBy(wildcard, source); return wildcard; } if (ref instanceof SingleTypeReference) { SingleTypeReference iRef = (SingleTypeReference) ref; TypeReference typeRef = new SingleTypeReference(iRef.token, (long)iRef.sourceStart << 32 | iRef.sourceEnd); if (source != null) setGeneratedBy(typeRef, source); return typeRef; } return ref; } public static Annotation[] copyAnnotations(ASTNode source, Annotation[]... allAnnotations) { List result = null; for (Annotation[] annotations : allAnnotations) { if (annotations != null) { for (Annotation annotation : annotations) { if (result == null) result = new ArrayList(); result.add(copyAnnotation(annotation, source)); } } } return result == null ? null : result.toArray(new Annotation[0]); } public static boolean hasAnnotation(Class type, EclipseNode node) { if (node == null) return false; if (type == null) return false; switch (node.getKind()) { case ARGUMENT: case FIELD: case LOCAL: case TYPE: case METHOD: for (EclipseNode child : node.down()) { if (annotationTypeMatches(type, child)) return true; } // intentional fallthrough default: return false; } } public static EclipseNode findAnnotation(Class type, EclipseNode node) { if (node == null) return null; if (type == null) return null; switch (node.getKind()) { case ARGUMENT: case FIELD: case LOCAL: case TYPE: case METHOD: for (EclipseNode child : node.down()) { if (annotationTypeMatches(type, child)) return child; } // intentional fallthrough default: return null; } } /** * Checks if the provided annotation type is likely to be the intended type for the given annotation node. * * This is a guess, but a decent one. */ public static boolean annotationTypeMatches(Class type, EclipseNode node) { if (node.getKind() != Kind.ANNOTATION) return false; return typeMatches(type, node, ((Annotation) node.get()).type); } public static TypeReference cloneSelfType(EclipseNode context) { return cloneSelfType(context, null); } public static TypeReference cloneSelfType(EclipseNode context, ASTNode source) { int pS = source == null ? 0 : source.sourceStart, pE = source == null ? 0 : source.sourceEnd; long p = (long)pS << 32 | pE; EclipseNode type = context; TypeReference result = null; while (type != null && type.getKind() != Kind.TYPE) type = type.up(); if (type != null && type.get() instanceof TypeDeclaration) { TypeDeclaration typeDecl = (TypeDeclaration) type.get(); if (typeDecl.typeParameters != null && typeDecl.typeParameters.length > 0) { TypeReference[] refs = new TypeReference[typeDecl.typeParameters.length]; int idx = 0; for (TypeParameter param : typeDecl.typeParameters) { TypeReference typeRef = new SingleTypeReference(param.name, (long)param.sourceStart << 32 | param.sourceEnd); if (source != null) setGeneratedBy(typeRef, source); refs[idx++] = typeRef; } result = new ParameterizedSingleTypeReference(typeDecl.name, refs, 0, p); } else { result = new SingleTypeReference(((TypeDeclaration)type.get()).name, p); } } if (result != null && source != null) setGeneratedBy(result, source); return result; } public static TypeReference makeType(TypeBinding binding, ASTNode pos, boolean allowCompound) { int dims = binding.dimensions(); binding = binding.leafComponentType(); // Primitives char[] base = null; switch (binding.id) { case TypeIds.T_int: base = TypeConstants.INT; break; case TypeIds.T_long: base = TypeConstants.LONG; break; case TypeIds.T_short: base = TypeConstants.SHORT; break; case TypeIds.T_byte: base = TypeConstants.BYTE; break; case TypeIds.T_double: base = TypeConstants.DOUBLE; break; case TypeIds.T_float: base = TypeConstants.FLOAT; break; case TypeIds.T_boolean: base = TypeConstants.BOOLEAN; break; case TypeIds.T_char: base = TypeConstants.CHAR; break; case TypeIds.T_void: base = TypeConstants.VOID; break; case TypeIds.T_null: return null; } if (base != null) { if (dims > 0) { TypeReference result = new ArrayTypeReference(base, dims, pos(pos)); setGeneratedBy(result, pos); return result; } TypeReference result = new SingleTypeReference(base, pos(pos)); setGeneratedBy(result, pos); return result; } if (binding.isAnonymousType()) { ReferenceBinding ref = (ReferenceBinding)binding; ReferenceBinding[] supers = ref.superInterfaces(); if (supers == null || supers.length == 0) supers = new ReferenceBinding[] {ref.superclass()}; if (supers[0] == null) { TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3)); setGeneratedBy(result, pos); return result; } return makeType(supers[0], pos, false); } if (binding instanceof CaptureBinding) { return makeType(((CaptureBinding)binding).wildcard, pos, allowCompound); } if (binding.isUnboundWildcard()) { if (!allowCompound) { TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3)); setGeneratedBy(result, pos); return result; } else { Wildcard out = new Wildcard(Wildcard.UNBOUND); setGeneratedBy(out, pos); out.sourceStart = pos.sourceStart; out.sourceEnd = pos.sourceEnd; return out; } } if (binding.isWildcard()) { WildcardBinding wildcard = (WildcardBinding) binding; if (wildcard.boundKind == Wildcard.EXTENDS) { if (!allowCompound) { return makeType(wildcard.bound, pos, false); } else { Wildcard out = new Wildcard(Wildcard.EXTENDS); setGeneratedBy(out, pos); out.bound = makeType(wildcard.bound, pos, false); out.sourceStart = pos.sourceStart; out.sourceEnd = pos.sourceEnd; return out; } } else if (allowCompound && wildcard.boundKind == Wildcard.SUPER) { Wildcard out = new Wildcard(Wildcard.SUPER); setGeneratedBy(out, pos); out.bound = makeType(wildcard.bound, pos, false); out.sourceStart = pos.sourceStart; out.sourceEnd = pos.sourceEnd; return out; } else { TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3)); setGeneratedBy(result, pos); return result; } } // Keep moving up via 'binding.enclosingType()' and gather generics from each binding. We stop after a local type, or a static type, or a top-level type. // Finally, add however many nullTypeArgument[] arrays as that are missing, inverse the list, toArray it, and use that as PTR's typeArgument argument. List params = new ArrayList(); /* Calculate generics */ { TypeBinding b = binding; while (true) { boolean isFinalStop = b.isLocalType() || !b.isMemberType() || b.enclosingType() == null; TypeReference[] tyParams = null; if (b instanceof ParameterizedTypeBinding) { ParameterizedTypeBinding paramized = (ParameterizedTypeBinding) b; if (paramized.arguments != null) { tyParams = new TypeReference[paramized.arguments.length]; for (int i = 0; i < tyParams.length; i++) { tyParams[i] = makeType(paramized.arguments[i], pos, true); } } } params.add(tyParams); if (isFinalStop) break; b = b.enclosingType(); } } char[][] parts; if (binding.isTypeVariable()) { parts = new char[][] { binding.shortReadableName() }; } else if (binding.isLocalType()) { parts = new char[][] { binding.sourceName() }; } else { String[] pkg = new String(binding.qualifiedPackageName()).split("\\."); String[] name = new String(binding.qualifiedSourceName()).split("\\."); if (pkg.length == 1 && pkg[0].isEmpty()) pkg = new String[0]; parts = new char[pkg.length + name.length][]; int ptr; for (ptr = 0; ptr < pkg.length; ptr++) parts[ptr] = pkg[ptr].toCharArray(); for (; ptr < pkg.length + name.length; ptr++) parts[ptr] = name[ptr - pkg.length].toCharArray(); } while (params.size() < parts.length) params.add(null); Collections.reverse(params); boolean isParamized = false; for (TypeReference[] tyParams : params) { if (tyParams != null) { isParamized = true; break; } } if (isParamized) { if (parts.length > 1) { TypeReference[][] typeArguments = params.toArray(new TypeReference[0][]); TypeReference result = new ParameterizedQualifiedTypeReference(parts, typeArguments, dims, poss(pos, parts.length)); setGeneratedBy(result, pos); return result; } TypeReference result = new ParameterizedSingleTypeReference(parts[0], params.get(0), dims, pos(pos)); setGeneratedBy(result, pos); return result; } if (dims > 0) { if (parts.length > 1) { TypeReference result = new ArrayQualifiedTypeReference(parts, dims, poss(pos, parts.length)); setGeneratedBy(result, pos); return result; } TypeReference result = new ArrayTypeReference(parts[0], dims, pos(pos)); setGeneratedBy(result, pos); return result; } if (parts.length > 1) { TypeReference result = new QualifiedTypeReference(parts, poss(pos, parts.length)); setGeneratedBy(result, pos); return result; } TypeReference result = new SingleTypeReference(parts[0], pos(pos)); setGeneratedBy(result, pos); return result; } /** * Provides AnnotationValues with the data it needs to do its thing. */ public static AnnotationValues createAnnotation(Class type, final EclipseNode annotationNode) { final Annotation annotation = (Annotation) annotationNode.get(); Map values = new HashMap(); MemberValuePair[] memberValuePairs = annotation.memberValuePairs(); if (memberValuePairs != null) for (final MemberValuePair pair : memberValuePairs) { List raws = new ArrayList(); List expressionValues = new ArrayList(); List guesses = new ArrayList(); Expression[] expressions = null; char[] n = pair.name; String mName = (n == null || n.length == 0) ? "value" : new String(pair.name); final Expression rhs = pair.value; if (rhs instanceof ArrayInitializer) { expressions = ((ArrayInitializer)rhs).expressions; } else if (rhs != null) { expressions = new Expression[] { rhs }; } if (expressions != null) for (Expression ex : expressions) { StringBuffer sb = new StringBuffer(); ex.print(0, sb); raws.add(sb.toString()); expressionValues.add(ex); guesses.add(calculateValue(ex)); } final Expression[] exprs = expressions; values.put(mName, new AnnotationValue(annotationNode, raws, expressionValues, guesses, true) { @Override public void setError(String message, int valueIdx) { Expression ex; if (valueIdx == -1) ex = rhs; else ex = exprs != null ? exprs[valueIdx] : null; if (ex == null) ex = annotation; int sourceStart = ex.sourceStart; int sourceEnd = ex.sourceEnd; annotationNode.addError(message, sourceStart, sourceEnd); } @Override public void setWarning(String message, int valueIdx) { Expression ex; if (valueIdx == -1) ex = rhs; else ex = exprs != null ? exprs[valueIdx] : null; if (ex == null) ex = annotation; int sourceStart = ex.sourceStart; int sourceEnd = ex.sourceEnd; annotationNode.addWarning(message, sourceStart, sourceEnd); } }); } for (Method m : type.getDeclaredMethods()) { if (!Modifier.isPublic(m.getModifiers())) continue; String name = m.getName(); if (!values.containsKey(name)) { values.put(name, new AnnotationValue(annotationNode, new ArrayList(), new ArrayList(), new ArrayList(), false) { @Override public void setError(String message, int valueIdx) { annotationNode.addError(message); } @Override public void setWarning(String message, int valueIdx) { annotationNode.addWarning(message); } }); } } return new AnnotationValues(type, values, annotationNode); } /** * Turns an {@code AccessLevel} instance into the flag bit used by eclipse. */ public static int toEclipseModifier(AccessLevel value) { switch (value) { case MODULE: case PACKAGE: return 0; default: case PUBLIC: return ClassFileConstants.AccPublic; case PROTECTED: return ClassFileConstants.AccProtected; case NONE: case PRIVATE: return ClassFileConstants.AccPrivate; } } private static class GetterMethod { private final char[] name; private final TypeReference type; GetterMethod(char[] name, TypeReference type) { this.name = name; this.type = type; } } static void registerCreatedLazyGetter(FieldDeclaration field, char[] methodName, TypeReference returnType) { if (isBoolean(returnType)) { FieldDeclaration_booleanLazyGetter.set(field, true); } } public static boolean isBoolean(TypeReference typeReference) { return nameEquals(typeReference.getTypeName(), "boolean") && typeReference.dimensions() == 0; } private static GetterMethod findGetter(EclipseNode field) { FieldDeclaration fieldDeclaration = (FieldDeclaration) field.get(); boolean forceBool = FieldDeclaration_booleanLazyGetter.get(fieldDeclaration); TypeReference fieldType = fieldDeclaration.type; boolean isBoolean = forceBool || isBoolean(fieldType); EclipseNode typeNode = field.up(); for (String potentialGetterName : toAllGetterNames(field, isBoolean)) { for (EclipseNode potentialGetter : typeNode.down()) { if (potentialGetter.getKind() != Kind.METHOD) continue; if (!(potentialGetter.get() instanceof MethodDeclaration)) continue; MethodDeclaration method = (MethodDeclaration) potentialGetter.get(); if (!potentialGetterName.equalsIgnoreCase(new String(method.selector))) continue; /** static getX() methods don't count. */ if ((method.modifiers & ClassFileConstants.AccStatic) != 0) continue; /** Nor do getters with a non-empty parameter list. */ if (method.arguments != null && method.arguments.length > 0) continue; return new GetterMethod(method.selector, method.returnType); } } // Check if the field has a @Getter annotation. boolean hasGetterAnnotation = false; for (EclipseNode child : field.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { AnnotationValues ann = createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } } // Check if the class has a @Getter annotation. if (!hasGetterAnnotation && new HandleGetter().fieldQualifiesForGetterGeneration(field)) { //Check if the class has @Getter or @Data annotation. EclipseNode containingType = field.up(); if (containingType != null) for (EclipseNode child : containingType.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Data.class, child)) hasGetterAnnotation = true; if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { AnnotationValues ann = createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } } } if (hasGetterAnnotation) { String getterName = toGetterName(field, isBoolean); if (getterName == null) return null; return new GetterMethod(getterName.toCharArray(), fieldType); } return null; } public enum FieldAccess { GETTER, PREFER_FIELD, ALWAYS_FIELD; } static boolean lookForGetter(EclipseNode field, FieldAccess fieldAccess) { if (fieldAccess == FieldAccess.GETTER) return true; if (fieldAccess == FieldAccess.ALWAYS_FIELD) return false; // If @Getter(lazy = true) is used, then using it is mandatory. for (EclipseNode child : field.down()) { if (child.getKind() != Kind.ANNOTATION) continue; if (annotationTypeMatches(Getter.class, child)) { AnnotationValues ann = createAnnotation(Getter.class, child); if (ann.getInstance().lazy()) return true; } } return false; } static TypeReference getFieldType(EclipseNode field, FieldAccess fieldAccess) { boolean lookForGetter = lookForGetter(field, fieldAccess); GetterMethod getter = lookForGetter ? findGetter(field) : null; if (getter == null) { return ((FieldDeclaration)field.get()).type; } return getter.type; } static Expression createFieldAccessor(EclipseNode field, FieldAccess fieldAccess, ASTNode source) { int pS = source == null ? 0 : source.sourceStart, pE = source == null ? 0 : source.sourceEnd; long p = (long)pS << 32 | pE; boolean lookForGetter = lookForGetter(field, fieldAccess); GetterMethod getter = lookForGetter ? findGetter(field) : null; if (getter == null) { FieldDeclaration fieldDecl = (FieldDeclaration)field.get(); FieldReference ref = new FieldReference(fieldDecl.name, p); if ((fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0) { EclipseNode containerNode = field.up(); if (containerNode != null && containerNode.get() instanceof TypeDeclaration) { ref.receiver = new SingleNameReference(((TypeDeclaration)containerNode.get()).name, p); } else { Expression smallRef = new FieldReference(field.getName().toCharArray(), p); if (source != null) setGeneratedBy(smallRef, source); return smallRef; } } else { ref.receiver = new ThisReference(pS, pE); } if (source != null) { setGeneratedBy(ref, source); setGeneratedBy(ref.receiver, source); } return ref; } MessageSend call = new MessageSend(); setGeneratedBy(call, source); call.sourceStart = pS; call.statementEnd = call.sourceEnd = pE; call.receiver = new ThisReference(pS, pE); setGeneratedBy(call.receiver, source); call.selector = getter.name; return call; } static Expression createFieldAccessor(EclipseNode field, FieldAccess fieldAccess, ASTNode source, char[] receiver) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; boolean lookForGetter = lookForGetter(field, fieldAccess); GetterMethod getter = lookForGetter ? findGetter(field) : null; if (getter == null) { NameReference ref; char[][] tokens = new char[2][]; tokens[0] = receiver; tokens[1] = field.getName().toCharArray(); long[] poss = {p, p}; ref = new QualifiedNameReference(tokens, poss, pS, pE); setGeneratedBy(ref, source); return ref; } MessageSend call = new MessageSend(); setGeneratedBy(call, source); call.sourceStart = pS; call.statementEnd = call.sourceEnd = pE; call.receiver = new SingleNameReference(receiver, p); setGeneratedBy(call.receiver, source); call.selector = getter.name; return call; } /** Serves as return value for the methods that check for the existence of fields and methods. */ public enum MemberExistsResult { NOT_EXISTS, EXISTS_BY_LOMBOK, EXISTS_BY_USER; } /** * Translates the given field into all possible getter names. * Convenient wrapper around {@link TransformationsUtil#toAllGetterNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static List toAllGetterNames(EclipseNode field, boolean isBoolean) { return HandlerUtil.toAllGetterNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); } /** * @return the likely getter name for the stated field. (e.g. private boolean foo; to isFoo). * * Convenient wrapper around {@link TransformationsUtil#toGetterName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toGetterName(EclipseNode field, boolean isBoolean) { return HandlerUtil.toGetterName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); } /** * Translates the given field into all possible setter names. * Convenient wrapper around {@link TransformationsUtil#toAllSetterNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static java.util.List toAllSetterNames(EclipseNode field, boolean isBoolean) { return HandlerUtil.toAllSetterNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); } /** * @return the likely setter name for the stated field. (e.g. private boolean foo; to setFoo). * * Convenient wrapper around {@link TransformationsUtil#toSetterName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toSetterName(EclipseNode field, boolean isBoolean) { return HandlerUtil.toSetterName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); } /** * Translates the given field into all possible wither names. * Convenient wrapper around {@link TransformationsUtil#toAllWitherNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static java.util.List toAllWitherNames(EclipseNode field, boolean isBoolean) { return HandlerUtil.toAllWitherNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); } /** * @return the likely wither name for the stated field. (e.g. private boolean foo; to withFoo). * * Convenient wrapper around {@link TransformationsUtil#toWitherName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toWitherName(EclipseNode field, boolean isBoolean) { return HandlerUtil.toWitherName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); } /** * When generating a setter, the setter either returns void (beanspec) or Self (fluent). * This method scans for the {@code Accessors} annotation and associated config properties to figure that out. */ public static boolean shouldReturnThis(EclipseNode field) { if ((((FieldDeclaration) field.get()).modifiers & ClassFileConstants.AccStatic) != 0) return false; AnnotationValues accessors = EclipseHandlerUtil.getAccessorsForField(field); return shouldReturnThis0(accessors, field.getAst()); } /** * Checks if the field should be included in operations that work on 'all' fields: * If the field is static, or starts with a '$', or is actually an enum constant, 'false' is returned, indicating you should skip it. */ public static boolean filterField(FieldDeclaration declaration) { return filterField(declaration, true); } public static boolean filterField(FieldDeclaration declaration, boolean skipStatic) { // Skip the fake fields that represent enum constants. if (declaration.initialization instanceof AllocationExpression && ((AllocationExpression)declaration.initialization).enumConstant != null) return false; if (declaration.type == null) return false; // Skip fields that start with $ if (declaration.name.length > 0 && declaration.name[0] == '$') return false; // Skip static fields. if (skipStatic && (declaration.modifiers & ClassFileConstants.AccStatic) != 0) return false; return true; } public static char[] removePrefixFromField(EclipseNode field) { List prefixes = null; for (EclipseNode node : field.down()) { if (annotationTypeMatches(Accessors.class, node)) { AnnotationValues ann = createAnnotation(Accessors.class, node); if (ann.isExplicit("prefix")) prefixes = Arrays.asList(ann.getInstance().prefix()); break; } } if (prefixes == null) { EclipseNode current = field.up(); outer: while (current != null) { for (EclipseNode node : current.down()) { if (annotationTypeMatches(Accessors.class, node)) { AnnotationValues ann = createAnnotation(Accessors.class, node); if (ann.isExplicit("prefix")) prefixes = Arrays.asList(ann.getInstance().prefix()); break outer; } } current = current.up(); } } if (prefixes == null) prefixes = field.getAst().readConfiguration(ConfigurationKeys.ACCESSORS_PREFIX); if (!prefixes.isEmpty()) { CharSequence newName = removePrefix(field.getName(), prefixes); if (newName != null) return newName.toString().toCharArray(); } return ((FieldDeclaration) field.get()).name; } public static AnnotationValues getAccessorsForField(EclipseNode field) { for (EclipseNode node : field.down()) { if (annotationTypeMatches(Accessors.class, node)) { return createAnnotation(Accessors.class, node); } } EclipseNode current = field.up(); while (current != null) { for (EclipseNode node : current.down()) { if (annotationTypeMatches(Accessors.class, node)) { return createAnnotation(Accessors.class, node); } } current = current.up(); } return AnnotationValues.of(Accessors.class, field); } /** * Checks if there is a field with the provided name. * * @param fieldName the field name to check for. * @param node Any node that represents the Type (TypeDeclaration) to look in, or any child node thereof. */ public static MemberExistsResult fieldExists(String fieldName, EclipseNode node) { while (node != null && !(node.get() instanceof TypeDeclaration)) { node = node.up(); } if (node != null && node.get() instanceof TypeDeclaration) { TypeDeclaration typeDecl = (TypeDeclaration)node.get(); if (typeDecl.fields != null) for (FieldDeclaration def : typeDecl.fields) { char[] fName = def.name; if (fName == null) continue; if (fieldName.equals(new String(fName))) { return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } return MemberExistsResult.NOT_EXISTS; } /** * Wrapper for {@link #methodExists(String, EclipseNode, boolean, int)} with {@code caseSensitive} = {@code true}. */ public static MemberExistsResult methodExists(String methodName, EclipseNode node, int params) { return methodExists(methodName, node, true, params); } /** * Checks if there is a method with the provided name. In case of multiple methods (overloading), only * the first method decides if EXISTS_BY_USER or EXISTS_BY_LOMBOK is returned. * * @param methodName the method name to check for. * @param node Any node that represents the Type (TypeDeclaration) to look in, or any child node thereof. * @param caseSensitive If the search should be case sensitive. * @param params The number of parameters the method should have; varargs count as 0-*. Set to -1 to find any method with the appropriate name regardless of parameter count. */ public static MemberExistsResult methodExists(String methodName, EclipseNode node, boolean caseSensitive, int params) { while (node != null && !(node.get() instanceof TypeDeclaration)) { node = node.up(); } if (node != null && node.get() instanceof TypeDeclaration) { TypeDeclaration typeDecl = (TypeDeclaration)node.get(); if (typeDecl.methods != null) top: for (AbstractMethodDeclaration def : typeDecl.methods) { if (def instanceof MethodDeclaration) { char[] mName = def.selector; if (mName == null) continue; boolean nameEquals = caseSensitive ? methodName.equals(new String(mName)) : methodName.equalsIgnoreCase(new String(mName)); if (nameEquals) { if (params > -1) { int minArgs = 0; int maxArgs = 0; if (def.arguments != null && def.arguments.length > 0) { minArgs = def.arguments.length; if ((def.arguments[def.arguments.length - 1].type.bits & ASTNode.IsVarArgs) != 0) { minArgs--; maxArgs = Integer.MAX_VALUE; } else { maxArgs = minArgs; } } if (params < minArgs || params > maxArgs) continue; } if (isTolerate(node, def)) continue top; return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } } return MemberExistsResult.NOT_EXISTS; } public static boolean isTolerate(EclipseNode node, AbstractMethodDeclaration def) { if (def.annotations != null) for (Annotation anno : def.annotations) { if (typeMatches(Tolerate.class, node, anno.type)) return true; } return false; } /** * Checks if there is a (non-default) constructor. In case of multiple constructors (overloading), only * the first constructor decides if EXISTS_BY_USER or EXISTS_BY_LOMBOK is returned. * * @param node Any node that represents the Type (TypeDeclaration) to look in, or any child node thereof. */ public static MemberExistsResult constructorExists(EclipseNode node) { while (node != null && !(node.get() instanceof TypeDeclaration)) { node = node.up(); } if (node != null && node.get() instanceof TypeDeclaration) { TypeDeclaration typeDecl = (TypeDeclaration)node.get(); if (typeDecl.methods != null) for (AbstractMethodDeclaration def : typeDecl.methods) { if (def instanceof ConstructorDeclaration) { if ((def.bits & ASTNode.IsDefaultConstructor) != 0) continue; if (isTolerate(node, def)) continue; return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } return MemberExistsResult.NOT_EXISTS; } /** * Inserts a field into an existing type. The type must represent a {@code TypeDeclaration}. * The field carries the @{@link SuppressWarnings}("all") annotation. */ public static EclipseNode injectFieldAndMarkGenerated(EclipseNode type, FieldDeclaration field) { field.annotations = addSuppressWarningsAll(type, field, field.annotations); field.annotations = addGenerated(type, field, field.annotations); return injectField(type, field); } /** * Inserts a field into an existing type. The type must represent a {@code TypeDeclaration}. */ public static EclipseNode injectField(EclipseNode type, FieldDeclaration field) { TypeDeclaration parent = (TypeDeclaration) type.get(); if (parent.fields == null) { parent.fields = new FieldDeclaration[1]; parent.fields[0] = field; } else { int size = parent.fields.length; FieldDeclaration[] newArray = new FieldDeclaration[size + 1]; System.arraycopy(parent.fields, 0, newArray, 0, size); int index = 0; for (; index < size; index++) { FieldDeclaration f = newArray[index]; if (isEnumConstant(f) || isGenerated(f)) continue; break; } System.arraycopy(newArray, index, newArray, index + 1, size - index); newArray[index] = field; parent.fields = newArray; } if (isEnumConstant(field) || (field.modifiers & Modifier.STATIC) != 0) { if (!hasClinit(parent)) { parent.addClinit(); } } return type.add(field, Kind.FIELD); } public static boolean isEnumConstant(final FieldDeclaration field) { return ((field.initialization instanceof AllocationExpression) && (((AllocationExpression) field.initialization).enumConstant == field)); } /** * Inserts a method into an existing type. The type must represent a {@code TypeDeclaration}. */ public static EclipseNode injectMethod(EclipseNode type, AbstractMethodDeclaration method) { method.annotations = addSuppressWarningsAll(type, method, method.annotations); method.annotations = addGenerated(type, method, method.annotations); TypeDeclaration parent = (TypeDeclaration) type.get(); if (parent.methods == null) { parent.methods = new AbstractMethodDeclaration[1]; parent.methods[0] = method; } else { if (method instanceof ConstructorDeclaration) { for (int i = 0 ; i < parent.methods.length ; i++) { if (parent.methods[i] instanceof ConstructorDeclaration && (parent.methods[i].bits & ASTNode.IsDefaultConstructor) != 0) { EclipseNode tossMe = type.getNodeFor(parent.methods[i]); AbstractMethodDeclaration[] withoutGeneratedConstructor = new AbstractMethodDeclaration[parent.methods.length - 1]; System.arraycopy(parent.methods, 0, withoutGeneratedConstructor, 0, i); System.arraycopy(parent.methods, i + 1, withoutGeneratedConstructor, i, parent.methods.length - i - 1); parent.methods = withoutGeneratedConstructor; if (tossMe != null) tossMe.up().removeChild(tossMe); break; } } } //We insert the method in the last position of the methods registered to the type //When changing this behavior, this may trigger issue #155 and #377 AbstractMethodDeclaration[] newArray = new AbstractMethodDeclaration[parent.methods.length + 1]; System.arraycopy(parent.methods, 0, newArray, 0, parent.methods.length); newArray[parent.methods.length] = method; parent.methods = newArray; } return type.add(method, Kind.METHOD); } /** * Adds an inner type (class, interface, enum) to the given type. Cannot inject top-level types. * * @param typeNode parent type to inject new type into * @param type New type (class, interface, etc) to inject. */ public static EclipseNode injectType(final EclipseNode typeNode, final TypeDeclaration type) { type.annotations = addSuppressWarningsAll(typeNode, type, type.annotations); type.annotations = addGenerated(typeNode, type, type.annotations); TypeDeclaration parent = (TypeDeclaration) typeNode.get(); if (parent.memberTypes == null) { parent.memberTypes = new TypeDeclaration[] { type }; } else { TypeDeclaration[] newArray = new TypeDeclaration[parent.memberTypes.length + 1]; System.arraycopy(parent.memberTypes, 0, newArray, 0, parent.memberTypes.length); newArray[parent.memberTypes.length] = type; parent.memberTypes = newArray; } return typeNode.add(type, Kind.TYPE); } private static final char[] ALL = "all".toCharArray(); private static final char[] JUSTIFICATION = "justification".toCharArray(); private static final char[] GENERATED_CODE = "generated code".toCharArray(); private static final char[] LOMBOK = "lombok".toCharArray(); private static final char[][] JAVAX_ANNOTATION_GENERATED = Eclipse.fromQualifiedName("javax.annotation.Generated"); private static final char[][] LOMBOK_GENERATED = Eclipse.fromQualifiedName("lombok.Generated"); private static final char[][] EDU_UMD_CS_FINDBUGS_ANNOTATIONS_SUPPRESSFBWARNINGS = Eclipse.fromQualifiedName("edu.umd.cs.findbugs.annotations.SuppressFBWarnings"); public static Annotation[] addSuppressWarningsAll(EclipseNode node, ASTNode source, Annotation[] originalAnnotationArray) { Annotation[] anns = addAnnotation(source, originalAnnotationArray, TypeConstants.JAVA_LANG_SUPPRESSWARNINGS, new StringLiteral(ALL, 0, 0, 0)); if (Boolean.TRUE.equals(node.getAst().readConfiguration(ConfigurationKeys.ADD_FINDBUGS_SUPPRESSWARNINGS_ANNOTATIONS))) { MemberValuePair mvp = new MemberValuePair(JUSTIFICATION, 0, 0, new StringLiteral(GENERATED_CODE, 0, 0, 0)); anns = addAnnotation(source, anns, EDU_UMD_CS_FINDBUGS_ANNOTATIONS_SUPPRESSFBWARNINGS, mvp); } return anns; } public static Annotation[] addGenerated(EclipseNode node, ASTNode source, Annotation[] originalAnnotationArray) { Annotation[] result = originalAnnotationArray; if (HandlerUtil.shouldAddGenerated(node)) { result = addAnnotation(source, result, JAVAX_ANNOTATION_GENERATED, new StringLiteral(LOMBOK, 0, 0, 0)); } if (Boolean.TRUE.equals(node.getAst().readConfiguration(ConfigurationKeys.ADD_LOMBOK_GENERATED_ANNOTATIONS))) { result = addAnnotation(source, result, LOMBOK_GENERATED, null); } return result; } private static Annotation[] addAnnotation(ASTNode source, Annotation[] originalAnnotationArray, char[][] annotationTypeFqn, ASTNode arg) { char[] simpleName = annotationTypeFqn[annotationTypeFqn.length - 1]; if (originalAnnotationArray != null) for (Annotation ann : originalAnnotationArray) { if (ann.type instanceof QualifiedTypeReference) { char[][] t = ((QualifiedTypeReference) ann.type).tokens; if (Arrays.deepEquals(t, annotationTypeFqn)) return originalAnnotationArray; } if (ann.type instanceof SingleTypeReference) { char[] lastToken = ((SingleTypeReference) ann.type).token; if (Arrays.equals(lastToken, simpleName)) return originalAnnotationArray; } } int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; long[] poss = new long[annotationTypeFqn.length]; Arrays.fill(poss, p); QualifiedTypeReference qualifiedType = new QualifiedTypeReference(annotationTypeFqn, poss); setGeneratedBy(qualifiedType, source); Annotation ann; if (arg instanceof Expression) { SingleMemberAnnotation sma = new SingleMemberAnnotation(qualifiedType, pS); sma.declarationSourceEnd = pE; arg.sourceStart = pS; arg.sourceEnd = pE; sma.memberValue = (Expression) arg; setGeneratedBy(sma.memberValue, source); ann = sma; } else if (arg instanceof MemberValuePair) { NormalAnnotation na = new NormalAnnotation(qualifiedType, pS); na.declarationSourceEnd = pE; arg.sourceStart = pS; arg.sourceEnd = pE; na.memberValuePairs = new MemberValuePair[] {(MemberValuePair) arg}; setGeneratedBy(na.memberValuePairs[0], source); setGeneratedBy(na.memberValuePairs[0].value, source); na.memberValuePairs[0].value.sourceStart = pS; na.memberValuePairs[0].value.sourceEnd = pE; ann = na; } else { MarkerAnnotation ma = new MarkerAnnotation(qualifiedType, pS); ma.declarationSourceEnd = pE; ann = ma; } setGeneratedBy(ann, source); if (originalAnnotationArray == null) return new Annotation[] { ann }; Annotation[] newAnnotationArray = new Annotation[originalAnnotationArray.length + 1]; System.arraycopy(originalAnnotationArray, 0, newAnnotationArray, 0, originalAnnotationArray.length); newAnnotationArray[originalAnnotationArray.length] = ann; return newAnnotationArray; } /** * Generates a new statement that checks if the given variable is null, and if so, throws a specified exception with the * variable name as message. * * @param exName The name of the exception to throw; normally {@code java.lang.NullPointerException}. */ public static Statement generateNullCheck(AbstractVariableDeclaration variable, EclipseNode sourceNode) { NullCheckExceptionType exceptionType = sourceNode.getAst().readConfiguration(ConfigurationKeys.NON_NULL_EXCEPTION_TYPE); if (exceptionType == null) exceptionType = NullCheckExceptionType.NULL_POINTER_EXCEPTION; ASTNode source = sourceNode.get(); int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; if (isPrimitive(variable.type)) return null; AllocationExpression exception = new AllocationExpression(); setGeneratedBy(exception, source); int partCount = 1; String exceptionTypeStr = exceptionType.getExceptionType(); for (int i = 0; i < exceptionTypeStr.length(); i++) if (exceptionTypeStr.charAt(i) == '.') partCount++; long[] ps = new long[partCount]; Arrays.fill(ps, 0L); exception.type = new QualifiedTypeReference(fromQualifiedName(exceptionTypeStr), ps); setGeneratedBy(exception.type, source); exception.arguments = new Expression[] { new StringLiteral(exceptionType.toExceptionMessage(new String(variable.name)).toCharArray(), pS, pE, 0) }; setGeneratedBy(exception.arguments[0], source); ThrowStatement throwStatement = new ThrowStatement(exception, pS, pE); setGeneratedBy(throwStatement, source); SingleNameReference varName = new SingleNameReference(variable.name, p); setGeneratedBy(varName, source); NullLiteral nullLiteral = new NullLiteral(pS, pE); setGeneratedBy(nullLiteral, source); EqualExpression equalExpression = new EqualExpression(varName, nullLiteral, OperatorIds.EQUAL_EQUAL); equalExpression.sourceStart = pS; equalExpression.statementEnd = equalExpression.sourceEnd = pE; setGeneratedBy(equalExpression, source); Block throwBlock = new Block(0); throwBlock.statements = new Statement[] {throwStatement}; throwBlock.sourceStart = pS; throwBlock.sourceEnd = pE; setGeneratedBy(throwBlock, source); IfStatement ifStatement = new IfStatement(equalExpression, throwBlock, 0, 0); setGeneratedBy(ifStatement, source); return ifStatement; } /** * Create an annotation of the given name, and is marked as being generated by the given source. */ public static MarkerAnnotation makeMarkerAnnotation(char[][] name, ASTNode source) { long pos = (long)source.sourceStart << 32 | source.sourceEnd; TypeReference typeRef = new QualifiedTypeReference(name, new long[] {pos, pos, pos}); setGeneratedBy(typeRef, source); MarkerAnnotation ann = new MarkerAnnotation(typeRef, (int)(pos >> 32)); ann.declarationSourceEnd = ann.sourceEnd = ann.statementEnd = (int)pos; setGeneratedBy(ann, source); return ann; } /** * Given a list of field names and a node referring to a type, finds each name in the list that does not match a field within the type. */ public static List createListOfNonExistentFields(List list, EclipseNode type, boolean excludeStandard, boolean excludeTransient) { boolean[] matched = new boolean[list.size()]; for (EclipseNode child : type.down()) { if (list.isEmpty()) break; if (child.getKind() != Kind.FIELD) continue; if (excludeStandard) { if ((((FieldDeclaration)child.get()).modifiers & ClassFileConstants.AccStatic) != 0) continue; if (child.getName().startsWith("$")) continue; } if (excludeTransient && (((FieldDeclaration)child.get()).modifiers & ClassFileConstants.AccTransient) != 0) continue; int idx = list.indexOf(child.getName()); if (idx > -1) matched[idx] = true; } List problematic = new ArrayList(); for (int i = 0 ; i < list.size() ; i++) { if (!matched[i]) problematic.add(i); } return problematic; } /** * In eclipse 3.7+, the CastExpression constructor was changed from a really weird version to * a less weird one. Unfortunately that means we need to use reflection as we want to be compatible * with eclipse versions before 3.7 and 3.7+. * * @param ref The {@code foo} in {@code (String)foo}. * @param castTo The {@code String} in {@code (String)foo}. */ public static CastExpression makeCastExpression(Expression ref, TypeReference castTo, ASTNode source) { CastExpression result; try { if (castExpressionConstructorIsTypeRefBased) { result = castExpressionConstructor.newInstance(ref, castTo); } else { Expression castToConverted = castTo; if (castTo.getClass() == SingleTypeReference.class && !isPrimitive(castTo)) { SingleTypeReference str = (SingleTypeReference) castTo; //Why a SingleNameReference instead of a SingleTypeReference you ask? I don't know. It seems dumb. Ask the ecj guys. castToConverted = new SingleNameReference(str.token, 0); castToConverted.bits = (castToConverted.bits & ~Binding.VARIABLE) | Binding.TYPE; castToConverted.sourceStart = str.sourceStart; castToConverted.sourceEnd = str.sourceEnd; setGeneratedBy(castToConverted, source); } else if (castTo.getClass() == QualifiedTypeReference.class) { QualifiedTypeReference qtr = (QualifiedTypeReference) castTo; //Same here, but for the more complex types, they stay types. castToConverted = new QualifiedNameReference(qtr.tokens, copy(qtr.sourcePositions), qtr.sourceStart, qtr.sourceEnd); castToConverted.bits = (castToConverted.bits & ~Binding.VARIABLE) | Binding.TYPE; setGeneratedBy(castToConverted, source); } result = castExpressionConstructor.newInstance(ref, castToConverted); } } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InstantiationException e) { throw Lombok.sneakyThrow(e); } result.sourceStart = source.sourceStart; result.sourceEnd = source.sourceEnd; result.statementEnd = source.sourceEnd; setGeneratedBy(result, source); return result; } private static final Constructor castExpressionConstructor; private static final boolean castExpressionConstructorIsTypeRefBased; static { Constructor constructor = null; for (Constructor ctor : CastExpression.class.getConstructors()) { if (ctor.getParameterTypes().length != 2) continue; constructor = ctor; } @SuppressWarnings("unchecked") Constructor castExpressionConstructor_ = (Constructor) constructor; castExpressionConstructor = castExpressionConstructor_; castExpressionConstructorIsTypeRefBased = (castExpressionConstructor.getParameterTypes()[1] == TypeReference.class); } /** * In eclipse 3.7+, IntLiterals are created using a factory-method * Unfortunately that means we need to use reflection as we want to be compatible * with eclipse versions before 3.7. */ public static IntLiteral makeIntLiteral(char[] token, ASTNode source) { int pS = source == null ? 0 : source.sourceStart, pE = source == null ? 0 : source.sourceEnd; IntLiteral result; try { if (intLiteralConstructor != null) { result = intLiteralConstructor.newInstance(token, pS, pE); } else { result = (IntLiteral) intLiteralFactoryMethod.invoke(null, token, pS, pE); } } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InstantiationException e) { throw Lombok.sneakyThrow(e); } if (source != null) setGeneratedBy(result, source); return result; } private static final Constructor intLiteralConstructor; private static final Method intLiteralFactoryMethod; static { Class[] parameterTypes = {char[].class, int.class, int.class}; Constructor intLiteralConstructor_ = null; Method intLiteralFactoryMethod_ = null; try { intLiteralConstructor_ = IntLiteral.class.getConstructor(parameterTypes); } catch (Throwable ignore) { // probably eclipse 3.7++ } try { intLiteralFactoryMethod_ = IntLiteral.class.getMethod("buildIntLiteral", parameterTypes); } catch (Throwable ignore) { // probably eclipse versions before 3.7 } intLiteralConstructor = intLiteralConstructor_; intLiteralFactoryMethod = intLiteralFactoryMethod_; } private static boolean isAllValidOnXCharacters(char[] in) { if (in == null || in.length == 0) return false; for (char c : in) if (c != '_' && c != 'X' && c != 'x' && c != '$') return false; return true; } public static void addError(String errorName, EclipseNode node) { if (node.getLatestJavaSpecSupported() < 8) { node.addError("The correct format is " + errorName + "_={@SomeAnnotation, @SomeOtherAnnotation})"); } else { node.addError("The correct format is " + errorName + "=@__({@SomeAnnotation, @SomeOtherAnnotation}))"); } } public static List unboxAndRemoveAnnotationParameter(Annotation annotation, String annotationName, String errorName, EclipseNode errorNode) { if ("value".equals(annotationName)) { // We can't unbox this, because SingleMemberAnnotation REQUIRES a value, and this method // is supposed to remove the value. That means we need to replace the SMA with either // MarkerAnnotation or NormalAnnotation and that is beyond the scope of this method as we // don't need that at the time of writing this method; we only unbox onMethod, onParameter // and onConstructor. Let's exit early and very obviously: throw new UnsupportedOperationException("Lombok cannot unbox 'value' from SingleMemberAnnotation at this time."); } if (!NormalAnnotation.class.equals(annotation.getClass())) { // Prevent MarkerAnnotation, SingleMemberAnnotation, and // CompletionOnAnnotationMemberValuePair from triggering this handler. return Collections.emptyList(); } NormalAnnotation normalAnnotation = (NormalAnnotation) annotation; MemberValuePair[] pairs = normalAnnotation.memberValuePairs; if (pairs == null) return Collections.emptyList(); char[] nameAsCharArray = annotationName.toCharArray(); top: for (int i = 0; i < pairs.length; i++) { boolean allowRaw; char[] name = pairs[i].name; if (name == null) continue; if (name.length < nameAsCharArray.length) continue; for (int j = 0; j < nameAsCharArray.length; j++) { if (name[j] != nameAsCharArray[j]) continue top; } allowRaw = name.length > nameAsCharArray.length; for (int j = nameAsCharArray.length; j < name.length; j++) { if (name[j] != '_') continue top; } // If we're still here it's the targeted annotation param. Expression value = pairs[i].value; MemberValuePair[] newPairs = new MemberValuePair[pairs.length - 1]; if (i > 0) System.arraycopy(pairs, 0, newPairs, 0, i); if (i < pairs.length - 1) System.arraycopy(pairs, i + 1, newPairs, i, pairs.length - i - 1); normalAnnotation.memberValuePairs = newPairs; // We have now removed the annotation parameter and stored the value, // which we must now unbox. It's either annotations, or @__(annotations). Expression content = null; if (value instanceof ArrayInitializer) { if (!allowRaw) { addError(errorName, errorNode); return Collections.emptyList(); } content = value; } else if (!(value instanceof Annotation)) { addError(errorName, errorNode); return Collections.emptyList(); } else { Annotation atDummyIdentifier = (Annotation) value; if (atDummyIdentifier.type instanceof SingleTypeReference && isAllValidOnXCharacters(((SingleTypeReference) atDummyIdentifier.type).token)) { if (atDummyIdentifier instanceof MarkerAnnotation) { return Collections.emptyList(); } else if (atDummyIdentifier instanceof NormalAnnotation) { MemberValuePair[] mvps = ((NormalAnnotation) atDummyIdentifier).memberValuePairs; if (mvps == null || mvps.length == 0) { return Collections.emptyList(); } if (mvps.length == 1 && Arrays.equals("value".toCharArray(), mvps[0].name)) { content = mvps[0].value; } } else if (atDummyIdentifier instanceof SingleMemberAnnotation) { content = ((SingleMemberAnnotation) atDummyIdentifier).memberValue; } else { addError(errorName, errorNode); return Collections.emptyList(); } } else { if (allowRaw) { content = atDummyIdentifier; } else { addError(errorName, errorNode); return Collections.emptyList(); } } } if (content == null) { addError(errorName, errorNode); return Collections.emptyList(); } if (content instanceof Annotation) { return Collections.singletonList((Annotation) content); } else if (content instanceof ArrayInitializer) { Expression[] expressions = ((ArrayInitializer) content).expressions; List result = new ArrayList(); if (expressions != null) for (Expression ex : expressions) { if (ex instanceof Annotation) result.add((Annotation) ex); else { addError(errorName, errorNode); return Collections.emptyList(); } } return result; } else { addError(errorName, errorNode); return Collections.emptyList(); } } return Collections.emptyList(); } public static NameReference createNameReference(String name, Annotation source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; char[][] nameTokens = fromQualifiedName(name); long[] pos = new long[nameTokens.length]; Arrays.fill(pos, p); QualifiedNameReference nameReference = new QualifiedNameReference(nameTokens, pos, pS, pE); nameReference.statementEnd = pE; setGeneratedBy(nameReference, source); return nameReference; } private static long[] copy(long[] array) { return array == null ? null : array.clone(); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/EclipseSingularsRecipes.java000066400000000000000000000344451312655740700270570ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.eclipse.jdt.internal.compiler.lookup.MethodScope; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import lombok.core.LombokImmutableList; import lombok.core.SpiLoadUtil; import lombok.core.TypeLibrary; import lombok.eclipse.EclipseNode; public class EclipseSingularsRecipes { private static final EclipseSingularsRecipes INSTANCE = new EclipseSingularsRecipes(); private final Map singularizers = new HashMap(); private final TypeLibrary singularizableTypes = new TypeLibrary(); private EclipseSingularsRecipes() { try { loadAll(singularizableTypes, singularizers); singularizableTypes.lock(); } catch (IOException e) { System.err.println("Lombok's @Singularizable feature is broken due to misconfigured SPI files: " + e); } } private static void loadAll(TypeLibrary library, Map map) throws IOException { for (EclipseSingularizer handler : SpiLoadUtil.findServices(EclipseSingularizer.class, EclipseSingularizer.class.getClassLoader())) { for (String type : handler.getSupportedTypes()) { EclipseSingularizer existingSingularizer = map.get(type); if (existingSingularizer != null) { EclipseSingularizer toKeep = existingSingularizer.getClass().getName().compareTo(handler.getClass().getName()) > 0 ? handler : existingSingularizer; System.err.println("Multiple singularizers found for type " + type + "; the alphabetically first class is used: " + toKeep.getClass().getName()); map.put(type, toKeep); } else { map.put(type, handler); library.addType(type); } } } } public static EclipseSingularsRecipes get() { return INSTANCE; } public String toQualified(String typeReference) { return singularizableTypes.toQualified(typeReference); } public EclipseSingularizer getSingularizer(String fqn) { return singularizers.get(fqn); } public static final class SingularData { private final EclipseNode annotation; private final char[] singularName; private final char[] pluralName; private final List typeArgs; private final String targetFqn; private final EclipseSingularizer singularizer; private final ASTNode source; public SingularData(EclipseNode annotation, char[] singularName, char[] pluralName, List typeArgs, String targetFqn, EclipseSingularizer singularizer, ASTNode source) { this.annotation = annotation; this.singularName = singularName; this.pluralName = pluralName; this.typeArgs = typeArgs; this.targetFqn = targetFqn; this.singularizer = singularizer; this.source = source; } public void setGeneratedByRecursive(ASTNode target) { SetGeneratedByVisitor visitor = new SetGeneratedByVisitor(source); if (target instanceof AbstractMethodDeclaration) { ((AbstractMethodDeclaration) target).traverse(visitor, (ClassScope) null); } else if (target instanceof FieldDeclaration) { ((FieldDeclaration) target).traverse(visitor, (MethodScope) null); } else { target.traverse(visitor, null); } } public ASTNode getSource() { return source; } public EclipseNode getAnnotation() { return annotation; } public char[] getSingularName() { return singularName; } public char[] getPluralName() { return pluralName; } public List getTypeArgs() { return typeArgs; } public String getTargetFqn() { return targetFqn; } public EclipseSingularizer getSingularizer() { return singularizer; } public String getTargetSimpleType() { int idx = targetFqn.lastIndexOf("."); return idx == -1 ? targetFqn : targetFqn.substring(idx + 1); } } public static abstract class EclipseSingularizer { protected static final long[] NULL_POSS = {0L}; public abstract LombokImmutableList getSupportedTypes(); /** Checks if any of the to-be-generated nodes (fields, methods) already exist. If so, errors on these (singulars don't support manually writing some of it, and returns true). */ public boolean checkForAlreadyExistingNodesAndGenerateError(EclipseNode builderType, SingularData data) { for (EclipseNode child : builderType.down()) { switch (child.getKind()) { case FIELD: { FieldDeclaration fd = (FieldDeclaration) child.get(); char[] name = fd.name; if (name == null) continue; if (getGeneratedBy(fd) != null) continue; for (char[] fieldToBeGenerated : listFieldsToBeGenerated(data, builderType)) { if (!Arrays.equals(name, fieldToBeGenerated)) continue; child.addError("Manually adding a field that @Singular @Builder would generate is not supported. If you want to manually manage the builder aspect for this field/parameter, don't use @Singular."); return true; } break; } case METHOD: { AbstractMethodDeclaration method = (AbstractMethodDeclaration) child.get(); char[] name = method.selector; if (name == null) continue; if (getGeneratedBy(method) != null) continue; for (char[] methodToBeGenerated : listMethodsToBeGenerated(data, builderType)) { if (!Arrays.equals(name, methodToBeGenerated)) continue; child.addError("Manually adding a method that @Singular @Builder would generate is not supported. If you want to manually manage the builder aspect for this field/parameter, don't use @Singular."); return true; } break; }} } return false; } public List listFieldsToBeGenerated(SingularData data, EclipseNode builderType) { return Collections.singletonList(data.pluralName); } public List listMethodsToBeGenerated(SingularData data, EclipseNode builderType) { char[] p = data.pluralName; char[] s = data.singularName; if (Arrays.equals(p, s)) return Collections.singletonList(p); return Arrays.asList(p, s); } public abstract List generateFields(SingularData data, EclipseNode builderType); public abstract void generateMethods(SingularData data, boolean deprecate, EclipseNode builderType, boolean fluent, boolean chain); public abstract void appendBuildCode(SingularData data, EclipseNode builderType, List statements, char[] targetVariableName); public boolean requiresCleaning() { try { return !getClass().getMethod("appendCleaningCode", SingularData.class, EclipseNode.class, List.class).getDeclaringClass().equals(EclipseSingularizer.class); } catch (NoSuchMethodException e) { return false; } } public void appendCleaningCode(SingularData data, EclipseNode builderType, List statements) { } // -- Utility methods -- /** * Adds the requested number of type arguments to the provided type, copying each argument in {@code typeArgs}. If typeArgs is too long, the extra elements are ignored. * If {@code typeArgs} is null or too short, {@code java.lang.Object} will be substituted for each missing type argument. * * @param count The number of type arguments requested. * @param addExtends If {@code true}, all bounds are either '? extends X' or just '?'. If false, the reverse is applied, and '? extends Foo' is converted to Foo, '?' to Object, etc. * @param node Some node in the same AST. Just used to obtain makers and contexts and such. * @param type The type to add generics to. * @param typeArgs the list of type args to clone. * @param source The source annotation that is the root cause of this code generation. */ protected TypeReference addTypeArgs(int count, boolean addExtends, EclipseNode node, TypeReference type, List typeArgs) { TypeReference[] clonedAndFixedArgs = createTypeArgs(count, addExtends, node, typeArgs); if (type instanceof SingleTypeReference) { type = new ParameterizedSingleTypeReference(((SingleTypeReference) type).token, clonedAndFixedArgs, 0, 0L); } else if (type instanceof QualifiedTypeReference) { QualifiedTypeReference qtr = (QualifiedTypeReference) type; TypeReference[][] trs = new TypeReference[qtr.tokens.length][]; trs[qtr.tokens.length - 1] = clonedAndFixedArgs; type = new ParameterizedQualifiedTypeReference(((QualifiedTypeReference) type).tokens, trs, 0, NULL_POSS); } else { node.addError("Don't know how to clone-and-parameterize type: " + type); } return type; } protected TypeReference[] createTypeArgs(int count, boolean addExtends, EclipseNode node, List typeArgs) { if (count < 0) throw new IllegalArgumentException("count is negative"); if (count == 0) return null; List arguments = new ArrayList(); if (typeArgs != null) for (TypeReference orig : typeArgs) { Wildcard wildcard = orig instanceof Wildcard ? (Wildcard) orig : null; if (!addExtends) { if (wildcard != null && (wildcard.kind == Wildcard.UNBOUND || wildcard.kind == Wildcard.SUPER)) { arguments.add(new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, NULL_POSS)); } else if (wildcard != null && wildcard.kind == Wildcard.EXTENDS) { try { arguments.add(copyType(wildcard.bound)); } catch (Exception e) { arguments.add(new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, NULL_POSS)); } } else { arguments.add(copyType(orig)); } } else { if (wildcard != null && (wildcard.kind == Wildcard.UNBOUND || wildcard.kind == Wildcard.SUPER)) { Wildcard w = new Wildcard(Wildcard.UNBOUND); arguments.add(w); } else if (wildcard != null && wildcard.kind == Wildcard.EXTENDS) { arguments.add(copyType(orig)); } else { Wildcard w = new Wildcard(Wildcard.EXTENDS); w.bound = copyType(orig); arguments.add(w); } } if (--count == 0) break; } while (count-- > 0) { if (addExtends) { arguments.add(new Wildcard(Wildcard.UNBOUND)); } else { arguments.add(new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, NULL_POSS)); } } if (arguments.isEmpty()) return null; return arguments.toArray(new TypeReference[arguments.size()]); } private static final char[] SIZE_TEXT = new char[] {'s', 'i', 'z', 'e'}; /** Generates 'this.name.size()' as an expression; if nullGuard is true, it's this.name == null ? 0 : this.name.size(). */ protected Expression getSize(EclipseNode builderType, char[] name, boolean nullGuard) { MessageSend invoke = new MessageSend(); ThisReference thisRef = new ThisReference(0, 0); FieldReference thisDotName = new FieldReference(name, 0L); thisDotName.receiver = thisRef; invoke.receiver = thisDotName; invoke.selector = SIZE_TEXT; if (!nullGuard) return invoke; ThisReference cdnThisRef = new ThisReference(0, 0); FieldReference cdnThisDotName = new FieldReference(name, 0L); cdnThisDotName.receiver = cdnThisRef; NullLiteral nullLiteral = new NullLiteral(0, 0); EqualExpression isNull = new EqualExpression(cdnThisDotName, nullLiteral, OperatorIds.EQUAL_EQUAL); IntLiteral zeroLiteral = makeIntLiteral(new char[] {'0'}, null); ConditionalExpression conditional = new ConditionalExpression(isNull, zeroLiteral, invoke); return conditional; } protected TypeReference cloneParamType(int index, List typeArgs, EclipseNode builderType) { if (typeArgs != null && typeArgs.size() > index) { TypeReference originalType = typeArgs.get(index); if (originalType instanceof Wildcard) { Wildcard wOriginalType = (Wildcard) originalType; if (wOriginalType.kind == Wildcard.EXTENDS) { try { return copyType(wOriginalType.bound); } catch (Exception e) { // fallthrough } } } else { return copyType(originalType); } } return new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, NULL_POSS); } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleAccessors.java000066400000000000000000000040071312655740700253200ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.handleExperimentalFlagUsage; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.experimental.Accessors; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.mangosdk.spi.ProviderFor; @ProviderFor(EclipseAnnotationHandler.class) @HandlerPriority(65536) public class HandleAccessors extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { // Accessors itself is handled by HandleGetter/Setter; this is just to ensure that usages are flagged if requested. handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.ACCESSORS_FLAG_USAGE, "@Accessors"); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleBuilder.java000066400000000000000000001114711312655740700247650ustar00rootroot00000000000000/* * Copyright (C) 2013-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.eclipse.Eclipse.*; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedThisReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.ast.UnaryExpression; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.eclipse.jdt.internal.compiler.lookup.MethodScope; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.mangosdk.spi.ProviderFor; import lombok.AccessLevel; import lombok.Builder; import lombok.Builder.ObtainVia; import lombok.ConfigurationKeys; import lombok.Singular; import lombok.core.AST.Kind; import lombok.core.handlers.HandlerUtil; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; import lombok.eclipse.handlers.EclipseSingularsRecipes.SingularData; import lombok.eclipse.handlers.HandleConstructor.SkipIfConstructorExists; import lombok.experimental.NonFinal; @ProviderFor(EclipseAnnotationHandler.class) @HandlerPriority(-1024) //-2^10; to ensure we've picked up @FieldDefault's changes (-2048) but @Value hasn't removed itself yet (-512), so that we can error on presence of it on the builder classes. public class HandleBuilder extends EclipseAnnotationHandler { private static final char[] CLEAN_FIELD_NAME = "$lombokUnclean".toCharArray(); private static final char[] CLEAN_METHOD_NAME = "$lombokClean".toCharArray(); private static final boolean toBoolean(Object expr, boolean defaultValue) { if (expr == null) return defaultValue; if (expr instanceof FalseLiteral) return false; if (expr instanceof TrueLiteral) return true; return ((Boolean) expr).booleanValue(); } private static class BuilderFieldData { TypeReference type; char[] rawName; char[] name; char[] nameOfDefaultProvider; char[] nameOfSetFlag; SingularData singularData; ObtainVia obtainVia; EclipseNode obtainViaNode; EclipseNode originalFieldNode; List createdFields = new ArrayList(); } private static boolean equals(String a, char[] b) { if (a.length() != b.length) return false; for (int i = 0; i < b.length; i++) { if (a.charAt(i) != b[i]) return false; } return true; } private static boolean equals(String a, char[][] b) { if (a == null || a.isEmpty()) return b.length == 0; String[] aParts = a.split("\\."); if (aParts.length != b.length) return false; for (int i = 0; i < b.length; i++) { if (!equals(aParts[i], b[i])) return false; } return true; } private static final char[] DEFAULT_PREFIX = {'$', 'd', 'e', 'f', 'a', 'u', 'l', 't', '$'}; private static final char[] SET_PREFIX = {'$', 's', 'e', 't'}; private static final char[] prefixWith(char[] prefix, char[] name) { char[] out = new char[prefix.length + name.length]; System.arraycopy(prefix, 0, out, 0, prefix.length); System.arraycopy(name, 0, out, prefix.length, name.length); return out; } @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { long p = (long) ast.sourceStart << 32 | ast.sourceEnd; Builder builderInstance = annotation.getInstance(); // These exist just to support the 'old' lombok.experimental.Builder, which had these properties. lombok.Builder no longer has them. boolean fluent = toBoolean(annotation.getActualExpression("fluent"), true); boolean chain = toBoolean(annotation.getActualExpression("chain"), true); String builderMethodName = builderInstance.builderMethodName(); String buildMethodName = builderInstance.buildMethodName(); String builderClassName = builderInstance.builderClassName(); String toBuilderMethodName = "toBuilder"; boolean toBuilder = builderInstance.toBuilder(); List typeArgsForToBuilder = null; if (builderMethodName == null) builderMethodName = "builder"; if (buildMethodName == null) builderMethodName = "build"; if (builderClassName == null) builderClassName = ""; if (!checkName("builderMethodName", builderMethodName, annotationNode)) return; if (!checkName("buildMethodName", buildMethodName, annotationNode)) return; if (!builderClassName.isEmpty()) { if (!checkName("builderClassName", builderClassName, annotationNode)) return; } EclipseNode parent = annotationNode.up(); List builderFields = new ArrayList(); TypeReference returnType; TypeParameter[] typeParams; TypeReference[] thrownExceptions; char[] nameOfStaticBuilderMethod; EclipseNode tdParent; EclipseNode fillParametersFrom = parent.get() instanceof AbstractMethodDeclaration ? parent : null; boolean addCleaning = false; boolean isStatic = true; if (parent.get() instanceof TypeDeclaration) { tdParent = parent; TypeDeclaration td = (TypeDeclaration) tdParent.get(); List allFields = new ArrayList(); @SuppressWarnings("deprecation") boolean valuePresent = (hasAnnotation(lombok.Value.class, parent) || hasAnnotation(lombok.experimental.Value.class, parent)); for (EclipseNode fieldNode : HandleConstructor.findAllFields(tdParent, true)) { FieldDeclaration fd = (FieldDeclaration) fieldNode.get(); EclipseNode isDefault = findAnnotation(Builder.Default.class, fieldNode); boolean isFinal = ((fd.modifiers & ClassFileConstants.AccFinal) != 0) || (valuePresent && !hasAnnotation(NonFinal.class, fieldNode)); BuilderFieldData bfd = new BuilderFieldData(); bfd.rawName = fieldNode.getName().toCharArray(); bfd.name = removePrefixFromField(fieldNode); bfd.type = fd.type; bfd.singularData = getSingularData(fieldNode, ast); bfd.originalFieldNode = fieldNode; if (bfd.singularData != null && isDefault != null) { isDefault.addError("@Builder.Default and @Singular cannot be mixed."); isDefault = null; } if (fd.initialization == null && isDefault != null) { isDefault.addWarning("@Builder.Default requires an initializing expression (' = something;')."); isDefault = null; } if (fd.initialization != null && isDefault == null) { if (isFinal) continue; fieldNode.addWarning("@Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final."); } if (isDefault != null) { bfd.nameOfDefaultProvider = prefixWith(DEFAULT_PREFIX, bfd.name); bfd.nameOfSetFlag = prefixWith(bfd.name, SET_PREFIX); MethodDeclaration md = generateDefaultProvider(bfd.nameOfDefaultProvider, fieldNode, ast); if (md != null) injectMethod(tdParent, md); } addObtainVia(bfd, fieldNode); builderFields.add(bfd); allFields.add(fieldNode); } new HandleConstructor().generateConstructor(tdParent, AccessLevel.PACKAGE, allFields, false, null, SkipIfConstructorExists.I_AM_BUILDER, Collections.emptyList(), annotationNode); returnType = namePlusTypeParamsToTypeReference(td.name, td.typeParameters, p); typeParams = td.typeParameters; thrownExceptions = null; nameOfStaticBuilderMethod = null; if (builderClassName.isEmpty()) builderClassName = new String(td.name) + "Builder"; } else if (parent.get() instanceof ConstructorDeclaration) { ConstructorDeclaration cd = (ConstructorDeclaration) parent.get(); if (cd.typeParameters != null && cd.typeParameters.length > 0) { annotationNode.addError("@Builder is not supported on constructors with constructor type parameters."); return; } tdParent = parent.up(); TypeDeclaration td = (TypeDeclaration) tdParent.get(); returnType = namePlusTypeParamsToTypeReference(td.name, td.typeParameters, p); typeParams = td.typeParameters; thrownExceptions = cd.thrownExceptions; nameOfStaticBuilderMethod = null; if (builderClassName.isEmpty()) builderClassName = new String(cd.selector) + "Builder"; } else if (parent.get() instanceof MethodDeclaration) { MethodDeclaration md = (MethodDeclaration) parent.get(); tdParent = parent.up(); isStatic = md.isStatic(); if (toBuilder) { final String TO_BUILDER_NOT_SUPPORTED = "@Builder(toBuilder=true) is only supported if you return your own type."; char[] token; char[][] pkg = null; if (md.returnType.dimensions() > 0) { annotationNode.addError(TO_BUILDER_NOT_SUPPORTED); return; } if (md.returnType instanceof SingleTypeReference) { token = ((SingleTypeReference) md.returnType).token; } else if (md.returnType instanceof QualifiedTypeReference) { pkg = ((QualifiedTypeReference) md.returnType).tokens; token = pkg[pkg.length]; char[][] pkg_ = new char[pkg.length - 1][]; System.arraycopy(pkg, 0, pkg_, 0, pkg_.length); pkg = pkg_; } else { annotationNode.addError(TO_BUILDER_NOT_SUPPORTED); return; } if (pkg != null && !equals(parent.getPackageDeclaration(), pkg)) { annotationNode.addError(TO_BUILDER_NOT_SUPPORTED); return; } if (tdParent == null || !equals(tdParent.getName(), token)) { annotationNode.addError(TO_BUILDER_NOT_SUPPORTED); return; } TypeParameter[] tpOnType = ((TypeDeclaration) tdParent.get()).typeParameters; TypeParameter[] tpOnMethod = md.typeParameters; TypeReference[][] tpOnRet_ = null; if (md.returnType instanceof ParameterizedSingleTypeReference) { tpOnRet_ = new TypeReference[1][]; tpOnRet_[0] = ((ParameterizedSingleTypeReference) md.returnType).typeArguments; } else if (md.returnType instanceof ParameterizedQualifiedTypeReference) { tpOnRet_ = ((ParameterizedQualifiedTypeReference) md.returnType).typeArguments; } if (tpOnRet_ != null) for (int i = 0; i < tpOnRet_.length - 1; i++) { if (tpOnRet_[i] != null && tpOnRet_[i].length > 0) { annotationNode.addError("@Builder(toBuilder=true) is not supported if returning a type with generics applied to an intermediate."); return; } } TypeReference[] tpOnRet = tpOnRet_ == null ? null : tpOnRet_[tpOnRet_.length - 1]; typeArgsForToBuilder = new ArrayList(); // Every typearg on this method needs to be found in the return type, but the reverse is not true. // We also need to 'map' them. if (tpOnMethod != null) for (TypeParameter onMethod : tpOnMethod) { int pos = -1; if (tpOnRet != null) for (int i = 0; i < tpOnRet.length; i++) { if (tpOnRet[i].getClass() != SingleTypeReference.class) continue; if (!Arrays.equals(((SingleTypeReference) tpOnRet[i]).token, onMethod.name)) continue; pos = i; } if (pos == -1 || tpOnType == null || tpOnType.length <= pos) { annotationNode.addError("@Builder(toBuilder=true) requires that each type parameter on the static method is part of the typeargs of the return value. Type parameter " + new String(onMethod.name) + " is not part of the return type."); return; } typeArgsForToBuilder.add(tpOnType[pos].name); } } returnType = copyType(md.returnType, ast); typeParams = md.typeParameters; thrownExceptions = md.thrownExceptions; nameOfStaticBuilderMethod = md.selector; if (builderClassName.isEmpty()) { char[] token; if (md.returnType instanceof QualifiedTypeReference) { char[][] tokens = ((QualifiedTypeReference) md.returnType).tokens; token = tokens[tokens.length - 1]; } else if (md.returnType instanceof SingleTypeReference) { token = ((SingleTypeReference) md.returnType).token; if (!(md.returnType instanceof ParameterizedSingleTypeReference) && typeParams != null) { for (TypeParameter tp : typeParams) { if (Arrays.equals(tp.name, token)) { annotationNode.addError("@Builder requires specifying 'builderClassName' if used on methods with a type parameter as return type."); return; } } } } else { annotationNode.addError("Unexpected kind of return type on annotated method. Specify 'builderClassName' to solve this problem."); return; } if (Character.isLowerCase(token[0])) { char[] newToken = new char[token.length]; System.arraycopy(token, 1, newToken, 1, token.length - 1); newToken[0] = Character.toTitleCase(token[0]); token = newToken; } builderClassName = new String(token) + "Builder"; } } else { annotationNode.addError("@Builder is only supported on types, constructors, and methods."); return; } if (fillParametersFrom != null) { for (EclipseNode param : fillParametersFrom.down()) { if (param.getKind() != Kind.ARGUMENT) continue; BuilderFieldData bfd = new BuilderFieldData(); Argument arg = (Argument) param.get(); bfd.rawName = arg.name; bfd.name = arg.name; bfd.type = arg.type; bfd.singularData = getSingularData(param, ast); bfd.originalFieldNode = param; addObtainVia(bfd, param); builderFields.add(bfd); } } EclipseNode builderType = findInnerClass(tdParent, builderClassName); if (builderType == null) { builderType = makeBuilderClass(isStatic, tdParent, builderClassName, typeParams, ast); } else { TypeDeclaration builderTypeDeclaration = (TypeDeclaration) builderType.get(); if (isStatic && (builderTypeDeclaration.modifiers & ClassFileConstants.AccStatic) == 0) { annotationNode.addError("Existing Builder must be a static inner class."); return; } else if (!isStatic && (builderTypeDeclaration.modifiers & ClassFileConstants.AccStatic) != 0) { annotationNode.addError("Existing Builder must be a non-static inner class."); return; } sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(builderType, annotationNode); /* generate errors for @Singular BFDs that have one already defined node. */ { for (BuilderFieldData bfd : builderFields) { SingularData sd = bfd.singularData; if (sd == null) continue; EclipseSingularizer singularizer = sd.getSingularizer(); if (singularizer == null) continue; if (singularizer.checkForAlreadyExistingNodesAndGenerateError(builderType, sd)) { bfd.singularData = null; } } } } for (BuilderFieldData bfd : builderFields) { if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { if (bfd.singularData.getSingularizer().requiresCleaning()) { addCleaning = true; break; } } if (bfd.obtainVia != null) { if (bfd.obtainVia.field().isEmpty() == bfd.obtainVia.method().isEmpty()) { bfd.obtainViaNode.addError("The syntax is either @ObtainVia(field = \"fieldName\") or @ObtainVia(method = \"methodName\")."); return; } if (bfd.obtainVia.method().isEmpty() && bfd.obtainVia.isStatic()) { bfd.obtainViaNode.addError("@ObtainVia(isStatic = true) is not valid unless 'method' has been set."); return; } } } generateBuilderFields(builderType, builderFields, ast); if (addCleaning) { FieldDeclaration cleanDecl = new FieldDeclaration(CLEAN_FIELD_NAME, 0, -1); cleanDecl.declarationSourceEnd = -1; cleanDecl.modifiers = ClassFileConstants.AccPrivate; cleanDecl.type = TypeReference.baseTypeReference(TypeIds.T_boolean, 0); injectFieldAndMarkGenerated(builderType, cleanDecl); } if (constructorExists(builderType) == MemberExistsResult.NOT_EXISTS) { ConstructorDeclaration cd = HandleConstructor.createConstructor( AccessLevel.PACKAGE, builderType, Collections.emptyList(), false, annotationNode, Collections.emptyList()); if (cd != null) injectMethod(builderType, cd); } for (BuilderFieldData bfd : builderFields) { makeSetterMethodsForBuilder(builderType, bfd, annotationNode, fluent, chain); } if (methodExists(buildMethodName, builderType, -1) == MemberExistsResult.NOT_EXISTS) { MethodDeclaration md = generateBuildMethod(tdParent, isStatic, buildMethodName, nameOfStaticBuilderMethod, returnType, builderFields, builderType, thrownExceptions, addCleaning, ast); if (md != null) injectMethod(builderType, md); } if (methodExists("toString", builderType, 0) == MemberExistsResult.NOT_EXISTS) { List fieldNodes = new ArrayList(); for (BuilderFieldData bfd : builderFields) { fieldNodes.addAll(bfd.createdFields); } MethodDeclaration md = HandleToString.createToString(builderType, fieldNodes, true, false, ast, FieldAccess.ALWAYS_FIELD); if (md != null) injectMethod(builderType, md); } if (addCleaning) { MethodDeclaration cleanMethod = generateCleanMethod(builderFields, builderType, ast); if (cleanMethod != null) injectMethod(builderType, cleanMethod); } if (methodExists(builderMethodName, tdParent, -1) == MemberExistsResult.NOT_EXISTS) { MethodDeclaration md = generateBuilderMethod(isStatic, builderMethodName, builderClassName, tdParent, typeParams, ast); if (md != null) injectMethod(tdParent, md); } if (toBuilder) switch (methodExists(toBuilderMethodName, tdParent, 0)) { case EXISTS_BY_USER: annotationNode.addWarning("Not generating toBuilder() as it already exists."); break; case NOT_EXISTS: TypeParameter[] tps = typeParams; if (typeArgsForToBuilder != null) { tps = new TypeParameter[typeArgsForToBuilder.size()]; for (int i = 0; i < tps.length; i++) { tps[i] = new TypeParameter(); tps[i].name = typeArgsForToBuilder.get(i); } } MethodDeclaration md = generateToBuilderMethod(toBuilderMethodName, builderClassName, tdParent, tps, builderFields, fluent, ast); if (md != null) injectMethod(tdParent, md); } } private MethodDeclaration generateToBuilderMethod(String methodName, String builderClassName, EclipseNode type, TypeParameter[] typeParams, List builderFields, boolean fluent, ASTNode source) { // return new ThingieBuilder().setA(this.a).setB(this.b); int pS = source.sourceStart, pE = source.sourceEnd; long p = (long) pS << 32 | pE; MethodDeclaration out = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); out.selector = methodName.toCharArray(); out.modifiers = ClassFileConstants.AccPublic; out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; out.returnType = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p); AllocationExpression invoke = new AllocationExpression(); invoke.type = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p); Expression receiver = invoke; for (BuilderFieldData bfd : builderFields) { char[] setterName = fluent ? bfd.name : HandlerUtil.buildAccessorName("set", new String(bfd.name)).toCharArray(); MessageSend ms = new MessageSend(); if (bfd.obtainVia == null || !bfd.obtainVia.field().isEmpty()) { char[] fieldName = bfd.obtainVia == null ? bfd.rawName : bfd.obtainVia.field().toCharArray(); FieldReference fr = new FieldReference(fieldName, 0); fr.receiver = new ThisReference(0, 0); ms.arguments = new Expression[] {fr}; } else { String obtainName = bfd.obtainVia.method(); boolean obtainIsStatic = bfd.obtainVia.isStatic(); MessageSend obtainExpr = new MessageSend(); obtainExpr.receiver = obtainIsStatic ? new SingleNameReference(type.getName().toCharArray(), 0) : new ThisReference(0, 0); obtainExpr.selector = obtainName.toCharArray(); if (obtainIsStatic) obtainExpr.arguments = new Expression[] {new ThisReference(0, 0)}; ms.arguments = new Expression[] {obtainExpr}; } ms.receiver = receiver; ms.selector = setterName; receiver = ms; } out.statements = new Statement[] {new ReturnStatement(receiver, pS, pE)}; out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope); return out; } private MethodDeclaration generateCleanMethod(List builderFields, EclipseNode builderType, ASTNode source) { List statements = new ArrayList(); for (BuilderFieldData bfd : builderFields) { if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, builderType, statements); } } FieldReference thisUnclean = new FieldReference(CLEAN_FIELD_NAME, 0); thisUnclean.receiver = new ThisReference(0, 0); statements.add(new Assignment(thisUnclean, new FalseLiteral(0, 0), 0)); MethodDeclaration decl = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); decl.selector = CLEAN_METHOD_NAME; decl.modifiers = ClassFileConstants.AccPrivate; decl.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; decl.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0); decl.statements = statements.toArray(new Statement[0]); decl.traverse(new SetGeneratedByVisitor(source), (ClassScope) null); return decl; } public MethodDeclaration generateBuildMethod(EclipseNode tdParent, boolean isStatic, String name, char[] staticName, TypeReference returnType, List builderFields, EclipseNode type, TypeReference[] thrownExceptions, boolean addCleaning, ASTNode source) { MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; List statements = new ArrayList(); if (addCleaning) { FieldReference thisUnclean = new FieldReference(CLEAN_FIELD_NAME, 0); thisUnclean.receiver = new ThisReference(0, 0); Expression notClean = new UnaryExpression(thisUnclean, OperatorIds.NOT); MessageSend invokeClean = new MessageSend(); invokeClean.selector = CLEAN_METHOD_NAME; statements.add(new IfStatement(notClean, invokeClean, 0, 0)); } for (BuilderFieldData bfd : builderFields) { if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { bfd.singularData.getSingularizer().appendBuildCode(bfd.singularData, type, statements, bfd.name); } } List args = new ArrayList(); for (BuilderFieldData bfd : builderFields) { if (bfd.nameOfSetFlag != null) { MessageSend inv = new MessageSend(); inv.sourceStart = source.sourceStart; inv.sourceEnd = source.sourceEnd; inv.receiver = new SingleNameReference(((TypeDeclaration) tdParent.get()).name, 0L); inv.selector = bfd.nameOfDefaultProvider; args.add(new ConditionalExpression( new SingleNameReference(bfd.nameOfSetFlag, 0L), new SingleNameReference(bfd.name, 0L), inv)); } else { args.add(new SingleNameReference(bfd.name, 0L)); } } if (addCleaning) { FieldReference thisUnclean = new FieldReference(CLEAN_FIELD_NAME, 0); thisUnclean.receiver = new ThisReference(0, 0); statements.add(new Assignment(thisUnclean, new TrueLiteral(0, 0), 0)); } out.modifiers = ClassFileConstants.AccPublic; out.selector = name.toCharArray(); out.thrownExceptions = copyTypes(thrownExceptions); out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; out.returnType = returnType; if (staticName == null) { AllocationExpression allocationStatement = new AllocationExpression(); allocationStatement.type = copyType(out.returnType); allocationStatement.arguments = args.isEmpty() ? null : args.toArray(new Expression[args.size()]); statements.add(new ReturnStatement(allocationStatement, 0, 0)); } else { MessageSend invoke = new MessageSend(); invoke.selector = staticName; if (isStatic) invoke.receiver = new SingleNameReference(type.up().getName().toCharArray(), 0); else invoke.receiver = new QualifiedThisReference(new SingleTypeReference(type.up().getName().toCharArray(), 0) , 0, 0); TypeParameter[] tps = ((TypeDeclaration) type.get()).typeParameters; if (tps != null) { TypeReference[] trs = new TypeReference[tps.length]; for (int i = 0; i < trs.length; i++) { trs[i] = new SingleTypeReference(tps[i].name, 0); } invoke.typeArguments = trs; } invoke.arguments = args.isEmpty() ? null : args.toArray(new Expression[args.size()]); if (returnType instanceof SingleTypeReference && Arrays.equals(TypeConstants.VOID, ((SingleTypeReference) returnType).token)) { statements.add(invoke); } else { statements.add(new ReturnStatement(invoke, 0, 0)); } } out.statements = statements.isEmpty() ? null : statements.toArray(new Statement[statements.size()]); out.traverse(new SetGeneratedByVisitor(source), (ClassScope) null); return out; } public MethodDeclaration generateDefaultProvider(char[] methodName, EclipseNode fieldNode, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) fieldNode.top().get()).compilationResult); out.selector = methodName; out.modifiers = ClassFileConstants.AccPrivate | ClassFileConstants.AccStatic; out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; FieldDeclaration fd = (FieldDeclaration) fieldNode.get(); out.returnType = copyType(fd.type, source); out.statements = new Statement[] {new ReturnStatement(fd.initialization, pS, pE)}; fd.initialization = null; out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) fieldNode.up().get()).scope); return out; } public MethodDeclaration generateBuilderMethod(boolean isStatic, String builderMethodName, String builderClassName, EclipseNode type, TypeParameter[] typeParams, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long) pS << 32 | pE; MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); out.selector = builderMethodName.toCharArray(); out.modifiers = ClassFileConstants.AccPublic; if (isStatic) out.modifiers |= ClassFileConstants.AccStatic; out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; out.returnType = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p); out.typeParameters = copyTypeParams(typeParams, source); AllocationExpression invoke = new AllocationExpression(); invoke.type = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p); out.statements = new Statement[] {new ReturnStatement(invoke, pS, pE)}; out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope); return out; } public void generateBuilderFields(EclipseNode builderType, List builderFields, ASTNode source) { List existing = new ArrayList(); for (EclipseNode child : builderType.down()) { if (child.getKind() == Kind.FIELD) existing.add(child); } for (BuilderFieldData bfd : builderFields) { if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { bfd.createdFields.addAll(bfd.singularData.getSingularizer().generateFields(bfd.singularData, builderType)); } else { EclipseNode field = null, setFlag = null; for (EclipseNode exists : existing) { char[] n = ((FieldDeclaration) exists.get()).name; if (Arrays.equals(n, bfd.name)) field = exists; if (bfd.nameOfSetFlag != null && Arrays.equals(n, bfd.nameOfSetFlag)) setFlag = exists; } if (field == null) { FieldDeclaration fd = new FieldDeclaration(bfd.name, 0, 0); fd.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; fd.modifiers = ClassFileConstants.AccPrivate; fd.type = copyType(bfd.type); fd.traverse(new SetGeneratedByVisitor(source), (MethodScope) null); field = injectFieldAndMarkGenerated(builderType, fd); } if (setFlag == null && bfd.nameOfSetFlag != null) { FieldDeclaration fd = new FieldDeclaration(bfd.nameOfSetFlag, 0, 0); fd.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; fd.modifiers = ClassFileConstants.AccPrivate; fd.type = TypeReference.baseTypeReference(TypeIds.T_boolean, 0); fd.traverse(new SetGeneratedByVisitor(source), (MethodScope) null); injectFieldAndMarkGenerated(builderType, fd); } bfd.createdFields.add(field); } } } private static final AbstractMethodDeclaration[] EMPTY = {}; public void makeSetterMethodsForBuilder(EclipseNode builderType, BuilderFieldData bfd, EclipseNode sourceNode, boolean fluent, boolean chain) { boolean deprecate = isFieldDeprecated(bfd.originalFieldNode); if (bfd.singularData == null || bfd.singularData.getSingularizer() == null) { makeSimpleSetterMethodForBuilder(builderType, deprecate, bfd.createdFields.get(0), bfd.nameOfSetFlag, sourceNode, fluent, chain); } else { bfd.singularData.getSingularizer().generateMethods(bfd.singularData, deprecate, builderType, fluent, chain); } } private void makeSimpleSetterMethodForBuilder(EclipseNode builderType, boolean deprecate, EclipseNode fieldNode, char[] nameOfSetFlag, EclipseNode sourceNode, boolean fluent, boolean chain) { TypeDeclaration td = (TypeDeclaration) builderType.get(); AbstractMethodDeclaration[] existing = td.methods; if (existing == null) existing = EMPTY; int len = existing.length; FieldDeclaration fd = (FieldDeclaration) fieldNode.get(); char[] name = fd.name; for (int i = 0; i < len; i++) { if (!(existing[i] instanceof MethodDeclaration)) continue; char[] existingName = existing[i].selector; if (Arrays.equals(name, existingName) && !isTolerate(fieldNode, existing[i])) return; } String setterName = fluent ? fieldNode.getName() : HandlerUtil.buildAccessorName("set", fieldNode.getName()); MethodDeclaration setter = HandleSetter.createSetter(td, deprecate, fieldNode, setterName, nameOfSetFlag, chain, ClassFileConstants.AccPublic, sourceNode, Collections.emptyList(), Collections.emptyList()); injectMethod(builderType, setter); } public EclipseNode findInnerClass(EclipseNode parent, String name) { char[] c = name.toCharArray(); for (EclipseNode child : parent.down()) { if (child.getKind() != Kind.TYPE) continue; TypeDeclaration td = (TypeDeclaration) child.get(); if (Arrays.equals(td.name, c)) return child; } return null; } public EclipseNode makeBuilderClass(boolean isStatic, EclipseNode tdParent, String builderClassName, TypeParameter[] typeParams, ASTNode source) { TypeDeclaration parent = (TypeDeclaration) tdParent.get(); TypeDeclaration builder = new TypeDeclaration(parent.compilationResult); builder.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; builder.modifiers |= ClassFileConstants.AccPublic; if (isStatic) builder.modifiers |= ClassFileConstants.AccStatic; builder.typeParameters = copyTypeParams(typeParams, source); builder.name = builderClassName.toCharArray(); builder.traverse(new SetGeneratedByVisitor(source), (ClassScope) null); return injectType(tdParent, builder); } private void addObtainVia(BuilderFieldData bfd, EclipseNode node) { for (EclipseNode child : node.down()) { if (!annotationTypeMatches(ObtainVia.class, child)) continue; AnnotationValues ann = createAnnotation(ObtainVia.class, child); bfd.obtainVia = ann.getInstance(); bfd.obtainViaNode = child; return; } } /** * Returns the explicitly requested singular annotation on this node (field * or parameter), or null if there's no {@code @Singular} annotation on it. * * @param node The node (field or method param) to inspect for its name and potential {@code @Singular} annotation. */ private SingularData getSingularData(EclipseNode node, ASTNode source) { for (EclipseNode child : node.down()) { if (!annotationTypeMatches(Singular.class, child)) continue; char[] pluralName = node.getKind() == Kind.FIELD ? removePrefixFromField(node) : ((AbstractVariableDeclaration) node.get()).name; AnnotationValues ann = createAnnotation(Singular.class, child); String explicitSingular = ann.getInstance().value(); if (explicitSingular.isEmpty()) { if (Boolean.FALSE.equals(node.getAst().readConfiguration(ConfigurationKeys.SINGULAR_AUTO))) { node.addError("The singular must be specified explicitly (e.g. @Singular(\"task\")) because auto singularization is disabled."); explicitSingular = new String(pluralName); } else { explicitSingular = autoSingularize(new String(pluralName)); if (explicitSingular == null) { node.addError("Can't singularize this name; please specify the singular explicitly (i.e. @Singular(\"sheep\"))"); explicitSingular = new String(pluralName); } } } char[] singularName = explicitSingular.toCharArray(); TypeReference type = ((AbstractVariableDeclaration) node.get()).type; TypeReference[] typeArgs = null; String typeName; if (type instanceof ParameterizedSingleTypeReference) { typeArgs = ((ParameterizedSingleTypeReference) type).typeArguments; typeName = new String(((ParameterizedSingleTypeReference) type).token); } else if (type instanceof ParameterizedQualifiedTypeReference) { TypeReference[][] tr = ((ParameterizedQualifiedTypeReference) type).typeArguments; if (tr != null) typeArgs = tr[tr.length - 1]; char[][] tokens = ((ParameterizedQualifiedTypeReference) type).tokens; StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length; i++) { if (i > 0) sb.append("."); sb.append(tokens[i]); } typeName = sb.toString(); } else { typeName = type.toString(); } String targetFqn = EclipseSingularsRecipes.get().toQualified(typeName); EclipseSingularizer singularizer = EclipseSingularsRecipes.get().getSingularizer(targetFqn); if (singularizer == null) { node.addError("Lombok does not know how to create the singular-form builder methods for type '" + typeName + "'; they won't be generated."); return null; } return new SingularData(child, singularName, pluralName, typeArgs == null ? Collections.emptyList() : Arrays.asList(typeArgs), targetFqn, singularizer, source); } return null; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleBuilderDefault.java000066400000000000000000000020411312655740700262620ustar00rootroot00000000000000package lombok.eclipse.handlers; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.mangosdk.spi.ProviderFor; import lombok.Builder; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; @ProviderFor(EclipseAnnotationHandler.class) @HandlerPriority(-1025) //HandleBuilder's level, minus one. public class HandleBuilderDefault extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { EclipseNode annotatedField = annotationNode.up(); if (annotatedField.getKind() != Kind.FIELD) return; EclipseNode classWithAnnotatedField = annotatedField.up(); if (!hasAnnotation(Builder.class, classWithAnnotatedField)) { annotationNode.addWarning("@Builder.Default requires @Builder on the class for it to mean anything."); } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleCleanup.java000066400000000000000000000260411312655740700247640ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.Arrays; import lombok.Cleanup; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.CaseStatement; import org.eclipse.jdt.internal.compiler.ast.CastExpression; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.SwitchStatement; import org.eclipse.jdt.internal.compiler.ast.TryStatement; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code lombok.Cleanup} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleCleanup extends EclipseAnnotationHandler { public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.CLEANUP_FLAG_USAGE, "@Cleanup"); String cleanupName = annotation.getInstance().value(); if (cleanupName.length() == 0) { annotationNode.addError("cleanupName cannot be the empty string."); return; } if (annotationNode.up().getKind() != Kind.LOCAL) { annotationNode.addError("@Cleanup is legal only on local variable declarations."); return; } LocalDeclaration decl = (LocalDeclaration)annotationNode.up().get(); if (decl.initialization == null) { annotationNode.addError("@Cleanup variable declarations need to be initialized."); return; } EclipseNode ancestor = annotationNode.up().directUp(); ASTNode blockNode = ancestor.get(); final boolean isSwitch; final Statement[] statements; if (blockNode instanceof AbstractMethodDeclaration) { isSwitch = false; statements = ((AbstractMethodDeclaration)blockNode).statements; } else if (blockNode instanceof Block) { isSwitch = false; statements = ((Block)blockNode).statements; } else if (blockNode instanceof SwitchStatement) { isSwitch = true; statements = ((SwitchStatement)blockNode).statements; } else { annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block."); return; } if (statements == null) { annotationNode.addError("LOMBOK BUG: Parent block does not contain any statements."); return; } int start = 0; for (; start < statements.length ; start++) { if (statements[start] == decl) break; } if (start == statements.length) { annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent."); return; } start++; //We start with try{} *AFTER* the var declaration. int end; if (isSwitch) { end = start + 1; for (; end < statements.length ; end++) { if (statements[end] instanceof CaseStatement) { break; } } } else end = statements.length; //At this point: // start-1 = Local Declaration marked with @Cleanup // start = first instruction that needs to be wrapped into a try block // end = last instruction of the scope -OR- last instruction before the next case label in switch statements. // hence: // [start, end) = statements for the try block. Statement[] tryBlock = new Statement[end - start]; System.arraycopy(statements, start, tryBlock, 0, end-start); //Remove the stuff we just dumped into the tryBlock, and then leave room for the try node. int newStatementsLength = statements.length - (end-start); //Remove room for every statement moved into try block... newStatementsLength += 1; //But add room for the TryStatement node itself. Statement[] newStatements = new Statement[newStatementsLength]; System.arraycopy(statements, 0, newStatements, 0, start); //copy all statements before the try block verbatim. System.arraycopy(statements, end, newStatements, start+1, statements.length - end); //For switch statements. doAssignmentCheck(annotationNode, tryBlock, decl.name); TryStatement tryStatement = new TryStatement(); setGeneratedBy(tryStatement, ast); tryStatement.tryBlock = new Block(0); tryStatement.tryBlock.statements = tryBlock; setGeneratedBy(tryStatement.tryBlock, ast); // Positions for in-method generated nodes are special int ss = decl.declarationSourceEnd + 1; int se = ss; if (tryBlock.length > 0) { se = tryBlock[tryBlock.length - 1].sourceEnd + 1; //+1 for the closing semicolon. Yes, there could be spaces. Bummer. tryStatement.sourceStart = ss; tryStatement.sourceEnd = se; tryStatement.tryBlock.sourceStart = ss; tryStatement.tryBlock.sourceEnd = se; } newStatements[start] = tryStatement; Statement[] finallyBlock = new Statement[1]; MessageSend unsafeClose = new MessageSend(); setGeneratedBy(unsafeClose, ast); unsafeClose.sourceStart = ast.sourceStart; unsafeClose.sourceEnd = ast.sourceEnd; SingleNameReference receiver = new SingleNameReference(decl.name, 0); setGeneratedBy(receiver, ast); unsafeClose.receiver = receiver; long nameSourcePosition = (long)ast.sourceStart << 32 | ast.sourceEnd; if (ast.memberValuePairs() != null) for (MemberValuePair pair : ast.memberValuePairs()) { if (pair.name != null && new String(pair.name).equals("value")) { nameSourcePosition = (long)pair.value.sourceStart << 32 | pair.value.sourceEnd; break; } } unsafeClose.nameSourcePosition = nameSourcePosition; unsafeClose.selector = cleanupName.toCharArray(); int pS = ast.sourceStart, pE = ast.sourceEnd; long p = (long)pS << 32 | pE; SingleNameReference varName = new SingleNameReference(decl.name, p); setGeneratedBy(varName, ast); NullLiteral nullLiteral = new NullLiteral(pS, pE); setGeneratedBy(nullLiteral, ast); MessageSend preventNullAnalysis = preventNullAnalysis(ast, varName); EqualExpression equalExpression = new EqualExpression(preventNullAnalysis, nullLiteral, OperatorIds.NOT_EQUAL); equalExpression.sourceStart = pS; equalExpression.sourceEnd = pE; setGeneratedBy(equalExpression, ast); Block closeBlock = new Block(0); closeBlock.statements = new Statement[1]; closeBlock.statements[0] = unsafeClose; setGeneratedBy(closeBlock, ast); IfStatement ifStatement = new IfStatement(equalExpression, closeBlock, 0, 0); setGeneratedBy(ifStatement, ast); finallyBlock[0] = ifStatement; tryStatement.finallyBlock = new Block(0); // Positions for in-method generated nodes are special if (!isSwitch) { tryStatement.finallyBlock.sourceStart = blockNode.sourceEnd; tryStatement.finallyBlock.sourceEnd = blockNode.sourceEnd; } setGeneratedBy(tryStatement.finallyBlock, ast); tryStatement.finallyBlock.statements = finallyBlock; tryStatement.catchArguments = null; tryStatement.catchBlocks = null; if (blockNode instanceof AbstractMethodDeclaration) { ((AbstractMethodDeclaration)blockNode).statements = newStatements; } else if (blockNode instanceof Block) { ((Block)blockNode).statements = newStatements; } else if (blockNode instanceof SwitchStatement) { ((SwitchStatement)blockNode).statements = newStatements; } ancestor.rebuild(); } public MessageSend preventNullAnalysis(Annotation ast, Expression expr) { MessageSend singletonList = new MessageSend(); setGeneratedBy(singletonList, ast); int pS = ast.sourceStart, pE = ast.sourceEnd; long p = (long)pS << 32 | pE; singletonList.receiver = createNameReference("java.util.Collections", ast); singletonList.selector = "singletonList".toCharArray(); singletonList.arguments = new Expression[] { expr }; singletonList.nameSourcePosition = p; singletonList.sourceStart = pS; singletonList.sourceEnd = singletonList.statementEnd = pE; MessageSend preventNullAnalysis = new MessageSend(); setGeneratedBy(preventNullAnalysis, ast); preventNullAnalysis.receiver = singletonList; preventNullAnalysis.selector = "get".toCharArray(); preventNullAnalysis.arguments = new Expression[] { makeIntLiteral("0".toCharArray(), ast) }; preventNullAnalysis.nameSourcePosition = p; preventNullAnalysis.sourceStart = pS; preventNullAnalysis.sourceEnd = singletonList.statementEnd = pE; return preventNullAnalysis; } public void doAssignmentCheck(EclipseNode node, Statement[] tryBlock, char[] varName) { for (Statement statement : tryBlock) doAssignmentCheck0(node, statement, varName); } private void doAssignmentCheck0(EclipseNode node, Statement statement, char[] varName) { if (statement instanceof Assignment) doAssignmentCheck0(node, ((Assignment)statement).expression, varName); else if (statement instanceof LocalDeclaration) doAssignmentCheck0(node, ((LocalDeclaration)statement).initialization, varName); else if (statement instanceof CastExpression) doAssignmentCheck0(node, ((CastExpression)statement).expression, varName); else if (statement instanceof SingleNameReference) { if (Arrays.equals(((SingleNameReference)statement).token, varName)) { EclipseNode problemNode = node.getNodeFor(statement); if (problemNode != null) problemNode.addWarning( "You're assigning an auto-cleanup variable to something else. This is a bad idea."); } } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleConstructor.java000066400000000000000000000526131312655740700257260ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.ConfigurationKeys; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.CharLiteral; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.DoubleLiteral; import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.FloatLiteral; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.LongLiteral; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.mangosdk.spi.ProviderFor; public class HandleConstructor { @ProviderFor(EclipseAnnotationHandler.class) public static class HandleNoArgsConstructor extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.NO_ARGS_CONSTRUCTOR_FLAG_USAGE, "@NoArgsConstructor", ConfigurationKeys.ANY_CONSTRUCTOR_FLAG_USAGE, "any @xArgsConstructor"); EclipseNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode, NoArgsConstructor.class.getSimpleName())) return; NoArgsConstructor ann = annotation.getInstance(); AccessLevel level = ann.access(); String staticName = ann.staticName(); if (level == AccessLevel.NONE) return; boolean force = ann.force(); List fields = force ? findFinalFields(typeNode) : Collections.emptyList(); List onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@NoArgsConstructor(onConstructor", annotationNode); new HandleConstructor().generateConstructor(typeNode, level, fields, force, staticName, SkipIfConstructorExists.NO, onConstructor, annotationNode); } } @ProviderFor(EclipseAnnotationHandler.class) public static class HandleRequiredArgsConstructor extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.REQUIRED_ARGS_CONSTRUCTOR_FLAG_USAGE, "@RequiredArgsConstructor", ConfigurationKeys.ANY_CONSTRUCTOR_FLAG_USAGE, "any @xArgsConstructor"); EclipseNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode, RequiredArgsConstructor.class.getSimpleName())) return; RequiredArgsConstructor ann = annotation.getInstance(); AccessLevel level = ann.access(); if (level == AccessLevel.NONE) return; String staticName = ann.staticName(); if (annotation.isExplicit("suppressConstructorProperties")) { annotationNode.addError("This deprecated feature is no longer supported. Remove it; you can create a lombok.config file with 'lombok.anyConstructor.suppressConstructorProperties = true'."); } List onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@RequiredArgsConstructor(onConstructor", annotationNode); new HandleConstructor().generateConstructor( typeNode, level, findRequiredFields(typeNode), false, staticName, SkipIfConstructorExists.NO, onConstructor, annotationNode); } } private static List findRequiredFields(EclipseNode typeNode) { return findFields(typeNode, true); } private static List findFinalFields(EclipseNode typeNode) { return findFields(typeNode, false); } private static List findFields(EclipseNode typeNode, boolean nullMarked) { List fields = new ArrayList(); for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); if (!filterField(fieldDecl)) continue; boolean isFinal = (fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0; boolean isNonNull = nullMarked && findAnnotations(fieldDecl, NON_NULL_PATTERN).length != 0; if ((isFinal || isNonNull) && fieldDecl.initialization == null) fields.add(child); } return fields; } static List findAllFields(EclipseNode typeNode) { return findAllFields(typeNode, false); } static List findAllFields(EclipseNode typeNode, boolean evenFinalInitialized) { List fields = new ArrayList(); for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); if (!filterField(fieldDecl)) continue; if (!evenFinalInitialized && ((fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0) && fieldDecl.initialization != null) continue; fields.add(child); } return fields; } @ProviderFor(EclipseAnnotationHandler.class) public static class HandleAllArgsConstructor extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.ALL_ARGS_CONSTRUCTOR_FLAG_USAGE, "@AllArgsConstructor", ConfigurationKeys.ANY_CONSTRUCTOR_FLAG_USAGE, "any @xArgsConstructor"); EclipseNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode, AllArgsConstructor.class.getSimpleName())) return; AllArgsConstructor ann = annotation.getInstance(); AccessLevel level = ann.access(); if (level == AccessLevel.NONE) return; String staticName = ann.staticName(); if (annotation.isExplicit("suppressConstructorProperties")) { annotationNode.addError("This deprecated feature is no longer supported. Remove it; you can create a lombok.config file with 'lombok.anyConstructor.suppressConstructorProperties = true'."); } List onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@AllArgsConstructor(onConstructor", annotationNode); new HandleConstructor().generateConstructor( typeNode, level, findAllFields(typeNode), false, staticName, SkipIfConstructorExists.NO, onConstructor, annotationNode); } } static boolean checkLegality(EclipseNode typeNode, EclipseNode errorNode, String name) { TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation)) != 0; if (typeDecl == null || notAClass) { errorNode.addError(name + " is only supported on a class or an enum."); return false; } return true; } public void generateRequiredArgsConstructor( EclipseNode typeNode, AccessLevel level, String staticName, SkipIfConstructorExists skipIfConstructorExists, List onConstructor, EclipseNode sourceNode) { generateConstructor(typeNode, level, findRequiredFields(typeNode), false, staticName, skipIfConstructorExists, onConstructor, sourceNode); } public void generateAllArgsConstructor( EclipseNode typeNode, AccessLevel level, String staticName, SkipIfConstructorExists skipIfConstructorExists, List onConstructor, EclipseNode sourceNode) { generateConstructor(typeNode, level, findAllFields(typeNode), false, staticName, skipIfConstructorExists, onConstructor, sourceNode); } public enum SkipIfConstructorExists { YES, NO, I_AM_BUILDER; } public void generateConstructor( EclipseNode typeNode, AccessLevel level, List fields, boolean allToDefault, String staticName, SkipIfConstructorExists skipIfConstructorExists, List onConstructor, EclipseNode sourceNode) { ASTNode source = sourceNode.get(); boolean staticConstrRequired = staticName != null && !staticName.equals(""); if (skipIfConstructorExists != SkipIfConstructorExists.NO && constructorExists(typeNode) != MemberExistsResult.NOT_EXISTS) return; if (skipIfConstructorExists != SkipIfConstructorExists.NO) { for (EclipseNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { boolean skipGeneration = (annotationTypeMatches(NoArgsConstructor.class, child) || annotationTypeMatches(AllArgsConstructor.class, child) || annotationTypeMatches(RequiredArgsConstructor.class, child)); if (!skipGeneration && skipIfConstructorExists == SkipIfConstructorExists.YES) { skipGeneration = annotationTypeMatches(Builder.class, child); } if (skipGeneration) { if (staticConstrRequired) { // @Data has asked us to generate a constructor, but we're going to skip this instruction, as an explicit 'make a constructor' annotation // will take care of it. However, @Data also wants a specific static name; this will be ignored; the appropriate way to do this is to use // the 'staticName' parameter of the @XArgsConstructor you've stuck on your type. // We should warn that we're ignoring @Data's 'staticConstructor' param. typeNode.addWarning( "Ignoring static constructor name: explicit @XxxArgsConstructor annotation present; its `staticName` parameter will be used.", source.sourceStart, source.sourceEnd); } return; } } } } ConstructorDeclaration constr = createConstructor( staticConstrRequired ? AccessLevel.PRIVATE : level, typeNode, fields, allToDefault, sourceNode, onConstructor); injectMethod(typeNode, constr); if (staticConstrRequired) { MethodDeclaration staticConstr = createStaticConstructor(level, staticName, typeNode, allToDefault ? Collections.emptyList() : fields, source); injectMethod(typeNode, staticConstr); } } private static final char[][] JAVA_BEANS_CONSTRUCTORPROPERTIES = new char[][] { "java".toCharArray(), "beans".toCharArray(), "ConstructorProperties".toCharArray() }; public static Annotation[] createConstructorProperties(ASTNode source, Collection fields) { if (fields.isEmpty()) return null; int pS = source.sourceStart, pE = source.sourceEnd; long p = (long) pS << 32 | pE; long[] poss = new long[3]; Arrays.fill(poss, p); QualifiedTypeReference constructorPropertiesType = new QualifiedTypeReference(JAVA_BEANS_CONSTRUCTORPROPERTIES, poss); setGeneratedBy(constructorPropertiesType, source); SingleMemberAnnotation ann = new SingleMemberAnnotation(constructorPropertiesType, pS); ann.declarationSourceEnd = pE; ArrayInitializer fieldNames = new ArrayInitializer(); fieldNames.sourceStart = pS; fieldNames.sourceEnd = pE; fieldNames.expressions = new Expression[fields.size()]; int ctr = 0; for (EclipseNode field : fields) { char[] fieldName = removePrefixFromField(field); fieldNames.expressions[ctr] = new StringLiteral(fieldName, pS, pE, 0); setGeneratedBy(fieldNames.expressions[ctr], source); ctr++; } ann.memberValue = fieldNames; setGeneratedBy(ann, source); setGeneratedBy(ann.memberValue, source); return new Annotation[] { ann }; } public static ConstructorDeclaration createConstructor( AccessLevel level, EclipseNode type, Collection fields, boolean allToDefault, EclipseNode sourceNode, List onConstructor) { ASTNode source = sourceNode.get(); TypeDeclaration typeDeclaration = ((TypeDeclaration) type.get()); long p = (long) source.sourceStart << 32 | source.sourceEnd; boolean isEnum = (((TypeDeclaration) type.get()).modifiers & ClassFileConstants.AccEnum) != 0; if (isEnum) level = AccessLevel.PRIVATE; boolean suppressConstructorProperties; if (fields.isEmpty()) { suppressConstructorProperties = false; } else { suppressConstructorProperties = Boolean.TRUE.equals(type.getAst().readConfiguration(ConfigurationKeys.ANY_CONSTRUCTOR_SUPPRESS_CONSTRUCTOR_PROPERTIES)); } ConstructorDeclaration constructor = new ConstructorDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); constructor.modifiers = toEclipseModifier(level); constructor.selector = typeDeclaration.name; constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); constructor.constructorCall.sourceStart = source.sourceStart; constructor.constructorCall.sourceEnd = source.sourceEnd; constructor.thrownExceptions = null; constructor.typeParameters = null; constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart; constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd; constructor.arguments = null; List params = new ArrayList(); List assigns = new ArrayList(); List nullChecks = new ArrayList(); for (EclipseNode fieldNode : fields) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); char[] rawName = field.name; char[] fieldName = removePrefixFromField(fieldNode); FieldReference thisX = new FieldReference(rawName, p); int s = (int) (p >> 32); int e = (int) p; thisX.receiver = new ThisReference(s, e); Expression assignmentExpr = allToDefault ? getDefaultExpr(field.type, s, e) : new SingleNameReference(fieldName, p); Assignment assignment = new Assignment(thisX, assignmentExpr, (int) p); assignment.sourceStart = (int) (p >> 32); assignment.sourceEnd = assignment.statementEnd = (int) (p >> 32); assigns.add(assignment); if (!allToDefault) { long fieldPos = (((long) field.sourceStart) << 32) | field.sourceEnd; Argument parameter = new Argument(fieldName, fieldPos, copyType(field.type, source), Modifier.FINAL); Annotation[] nonNulls = findAnnotations(field, NON_NULL_PATTERN); Annotation[] nullables = findAnnotations(field, NULLABLE_PATTERN); if (nonNulls.length != 0) { Statement nullCheck = generateNullCheck(field, sourceNode); if (nullCheck != null) nullChecks.add(nullCheck); } parameter.annotations = copyAnnotations(source, nonNulls, nullables); params.add(parameter); } } nullChecks.addAll(assigns); constructor.statements = nullChecks.isEmpty() ? null : nullChecks.toArray(new Statement[nullChecks.size()]); constructor.arguments = params.isEmpty() ? null : params.toArray(new Argument[params.size()]); /* Generate annotations that must be put on the generated method, and attach them. */ { Annotation[] constructorProperties = null; if (!allToDefault && !suppressConstructorProperties && !isLocalType(type)) { constructorProperties = createConstructorProperties(source, fields); } constructor.annotations = copyAnnotations(source, onConstructor.toArray(new Annotation[0]), constructorProperties); } constructor.traverse(new SetGeneratedByVisitor(source), typeDeclaration.scope); return constructor; } private static Expression getDefaultExpr(TypeReference type, int s, int e) { boolean array = type instanceof ArrayTypeReference; if (array) return new NullLiteral(s, e); char[] lastToken = type.getLastToken(); if (Arrays.equals(TypeConstants.BOOLEAN, lastToken)) return new FalseLiteral(s, e); if (Arrays.equals(TypeConstants.CHAR, lastToken)) return new CharLiteral(new char[] {'\'', '\\', '0', '\''}, s, e); if (Arrays.equals(TypeConstants.BYTE, lastToken) || Arrays.equals(TypeConstants.SHORT, lastToken) || Arrays.equals(TypeConstants.INT, lastToken)) return IntLiteral.buildIntLiteral(new char[] {'0'}, s, e); if (Arrays.equals(TypeConstants.LONG, lastToken)) return LongLiteral.buildLongLiteral(new char[] {'0', 'L'}, s, e); if (Arrays.equals(TypeConstants.FLOAT, lastToken)) return new FloatLiteral(new char[] {'0', 'F'}, s, e); if (Arrays.equals(TypeConstants.DOUBLE, lastToken)) return new DoubleLiteral(new char[] {'0', 'D'}, s, e); return new NullLiteral(s, e); } public static boolean isLocalType(EclipseNode type) { Kind kind = type.up().getKind(); if (kind == Kind.COMPILATION_UNIT) return false; if (kind == Kind.TYPE) return isLocalType(type.up()); return true; } public MethodDeclaration createStaticConstructor(AccessLevel level, String name, EclipseNode type, Collection fields, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long) pS << 32 | pE; MethodDeclaration constructor = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); constructor.modifiers = toEclipseModifier(level) | ClassFileConstants.AccStatic; TypeDeclaration typeDecl = (TypeDeclaration) type.get(); constructor.returnType = EclipseHandlerUtil.namePlusTypeParamsToTypeReference(typeDecl.name, typeDecl.typeParameters, p); constructor.annotations = null; constructor.selector = name.toCharArray(); constructor.thrownExceptions = null; constructor.typeParameters = copyTypeParams(((TypeDeclaration) type.get()).typeParameters, source); constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart; constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd; List params = new ArrayList(); List assigns = new ArrayList(); AllocationExpression statement = new AllocationExpression(); statement.sourceStart = pS; statement.sourceEnd = pE; statement.type = copyType(constructor.returnType, source); for (EclipseNode fieldNode : fields) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); long fieldPos = (((long) field.sourceStart) << 32) | field.sourceEnd; SingleNameReference nameRef = new SingleNameReference(field.name, fieldPos); assigns.add(nameRef); Argument parameter = new Argument(field.name, fieldPos, copyType(field.type, source), Modifier.FINAL); parameter.annotations = copyAnnotations(source, findAnnotations(field, NON_NULL_PATTERN), findAnnotations(field, NULLABLE_PATTERN)); params.add(parameter); } statement.arguments = assigns.isEmpty() ? null : assigns.toArray(new Expression[assigns.size()]); constructor.arguments = params.isEmpty() ? null : params.toArray(new Argument[params.size()]); constructor.statements = new Statement[] { new ReturnStatement(statement, (int) (p >> 32), (int)p) }; constructor.traverse(new SetGeneratedByVisitor(source), typeDecl.scope); return constructor; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleData.java000066400000000000000000000071471312655740700242540ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import java.util.Collections; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.Data; import lombok.core.AnnotationValues; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.HandleConstructor.SkipIfConstructorExists; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code lombok.Data} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleData extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.DATA_FLAG_USAGE, "@Data"); Data ann = annotation.getInstance(); EclipseNode typeNode = annotationNode.up(); TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; if (typeDecl == null || notAClass) { annotationNode.addError("@Data is only supported on a class."); return; } //Careful: Generate the public static constructor (if there is one) LAST, so that any attempt to //'find callers' on the annotation node will find callers of the constructor, which is by far the //most useful of the many methods built by @Data. This trick won't work for the non-static constructor, //for whatever reason, though you can find callers of that one by focusing on the class name itself //and hitting 'find callers'. new HandleGetter().generateGetterForType(typeNode, annotationNode, AccessLevel.PUBLIC, true); new HandleSetter().generateSetterForType(typeNode, annotationNode, AccessLevel.PUBLIC, true); new HandleEqualsAndHashCode().generateEqualsAndHashCodeForType(typeNode, annotationNode); new HandleToString().generateToStringForType(typeNode, annotationNode); new HandleConstructor().generateRequiredArgsConstructor( typeNode, AccessLevel.PUBLIC, ann.staticConstructor(), SkipIfConstructorExists.YES, Collections.emptyList(), annotationNode); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleDelegate.java000066400000000000000000000037021312655740700251060ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.handleExperimentalFlagUsage; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.experimental.Delegate; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.mangosdk.spi.ProviderFor; /** * This class just handles basic error cases. The real meat of eclipse '@Delegate' support is in {@code PatchDelegate}. */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleDelegate extends EclipseAnnotationHandler { public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.DELEGATE_FLAG_USAGE, "@Delegate"); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java000066400000000000000000001232721312655740700266550ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.EqualsAndHashCode; import lombok.core.AST.Kind; import lombok.core.handlers.HandlerUtil; import lombok.core.AnnotationValues; import lombok.core.configuration.CallSuperType; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; import lombok.eclipse.handlers.EclipseHandlerUtil.MemberExistsResult; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.BinaryExpression; import org.eclipse.jdt.internal.compiler.ast.CastExpression; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.InstanceOfExpression; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NameReference; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.SuperReference; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.ast.UnaryExpression; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code EqualsAndHashCode} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleEqualsAndHashCode extends EclipseAnnotationHandler { private final char[] PRIME = "PRIME".toCharArray(); private final char[] RESULT = "result".toCharArray(); public static final Set BUILT_IN_TYPES = Collections.unmodifiableSet(new HashSet(Arrays.asList( "byte", "short", "int", "long", "char", "boolean", "double", "float"))); public void checkForBogusFieldNames(EclipseNode type, AnnotationValues annotation) { if (annotation.isExplicit("exclude")) { for (int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().exclude()), type, true, true)) { annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); } } if (annotation.isExplicit("of")) { for (int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().of()), type, false, false)) { annotation.setWarning("of", "This field does not exist.", i); } } } public void generateEqualsAndHashCodeForType(EclipseNode typeNode, EclipseNode errorNode) { if (hasAnnotation(EqualsAndHashCode.class, typeNode)) { //The annotation will make it happen, so we can skip it. return; } Boolean doNotUseGettersConfiguration = typeNode.getAst().readConfiguration(ConfigurationKeys.EQUALS_AND_HASH_CODE_DO_NOT_USE_GETTERS); FieldAccess access = doNotUseGettersConfiguration == null || !doNotUseGettersConfiguration ? FieldAccess.GETTER : FieldAccess.PREFER_FIELD; generateMethods(typeNode, errorNode, null, null, null, false, access, new ArrayList()); } @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.EQUALS_AND_HASH_CODE_FLAG_USAGE, "@EqualsAndHashCode"); EqualsAndHashCode ann = annotation.getInstance(); List excludes = Arrays.asList(ann.exclude()); List includes = Arrays.asList(ann.of()); EclipseNode typeNode = annotationNode.up(); List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@EqualsAndHashCode(onParam", annotationNode); checkForBogusFieldNames(typeNode, annotation); Boolean callSuper = ann.callSuper(); if (!annotation.isExplicit("callSuper")) callSuper = null; if (!annotation.isExplicit("exclude")) excludes = null; if (!annotation.isExplicit("of")) includes = null; if (excludes != null && includes != null) { excludes = null; annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored."); } Boolean doNotUseGettersConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.EQUALS_AND_HASH_CODE_DO_NOT_USE_GETTERS); boolean doNotUseGetters = annotation.isExplicit("doNotUseGetters") || doNotUseGettersConfiguration == null ? ann.doNotUseGetters() : doNotUseGettersConfiguration; FieldAccess fieldAccess = doNotUseGetters ? FieldAccess.PREFER_FIELD : FieldAccess.GETTER; generateMethods(typeNode, annotationNode, excludes, includes, callSuper, true, fieldAccess, onParam); } public void generateMethods(EclipseNode typeNode, EclipseNode errorNode, List excludes, List includes, Boolean callSuper, boolean whineIfExists, FieldAccess fieldAccess, List onParam) { assert excludes == null || includes == null; TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; if (typeDecl == null || notAClass) { errorNode.addError("@EqualsAndHashCode is only supported on a class."); return; } boolean implicitCallSuper = callSuper == null; if (callSuper == null) { try { callSuper = ((Boolean)EqualsAndHashCode.class.getMethod("callSuper").getDefaultValue()).booleanValue(); } catch (Exception ignore) { throw new InternalError("Lombok bug - this cannot happen - can't find callSuper field in EqualsAndHashCode annotation."); } } boolean isDirectDescendantOfObject = true; if (typeDecl.superclass != null) { String p = typeDecl.superclass.toString(); isDirectDescendantOfObject = p.equals("Object") || p.equals("java.lang.Object"); } if (isDirectDescendantOfObject && callSuper) { errorNode.addError("Generating equals/hashCode with a supercall to java.lang.Object is pointless."); return; } if (implicitCallSuper && !isDirectDescendantOfObject) { CallSuperType cst = typeNode.getAst().readConfiguration(ConfigurationKeys.EQUALS_AND_HASH_CODE_CALL_SUPER); if (cst == null) cst = CallSuperType.WARN; switch (cst) { default: case WARN: errorNode.addWarning("Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.lang.Object. If this is intentional, add '@EqualsAndHashCode(callSuper=false)' to your type."); callSuper = false; break; case SKIP: callSuper = false; break; case CALL: callSuper = true; break; } } List nodesForEquality = new ArrayList(); if (includes != null) { for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); if (includes.contains(new String(fieldDecl.name))) nodesForEquality.add(child); } } else { for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); if (!filterField(fieldDecl)) continue; //Skip transient fields. if ((fieldDecl.modifiers & ClassFileConstants.AccTransient) != 0) continue; //Skip excluded fields. if (excludes != null && excludes.contains(new String(fieldDecl.name))) continue; nodesForEquality.add(child); } } boolean isFinal = (typeDecl.modifiers & ClassFileConstants.AccFinal) != 0; boolean needsCanEqual = !isFinal || !isDirectDescendantOfObject; MemberExistsResult equalsExists = methodExists("equals", typeNode, 1); MemberExistsResult hashCodeExists = methodExists("hashCode", typeNode, 0); MemberExistsResult canEqualExists = methodExists("canEqual", typeNode, 1); switch (Collections.max(Arrays.asList(equalsExists, hashCodeExists))) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: if (whineIfExists) { String msg = "Not generating equals and hashCode: A method with one of those names already exists. (Either both or none of these methods will be generated)."; errorNode.addWarning(msg); } else if (equalsExists == MemberExistsResult.NOT_EXISTS || hashCodeExists == MemberExistsResult.NOT_EXISTS) { // This means equals OR hashCode exists and not both. // Even though we should suppress the message about not generating these, this is such a weird and surprising situation we should ALWAYS generate a warning. // The user code couldn't possibly (barring really weird subclassing shenanigans) be in a shippable state anyway; the implementations of these 2 methods are // all inter-related and should be written by the same entity. String msg = String.format("Not generating %s: One of equals or hashCode exists. " + "You should either write both of these or none of these (in the latter case, lombok generates them).", equalsExists == MemberExistsResult.NOT_EXISTS ? "equals" : "hashCode"); errorNode.addWarning(msg); } return; case NOT_EXISTS: default: //fallthrough } MethodDeclaration equalsMethod = createEquals(typeNode, nodesForEquality, callSuper, errorNode.get(), fieldAccess, needsCanEqual, onParam); equalsMethod.traverse(new SetGeneratedByVisitor(errorNode.get()), ((TypeDeclaration)typeNode.get()).scope); injectMethod(typeNode, equalsMethod); if (needsCanEqual && canEqualExists == MemberExistsResult.NOT_EXISTS) { MethodDeclaration canEqualMethod = createCanEqual(typeNode, errorNode.get(), onParam); canEqualMethod.traverse(new SetGeneratedByVisitor(errorNode.get()), ((TypeDeclaration)typeNode.get()).scope); injectMethod(typeNode, canEqualMethod); } MethodDeclaration hashCodeMethod = createHashCode(typeNode, nodesForEquality, callSuper, errorNode.get(), fieldAccess); hashCodeMethod.traverse(new SetGeneratedByVisitor(errorNode.get()), ((TypeDeclaration)typeNode.get()).scope); injectMethod(typeNode, hashCodeMethod); } public MethodDeclaration createHashCode(EclipseNode type, Collection fields, boolean callSuper, ASTNode source, FieldAccess fieldAccess) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; MethodDeclaration method = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); setGeneratedBy(method, source); method.modifiers = toEclipseModifier(AccessLevel.PUBLIC); method.returnType = TypeReference.baseTypeReference(TypeIds.T_int, 0); setGeneratedBy(method.returnType, source); method.annotations = new Annotation[] {makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source)}; method.selector = "hashCode".toCharArray(); method.thrownExceptions = null; method.typeParameters = null; method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; method.arguments = null; List statements = new ArrayList(); final boolean isEmpty = fields.isEmpty(); /* final int PRIME = X; */ { /* Without fields, PRIME isn't used, and that would trigger a 'local variable not used' warning. */ if (!isEmpty || callSuper) { LocalDeclaration primeDecl = new LocalDeclaration(PRIME, pS, pE); setGeneratedBy(primeDecl, source); primeDecl.modifiers |= Modifier.FINAL; primeDecl.type = TypeReference.baseTypeReference(TypeIds.T_int, 0); primeDecl.type.sourceStart = pS; primeDecl.type.sourceEnd = pE; setGeneratedBy(primeDecl.type, source); primeDecl.initialization = makeIntLiteral(String.valueOf(HandlerUtil.primeForHashcode()).toCharArray(), source); statements.add(primeDecl); } } /* int result = 1; */ { LocalDeclaration resultDecl = new LocalDeclaration(RESULT, pS, pE); setGeneratedBy(resultDecl, source); resultDecl.initialization = makeIntLiteral("1".toCharArray(), source); resultDecl.type = TypeReference.baseTypeReference(TypeIds.T_int, 0); resultDecl.type.sourceStart = pS; resultDecl.type.sourceEnd = pE; setGeneratedBy(resultDecl.type, source); statements.add(resultDecl); } if (callSuper) { MessageSend callToSuper = new MessageSend(); setGeneratedBy(callToSuper, source); callToSuper.sourceStart = pS; callToSuper.sourceEnd = pE; callToSuper.receiver = new SuperReference(pS, pE); setGeneratedBy(callToSuper.receiver, source); callToSuper.selector = "hashCode".toCharArray(); statements.add(createResultCalculation(source, callToSuper)); } for (EclipseNode field : fields) { TypeReference fType = getFieldType(field, fieldAccess); char[] dollarFieldName = ("$" + field.getName()).toCharArray(); char[] token = fType.getLastToken(); Expression fieldAccessor = createFieldAccessor(field, fieldAccess, source); if (fType.dimensions() == 0 && token != null) { if (Arrays.equals(TypeConstants.BOOLEAN, token)) { /* booleanField ? X : Y */ IntLiteral intTrue = makeIntLiteral(String.valueOf(HandlerUtil.primeForTrue()).toCharArray(), source); IntLiteral intFalse = makeIntLiteral(String.valueOf(HandlerUtil.primeForFalse()).toCharArray(), source); ConditionalExpression intForBool = new ConditionalExpression(fieldAccessor, intTrue, intFalse); setGeneratedBy(intForBool, source); statements.add(createResultCalculation(source, intForBool)); } else if (Arrays.equals(TypeConstants.LONG, token)) { statements.add(createLocalDeclaration(source, dollarFieldName, TypeReference.baseTypeReference(TypeIds.T_long, 0), fieldAccessor)); SingleNameReference copy1 = new SingleNameReference(dollarFieldName, p); setGeneratedBy(copy1, source); SingleNameReference copy2 = new SingleNameReference(dollarFieldName, p); setGeneratedBy(copy2, source); statements.add(createResultCalculation(source, longToIntForHashCode(copy1, copy2, source))); } else if (Arrays.equals(TypeConstants.FLOAT, token)) { /* Float.floatToIntBits(fieldName) */ MessageSend floatToIntBits = new MessageSend(); floatToIntBits.sourceStart = pS; floatToIntBits.sourceEnd = pE; setGeneratedBy(floatToIntBits, source); floatToIntBits.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA_LANG_FLOAT); floatToIntBits.selector = "floatToIntBits".toCharArray(); floatToIntBits.arguments = new Expression[] { fieldAccessor }; statements.add(createResultCalculation(source, floatToIntBits)); } else if (Arrays.equals(TypeConstants.DOUBLE, token)) { /* longToIntForHashCode(Double.doubleToLongBits(fieldName)) */ MessageSend doubleToLongBits = new MessageSend(); doubleToLongBits.sourceStart = pS; doubleToLongBits.sourceEnd = pE; setGeneratedBy(doubleToLongBits, source); doubleToLongBits.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA_LANG_DOUBLE); doubleToLongBits.selector = "doubleToLongBits".toCharArray(); doubleToLongBits.arguments = new Expression[] { fieldAccessor }; statements.add(createLocalDeclaration(source, dollarFieldName, TypeReference.baseTypeReference(TypeIds.T_long, 0), doubleToLongBits)); SingleNameReference copy1 = new SingleNameReference(dollarFieldName, p); setGeneratedBy(copy1, source); SingleNameReference copy2 = new SingleNameReference(dollarFieldName, p); setGeneratedBy(copy2, source); statements.add(createResultCalculation(source, longToIntForHashCode(copy1, copy2, source))); } else if (BUILT_IN_TYPES.contains(new String(token))) { statements.add(createResultCalculation(source, fieldAccessor)); } else /* objects */ { /* final java.lang.Object $fieldName = this.fieldName; */ /* $fieldName == null ? NULL_PRIME : $fieldName.hashCode() */ statements.add(createLocalDeclaration(source, dollarFieldName, generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), fieldAccessor)); SingleNameReference copy1 = new SingleNameReference(dollarFieldName, p); setGeneratedBy(copy1, source); SingleNameReference copy2 = new SingleNameReference(dollarFieldName, p); setGeneratedBy(copy2, source); MessageSend hashCodeCall = new MessageSend(); hashCodeCall.sourceStart = pS; hashCodeCall.sourceEnd = pE; setGeneratedBy(hashCodeCall, source); hashCodeCall.receiver = copy1; hashCodeCall.selector = "hashCode".toCharArray(); NullLiteral nullLiteral = new NullLiteral(pS, pE); setGeneratedBy(nullLiteral, source); EqualExpression objIsNull = new EqualExpression(copy2, nullLiteral, OperatorIds.EQUAL_EQUAL); setGeneratedBy(objIsNull, source); IntLiteral intMagic = makeIntLiteral(String.valueOf(HandlerUtil.primeForNull()).toCharArray(), source); ConditionalExpression nullOrHashCode = new ConditionalExpression(objIsNull, intMagic, hashCodeCall); nullOrHashCode.sourceStart = pS; nullOrHashCode.sourceEnd = pE; setGeneratedBy(nullOrHashCode, source); statements.add(createResultCalculation(source, nullOrHashCode)); } } else if (fType.dimensions() > 0 && token != null) { /* Arrays.deepHashCode(array) //just hashCode for simple arrays */ MessageSend arraysHashCodeCall = new MessageSend(); arraysHashCodeCall.sourceStart = pS; arraysHashCodeCall.sourceEnd = pE; setGeneratedBy(arraysHashCodeCall, source); arraysHashCodeCall.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); if (fType.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token))) { arraysHashCodeCall.selector = "deepHashCode".toCharArray(); } else { arraysHashCodeCall.selector = "hashCode".toCharArray(); } arraysHashCodeCall.arguments = new Expression[] { fieldAccessor }; statements.add(createResultCalculation(source, arraysHashCodeCall)); } } /* return result; */ { SingleNameReference resultRef = new SingleNameReference(RESULT, p); setGeneratedBy(resultRef, source); ReturnStatement returnStatement = new ReturnStatement(resultRef, pS, pE); setGeneratedBy(returnStatement, source); statements.add(returnStatement); } method.statements = statements.toArray(new Statement[statements.size()]); return method; } public LocalDeclaration createLocalDeclaration(ASTNode source, char[] dollarFieldName, TypeReference type, Expression initializer) { int pS = source.sourceStart, pE = source.sourceEnd; LocalDeclaration tempVar = new LocalDeclaration(dollarFieldName, pS, pE); setGeneratedBy(tempVar, source); tempVar.initialization = initializer; tempVar.type = type; tempVar.type.sourceStart = pS; tempVar.type.sourceEnd = pE; setGeneratedBy(tempVar.type, source); tempVar.modifiers = Modifier.FINAL; return tempVar; } public Expression createResultCalculation(ASTNode source, Expression ex) { /* result = result * PRIME + (ex); */ int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; SingleNameReference resultRef = new SingleNameReference(RESULT, p); setGeneratedBy(resultRef, source); SingleNameReference primeRef = new SingleNameReference(PRIME, p); setGeneratedBy(primeRef, source); BinaryExpression multiplyByPrime = new BinaryExpression(resultRef, primeRef, OperatorIds.MULTIPLY); multiplyByPrime.sourceStart = pS; multiplyByPrime.sourceEnd = pE; setGeneratedBy(multiplyByPrime, source); BinaryExpression addItem = new BinaryExpression(multiplyByPrime, ex, OperatorIds.PLUS); addItem.sourceStart = pS; addItem.sourceEnd = pE; setGeneratedBy(addItem, source); resultRef = new SingleNameReference(RESULT, p); setGeneratedBy(resultRef, source); Assignment assignment = new Assignment(resultRef, addItem, pE); assignment.sourceStart = pS; assignment.sourceEnd = assignment.statementEnd = pE; setGeneratedBy(assignment, source); return assignment; } /** * @param type Type to 'copy' into a typeref * @param p position * @param addWildcards If false, all generics are cut off. If true, replaces all genericparams with a ?. * @return */ public TypeReference createTypeReference(EclipseNode type, long p, ASTNode source, boolean addWildcards) { int pS = source.sourceStart; int pE = source.sourceEnd; List list = new ArrayList(); list.add(type.getName()); EclipseNode tNode = type.up(); while (tNode != null && tNode.getKind() == Kind.TYPE) { list.add(tNode.getName()); tNode = tNode.up(); } Collections.reverse(list); TypeDeclaration typeDecl = (TypeDeclaration) type.get(); int typeParamCount = typeDecl.typeParameters == null ? 0 : typeDecl.typeParameters.length; if (typeParamCount == 0) addWildcards = false; TypeReference[] typeArgs = null; if (addWildcards) { typeArgs = new TypeReference[typeParamCount]; for (int i = 0; i < typeParamCount; i++) { typeArgs[i] = new Wildcard(Wildcard.UNBOUND); typeArgs[i].sourceStart = pS; typeArgs[i].sourceEnd = pE; setGeneratedBy(typeArgs[i], source); } } if (list.size() == 1) { if (addWildcards) { return new ParameterizedSingleTypeReference(list.get(0).toCharArray(), typeArgs, 0, p); } else { return new SingleTypeReference(list.get(0).toCharArray(), p); } } long[] ps = new long[list.size()]; char[][] tokens = new char[list.size()][]; for (int i = 0; i < list.size(); i++) { ps[i] = p; tokens[i] = list.get(i).toCharArray(); } if (addWildcards) { TypeReference[][] typeArgs2 = new TypeReference[tokens.length][]; typeArgs2[typeArgs2.length - 1] = typeArgs; return new ParameterizedQualifiedTypeReference(tokens, typeArgs2, 0, ps); } else { return new QualifiedTypeReference(tokens, ps); } } public MethodDeclaration createEquals(EclipseNode type, Collection fields, boolean callSuper, ASTNode source, FieldAccess fieldAccess, boolean needsCanEqual, List onParam) { int pS = source.sourceStart; int pE = source.sourceEnd; long p = (long)pS << 32 | pE; MethodDeclaration method = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); setGeneratedBy(method, source); method.modifiers = toEclipseModifier(AccessLevel.PUBLIC); method.returnType = TypeReference.baseTypeReference(TypeIds.T_boolean, 0); method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; setGeneratedBy(method.returnType, source); method.annotations = new Annotation[] {makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source)}; method.selector = "equals".toCharArray(); method.thrownExceptions = null; method.typeParameters = null; method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; TypeReference objectRef = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { p, p, p }); setGeneratedBy(objectRef, source); method.arguments = new Argument[] {new Argument(new char[] { 'o' }, 0, objectRef, Modifier.FINAL)}; method.arguments[0].sourceStart = pS; method.arguments[0].sourceEnd = pE; if (!onParam.isEmpty()) method.arguments[0].annotations = onParam.toArray(new Annotation[0]); setGeneratedBy(method.arguments[0], source); List statements = new ArrayList(); /* if (o == this) return true; */ { SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p); setGeneratedBy(oRef, source); ThisReference thisRef = new ThisReference(pS, pE); setGeneratedBy(thisRef, source); EqualExpression otherEqualsThis = new EqualExpression(oRef, thisRef, OperatorIds.EQUAL_EQUAL); setGeneratedBy(otherEqualsThis, source); TrueLiteral trueLiteral = new TrueLiteral(pS, pE); setGeneratedBy(trueLiteral, source); ReturnStatement returnTrue = new ReturnStatement(trueLiteral, pS, pE); setGeneratedBy(returnTrue, source); IfStatement ifOtherEqualsThis = new IfStatement(otherEqualsThis, returnTrue, pS, pE); setGeneratedBy(ifOtherEqualsThis, source); statements.add(ifOtherEqualsThis); } /* if (!(o instanceof Outer.Inner.MyType) return false; */ { SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p); setGeneratedBy(oRef, source); TypeReference typeReference = createTypeReference(type, p, source, false); setGeneratedBy(typeReference, source); InstanceOfExpression instanceOf = new InstanceOfExpression(oRef, typeReference); instanceOf.sourceStart = pS; instanceOf.sourceEnd = pE; setGeneratedBy(instanceOf, source); Expression notInstanceOf = new UnaryExpression(instanceOf, OperatorIds.NOT); setGeneratedBy(notInstanceOf, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); setGeneratedBy(falseLiteral, source); ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE); setGeneratedBy(returnFalse, source); IfStatement ifNotInstanceOf = new IfStatement(notInstanceOf, returnFalse, pS, pE); setGeneratedBy(ifNotInstanceOf, source); statements.add(ifNotInstanceOf); } char[] otherName = "other".toCharArray(); /* Outer.Inner.MyType other = (Outer.Inner.MyType) o; */ { if (!fields.isEmpty() || needsCanEqual) { LocalDeclaration other = new LocalDeclaration(otherName, pS, pE); other.modifiers |= ClassFileConstants.AccFinal; setGeneratedBy(other, source); TypeReference targetType = createTypeReference(type, p, source, true); setGeneratedBy(targetType, source); other.type = createTypeReference(type, p, source, true); setGeneratedBy(other.type, source); NameReference oRef = new SingleNameReference(new char[] { 'o' }, p); setGeneratedBy(oRef, source); other.initialization = makeCastExpression(oRef, targetType, source); statements.add(other); } } /* if (!other.canEqual((java.lang.Object) this)) return false; */ { if (needsCanEqual) { MessageSend otherCanEqual = new MessageSend(); otherCanEqual.sourceStart = pS; otherCanEqual.sourceEnd = pE; setGeneratedBy(otherCanEqual, source); otherCanEqual.receiver = new SingleNameReference(otherName, p); setGeneratedBy(otherCanEqual.receiver, source); otherCanEqual.selector = "canEqual".toCharArray(); ThisReference thisReference = new ThisReference(pS, pE); setGeneratedBy(thisReference, source); CastExpression castThisRef = makeCastExpression(thisReference, generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), source); castThisRef.sourceStart = pS; castThisRef.sourceEnd = pE; otherCanEqual.arguments = new Expression[] {castThisRef}; Expression notOtherCanEqual = new UnaryExpression(otherCanEqual, OperatorIds.NOT); setGeneratedBy(notOtherCanEqual, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); setGeneratedBy(falseLiteral, source); ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE); setGeneratedBy(returnFalse, source); IfStatement ifNotCanEqual = new IfStatement(notOtherCanEqual, returnFalse, pS, pE); setGeneratedBy(ifNotCanEqual, source); statements.add(ifNotCanEqual); } } /* if (!super.equals(o)) return false; */ if (callSuper) { MessageSend callToSuper = new MessageSend(); callToSuper.sourceStart = pS; callToSuper.sourceEnd = pE; setGeneratedBy(callToSuper, source); callToSuper.receiver = new SuperReference(pS, pE); setGeneratedBy(callToSuper.receiver, source); callToSuper.selector = "equals".toCharArray(); SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p); setGeneratedBy(oRef, source); callToSuper.arguments = new Expression[] {oRef}; Expression superNotEqual = new UnaryExpression(callToSuper, OperatorIds.NOT); setGeneratedBy(superNotEqual, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); setGeneratedBy(falseLiteral, source); ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE); setGeneratedBy(returnFalse, source); IfStatement ifSuperEquals = new IfStatement(superNotEqual, returnFalse, pS, pE); setGeneratedBy(ifSuperEquals, source); statements.add(ifSuperEquals); } for (EclipseNode field : fields) { TypeReference fType = getFieldType(field, fieldAccess); char[] token = fType.getLastToken(); Expression thisFieldAccessor = createFieldAccessor(field, fieldAccess, source); Expression otherFieldAccessor = createFieldAccessor(field, fieldAccess, source, otherName); if (fType.dimensions() == 0 && token != null) { if (Arrays.equals(TypeConstants.FLOAT, token)) { statements.add(generateCompareFloatOrDouble(thisFieldAccessor, otherFieldAccessor, "Float".toCharArray(), source)); } else if (Arrays.equals(TypeConstants.DOUBLE, token)) { statements.add(generateCompareFloatOrDouble(thisFieldAccessor, otherFieldAccessor, "Double".toCharArray(), source)); } else if (BUILT_IN_TYPES.contains(new String(token))) { EqualExpression fieldsNotEqual = new EqualExpression(thisFieldAccessor, otherFieldAccessor, OperatorIds.NOT_EQUAL); setGeneratedBy(fieldsNotEqual, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); setGeneratedBy(falseLiteral, source); ReturnStatement returnStatement = new ReturnStatement(falseLiteral, pS, pE); setGeneratedBy(returnStatement, source); IfStatement ifStatement = new IfStatement(fieldsNotEqual, returnStatement, pS, pE); setGeneratedBy(ifStatement, source); statements.add(ifStatement); } else /* objects */ { /* final java.lang.Object this$fieldName = this.fieldName; */ /* final java.lang.Object other$fieldName = other.fieldName; */ /* if (this$fieldName == null ? other$fieldName != null : !this$fieldName.equals(other$fieldName)) return false;; */ char[] thisDollarFieldName = ("this$" + field.getName()).toCharArray(); char[] otherDollarFieldName = ("other$" + field.getName()).toCharArray(); statements.add(createLocalDeclaration(source, thisDollarFieldName, generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), thisFieldAccessor)); statements.add(createLocalDeclaration(source, otherDollarFieldName, generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), otherFieldAccessor)); SingleNameReference this1 = new SingleNameReference(thisDollarFieldName, p); setGeneratedBy(this1, source); SingleNameReference this2 = new SingleNameReference(thisDollarFieldName, p); setGeneratedBy(this2, source); SingleNameReference other1 = new SingleNameReference(otherDollarFieldName, p); setGeneratedBy(other1, source); SingleNameReference other2 = new SingleNameReference(otherDollarFieldName, p); setGeneratedBy(other2, source); NullLiteral nullLiteral = new NullLiteral(pS, pE); setGeneratedBy(nullLiteral, source); EqualExpression fieldIsNull = new EqualExpression(this1, nullLiteral, OperatorIds.EQUAL_EQUAL); nullLiteral = new NullLiteral(pS, pE); setGeneratedBy(nullLiteral, source); EqualExpression otherFieldIsntNull = new EqualExpression(other1, nullLiteral, OperatorIds.NOT_EQUAL); MessageSend equalsCall = new MessageSend(); equalsCall.sourceStart = pS; equalsCall.sourceEnd = pE; setGeneratedBy(equalsCall, source); equalsCall.receiver = this2; equalsCall.selector = "equals".toCharArray(); equalsCall.arguments = new Expression[] { other2 }; UnaryExpression fieldsNotEqual = new UnaryExpression(equalsCall, OperatorIds.NOT); fieldsNotEqual.sourceStart = pS; fieldsNotEqual.sourceEnd = pE; setGeneratedBy(fieldsNotEqual, source); ConditionalExpression fullEquals = new ConditionalExpression(fieldIsNull, otherFieldIsntNull, fieldsNotEqual); fullEquals.sourceStart = pS; fullEquals.sourceEnd = pE; setGeneratedBy(fullEquals, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); setGeneratedBy(falseLiteral, source); ReturnStatement returnStatement = new ReturnStatement(falseLiteral, pS, pE); setGeneratedBy(returnStatement, source); IfStatement ifStatement = new IfStatement(fullEquals, returnStatement, pS, pE); setGeneratedBy(ifStatement, source); statements.add(ifStatement); } } else if (fType.dimensions() > 0 && token != null) { MessageSend arraysEqualCall = new MessageSend(); arraysEqualCall.sourceStart = pS; arraysEqualCall.sourceEnd = pE; setGeneratedBy(arraysEqualCall, source); arraysEqualCall.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); if (fType.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token))) { arraysEqualCall.selector = "deepEquals".toCharArray(); } else { arraysEqualCall.selector = "equals".toCharArray(); } arraysEqualCall.arguments = new Expression[] { thisFieldAccessor, otherFieldAccessor }; UnaryExpression arraysNotEqual = new UnaryExpression(arraysEqualCall, OperatorIds.NOT); arraysNotEqual.sourceStart = pS; arraysNotEqual.sourceEnd = pE; setGeneratedBy(arraysNotEqual, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); setGeneratedBy(falseLiteral, source); ReturnStatement returnStatement = new ReturnStatement(falseLiteral, pS, pE); setGeneratedBy(returnStatement, source); IfStatement ifStatement = new IfStatement(arraysNotEqual, returnStatement, pS, pE); setGeneratedBy(ifStatement, source); statements.add(ifStatement); } } /* return true; */ { TrueLiteral trueLiteral = new TrueLiteral(pS, pE); setGeneratedBy(trueLiteral, source); ReturnStatement returnStatement = new ReturnStatement(trueLiteral, pS, pE); setGeneratedBy(returnStatement, source); statements.add(returnStatement); } method.statements = statements.toArray(new Statement[statements.size()]); return method; } public MethodDeclaration createCanEqual(EclipseNode type, ASTNode source, List onParam) { /* protected boolean canEqual(final java.lang.Object other) { * return other instanceof Outer.Inner.MyType; * } */ int pS = source.sourceStart; int pE = source.sourceEnd; long p = (long)pS << 32 | pE; char[] otherName = "other".toCharArray(); MethodDeclaration method = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); setGeneratedBy(method, source); method.modifiers = toEclipseModifier(AccessLevel.PROTECTED); method.returnType = TypeReference.baseTypeReference(TypeIds.T_boolean, 0); method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; setGeneratedBy(method.returnType, source); method.selector = "canEqual".toCharArray(); method.thrownExceptions = null; method.typeParameters = null; method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; TypeReference objectRef = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { p, p, p }); setGeneratedBy(objectRef, source); method.arguments = new Argument[] {new Argument(otherName, 0, objectRef, Modifier.FINAL)}; method.arguments[0].sourceStart = pS; method.arguments[0].sourceEnd = pE; if (!onParam.isEmpty()) method.arguments[0].annotations = onParam.toArray(new Annotation[0]); setGeneratedBy(method.arguments[0], source); SingleNameReference otherRef = new SingleNameReference(otherName, p); setGeneratedBy(otherRef, source); TypeReference typeReference = createTypeReference(type, p, source, false); setGeneratedBy(typeReference, source); InstanceOfExpression instanceOf = new InstanceOfExpression(otherRef, typeReference); instanceOf.sourceStart = pS; instanceOf.sourceEnd = pE; setGeneratedBy(instanceOf, source); ReturnStatement returnStatement = new ReturnStatement(instanceOf, pS, pE); setGeneratedBy(returnStatement, source); method.statements = new Statement[] {returnStatement}; return method; } public IfStatement generateCompareFloatOrDouble(Expression thisRef, Expression otherRef, char[] floatOrDouble, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; /* if (Float.compare(fieldName, other.fieldName) != 0) return false */ MessageSend floatCompare = new MessageSend(); floatCompare.sourceStart = pS; floatCompare.sourceEnd = pE; setGeneratedBy(floatCompare, source); floatCompare.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.LANG, floatOrDouble); floatCompare.selector = "compare".toCharArray(); floatCompare.arguments = new Expression[] {thisRef, otherRef}; IntLiteral int0 = makeIntLiteral("0".toCharArray(), source); EqualExpression ifFloatCompareIsNot0 = new EqualExpression(floatCompare, int0, OperatorIds.NOT_EQUAL); ifFloatCompareIsNot0.sourceStart = pS; ifFloatCompareIsNot0.sourceEnd = pE; setGeneratedBy(ifFloatCompareIsNot0, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); setGeneratedBy(falseLiteral, source); ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE); setGeneratedBy(returnFalse, source); IfStatement ifStatement = new IfStatement(ifFloatCompareIsNot0, returnFalse, pS, pE); setGeneratedBy(ifStatement, source); return ifStatement; } /** Give 2 clones! */ public Expression longToIntForHashCode(Expression ref1, Expression ref2, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; /* (int)(ref >>> 32 ^ ref) */ IntLiteral int32 = makeIntLiteral("32".toCharArray(), source); BinaryExpression higherBits = new BinaryExpression(ref1, int32, OperatorIds.UNSIGNED_RIGHT_SHIFT); setGeneratedBy(higherBits, source); BinaryExpression xorParts = new BinaryExpression(ref2, higherBits, OperatorIds.XOR); setGeneratedBy(xorParts, source); TypeReference intRef = TypeReference.baseTypeReference(TypeIds.T_int, 0); intRef.sourceStart = pS; intRef.sourceEnd = pE; setGeneratedBy(intRef, source); CastExpression expr = makeCastExpression(xorParts, intRef, source); expr.sourceStart = pS; expr.sourceEnd = pE; return expr; } public NameReference generateQualifiedNameRef(ASTNode source, char[]... varNames) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; NameReference ref; if (varNames.length > 1) ref = new QualifiedNameReference(varNames, new long[varNames.length], pS, pE); else ref = new SingleNameReference(varNames[0], p); setGeneratedBy(ref, source); return ref; } public TypeReference generateQualifiedTypeRef(ASTNode source, char[]... varNames) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; TypeReference ref; long[] poss = Eclipse.poss(source, varNames.length); if (varNames.length > 1) ref = new QualifiedTypeReference(varNames, poss); else ref = new SingleTypeReference(varNames[0], p); setGeneratedBy(ref, source); return ref; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleExtensionMethod.java000066400000000000000000000056751312655740700265240ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import java.util.List; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.mangosdk.spi.ProviderFor; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.experimental.ExtensionMethod; // This handler just does some additional error checking; the real work is done in the agent. @ProviderFor(EclipseAnnotationHandler.class) @HandlerPriority(66560) // 2^16 + 2^10; we must run AFTER HandleVal which is at 2^16 public class HandleExtensionMethod extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.EXTENSION_METHOD_FLAG_USAGE, "@ExtensionMethod"); TypeDeclaration typeDecl = null; EclipseNode owner = annotationNode.up(); if (owner.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) owner.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation)) != 0; if (typeDecl == null || notAClass) { annotationNode.addError("@ExtensionMethod is legal only on classes and enums."); return; } List listenerInterfaces = annotation.getActualExpressions("value"); if (listenerInterfaces.isEmpty()) { annotationNode.addWarning(String.format("@ExtensionMethod has no effect since no extension types were specified.")); return; } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleFieldDefaults.java000066400000000000000000000165771312655740700261250ustar00rootroot00000000000000/* * Copyright (C) 2012-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.Arrays; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseASTAdapter; import lombok.eclipse.EclipseASTVisitor; import lombok.eclipse.EclipseNode; import lombok.experimental.FieldDefaults; import lombok.experimental.NonFinal; import lombok.experimental.PackagePrivate; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code lombok.FieldDefaults} annotation for eclipse. */ @ProviderFor(EclipseASTVisitor.class) @HandlerPriority(-2048) //-2^11; to ensure @Value picks up on messing with the fields' 'final' state, run earlier. public class HandleFieldDefaults extends EclipseASTAdapter { public boolean generateFieldDefaultsForType(EclipseNode typeNode, EclipseNode pos, AccessLevel level, boolean makeFinal, boolean checkForTypeLevelFieldDefaults) { if (checkForTypeLevelFieldDefaults) { if (hasAnnotation(FieldDefaults.class, typeNode)) { //The annotation will make it happen, so we can skip it. return true; } } TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation)) != 0; if (typeDecl == null || notAClass) { pos.addError("@FieldDefaults is only supported on a class or an enum."); return false; } for (EclipseNode field : typeNode.down()) { if (field.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) field.get(); if (!filterField(fieldDecl, false)) continue; Class t = field.get().getClass(); if (t == FieldDeclaration.class) { // There are various other things that extend FieldDeclaration that really // aren't field declarations. Typing 'ma' in an otherwise blank class is a // CompletionOnFieldType object (extends FieldDeclaration). If we mess with the // modifiers of such a thing, you take away template suggestions such as // 'main method'. See issue 411. setFieldDefaultsForField(field, pos.get(), level, makeFinal); } } return true; } public void setFieldDefaultsForField(EclipseNode fieldNode, ASTNode pos, AccessLevel level, boolean makeFinal) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); if (level != null && level != AccessLevel.NONE) { if ((field.modifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected)) == 0) { if (!hasAnnotation(PackagePrivate.class, fieldNode)) { if ((field.modifiers & ClassFileConstants.AccStatic) == 0) { field.modifiers |= EclipseHandlerUtil.toEclipseModifier(level); } } } } if (makeFinal && (field.modifiers & ClassFileConstants.AccFinal) == 0) { if (!hasAnnotation(NonFinal.class, fieldNode)) { if ((field.modifiers & ClassFileConstants.AccStatic) == 0) { field.modifiers |= ClassFileConstants.AccFinal; } } } fieldNode.rebuild(); } private static final char[] FIELD_DEFAULTS = "FieldDefaults".toCharArray(); @Override public void visitType(EclipseNode typeNode, TypeDeclaration type) { AnnotationValues fieldDefaults = null; EclipseNode source = typeNode; boolean levelIsExplicit = false; boolean makeFinalIsExplicit = false; FieldDefaults fd = null; for (EclipseNode jn : typeNode.down()) { if (jn.getKind() != Kind.ANNOTATION) continue; Annotation ann = (Annotation) jn.get(); TypeReference typeTree = ann.type; if (typeTree == null) continue; if (typeTree instanceof SingleTypeReference) { char[] t = ((SingleTypeReference) typeTree).token; if (!Arrays.equals(t, FIELD_DEFAULTS)) continue; } else if (typeTree instanceof QualifiedTypeReference) { char[][] t = ((QualifiedTypeReference) typeTree).tokens; if (!Eclipse.nameEquals(t, "lombok.experimental.FieldDefaults")) continue; } else { continue; } if (!typeMatches(FieldDefaults.class, jn, typeTree)) continue; source = jn; fieldDefaults = createAnnotation(FieldDefaults.class, jn); levelIsExplicit = fieldDefaults.isExplicit("level"); makeFinalIsExplicit = fieldDefaults.isExplicit("makeFinal"); handleExperimentalFlagUsage(jn, ConfigurationKeys.FIELD_DEFAULTS_FLAG_USAGE, "@FieldDefaults"); fd = fieldDefaults.getInstance(); if (!levelIsExplicit && !makeFinalIsExplicit) { jn.addError("This does nothing; provide either level or makeFinal or both."); } if (levelIsExplicit && fd.level() == AccessLevel.NONE) { jn.addError("AccessLevel.NONE doesn't mean anything here. Pick another value."); levelIsExplicit = false; } break; } if (fd == null && (type.modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation)) != 0) return; boolean defaultToPrivate = levelIsExplicit ? false : Boolean.TRUE.equals(typeNode.getAst().readConfiguration(ConfigurationKeys.FIELD_DEFAULTS_PRIVATE_EVERYWHERE)); boolean defaultToFinal = makeFinalIsExplicit ? false : Boolean.TRUE.equals(typeNode.getAst().readConfiguration(ConfigurationKeys.FIELD_DEFAULTS_FINAL_EVERYWHERE)); if (!defaultToPrivate && !defaultToFinal && fieldDefaults == null) return; AccessLevel fdAccessLevel = (fieldDefaults != null && levelIsExplicit) ? fd.level() : defaultToPrivate ? AccessLevel.PRIVATE : null; boolean fdToFinal = (fieldDefaults != null && makeFinalIsExplicit) ? fd.makeFinal() : defaultToFinal; generateFieldDefaultsForType(typeNode, source, fdAccessLevel, fdToFinal, false); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleGetter.java000066400000000000000000000520701312655740700246300ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.experimental.Delegate; import lombok.Getter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.agent.PatchDelegate; import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.BinaryExpression; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.CastExpression; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code lombok.Getter} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleGetter extends EclipseAnnotationHandler { private static final Annotation[] EMPTY_ANNOTATIONS_ARRAY = new Annotation[0]; public boolean generateGetterForType(EclipseNode typeNode, EclipseNode pos, AccessLevel level, boolean checkForTypeLevelGetter) { if (checkForTypeLevelGetter) { if (hasAnnotation(Getter.class, typeNode)) { //The annotation will make it happen, so we can skip it. return true; } } TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation)) != 0; if (typeDecl == null || notAClass) { pos.addError("@Getter is only supported on a class, an enum, or a field."); return false; } for (EclipseNode field : typeNode.down()) { if (fieldQualifiesForGetterGeneration(field)) generateGetterForField(field, pos.get(), level, false); } return true; } public boolean fieldQualifiesForGetterGeneration(EclipseNode field) { if (field.getKind() != Kind.FIELD) return false; FieldDeclaration fieldDecl = (FieldDeclaration) field.get(); return filterField(fieldDecl); } /** * Generates a getter on the stated field. * * Used by {@link HandleData}. * * The difference between this call and the handle method is as follows: * * If there is a {@code lombok.Getter} annotation on the field, it is used and the * same rules apply (e.g. warning if the method already exists, stated access level applies). * If not, the getter is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. */ public void generateGetterForField(EclipseNode fieldNode, ASTNode pos, AccessLevel level, boolean lazy) { if (hasAnnotation(Getter.class, fieldNode)) { //The annotation will make it happen, so we can skip it. return; } createGetterForField(level, fieldNode, fieldNode, pos, false, lazy, Collections.emptyList()); } public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.GETTER_FLAG_USAGE, "@Getter"); EclipseNode node = annotationNode.up(); Getter annotationInstance = annotation.getInstance(); AccessLevel level = annotationInstance.value(); boolean lazy = annotationInstance.lazy(); if (lazy) handleFlagUsage(annotationNode, ConfigurationKeys.GETTER_LAZY_FLAG_USAGE, "@Getter(lazy=true)"); if (level == AccessLevel.NONE) { if (lazy) annotationNode.addWarning("'lazy' does not work with AccessLevel.NONE."); return; } if (node == null) return; List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Getter(onMethod", annotationNode); switch (node.getKind()) { case FIELD: createGetterForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, annotationNode.get(), true, lazy, onMethod); break; case TYPE: if (!onMethod.isEmpty()) { annotationNode.addError("'onMethod' is not supported for @Getter on a type."); } if (lazy) annotationNode.addError("'lazy' is not supported for @Getter on a type."); generateGetterForType(node, annotationNode, level, false); break; } } public void createGetterForFields(AccessLevel level, Collection fieldNodes, EclipseNode errorNode, ASTNode source, boolean whineIfExists, boolean lazy, List onMethod) { for (EclipseNode fieldNode : fieldNodes) { createGetterForField(level, fieldNode, errorNode, source, whineIfExists, lazy, onMethod); } } public void createGetterForField(AccessLevel level, EclipseNode fieldNode, EclipseNode errorNode, ASTNode source, boolean whineIfExists, boolean lazy, List onMethod) { if (fieldNode.getKind() != Kind.FIELD) { errorNode.addError("@Getter is only supported on a class or a field."); return; } FieldDeclaration field = (FieldDeclaration) fieldNode.get(); if (lazy) { if ((field.modifiers & ClassFileConstants.AccPrivate) == 0 || (field.modifiers & ClassFileConstants.AccFinal) == 0) { errorNode.addError("'lazy' requires the field to be private and final."); return; } if ((field.modifiers & ClassFileConstants.AccTransient) != 0) { errorNode.addError("'lazy' is not supported on transient fields."); return; } if (field.initialization == null) { errorNode.addError("'lazy' requires field initialization."); return; } } TypeReference fieldType = copyType(field.type, source); boolean isBoolean = isBoolean(fieldType); String getterName = toGetterName(fieldNode, isBoolean); if (getterName == null) { errorNode.addWarning("Not generating getter for this field: It does not fit your @Accessors prefix list."); return; } int modifier = toEclipseModifier(level) | (field.modifiers & ClassFileConstants.AccStatic); for (String altName : toAllGetterNames(fieldNode, isBoolean)) { switch (methodExists(altName, fieldNode, false, 0)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: if (whineIfExists) { String altNameExpl = ""; if (!altName.equals(getterName)) altNameExpl = String.format(" (%s)", altName); errorNode.addWarning( String.format("Not generating %s(): A method with that name already exists%s", getterName, altNameExpl)); } return; default: case NOT_EXISTS: //continue scanning the other alt names. } } MethodDeclaration method = createGetter((TypeDeclaration) fieldNode.up().get(), fieldNode, getterName, modifier, source, lazy, onMethod); injectMethod(fieldNode.up(), method); } public static Annotation[] findDelegatesAndMarkAsHandled(EclipseNode fieldNode) { List delegates = new ArrayList(); for (EclipseNode child : fieldNode.down()) { if (annotationTypeMatches(Delegate.class, child)) { Annotation delegate = (Annotation)child.get(); PatchDelegate.markHandled(delegate); delegates.add(delegate); } } return delegates.toArray(EMPTY_ANNOTATIONS_ARRAY); } public MethodDeclaration createGetter(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, ASTNode source, boolean lazy, List onMethod) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); // Remember the type; lazy will change it; TypeReference returnType = copyType(((FieldDeclaration) fieldNode.get()).type, source); Statement[] statements; if (lazy) { statements = createLazyGetterBody(source, fieldNode); } else { statements = createSimpleGetterBody(source, fieldNode); } MethodDeclaration method = new MethodDeclaration(parent.compilationResult); method.modifiers = modifier; method.returnType = returnType; method.annotations = null; method.arguments = null; method.selector = name.toCharArray(); method.binding = null; method.thrownExceptions = null; method.typeParameters = null; method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; method.statements = statements; EclipseHandlerUtil.registerCreatedLazyGetter((FieldDeclaration) fieldNode.get(), method.selector, returnType); /* Generate annotations that must be put on the generated method, and attach them. */ { Annotation[] deprecated = null; if (isFieldDeprecated(fieldNode)) { deprecated = new Annotation[] { generateDeprecatedAnnotation(source) }; } method.annotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), findAnnotations(field, NON_NULL_PATTERN), findAnnotations(field, NULLABLE_PATTERN), findDelegatesAndMarkAsHandled(fieldNode), deprecated); } method.traverse(new SetGeneratedByVisitor(source), parent.scope); return method; } public Statement[] createSimpleGetterBody(ASTNode source, EclipseNode fieldNode) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); Statement returnStatement = new ReturnStatement(fieldRef, field.sourceStart, field.sourceEnd); return new Statement[] {returnStatement}; } private static final char[][] AR = fromQualifiedName("java.util.concurrent.atomic.AtomicReference"); public static final java.util.Map TYPE_MAP; static { Map m = new HashMap(); m.put("int", fromQualifiedName("java.lang.Integer")); m.put("double", fromQualifiedName("java.lang.Double")); m.put("float", fromQualifiedName("java.lang.Float")); m.put("short", fromQualifiedName("java.lang.Short")); m.put("byte", fromQualifiedName("java.lang.Byte")); m.put("long", fromQualifiedName("java.lang.Long")); m.put("boolean", fromQualifiedName("java.lang.Boolean")); m.put("char", fromQualifiedName("java.lang.Character")); TYPE_MAP = Collections.unmodifiableMap(m); } private static char[] valueName = "value".toCharArray(); private static char[] actualValueName = "actualValue".toCharArray(); private static final int PARENTHESIZED = (1 << ASTNode.ParenthesizedSHIFT) & ASTNode.ParenthesizedMASK; public Statement[] createLazyGetterBody(ASTNode source, EclipseNode fieldNode) { /* java.lang.Object value = this.fieldName.get(); if (value == null) { synchronized (this.fieldName) { value = this.fieldName.get(); if (value == null) { final RawValueType actualValue = INITIALIZER_EXPRESSION; [IF PRIMITIVE] value = actualValue; [ELSE] value = actualValue == null ? this.fieldName : actualValue; [END IF] this.fieldName.set(value); } } } [IF PRIMITIVE] return (BoxedValueType) value; [ELSE] return (BoxedValueType) (value == this.fieldName ? null : value); [END IF] */ FieldDeclaration field = (FieldDeclaration) fieldNode.get(); int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; TypeReference rawComponentType = copyType(field.type, source); TypeReference boxedComponentType = null; boolean isPrimitive = false; if (field.type instanceof SingleTypeReference && !(field.type instanceof ArrayTypeReference)) { char[][] newType = TYPE_MAP.get(new String(((SingleTypeReference)field.type).token)); if (newType != null) { boxedComponentType = new QualifiedTypeReference(newType, poss(source, 3)); isPrimitive = true; } } if (boxedComponentType == null) boxedComponentType = copyType(field.type, source); boxedComponentType.sourceStart = pS; boxedComponentType.sourceEnd = boxedComponentType.statementEnd = pE; Statement[] statements = new Statement[3]; /* java.lang.Object value = this.fieldName.get(); */ { LocalDeclaration valueDecl = new LocalDeclaration(valueName, pS, pE); valueDecl.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(source, 3)); valueDecl.type.sourceStart = pS; valueDecl.type.sourceEnd = valueDecl.type.statementEnd = pE; MessageSend getter = new MessageSend(); getter.sourceStart = pS; getter.statementEnd = getter.sourceEnd = pE; getter.selector = new char[] {'g', 'e', 't'}; getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); valueDecl.initialization = getter; statements[0] = valueDecl; } /* if (value == null) { synchronized (this.fieldName) { value = this.fieldName.get(); if (value == null) { final ValueType actualValue = INITIALIZER_EXPRESSION; [IF PRIMITIVE] value = actualValue; [ELSE] value = actualValue == null ? this.fieldName : actualValue; [END IF] this.fieldName.set(value); } } } */ { EqualExpression cond = new EqualExpression( new SingleNameReference(valueName, p), new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL); Block then = new Block(0); Expression lock = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); Block inner = new Block(0); inner.statements = new Statement[2]; /* value = this.fieldName.get(); */ { MessageSend getter = new MessageSend(); getter.sourceStart = pS; getter.sourceEnd = getter.statementEnd = pE; getter.selector = new char[] {'g', 'e', 't'}; getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); Assignment assign = new Assignment(new SingleNameReference(valueName, p), getter, pE); assign.sourceStart = pS; assign.statementEnd = assign.sourceEnd = pE; inner.statements[0] = assign; } /* if (value == null) */ { EqualExpression innerCond = new EqualExpression( new SingleNameReference(valueName, p), new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL); innerCond.sourceStart = pS; innerCond.sourceEnd = innerCond.statementEnd = pE; Block innerThen = new Block(0); innerThen.statements = new Statement[3]; /* final ValueType actualValue = INITIALIZER_EXPRESSION */ { LocalDeclaration actualValueDecl = new LocalDeclaration(actualValueName, pS, pE); actualValueDecl.type = rawComponentType; actualValueDecl.type.sourceStart = pS; actualValueDecl.type.sourceEnd = actualValueDecl.type.statementEnd = pE; actualValueDecl.initialization = field.initialization; actualValueDecl.modifiers = ClassFileConstants.AccFinal; innerThen.statements[0] = actualValueDecl; } /* [IF PRIMITIVE] value = actualValue; */ { if (isPrimitive) { Assignment innerAssign = new Assignment(new SingleNameReference(valueName, p), new SingleNameReference(actualValueName, p), pE); innerAssign.sourceStart = pS; innerAssign.statementEnd = innerAssign.sourceEnd = pE; innerThen.statements[1] = innerAssign; } } /* [ELSE] value = actualValue == null ? this.fieldName : actualValue; */ { if (!isPrimitive) { EqualExpression avIsNull = new EqualExpression( new SingleNameReference(actualValueName, p), new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL); avIsNull.sourceStart = pS; avIsNull.sourceEnd = avIsNull.statementEnd = pE; Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); ConditionalExpression ternary = new ConditionalExpression(avIsNull, fieldRef, new SingleNameReference(actualValueName, p)); ternary.sourceStart = pS; ternary.sourceEnd = ternary.statementEnd = pE; Assignment innerAssign = new Assignment(new SingleNameReference(valueName, p), ternary, pE); innerAssign.sourceStart = pS; innerAssign.statementEnd = innerAssign.sourceEnd = pE; innerThen.statements[1] = innerAssign; } } /* this.fieldName.set(value); */ { MessageSend setter = new MessageSend(); setter.sourceStart = pS; setter.sourceEnd = setter.statementEnd = pE; setter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); setter.selector = new char[] { 's', 'e', 't' }; setter.arguments = new Expression[] { new SingleNameReference(valueName, p)}; innerThen.statements[2] = setter; } IfStatement innerIf = new IfStatement(innerCond, innerThen, pS, pE); inner.statements[1] = innerIf; } SynchronizedStatement sync = new SynchronizedStatement(lock, inner, pS, pE); then.statements = new Statement[] {sync}; IfStatement ifStatement = new IfStatement(cond, then, pS, pE); statements[1] = ifStatement; } /* [IF PRIMITIVE] return (BoxedValueType)value; */ { if (isPrimitive) { CastExpression cast = makeCastExpression(new SingleNameReference(valueName, p), boxedComponentType, source); statements[2] = new ReturnStatement(cast, pS, pE); } } /* [ELSE] return (BoxedValueType)(value == this.fieldName ? null : value); */ { if (!isPrimitive) { EqualExpression vIsThisFieldName = new EqualExpression( new SingleNameReference(valueName, p), createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source), BinaryExpression.EQUAL_EQUAL); vIsThisFieldName.sourceStart = pS; vIsThisFieldName.sourceEnd = vIsThisFieldName.statementEnd = pE; ConditionalExpression ternary = new ConditionalExpression(vIsThisFieldName, new NullLiteral(pS, pE), new SingleNameReference(valueName, p)); ternary.sourceStart = pS; ternary.sourceEnd = ternary.statementEnd = pE; ternary.bits |= PARENTHESIZED; CastExpression cast = makeCastExpression(ternary, boxedComponentType, source); statements[2] = new ReturnStatement(cast, pS, pE); } } // update the field type and init last /* private final java.util.concurrent.atomic.AtomicReference fieldName = new java.util.concurrent.atomic.AtomicReference(); */ { TypeReference innerType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(source, 3)); TypeReference[][] typeParams = new TypeReference[5][]; typeParams[4] = new TypeReference[] {innerType}; TypeReference type = new ParameterizedQualifiedTypeReference(AR, typeParams, 0, poss(source, 5)); // Some magic here type.sourceStart = -1; type.sourceEnd = -2; field.type = type; AllocationExpression init = new AllocationExpression(); // Some magic here init.sourceStart = field.initialization.sourceStart; init.sourceEnd = init.statementEnd = field.initialization.sourceEnd; init.type = copyType(type, source); field.initialization = init; } return statements; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleHelper.java000066400000000000000000000155761312655740700246270ustar00rootroot00000000000000/* * Copyright (C) 2015-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.handleExperimentalFlagUsage; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.jdt.internal.compiler.ASTVisitor; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.SwitchStatement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.mangosdk.spi.ProviderFor; import lombok.ConfigurationKeys; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.experimental.Helper; /** * Handles the {@code lombok.Cleanup} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleHelper extends EclipseAnnotationHandler { private Statement[] getStatementsFromAstNode(ASTNode node) { if (node instanceof Block) return ((Block) node).statements; if (node instanceof AbstractMethodDeclaration) return ((AbstractMethodDeclaration) node).statements; if (node instanceof SwitchStatement) return ((SwitchStatement) node).statements; return null; } private void setStatementsOfAstNode(ASTNode node, Statement[] statements) { if (node instanceof Block) ((Block) node).statements = statements; else if (node instanceof AbstractMethodDeclaration) ((AbstractMethodDeclaration) node).statements = statements; else if (node instanceof SwitchStatement) ((SwitchStatement) node).statements = statements; else throw new IllegalArgumentException("Can't set statements on node type: " + node.getClass()); } @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.HELPER_FLAG_USAGE, "@Helper"); EclipseNode annotatedType = annotationNode.up(); EclipseNode containingBlock = annotatedType == null ? null : annotatedType.directUp(); Statement[] origStatements = getStatementsFromAstNode(containingBlock == null ? null : containingBlock.get()); if (annotatedType == null || annotatedType.getKind() != Kind.TYPE || origStatements == null) { annotationNode.addError("@Helper is legal only on method-local classes."); return; } TypeDeclaration annotatedType_ = (TypeDeclaration) annotatedType.get(); int indexOfType = -1; for (int i = 0; i < origStatements.length; i++) { if (origStatements[i] == annotatedType_) { indexOfType = i; break; } } final List knownMethodNames = new ArrayList(); for (AbstractMethodDeclaration methodOfHelper : annotatedType_.methods) { if (!(methodOfHelper instanceof MethodDeclaration)) continue; char[] name = methodOfHelper.selector; if (name != null && name.length > 0 && name[0] != '<') knownMethodNames.add(new String(name)); } Collections.sort(knownMethodNames); final String[] knownMethodNames_ = knownMethodNames.toArray(new String[knownMethodNames.size()]); final char[] helperName = new char[annotatedType_.name.length + 1]; final boolean[] helperUsed = new boolean[1]; helperName[0] = '$'; System.arraycopy(annotatedType_.name, 0, helperName, 1, helperName.length - 1); ASTVisitor visitor = new ASTVisitor() { @Override public boolean visit(MessageSend messageSend, BlockScope scope) { if (messageSend.receiver instanceof ThisReference) { if ((((ThisReference) messageSend.receiver).bits & ASTNode.IsImplicitThis) == 0) return true; } else if (messageSend.receiver != null) return true; char[] name = messageSend.selector; if (name == null || name.length == 0 || name[0] == '<') return true; String n = new String(name); if (Arrays.binarySearch(knownMethodNames_, n) < 0) return true; messageSend.receiver = new SingleNameReference(helperName, messageSend.nameSourcePosition); helperUsed[0] = true; return true; } }; for (int i = indexOfType + 1; i < origStatements.length; i++) { origStatements[i].traverse(visitor, null); } if (!helperUsed[0]) { annotationNode.addWarning("No methods of this helper class are ever used."); return; } Statement[] newStatements = new Statement[origStatements.length + 1]; System.arraycopy(origStatements, 0, newStatements, 0, indexOfType + 1); System.arraycopy(origStatements, indexOfType + 1, newStatements, indexOfType + 2, origStatements.length - indexOfType - 1); LocalDeclaration decl = new LocalDeclaration(helperName, 0, 0); decl.modifiers |= ClassFileConstants.AccFinal; AllocationExpression alloc = new AllocationExpression(); alloc.type = new SingleTypeReference(annotatedType_.name, 0L); decl.initialization = alloc; decl.type = new SingleTypeReference(annotatedType_.name, 0L); SetGeneratedByVisitor sgbvVisitor = new SetGeneratedByVisitor(annotationNode.get()); decl.traverse(sgbvVisitor, null); newStatements[indexOfType + 1] = decl; setStatementsOfAstNode(containingBlock.get(), newStatements); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleLog.java000066400000000000000000000344311312655740700241200ustar00rootroot00000000000000/* * Copyright (C) 2010-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.Eclipse.fromQualifiedName; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.lang.reflect.Modifier; import java.util.Arrays; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseHandlerUtil.MemberExistsResult; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.mangosdk.spi.ProviderFor; public class HandleLog { private HandleLog() { throw new UnsupportedOperationException(); } public static void processAnnotation(LoggingFramework framework, AnnotationValues annotation, Annotation source, EclipseNode annotationNode, String loggerTopic) { EclipseNode owner = annotationNode.up(); switch (owner.getKind()) { case TYPE: String logFieldName = annotationNode.getAst().readConfiguration(ConfigurationKeys.LOG_ANY_FIELD_NAME); if (logFieldName == null) logFieldName = "log"; boolean useStatic = !Boolean.FALSE.equals(annotationNode.getAst().readConfiguration(ConfigurationKeys.LOG_ANY_FIELD_IS_STATIC)); TypeDeclaration typeDecl = null; if (owner.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) owner.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation)) != 0; if (typeDecl == null || notAClass) { annotationNode.addError(framework.getAnnotationAsString() + " is legal only on classes and enums."); return; } if (fieldExists(logFieldName, owner) != MemberExistsResult.NOT_EXISTS) { annotationNode.addWarning("Field '" + logFieldName + "' already exists."); return; } ClassLiteralAccess loggingType = selfType(owner, source); FieldDeclaration fieldDeclaration = createField(framework, source, loggingType, logFieldName, useStatic, loggerTopic); fieldDeclaration.traverse(new SetGeneratedByVisitor(source), typeDecl.staticInitializerScope); // TODO temporary workaround for issue 217. http://code.google.com/p/projectlombok/issues/detail?id=217 // injectFieldSuppressWarnings(owner, fieldDeclaration); injectField(owner, fieldDeclaration); owner.rebuild(); break; default: break; } } public static ClassLiteralAccess selfType(EclipseNode type, Annotation source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; TypeDeclaration typeDeclaration = (TypeDeclaration)type.get(); TypeReference typeReference = new SingleTypeReference(typeDeclaration.name, p); setGeneratedBy(typeReference, source); ClassLiteralAccess result = new ClassLiteralAccess(source.sourceEnd, typeReference); setGeneratedBy(result, source); return result; } private static FieldDeclaration createField(LoggingFramework framework, Annotation source, ClassLiteralAccess loggingType, String logFieldName, boolean useStatic, String loggerTopic) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; // private static final log = (); FieldDeclaration fieldDecl = new FieldDeclaration(logFieldName.toCharArray(), 0, -1); setGeneratedBy(fieldDecl, source); fieldDecl.declarationSourceEnd = -1; fieldDecl.modifiers = Modifier.PRIVATE | (useStatic ? Modifier.STATIC : 0) | Modifier.FINAL; fieldDecl.type = createTypeReference(framework.getLoggerTypeName(), source); MessageSend factoryMethodCall = new MessageSend(); setGeneratedBy(factoryMethodCall, source); factoryMethodCall.receiver = createNameReference(framework.getLoggerFactoryTypeName(), source); factoryMethodCall.selector = framework.getLoggerFactoryMethodName().toCharArray(); Expression parameter; if (loggerTopic == null || loggerTopic.trim().length() == 0) { parameter = framework.createFactoryParameter(loggingType, source); } else { parameter = new StringLiteral(loggerTopic.toCharArray(), pS, pE, 0); } factoryMethodCall.arguments = new Expression[] { parameter }; factoryMethodCall.nameSourcePosition = p; factoryMethodCall.sourceStart = pS; factoryMethodCall.sourceEnd = factoryMethodCall.statementEnd = pE; fieldDecl.initialization = factoryMethodCall; return fieldDecl; } public static TypeReference createTypeReference(String typeName, Annotation source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; TypeReference typeReference; if (typeName.contains(".")) { char[][] typeNameTokens = fromQualifiedName(typeName); long[] pos = new long[typeNameTokens.length]; Arrays.fill(pos, p); typeReference = new QualifiedTypeReference(typeNameTokens, pos); } else { typeReference = null; } setGeneratedBy(typeReference, source); return typeReference; } /** * Handles the {@link lombok.extern.apachecommons.CommonsLog} annotation for Eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public static class HandleCommonsLog extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_COMMONS_FLAG_USAGE, "@apachecommons.CommonsLog", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.COMMONS, annotation, source, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.java.Log} annotation for Eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public static class HandleJulLog extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_JUL_FLAG_USAGE, "@java.Log", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.JUL, annotation, source, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.log4j.Log4j} annotation for Eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public static class HandleLog4jLog extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_LOG4J_FLAG_USAGE, "@Log4j", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.LOG4J, annotation, source, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.log4j.Log4j2} annotation for Eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public static class HandleLog4j2Log extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_LOG4J2_FLAG_USAGE, "@Log4j2", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.LOG4J2, annotation, source, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.slf4j.Slf4j} annotation for Eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public static class HandleSlf4jLog extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_SLF4J_FLAG_USAGE, "@Slf4j", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.SLF4J, annotation, source, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.slf4j.XSlf4j} annotation for Eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public static class HandleXSlf4jLog extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_XSLF4J_FLAG_USAGE, "@XSlf4j", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.XSLF4J, annotation, source, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.jbosslog.JBossLog} annotation for Eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public static class HandleJBossLog extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_JBOSSLOG_FLAG_USAGE, "@JBossLog", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.JBOSSLOG, annotation, source, annotationNode, annotation.getInstance().topic()); } } enum LoggingFramework { // private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(TargetType.class); COMMONS("org.apache.commons.logging.Log", "org.apache.commons.logging.LogFactory", "getLog", "@CommonsLog"), // private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(TargetType.class.getName()); JUL("java.util.logging.Logger", "java.util.logging.Logger", "getLogger", "@Log") { @Override public Expression createFactoryParameter(ClassLiteralAccess type, Annotation source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; MessageSend factoryParameterCall = new MessageSend(); setGeneratedBy(factoryParameterCall, source); factoryParameterCall.receiver = super.createFactoryParameter(type, source); factoryParameterCall.selector = "getName".toCharArray(); factoryParameterCall.nameSourcePosition = p; factoryParameterCall.sourceStart = pS; factoryParameterCall.sourceEnd = factoryParameterCall.statementEnd = pE; return factoryParameterCall; } }, // private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(TargetType.class); LOG4J("org.apache.log4j.Logger", "org.apache.log4j.Logger", "getLogger", "@Log4j"), // private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(TargetType.class); LOG4J2("org.apache.logging.log4j.Logger", "org.apache.logging.log4j.LogManager", "getLogger", "@Log4j2"), // private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TargetType.class); SLF4J("org.slf4j.Logger", "org.slf4j.LoggerFactory", "getLogger", "@Slf4j"), // private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(TargetType.class); XSLF4J("org.slf4j.ext.XLogger", "org.slf4j.ext.XLoggerFactory", "getXLogger", "@XSlf4j"), // private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(TargetType.class); JBOSSLOG("org.jboss.logging.Logger", "org.jboss.logging.Logger", "getLogger", "@JBossLog"), ; private final String loggerTypeName; private final String loggerFactoryTypeName; private final String loggerFactoryMethodName; private final String annotationAsString; LoggingFramework(String loggerTypeName, String loggerFactoryTypeName, String loggerFactoryMethodName, String annotationAsString) { this.loggerTypeName = loggerTypeName; this.loggerFactoryTypeName = loggerFactoryTypeName; this.loggerFactoryMethodName = loggerFactoryMethodName; this.annotationAsString = annotationAsString; } final String getAnnotationAsString() { return annotationAsString; } final String getLoggerTypeName() { return loggerTypeName; } final String getLoggerFactoryTypeName() { return loggerFactoryTypeName; } final String getLoggerFactoryMethodName() { return loggerFactoryMethodName; } Expression createFactoryParameter(ClassLiteralAccess loggingType, Annotation source){ TypeReference copy = copyType(loggingType.type, source); ClassLiteralAccess result = new ClassLiteralAccess(source.sourceEnd, copy); setGeneratedBy(result, source); return result; }; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleNonNull.java000066400000000000000000000167531312655740700247730ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.Eclipse.isPrimitive; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.Arrays; import lombok.ConfigurationKeys; import lombok.NonNull; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.eclipse.DeferUntilPostDiet; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement; import org.eclipse.jdt.internal.compiler.ast.ThrowStatement; import org.eclipse.jdt.internal.compiler.ast.TryStatement; import org.mangosdk.spi.ProviderFor; @DeferUntilPostDiet @ProviderFor(EclipseAnnotationHandler.class) @HandlerPriority(value = 512) // 2^9; onParameter=@__(@NonNull) has to run first. public class HandleNonNull extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.NON_NULL_FLAG_USAGE, "@NonNull"); if (annotationNode.up().getKind() == Kind.FIELD) { // This is meaningless unless the field is used to generate a method (@Setter, @RequiredArgsConstructor, etc), // but in that case those handlers will take care of it. However, we DO check if the annotation is applied to // a primitive, because those handlers trigger on any annotation named @NonNull and we only want the warning // behaviour on _OUR_ 'lombok.NonNull'. try { if (isPrimitive(((AbstractVariableDeclaration) annotationNode.up().get()).type)) { annotationNode.addWarning("@NonNull is meaningless on a primitive."); } } catch (Exception ignore) {} return; } if (annotationNode.up().getKind() != Kind.ARGUMENT) return; Argument arg; AbstractMethodDeclaration declaration; try { arg = (Argument) annotationNode.up().get(); declaration = (AbstractMethodDeclaration) annotationNode.up().up().get(); } catch (Exception e) { return; } if (isGenerated(declaration)) return; if (declaration.isAbstract()) { // This used to be a warning, but as @NonNull also has a documentary purpose, better to not warn about this. Since 1.16.7 return; } // Possibly, if 'declaration instanceof ConstructorDeclaration', fetch declaration.constructorCall, search it for any references to our parameter, // and if they exist, create a new method in the class: 'private static T lombok$nullCheck(T expr, String msg) {if (expr == null) throw NPE; return expr;}' and // wrap all references to it in the super/this to a call to this method. Statement nullCheck = generateNullCheck(arg, annotationNode); if (nullCheck == null) { // @NonNull applied to a primitive. Kinda pointless. Let's generate a warning. annotationNode.addWarning("@NonNull is meaningless on a primitive."); return; } if (declaration.statements == null) { declaration.statements = new Statement[] {nullCheck}; } else { char[] expectedName = arg.name; /* Abort if the null check is already there, delving into try and synchronized statements */ { Statement[] stats = declaration.statements; int idx = 0; while (stats != null && stats.length > idx) { Statement stat = stats[idx++]; if (stat instanceof TryStatement) { stats = ((TryStatement) stat).tryBlock.statements; idx = 0; continue; } if (stat instanceof SynchronizedStatement) { stats = ((SynchronizedStatement) stat).block.statements; idx = 0; continue; } char[] varNameOfNullCheck = returnVarNameIfNullCheck(stat); if (varNameOfNullCheck == null) break; if (Arrays.equals(varNameOfNullCheck, expectedName)) return; } } Statement[] newStatements = new Statement[declaration.statements.length + 1]; int skipOver = 0; for (Statement stat : declaration.statements) { if (isGenerated(stat) && isNullCheck(stat)) skipOver++; else break; } System.arraycopy(declaration.statements, 0, newStatements, 0, skipOver); System.arraycopy(declaration.statements, skipOver, newStatements, skipOver + 1, declaration.statements.length - skipOver); newStatements[skipOver] = nullCheck; declaration.statements = newStatements; } annotationNode.up().up().rebuild(); } public boolean isNullCheck(Statement stat) { return returnVarNameIfNullCheck(stat) != null; } public char[] returnVarNameIfNullCheck(Statement stat) { if (!(stat instanceof IfStatement)) return null; /* Check that the if's statement is a throw statement, possibly in a block. */ { Statement then = ((IfStatement) stat).thenStatement; if (then instanceof Block) { Statement[] blockStatements = ((Block) then).statements; if (blockStatements == null || blockStatements.length == 0) return null; then = blockStatements[0]; } if (!(then instanceof ThrowStatement)) return null; } /* Check that the if's conditional is like 'x == null'. Return from this method (don't generate a nullcheck) if 'x' is equal to our own variable's name: There's already a nullcheck here. */ { Expression cond = ((IfStatement) stat).condition; if (!(cond instanceof EqualExpression)) return null; EqualExpression bin = (EqualExpression) cond; int operatorId = ((bin.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT); if (operatorId != OperatorIds.EQUAL_EQUAL) return null; if (!(bin.left instanceof SingleNameReference)) return null; if (!(bin.right instanceof NullLiteral)) return null; return ((SingleNameReference) bin.left).token; } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandlePrintAST.java000066400000000000000000000051001312655740700250320ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.mangosdk.spi.ProviderFor; import lombok.Lombok; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.core.PrintAST; import lombok.eclipse.DeferUntilPostDiet; import lombok.eclipse.EclipseASTVisitor; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; /** * Handles the {@code lombok.core.PrintAST} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) @DeferUntilPostDiet @HandlerPriority(536870912) // 2^29; this handler is customarily run at the very end. public class HandlePrintAST extends EclipseAnnotationHandler { public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { PrintStream stream = System.out; String fileName = annotation.getInstance().outfile(); if (fileName.length() > 0) try { stream = new PrintStream(new File(fileName)); } catch (FileNotFoundException e) { throw Lombok.sneakyThrow(e); } try { annotationNode.up().traverse(new EclipseASTVisitor.Printer(annotation.getInstance().printContent(), stream, annotation.getInstance().printPositions())); } finally { if (stream != System.out) { try { stream.close(); } catch (Exception e) { throw Lombok.sneakyThrow(e); } } } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleSetter.java000066400000000000000000000256251312655740700246520ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.Setter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NameReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code lombok.Setter} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleSetter extends EclipseAnnotationHandler { public boolean generateSetterForType(EclipseNode typeNode, EclipseNode pos, AccessLevel level, boolean checkForTypeLevelSetter) { if (checkForTypeLevelSetter) { if (hasAnnotation(Setter.class, typeNode)) { //The annotation will make it happen, so we can skip it. return true; } } TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; if (typeDecl == null || notAClass) { pos.addError("@Setter is only supported on a class or a field."); return false; } for (EclipseNode field : typeNode.down()) { if (field.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) field.get(); if (!filterField(fieldDecl)) continue; //Skip final fields. if ((fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0) continue; generateSetterForField(field, pos, level); } return true; } /** * Generates a setter on the stated field. * * Used by {@link HandleData}. * * The difference between this call and the handle method is as follows: * * If there is a {@code lombok.Setter} annotation on the field, it is used and the * same rules apply (e.g. warning if the method already exists, stated access level applies). * If not, the setter is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. */ public void generateSetterForField(EclipseNode fieldNode, EclipseNode sourceNode, AccessLevel level) { if (hasAnnotation(Setter.class, fieldNode)) { //The annotation will make it happen, so we can skip it. return; } List empty = Collections.emptyList(); createSetterForField(level, fieldNode, sourceNode, false, empty, empty); } public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.SETTER_FLAG_USAGE, "@Setter"); EclipseNode node = annotationNode.up(); AccessLevel level = annotation.getInstance().value(); if (level == AccessLevel.NONE || node == null) return; List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Setter(onMethod", annotationNode); List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Setter(onParam", annotationNode); switch (node.getKind()) { case FIELD: createSetterForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, true, onMethod, onParam); break; case TYPE: if (!onMethod.isEmpty()) { annotationNode.addError("'onMethod' is not supported for @Setter on a type."); } if (!onParam.isEmpty()) { annotationNode.addError("'onParam' is not supported for @Setter on a type."); } generateSetterForType(node, annotationNode, level, false); break; } } public void createSetterForFields(AccessLevel level, Collection fieldNodes, EclipseNode sourceNode, boolean whineIfExists, List onMethod, List onParam) { for (EclipseNode fieldNode : fieldNodes) { createSetterForField(level, fieldNode, sourceNode, whineIfExists, onMethod, onParam); } } public void createSetterForField( AccessLevel level, EclipseNode fieldNode, EclipseNode sourceNode, boolean whineIfExists, List onMethod, List onParam) { ASTNode source = sourceNode.get(); if (fieldNode.getKind() != Kind.FIELD) { sourceNode.addError("@Setter is only supported on a class or a field."); return; } FieldDeclaration field = (FieldDeclaration) fieldNode.get(); TypeReference fieldType = copyType(field.type, source); boolean isBoolean = isBoolean(fieldType); String setterName = toSetterName(fieldNode, isBoolean); boolean shouldReturnThis = shouldReturnThis(fieldNode); if (setterName == null) { fieldNode.addWarning("Not generating setter for this field: It does not fit your @Accessors prefix list."); return; } int modifier = toEclipseModifier(level) | (field.modifiers & ClassFileConstants.AccStatic); for (String altName : toAllSetterNames(fieldNode, isBoolean)) { switch (methodExists(altName, fieldNode, false, 1)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: if (whineIfExists) { String altNameExpl = ""; if (!altName.equals(setterName)) altNameExpl = String.format(" (%s)", altName); fieldNode.addWarning( String.format("Not generating %s(): A method with that name already exists%s", setterName, altNameExpl)); } return; default: case NOT_EXISTS: //continue scanning the other alt names. } } MethodDeclaration method = createSetter((TypeDeclaration) fieldNode.up().get(), false, fieldNode, setterName, null, shouldReturnThis, modifier, sourceNode, onMethod, onParam); injectMethod(fieldNode.up(), method); } static MethodDeclaration createSetter(TypeDeclaration parent, boolean deprecate, EclipseNode fieldNode, String name, char[] booleanFieldToSet, boolean shouldReturnThis, int modifier, EclipseNode sourceNode, List onMethod, List onParam) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); ASTNode source = sourceNode.get(); int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; MethodDeclaration method = new MethodDeclaration(parent.compilationResult); method.modifiers = modifier; if (shouldReturnThis) { method.returnType = cloneSelfType(fieldNode, source); } if (method.returnType == null) { method.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0); method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; shouldReturnThis = false; } Annotation[] deprecated = null; if (isFieldDeprecated(fieldNode) || deprecate) { deprecated = new Annotation[] { generateDeprecatedAnnotation(source) }; } method.annotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), deprecated); Argument param = new Argument(field.name, p, copyType(field.type, source), Modifier.FINAL); param.sourceStart = pS; param.sourceEnd = pE; method.arguments = new Argument[] { param }; method.selector = name.toCharArray(); method.binding = null; method.thrownExceptions = null; method.typeParameters = null; method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); NameReference fieldNameRef = new SingleNameReference(field.name, p); Assignment assignment = new Assignment(fieldRef, fieldNameRef, (int)p); assignment.sourceStart = pS; assignment.sourceEnd = assignment.statementEnd = pE; method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; Annotation[] nonNulls = findAnnotations(field, NON_NULL_PATTERN); Annotation[] nullables = findAnnotations(field, NULLABLE_PATTERN); List statements = new ArrayList(5); if (nonNulls.length == 0) { statements.add(assignment); } else { Statement nullCheck = generateNullCheck(field, sourceNode); if (nullCheck != null) statements.add(nullCheck); statements.add(assignment); } if (booleanFieldToSet != null) { statements.add(new Assignment(new SingleNameReference(booleanFieldToSet, p), new TrueLiteral(pS, pE), pE)); } if (shouldReturnThis) { ThisReference thisRef = new ThisReference(pS, pE); ReturnStatement returnThis = new ReturnStatement(thisRef, pS, pE); statements.add(returnThis); } method.statements = statements.toArray(new Statement[0]); param.annotations = copyAnnotations(source, nonNulls, nullables, onParam.toArray(new Annotation[0])); method.traverse(new SetGeneratedByVisitor(source), parent.scope); return method; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleSneakyThrows.java000066400000000000000000000253541312655740700260440ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.ConfigurationKeys; import lombok.SneakyThrows; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.eclipse.DeferUntilPostDiet; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThrowStatement; import org.eclipse.jdt.internal.compiler.ast.TryStatement; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code lombok.HandleSneakyThrows} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) @DeferUntilPostDiet @HandlerPriority(value = 1024) // 2^10; @NonNull must have run first, so that we wrap around the statements generated by it. public class HandleSneakyThrows extends EclipseAnnotationHandler { private static class DeclaredException { final String exceptionName; final ASTNode node; DeclaredException(String exceptionName, ASTNode node) { this.exceptionName = exceptionName; this.node = node; } } @Override public void handle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.SNEAKY_THROWS_FLAG_USAGE, "@SneakyThrows"); List exceptionNames = annotation.getRawExpressions("value"); List exceptions = new ArrayList(); MemberValuePair[] memberValuePairs = source.memberValuePairs(); if (memberValuePairs == null || memberValuePairs.length == 0) { exceptions.add(new DeclaredException("java.lang.Throwable", source)); } else { Expression arrayOrSingle = memberValuePairs[0].value; final Expression[] exceptionNameNodes; if (arrayOrSingle instanceof ArrayInitializer) { exceptionNameNodes = ((ArrayInitializer)arrayOrSingle).expressions; } else exceptionNameNodes = new Expression[] { arrayOrSingle }; if (exceptionNames.size() != exceptionNameNodes.length) { annotationNode.addError( "LOMBOK BUG: The number of exception classes in the annotation isn't the same pre- and post- guessing."); } int idx = 0; for (String exceptionName : exceptionNames) { if (exceptionName.endsWith(".class")) exceptionName = exceptionName.substring(0, exceptionName.length() - 6); exceptions.add(new DeclaredException(exceptionName, exceptionNameNodes[idx++])); } } EclipseNode owner = annotationNode.up(); switch (owner.getKind()) { // case FIELD: // return handleField(annotationNode, (FieldDeclaration)owner.get(), exceptions); case METHOD: handleMethod(annotationNode, (AbstractMethodDeclaration)owner.get(), exceptions); break; default: annotationNode.addError("@SneakyThrows is legal only on methods and constructors."); } } // private boolean handleField(Node annotation, FieldDeclaration field, List exceptions) { // if (field.initialization == null) { // annotation.addError("@SneakyThrows can only be used on fields with an initialization statement."); // return true; // } // // Expression expression = field.initialization; // Statement[] content = new Statement[] {new Assignment( // new SingleNameReference(field.name, 0), expression, 0)}; // field.initialization = null; // // for (DeclaredException exception : exceptions) { // content = new Statement[] { buildTryCatchBlock(content, exception) }; // } // // Block block = new Block(0); // block.statements = content; // // Node typeNode = annotation.up().up(); // // Initializer initializer = new Initializer(block, field.modifiers & Modifier.STATIC); // initializer.sourceStart = expression.sourceStart; // initializer.sourceEnd = expression.sourceEnd; // initializer.declarationSourceStart = expression.sourceStart; // initializer.declarationSourceEnd = expression.sourceEnd; // injectField(typeNode, initializer); // // typeNode.rebuild(); // // return true; // } public void handleMethod(EclipseNode annotation, AbstractMethodDeclaration method, List exceptions) { if (method.isAbstract()) { annotation.addError("@SneakyThrows can only be used on concrete methods."); return; } if (method.statements == null || method.statements.length == 0) { boolean hasConstructorCall = false; if (method instanceof ConstructorDeclaration) { ExplicitConstructorCall constructorCall = ((ConstructorDeclaration) method).constructorCall; hasConstructorCall = constructorCall != null && !constructorCall.isImplicitSuper() && !constructorCall.isImplicitThis(); } if (hasConstructorCall) { annotation.addWarning("Calls to sibling / super constructors are always excluded from @SneakyThrows; @SneakyThrows has been ignored because there is no other code in this constructor."); } else { annotation.addWarning("This method or constructor is empty; @SneakyThrows has been ignored."); } return; } Statement[] contents = method.statements; for (DeclaredException exception : exceptions) { contents = new Statement[] { buildTryCatchBlock(contents, exception, exception.node, method) }; } method.statements = contents; annotation.up().rebuild(); } public Statement buildTryCatchBlock(Statement[] contents, DeclaredException exception, ASTNode source, AbstractMethodDeclaration method) { int methodStart = method.bodyStart; int methodEnd = method.bodyEnd; long methodPosEnd = ((long) methodEnd) << 32 | (methodEnd & 0xFFFFFFFFL); TryStatement tryStatement = new TryStatement(); setGeneratedBy(tryStatement, source); tryStatement.tryBlock = new Block(0); // Positions for in-method generated nodes are special tryStatement.tryBlock.sourceStart = methodStart; tryStatement.tryBlock.sourceEnd = methodEnd; setGeneratedBy(tryStatement.tryBlock, source); tryStatement.tryBlock.statements = contents; TypeReference typeReference; if (exception.exceptionName.indexOf('.') == -1) { typeReference = new SingleTypeReference(exception.exceptionName.toCharArray(), methodPosEnd); typeReference.statementEnd = methodEnd; } else { String[] x = exception.exceptionName.split("\\."); char[][] elems = new char[x.length][]; long[] poss = new long[x.length]; Arrays.fill(poss, methodPosEnd); for (int i = 0; i < x.length; i++) { elems[i] = x[i].trim().toCharArray(); } typeReference = new QualifiedTypeReference(elems, poss); } setGeneratedBy(typeReference, source); Argument catchArg = new Argument("$ex".toCharArray(), methodPosEnd, typeReference, Modifier.FINAL); setGeneratedBy(catchArg, source); catchArg.declarationSourceEnd = catchArg.declarationEnd = catchArg.sourceEnd = methodEnd; catchArg.declarationSourceStart = catchArg.modifiersSourceStart = catchArg.sourceStart = methodEnd; tryStatement.catchArguments = new Argument[] { catchArg }; MessageSend sneakyThrowStatement = new MessageSend(); setGeneratedBy(sneakyThrowStatement, source); sneakyThrowStatement.receiver = new QualifiedNameReference(new char[][] { "lombok".toCharArray(), "Lombok".toCharArray() }, new long[2], methodEnd, methodEnd); setGeneratedBy(sneakyThrowStatement.receiver, source); sneakyThrowStatement.receiver.statementEnd = methodEnd; sneakyThrowStatement.selector = "sneakyThrow".toCharArray(); SingleNameReference exRef = new SingleNameReference("$ex".toCharArray(), methodPosEnd); setGeneratedBy(exRef, source); exRef.statementEnd = methodEnd; sneakyThrowStatement.arguments = new Expression[] { exRef }; // This is the magic fix for rendering issues // In org.eclipse.jdt.core.dom.ASTConverter#convert(org.eclipse.jdt.internal.compiler.ast.MessageSend) // a new SimpleName is created and the setSourceRange should receive -1, 0. That's why we provide -2L :-) sneakyThrowStatement.nameSourcePosition = -2L; sneakyThrowStatement.sourceStart = methodEnd; sneakyThrowStatement.sourceEnd = sneakyThrowStatement.statementEnd = methodEnd; Statement rethrowStatement = new ThrowStatement(sneakyThrowStatement, methodEnd, methodEnd); setGeneratedBy(rethrowStatement, source); Block block = new Block(0); block.sourceStart = methodEnd; block.sourceEnd = methodEnd; setGeneratedBy(block, source); block.statements = new Statement[] { rethrowStatement }; tryStatement.catchBlocks = new Block[] { block }; // Positions for in-method generated nodes are special tryStatement.sourceStart = method.bodyStart; tryStatement.sourceEnd = method.bodyEnd; return tryStatement; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleSynchronized.java000066400000000000000000000161301312655740700260520ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.lang.reflect.Modifier; import lombok.ConfigurationKeys; import lombok.Synchronized; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.core.AST.Kind; import lombok.eclipse.DeferUntilPostDiet; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code lombok.Synchronized} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) @DeferUntilPostDiet @HandlerPriority(value = 1024) // 2^10; @NonNull must have run first, so that we wrap around the statements generated by it. public class HandleSynchronized extends EclipseAnnotationHandler { private static final char[] INSTANCE_LOCK_NAME = "$lock".toCharArray(); private static final char[] STATIC_LOCK_NAME = "$LOCK".toCharArray(); @Override public void preHandle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { EclipseNode methodNode = annotationNode.up(); if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof MethodDeclaration)) return; MethodDeclaration method = (MethodDeclaration)methodNode.get(); if (method.isAbstract()) return; createLockField(annotation, annotationNode, method.isStatic(), false); } public char[] createLockField(AnnotationValues annotation, EclipseNode annotationNode, boolean isStatic, boolean reportErrors) { char[] lockName = annotation.getInstance().value().toCharArray(); Annotation source = (Annotation) annotationNode.get(); boolean autoMake = false; if (lockName.length == 0) { autoMake = true; lockName = isStatic ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME; } if (fieldExists(new String(lockName), annotationNode) == MemberExistsResult.NOT_EXISTS) { if (!autoMake) { if (reportErrors) annotationNode.addError(String.format("The field %s does not exist.", new String(lockName))); return null; } FieldDeclaration fieldDecl = new FieldDeclaration(lockName, 0, -1); setGeneratedBy(fieldDecl, source); fieldDecl.declarationSourceEnd = -1; fieldDecl.modifiers = (isStatic ? Modifier.STATIC : 0) | Modifier.FINAL | Modifier.PRIVATE; //We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable! ArrayAllocationExpression arrayAlloc = new ArrayAllocationExpression(); setGeneratedBy(arrayAlloc, source); arrayAlloc.dimensions = new Expression[] { makeIntLiteral("0".toCharArray(), source) }; arrayAlloc.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { 0, 0, 0 }); setGeneratedBy(arrayAlloc.type, source); fieldDecl.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { 0, 0, 0 }); setGeneratedBy(fieldDecl.type, source); fieldDecl.initialization = arrayAlloc; // TODO temporary workaround for issue 217. http://code.google.com/p/projectlombok/issues/detail?id=217 // injectFieldSuppressWarnings(annotationNode.up().up(), fieldDecl); injectField(annotationNode.up().up(), fieldDecl); } return lockName; } @Override public void handle(AnnotationValues annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.SYNCHRONIZED_FLAG_USAGE, "@Synchronized"); int p1 = source.sourceStart -1; int p2 = source.sourceStart -2; long pos = (((long)p1) << 32) | p2; EclipseNode methodNode = annotationNode.up(); if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof MethodDeclaration)) { annotationNode.addError("@Synchronized is legal only on methods."); return; } MethodDeclaration method = (MethodDeclaration)methodNode.get(); if (method.isAbstract()) { annotationNode.addError("@Synchronized is legal only on concrete methods."); return; } char[] lockName = createLockField(annotation, annotationNode, method.isStatic(), true); if (lockName == null) return; if (method.statements == null) return; Block block = new Block(0); setGeneratedBy(block, source); block.statements = method.statements; // Positions for in-method generated nodes are special block.sourceEnd = method.bodyEnd; block.sourceStart = method.bodyStart; Expression lockVariable; if (method.isStatic()) lockVariable = new QualifiedNameReference(new char[][] { methodNode.up().getName().toCharArray(), lockName }, new long[] { pos, pos }, p1, p2); else { lockVariable = new FieldReference(lockName, pos); ThisReference thisReference = new ThisReference(p1, p2); setGeneratedBy(thisReference, source); ((FieldReference)lockVariable).receiver = thisReference; } setGeneratedBy(lockVariable, source); method.statements = new Statement[] { new SynchronizedStatement(lockVariable, block, 0, 0) }; // Positions for in-method generated nodes are special method.statements[0].sourceEnd = method.bodyEnd; method.statements[0].sourceStart = method.bodyStart; setGeneratedBy(method.statements[0], source); methodNode.rebuild(); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleToString.java000066400000000000000000000342111312655740700251440ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.ToString; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.BinaryExpression; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NameReference; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.SuperReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code ToString} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleToString extends EclipseAnnotationHandler { public void checkForBogusFieldNames(EclipseNode type, AnnotationValues annotation) { if (annotation.isExplicit("exclude")) { for (int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().exclude()), type, true, false)) { annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); } } if (annotation.isExplicit("of")) { for (int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().of()), type, false, false)) { annotation.setWarning("of", "This field does not exist.", i); } } } public void generateToStringForType(EclipseNode typeNode, EclipseNode errorNode) { if (hasAnnotation(ToString.class, typeNode)) { //The annotation will make it happen, so we can skip it. return; } boolean includeFieldNames = true; try { Boolean configuration = typeNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_INCLUDE_FIELD_NAMES); includeFieldNames = configuration != null ? configuration : ((Boolean)ToString.class.getMethod("includeFieldNames").getDefaultValue()).booleanValue(); } catch (Exception ignore) {} Boolean doNotUseGettersConfiguration = typeNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_DO_NOT_USE_GETTERS); FieldAccess access = doNotUseGettersConfiguration == null || !doNotUseGettersConfiguration ? FieldAccess.GETTER : FieldAccess.PREFER_FIELD; generateToString(typeNode, errorNode, null, null, includeFieldNames, null, false, access); } public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.TO_STRING_FLAG_USAGE, "@ToString"); ToString ann = annotation.getInstance(); List excludes = Arrays.asList(ann.exclude()); List includes = Arrays.asList(ann.of()); EclipseNode typeNode = annotationNode.up(); Boolean callSuper = ann.callSuper(); if (!annotation.isExplicit("callSuper")) callSuper = null; if (!annotation.isExplicit("exclude")) excludes = null; if (!annotation.isExplicit("of")) includes = null; if (excludes != null && includes != null) { excludes = null; annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored."); } checkForBogusFieldNames(typeNode, annotation); Boolean doNotUseGettersConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_DO_NOT_USE_GETTERS); boolean doNotUseGetters = annotation.isExplicit("doNotUseGetters") || doNotUseGettersConfiguration == null ? ann.doNotUseGetters() : doNotUseGettersConfiguration; FieldAccess fieldAccess = doNotUseGetters ? FieldAccess.PREFER_FIELD : FieldAccess.GETTER; Boolean fieldNamesConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_INCLUDE_FIELD_NAMES); boolean includeFieldNames = annotation.isExplicit("includeFieldNames") || fieldNamesConfiguration == null ? ann.includeFieldNames() : fieldNamesConfiguration; generateToString(typeNode, annotationNode, excludes, includes, includeFieldNames, callSuper, true, fieldAccess); } public void generateToString(EclipseNode typeNode, EclipseNode errorNode, List excludes, List includes, boolean includeFieldNames, Boolean callSuper, boolean whineIfExists, FieldAccess fieldAccess) { TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation)) != 0; if (typeDecl == null || notAClass) { errorNode.addError("@ToString is only supported on a class or enum."); } if (callSuper == null) { try { callSuper = ((Boolean)ToString.class.getMethod("callSuper").getDefaultValue()).booleanValue(); } catch (Exception ignore) {} } List nodesForToString = new ArrayList(); if (includes != null) { for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); if (includes.contains(new String(fieldDecl.name))) nodesForToString.add(child); } } else { for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); if (!filterField(fieldDecl)) continue; //Skip excluded fields. if (excludes != null && excludes.contains(new String(fieldDecl.name))) continue; nodesForToString.add(child); } } switch (methodExists("toString", typeNode, 0)) { case NOT_EXISTS: MethodDeclaration toString = createToString(typeNode, nodesForToString, includeFieldNames, callSuper, errorNode.get(), fieldAccess); injectMethod(typeNode, toString); break; case EXISTS_BY_LOMBOK: break; default: case EXISTS_BY_USER: if (whineIfExists) { errorNode.addWarning("Not generating toString(): A method with that name already exists"); } } } public static MethodDeclaration createToString(EclipseNode type, Collection fields, boolean includeFieldNames, boolean callSuper, ASTNode source, FieldAccess fieldAccess) { String typeName = getTypeName(type); char[] suffix = ")".toCharArray(); String infixS = ", "; char[] infix = infixS.toCharArray(); int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; final int PLUS = OperatorIds.PLUS; char[] prefix; if (callSuper) { prefix = (typeName + "(super=").toCharArray(); } else if (fields.isEmpty()) { prefix = (typeName + "()").toCharArray(); } else if (includeFieldNames) { prefix = (typeName + "(" + new String(((FieldDeclaration)fields.iterator().next().get()).name) + "=").toCharArray(); } else { prefix = (typeName + "(").toCharArray(); } boolean first = true; Expression current = new StringLiteral(prefix, pS, pE, 0); setGeneratedBy(current, source); if (callSuper) { MessageSend callToSuper = new MessageSend(); callToSuper.sourceStart = pS; callToSuper.sourceEnd = pE; setGeneratedBy(callToSuper, source); callToSuper.receiver = new SuperReference(pS, pE); setGeneratedBy(callToSuper, source); callToSuper.selector = "toString".toCharArray(); current = new BinaryExpression(current, callToSuper, PLUS); setGeneratedBy(current, source); first = false; } for (EclipseNode field : fields) { TypeReference fieldType = getFieldType(field, fieldAccess); Expression fieldAccessor = createFieldAccessor(field, fieldAccess, source); // The distinction between primitive and object will be useful if we ever add a 'hideNulls' option. boolean fieldBaseTypeIsPrimitive = BUILT_IN_TYPES.contains(new String(fieldType.getLastToken())); boolean fieldIsPrimitive = fieldType.dimensions() == 0 && fieldBaseTypeIsPrimitive; boolean fieldIsPrimitiveArray = fieldType.dimensions() == 1 && fieldBaseTypeIsPrimitive; boolean fieldIsObjectArray = fieldType.dimensions() > 0 && !fieldIsPrimitiveArray; @SuppressWarnings("unused") boolean fieldIsObject = !fieldIsPrimitive && !fieldIsPrimitiveArray && !fieldIsObjectArray; Expression ex; if (fieldIsPrimitiveArray || fieldIsObjectArray) { MessageSend arrayToString = new MessageSend(); arrayToString.sourceStart = pS; arrayToString.sourceEnd = pE; arrayToString.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); arrayToString.arguments = new Expression[] { fieldAccessor }; setGeneratedBy(arrayToString.arguments[0], source); arrayToString.selector = (fieldIsObjectArray ? "deepToString" : "toString").toCharArray(); ex = arrayToString; } else { ex = fieldAccessor; } setGeneratedBy(ex, source); if (first) { current = new BinaryExpression(current, ex, PLUS); current.sourceStart = pS; current.sourceEnd = pE; setGeneratedBy(current, source); first = false; continue; } StringLiteral fieldNameLiteral; if (includeFieldNames) { char[] namePlusEqualsSign = (infixS + field.getName() + "=").toCharArray(); fieldNameLiteral = new StringLiteral(namePlusEqualsSign, pS, pE, 0); } else { fieldNameLiteral = new StringLiteral(infix, pS, pE, 0); } setGeneratedBy(fieldNameLiteral, source); current = new BinaryExpression(current, fieldNameLiteral, PLUS); setGeneratedBy(current, source); current = new BinaryExpression(current, ex, PLUS); setGeneratedBy(current, source); } if (!first) { StringLiteral suffixLiteral = new StringLiteral(suffix, pS, pE, 0); setGeneratedBy(suffixLiteral, source); current = new BinaryExpression(current, suffixLiteral, PLUS); setGeneratedBy(current, source); } ReturnStatement returnStatement = new ReturnStatement(current, pS, pE); setGeneratedBy(returnStatement, source); MethodDeclaration method = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); setGeneratedBy(method, source); method.modifiers = toEclipseModifier(AccessLevel.PUBLIC); method.returnType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_STRING, new long[] {p, p, p}); setGeneratedBy(method.returnType, source); method.annotations = new Annotation[] {makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source)}; method.arguments = null; method.selector = "toString".toCharArray(); method.thrownExceptions = null; method.typeParameters = null; method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; method.statements = new Statement[] { returnStatement }; return method; } public static String getTypeName(EclipseNode type) { String typeName = getSingleTypeName(type); EclipseNode upType = type.up(); while (upType.getKind() == Kind.TYPE) { typeName = getSingleTypeName(upType) + "." + typeName; upType = upType.up(); } return typeName; } public static String getSingleTypeName(EclipseNode type) { TypeDeclaration typeDeclaration = (TypeDeclaration)type.get(); char[] rawTypeName = typeDeclaration.name; return rawTypeName == null ? "" : new String(rawTypeName); } private static final Set BUILT_IN_TYPES = Collections.unmodifiableSet(new HashSet(Arrays.asList( "byte", "short", "int", "long", "char", "boolean", "double", "float"))); public static NameReference generateQualifiedNameRef(ASTNode source, char[]... varNames) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; NameReference ref; if (varNames.length > 1) ref = new QualifiedNameReference(varNames, new long[varNames.length], pS, pE); else ref = new SingleNameReference(varNames[0], p); setGeneratedBy(ref, source); return ref; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleUtilityClass.java000066400000000000000000000220371312655740700260270ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.Arrays; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Clinit; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.ThrowStatement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.mangosdk.spi.ProviderFor; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.core.AST.Kind; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.experimental.UtilityClass; /** * Handles the {@code lombok.experimental.UtilityClass} annotation for eclipse. */ @HandlerPriority(-4096) //-2^12; to ensure @FieldDefaults picks up on the 'static' we set here. @ProviderFor(EclipseAnnotationHandler.class) public class HandleUtilityClass extends EclipseAnnotationHandler { @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.UTILITY_CLASS_FLAG_USAGE, "@UtilityClass"); EclipseNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode)) return; changeModifiersAndGenerateConstructor(annotationNode.up(), annotationNode); } private static boolean checkLegality(EclipseNode typeNode, EclipseNode errorNode) { TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; if (typeDecl == null || notAClass) { errorNode.addError("@UtilityClass is only supported on a class (can't be an interface, enum, or annotation)."); return false; } // It might be an inner class. This is okay, but only if it is / can be a static inner class. Thus, all of its parents have to be static inner classes until the top-level. EclipseNode typeWalk = typeNode; while (true) { typeWalk = typeWalk.up(); switch (typeWalk.getKind()) { case TYPE: if ((((TypeDeclaration) typeWalk.get()).modifiers & (ClassFileConstants.AccStatic | ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0) continue; if (typeWalk.up().getKind() == Kind.COMPILATION_UNIT) return true; errorNode.addError("@UtilityClass automatically makes the class static, however, this class cannot be made static."); return false; case COMPILATION_UNIT: return true; default: errorNode.addError("@UtilityClass cannot be placed on a method local or anonymous inner class, or any class nested in such a class."); return false; } } } private void changeModifiersAndGenerateConstructor(EclipseNode typeNode, EclipseNode annotationNode) { TypeDeclaration classDecl = (TypeDeclaration) typeNode.get(); boolean makeConstructor = true; classDecl.modifiers |= ClassFileConstants.AccFinal; boolean markStatic = true; boolean requiresClInit = false; boolean alreadyHasClinit = false; if (typeNode.up().getKind() == Kind.COMPILATION_UNIT) markStatic = false; if (markStatic && typeNode.up().getKind() == Kind.TYPE) { TypeDeclaration typeDecl = (TypeDeclaration) typeNode.up().get(); if ((typeDecl.modifiers & ClassFileConstants.AccInterface) != 0) markStatic = false; } if (markStatic) classDecl.modifiers |= ClassFileConstants.AccStatic; for (EclipseNode element : typeNode.down()) { if (element.getKind() == Kind.FIELD) { FieldDeclaration fieldDecl = (FieldDeclaration) element.get(); if ((fieldDecl.modifiers & ClassFileConstants.AccStatic) == 0) { requiresClInit = true; fieldDecl.modifiers |= ClassFileConstants.AccStatic; } } else if (element.getKind() == Kind.METHOD) { AbstractMethodDeclaration amd = (AbstractMethodDeclaration) element.get(); if (amd instanceof ConstructorDeclaration) { ConstructorDeclaration constrDecl = (ConstructorDeclaration) element.get(); if (getGeneratedBy(constrDecl) == null && (constrDecl.bits & ASTNode.IsDefaultConstructor) == 0) { element.addError("@UtilityClasses cannot have declared constructors."); makeConstructor = false; continue; } } else if (amd instanceof MethodDeclaration) { amd.modifiers |= ClassFileConstants.AccStatic; } else if (amd instanceof Clinit) { alreadyHasClinit = true; } } else if (element.getKind() == Kind.TYPE) { ((TypeDeclaration) element.get()).modifiers |= ClassFileConstants.AccStatic; } } if (makeConstructor) createPrivateDefaultConstructor(typeNode, annotationNode); if (requiresClInit && !alreadyHasClinit) classDecl.addClinit(); } private static final char[][] JAVA_LANG_UNSUPPORTED_OPERATION_EXCEPTION = new char[][] { TypeConstants.JAVA, TypeConstants.LANG, "UnsupportedOperationException".toCharArray() }; private static final char[] UNSUPPORTED_MESSAGE = "This is a utility class and cannot be instantiated".toCharArray(); private void createPrivateDefaultConstructor(EclipseNode typeNode, EclipseNode sourceNode) { ASTNode source = sourceNode.get(); TypeDeclaration typeDeclaration = ((TypeDeclaration) typeNode.get()); long p = (long) source.sourceStart << 32 | source.sourceEnd; ConstructorDeclaration constructor = new ConstructorDeclaration(((CompilationUnitDeclaration) typeNode.top().get()).compilationResult); constructor.modifiers = ClassFileConstants.AccPrivate; constructor.selector = typeDeclaration.name; constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); constructor.constructorCall.sourceStart = source.sourceStart; constructor.constructorCall.sourceEnd = source.sourceEnd; constructor.thrownExceptions = null; constructor.typeParameters = null; constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart; constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd; constructor.arguments = null; AllocationExpression exception = new AllocationExpression(); setGeneratedBy(exception, source); long[] ps = new long[JAVA_LANG_UNSUPPORTED_OPERATION_EXCEPTION.length]; Arrays.fill(ps, p); exception.type = new QualifiedTypeReference(JAVA_LANG_UNSUPPORTED_OPERATION_EXCEPTION, ps); setGeneratedBy(exception.type, source); exception.arguments = new Expression[] { new StringLiteral(UNSUPPORTED_MESSAGE, source.sourceStart, source.sourceEnd, 0) }; setGeneratedBy(exception.arguments[0], source); ThrowStatement throwStatement = new ThrowStatement(exception, source.sourceStart, source.sourceEnd); setGeneratedBy(throwStatement, source); constructor.statements = new Statement[] {throwStatement}; injectMethod(typeNode, constructor); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleVal.java000066400000000000000000000100141312655740700241100ustar00rootroot00000000000000/* * Copyright (C) 2010-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.handleFlagUsage; import static lombok.eclipse.handlers.EclipseHandlerUtil.typeMatches; import lombok.ConfigurationKeys; import lombok.val; import lombok.core.HandlerPriority; import lombok.eclipse.DeferUntilPostDiet; import lombok.eclipse.EclipseASTAdapter; import lombok.eclipse.EclipseASTVisitor; import lombok.eclipse.EclipseNode; import lombok.experimental.var; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.eclipse.jdt.internal.compiler.ast.ForStatement; import org.eclipse.jdt.internal.compiler.ast.ForeachStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.mangosdk.spi.ProviderFor; /* * This class just handles 3 basic error cases. The real meat of eclipse 'val' support is in {@code PatchVal} and {@code PatchValEclipse}. */ @ProviderFor(EclipseASTVisitor.class) @DeferUntilPostDiet @HandlerPriority(65536) // 2^16; resolution needs to work, so if the RHS expression is i.e. a call to a generated getter, we have to run after that getter has been generated. public class HandleVal extends EclipseASTAdapter { @Override public void visitLocal(EclipseNode localNode, LocalDeclaration local) { TypeReference type = local.type; boolean isVal = typeMatches(val.class, localNode, type); boolean isVar = typeMatches(var.class, localNode, type); if (!(isVal || isVar)) return; if (isVal) handleFlagUsage(localNode, ConfigurationKeys.VAL_FLAG_USAGE, "val"); if (isVar) handleFlagUsage(localNode, ConfigurationKeys.VAR_FLAG_USAGE, "var"); boolean variableOfForEach = false; if (localNode.directUp().get() instanceof ForeachStatement) { ForeachStatement fs = (ForeachStatement) localNode.directUp().get(); variableOfForEach = fs.elementVariable == local; } String annotation = isVal ? "val" : "var"; if (local.initialization == null && !variableOfForEach) { localNode.addError("'" + annotation + "' on a local variable requires an initializer expression"); return; } if (local.initialization instanceof ArrayInitializer) { localNode.addError("'" + annotation + "' is not compatible with array initializer expressions. Use the full form (new int[] { ... } instead of just { ... })"); return; } if (isVal && localNode.directUp().get() instanceof ForStatement) { localNode.addError("'val' is not allowed in old-style for loops"); return; } if (local.initialization != null && local.initialization.getClass().getName().equals("org.eclipse.jdt.internal.compiler.ast.LambdaExpression")) { localNode.addError("'" + annotation + "' is not allowed with lambda expressions."); return; } if(isVar && local.initialization instanceof NullLiteral) { localNode.addError("variable initializer is 'null'"); return; } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleValue.java000066400000000000000000000102151312655740700244450ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.Collections; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.HandleConstructor.SkipIfConstructorExists; import lombok.experimental.NonFinal; import lombok.Value; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.mangosdk.spi.ProviderFor; /** * Handles the {@code lombok.Value} annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) @HandlerPriority(-512) //-2^9; to ensure @EqualsAndHashCode and such pick up on this handler making the class final and messing with the fields' access levels, run earlier. public class HandleValue extends EclipseAnnotationHandler { public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.VALUE_FLAG_USAGE, "@Value"); Value ann = annotation.getInstance(); EclipseNode typeNode = annotationNode.up(); TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; if (typeDecl == null || notAClass) { annotationNode.addError("@Value is only supported on a class."); return; } // Make class final. if (!hasAnnotation(NonFinal.class, typeNode)) { if ((typeDecl.modifiers & ClassFileConstants.AccFinal) == 0) { typeDecl.modifiers |= ClassFileConstants.AccFinal; typeNode.rebuild(); } } new HandleFieldDefaults().generateFieldDefaultsForType(typeNode, annotationNode, AccessLevel.PRIVATE, true, true); //Careful: Generate the public static constructor (if there is one) LAST, so that any attempt to //'find callers' on the annotation node will find callers of the constructor, which is by far the //most useful of the many methods built by @Value. This trick won't work for the non-static constructor, //for whatever reason, though you can find callers of that one by focusing on the class name itself //and hitting 'find callers'. new HandleGetter().generateGetterForType(typeNode, annotationNode, AccessLevel.PUBLIC, true); new HandleEqualsAndHashCode().generateEqualsAndHashCodeForType(typeNode, annotationNode); new HandleToString().generateToStringForType(typeNode, annotationNode); new HandleConstructor().generateAllArgsConstructor(typeNode, AccessLevel.PUBLIC, ann.staticConstructor(), SkipIfConstructorExists.YES, Collections.emptyList(), annotationNode); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/HandleWither.java000066400000000000000000000307631312655740700246450ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; import lombok.experimental.Wither; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.mangosdk.spi.ProviderFor; @ProviderFor(EclipseAnnotationHandler.class) public class HandleWither extends EclipseAnnotationHandler { public boolean generateWitherForType(EclipseNode typeNode, EclipseNode pos, AccessLevel level, boolean checkForTypeLevelWither) { if (checkForTypeLevelWither) { if (hasAnnotation(Wither.class, typeNode)) { //The annotation will make it happen, so we can skip it. return true; } } TypeDeclaration typeDecl = null; if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; if (typeDecl == null || notAClass) { pos.addError("@Wither is only supported on a class or a field."); return false; } for (EclipseNode field : typeNode.down()) { if (field.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) field.get(); if (!filterField(fieldDecl)) continue; //Skip final fields. if ((fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0 && fieldDecl.initialization != null) continue; generateWitherForField(field, pos, level); } return true; } /** * Generates a wither on the stated field. * * Used by {@link HandleValue}. * * The difference between this call and the handle method is as follows: * * If there is a {@code lombok.experimental.Wither} annotation on the field, it is used and the * same rules apply (e.g. warning if the method already exists, stated access level applies). * If not, the wither is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. */ public void generateWitherForField(EclipseNode fieldNode, EclipseNode sourceNode, AccessLevel level) { for (EclipseNode child : fieldNode.down()) { if (child.getKind() == Kind.ANNOTATION) { if (annotationTypeMatches(Wither.class, child)) { //The annotation will make it happen, so we can skip it. return; } } } List empty = Collections.emptyList(); createWitherForField(level, fieldNode, sourceNode, false, empty, empty); } @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.WITHER_FLAG_USAGE, "@Wither"); EclipseNode node = annotationNode.up(); AccessLevel level = annotation.getInstance().value(); if (level == AccessLevel.NONE || node == null) return; List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Wither(onMethod", annotationNode); List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Wither(onParam", annotationNode); switch (node.getKind()) { case FIELD: createWitherForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, true, onMethod, onParam); break; case TYPE: if (!onMethod.isEmpty()) { annotationNode.addError("'onMethod' is not supported for @Wither on a type."); } if (!onParam.isEmpty()) { annotationNode.addError("'onParam' is not supported for @Wither on a type."); } generateWitherForType(node, annotationNode, level, false); break; } } public void createWitherForFields(AccessLevel level, Collection fieldNodes, EclipseNode sourceNode, boolean whineIfExists, List onMethod, List onParam) { for (EclipseNode fieldNode : fieldNodes) { createWitherForField(level, fieldNode, sourceNode, whineIfExists, onMethod, onParam); } } public void createWitherForField( AccessLevel level, EclipseNode fieldNode, EclipseNode sourceNode, boolean whineIfExists, List onMethod, List onParam) { ASTNode source = sourceNode.get(); if (fieldNode.getKind() != Kind.FIELD) { sourceNode.addError("@Wither is only supported on a class or a field."); return; } EclipseNode typeNode = fieldNode.up(); boolean makeAbstract = typeNode != null && typeNode.getKind() == Kind.TYPE && (((TypeDeclaration) typeNode.get()).modifiers & ClassFileConstants.AccAbstract) != 0; FieldDeclaration field = (FieldDeclaration) fieldNode.get(); TypeReference fieldType = copyType(field.type, source); boolean isBoolean = isBoolean(fieldType); String witherName = toWitherName(fieldNode, isBoolean); if (witherName == null) { fieldNode.addWarning("Not generating wither for this field: It does not fit your @Accessors prefix list."); return; } if ((field.modifiers & ClassFileConstants.AccStatic) != 0) { fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for static fields."); return; } if ((field.modifiers & ClassFileConstants.AccFinal) != 0 && field.initialization != null) { fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for final, initialized fields."); return; } if (field.name != null && field.name.length > 0 && field.name[0] == '$') { fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for fields starting with $."); return; } for (String altName : toAllWitherNames(fieldNode, isBoolean)) { switch (methodExists(altName, fieldNode, false, 1)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: if (whineIfExists) { String altNameExpl = ""; if (!altName.equals(witherName)) altNameExpl = String.format(" (%s)", altName); fieldNode.addWarning( String.format("Not generating %s(): A method with that name already exists%s", witherName, altNameExpl)); } return; default: case NOT_EXISTS: //continue scanning the other alt names. } } int modifier = toEclipseModifier(level); MethodDeclaration method = createWither((TypeDeclaration) fieldNode.up().get(), fieldNode, witherName, modifier, sourceNode, onMethod, onParam, makeAbstract); injectMethod(fieldNode.up(), method); } public MethodDeclaration createWither(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, EclipseNode sourceNode, List onMethod, List onParam, boolean makeAbstract ) { ASTNode source = sourceNode.get(); if (name == null) return null; FieldDeclaration field = (FieldDeclaration) fieldNode.get(); int pS = source.sourceStart, pE = source.sourceEnd; long p = (long) pS << 32 | pE; MethodDeclaration method = new MethodDeclaration(parent.compilationResult); if (makeAbstract) modifier = modifier | ClassFileConstants.AccAbstract | ExtraCompilerModifiers.AccSemicolonBody; method.modifiers = modifier; method.returnType = cloneSelfType(fieldNode, source); if (method.returnType == null) return null; Annotation[] deprecated = null; if (isFieldDeprecated(fieldNode)) { deprecated = new Annotation[] { generateDeprecatedAnnotation(source) }; } method.annotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), deprecated); Argument param = new Argument(field.name, p, copyType(field.type, source), ClassFileConstants.AccFinal); param.sourceStart = pS; param.sourceEnd = pE; method.arguments = new Argument[] { param }; method.selector = name.toCharArray(); method.binding = null; method.thrownExceptions = null; method.typeParameters = null; method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; Annotation[] nonNulls = findAnnotations(field, NON_NULL_PATTERN); Annotation[] nullables = findAnnotations(field, NULLABLE_PATTERN); if (!makeAbstract) { List args = new ArrayList(); for (EclipseNode child : fieldNode.up().down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration childDecl = (FieldDeclaration) child.get(); // Skip fields that start with $ if (childDecl.name != null && childDecl.name.length > 0 && childDecl.name[0] == '$') continue; long fieldFlags = childDecl.modifiers; // Skip static fields. if ((fieldFlags & ClassFileConstants.AccStatic) != 0) continue; // Skip initialized final fields. if (((fieldFlags & ClassFileConstants.AccFinal) != 0) && childDecl.initialization != null) continue; if (child.get() == fieldNode.get()) { args.add(new SingleNameReference(field.name, p)); } else { args.add(createFieldAccessor(child, FieldAccess.ALWAYS_FIELD, source)); } } AllocationExpression constructorCall = new AllocationExpression(); constructorCall.arguments = args.toArray(new Expression[0]); constructorCall.type = cloneSelfType(fieldNode, source); Expression identityCheck = new EqualExpression( createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source), new SingleNameReference(field.name, p), OperatorIds.EQUAL_EQUAL); ThisReference thisRef = new ThisReference(pS, pE); Expression conditional = new ConditionalExpression(identityCheck, thisRef, constructorCall); Statement returnStatement = new ReturnStatement(conditional, pS, pE); method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; List statements = new ArrayList(5); if (nonNulls.length > 0) { Statement nullCheck = generateNullCheck(field, sourceNode); if (nullCheck != null) statements.add(nullCheck); } statements.add(returnStatement); method.statements = statements.toArray(new Statement[0]); } param.annotations = copyAnnotations(source, nonNulls, nullables, onParam.toArray(new Annotation[0])); method.traverse(new SetGeneratedByVisitor(source), parent.scope); return method; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/SetGeneratedByVisitor.java000066400000000000000000001043121312655740700265040ustar00rootroot00000000000000/* * Copyright (C) 2011-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.Arrays; import org.eclipse.jdt.internal.compiler.ASTVisitor; import org.eclipse.jdt.internal.compiler.ast.AND_AND_Expression; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ArrayReference; import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference; import org.eclipse.jdt.internal.compiler.ast.AssertStatement; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.BinaryExpression; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.BreakStatement; import org.eclipse.jdt.internal.compiler.ast.CaseStatement; import org.eclipse.jdt.internal.compiler.ast.CastExpression; import org.eclipse.jdt.internal.compiler.ast.CharLiteral; import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.eclipse.jdt.internal.compiler.ast.Clinit; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.CompoundAssignment; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.ContinueStatement; import org.eclipse.jdt.internal.compiler.ast.DoStatement; import org.eclipse.jdt.internal.compiler.ast.DoubleLiteral; import org.eclipse.jdt.internal.compiler.ast.EmptyStatement; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral; import org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.FloatLiteral; import org.eclipse.jdt.internal.compiler.ast.ForStatement; import org.eclipse.jdt.internal.compiler.ast.ForeachStatement; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.ImportReference; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.InstanceOfExpression; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.Javadoc; import org.eclipse.jdt.internal.compiler.ast.JavadocAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.JavadocArgumentExpression; import org.eclipse.jdt.internal.compiler.ast.JavadocArrayQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.JavadocArraySingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.JavadocFieldReference; import org.eclipse.jdt.internal.compiler.ast.JavadocImplicitTypeReference; import org.eclipse.jdt.internal.compiler.ast.JavadocMessageSend; import org.eclipse.jdt.internal.compiler.ast.JavadocQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.JavadocReturnStatement; import org.eclipse.jdt.internal.compiler.ast.JavadocSingleNameReference; import org.eclipse.jdt.internal.compiler.ast.JavadocSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.LabeledStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.LongLiteral; import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; import org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OR_OR_Expression; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.PostfixExpression; import org.eclipse.jdt.internal.compiler.ast.PrefixExpression; import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedSuperReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedThisReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.StringLiteralConcatenation; import org.eclipse.jdt.internal.compiler.ast.SuperReference; import org.eclipse.jdt.internal.compiler.ast.SwitchStatement; import org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.ThrowStatement; import org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.eclipse.jdt.internal.compiler.ast.TryStatement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.UnaryExpression; import org.eclipse.jdt.internal.compiler.ast.WhileStatement; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.jdt.internal.compiler.lookup.MethodScope; public final class SetGeneratedByVisitor extends ASTVisitor { private static final long INT_TO_LONG_MASK = 0x00000000FFFFFFFFL; private final ASTNode source; private final int sourceStart; private final int sourceEnd; private final long sourcePos; public SetGeneratedByVisitor(ASTNode source) { this.source = source; this.sourceStart = this.source.sourceStart; this.sourceEnd = this.source.sourceEnd; this.sourcePos = (long)sourceStart << 32 | (sourceEnd & INT_TO_LONG_MASK); } private void fixPositions(JavadocAllocationExpression node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; node.memberStart = sourceStart; node.tagSourceEnd = sourceEnd; node.tagSourceStart = sourceStart; } private void fixPositions(JavadocMessageSend node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; node.nameSourcePosition = sourcePos; node.tagSourceEnd = sourceEnd; node.tagSourceStart = sourceStart; } private void fixPositions(JavadocSingleNameReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; node.tagSourceEnd = sourceEnd; node.tagSourceStart = sourceStart; } private void fixPositions(JavadocSingleTypeReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; node.tagSourceEnd = sourceEnd; node.tagSourceStart = sourceStart; } private void fixPositions(JavadocFieldReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; node.nameSourcePosition = sourcePos; node.tagSourceEnd = sourceEnd; node.tagSourceStart = sourceStart; } private void fixPositions(JavadocArrayQualifiedTypeReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; if (node.sourcePositions == null || node.sourcePositions.length != node.tokens.length) node.sourcePositions = new long[node.tokens.length]; Arrays.fill(node.sourcePositions, sourcePos); node.tagSourceEnd = sourceEnd; node.tagSourceStart = sourceStart; } private void fixPositions(JavadocQualifiedTypeReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; if (node.sourcePositions == null || node.sourcePositions.length != node.tokens.length) node.sourcePositions = new long[node.tokens.length]; Arrays.fill(node.sourcePositions, sourcePos); node.tagSourceEnd = sourceEnd; node.tagSourceStart = sourceStart; } private void fixPositions(Annotation node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; node.declarationSourceEnd = sourceEnd; } private void fixPositions(ArrayTypeReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; node.originalSourceEnd = sourceEnd; } private void fixPositions(AbstractMethodDeclaration node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.bodyEnd = sourceEnd; node.bodyStart = sourceStart; node.declarationSourceEnd = sourceEnd; node.declarationSourceStart = sourceStart; node.modifiersSourceStart = sourceStart; } private void fixPositions(Javadoc node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.valuePositions = sourceStart; } private void fixPositions(Initializer node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.declarationEnd = sourceEnd; node.declarationSourceEnd = sourceEnd; node.declarationSourceStart = sourceStart; node.modifiersSourceStart = sourceStart; node.endPart1Position = sourceEnd; node.endPart2Position = sourceEnd; node.bodyStart = sourceStart; node.bodyEnd = sourceEnd; } private void fixPositions(TypeDeclaration node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.bodyEnd = sourceEnd; node.bodyStart = sourceStart; node.declarationSourceEnd = sourceEnd; node.declarationSourceStart = sourceStart; node.modifiersSourceStart = sourceStart; } private void fixPositions(ImportReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.declarationEnd = sourceEnd; node.declarationSourceEnd = sourceEnd; node.declarationSourceStart = sourceStart; if (node.sourcePositions == null || node.sourcePositions.length != node.tokens.length) node.sourcePositions = new long[node.tokens.length]; Arrays.fill(node.sourcePositions, sourcePos); } private void fixPositions(ASTNode node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; } private void fixPositions(SwitchStatement node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.blockStart = sourceStart; } private void fixPositions(Expression node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; } private void fixPositions(AbstractVariableDeclaration node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.declarationEnd = sourceEnd; node.declarationSourceEnd = sourceEnd; node.declarationSourceStart = sourceStart; node.modifiersSourceStart = sourceStart; } private void fixPositions(FieldDeclaration node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.declarationEnd = sourceEnd; node.declarationSourceEnd = sourceEnd; node.declarationSourceStart = sourceStart; node.modifiersSourceStart = sourceStart; node.endPart1Position = sourceEnd; node.endPart2Position = sourceEnd; } private void fixPositions(FieldReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; node.nameSourcePosition = sourcePos; } private void fixPositions(MessageSend node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; node.nameSourcePosition = sourcePos; } private void fixPositions(QualifiedNameReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; if (node.sourcePositions == null || node.sourcePositions.length != node.tokens.length) node.sourcePositions = new long[node.tokens.length]; Arrays.fill(node.sourcePositions, sourcePos); } private void fixPositions(QualifiedTypeReference node) { node.sourceEnd = sourceEnd; node.sourceStart = sourceStart; node.statementEnd = sourceEnd; if (node.sourcePositions == null || node.sourcePositions.length != node.tokens.length) node.sourcePositions = new long[node.tokens.length]; Arrays.fill(node.sourcePositions, sourcePos); } @Override public boolean visit(AllocationExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(AND_AND_Expression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(AnnotationMethodDeclaration node, ClassScope classScope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, classScope); } @Override public boolean visit(Argument node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(Argument node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ArrayAllocationExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ArrayInitializer node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ArrayInitializer node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ArrayQualifiedTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ArrayQualifiedTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ArrayReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ArrayTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ArrayTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(AssertStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(Assignment node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(BinaryExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(Block node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(BreakStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(CaseStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(CastExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(CharLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ClassLiteralAccess node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(Clinit node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(CompilationUnitDeclaration node, CompilationUnitScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(CompoundAssignment node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ConditionalExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ConstructorDeclaration node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ContinueStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(DoStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(DoubleLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(EmptyStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(EqualExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ExplicitConstructorCall node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ExtendedStringLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(FalseLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(FieldDeclaration node, MethodScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(FieldReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(FieldReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(FloatLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ForeachStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ForStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(IfStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ImportReference node, CompilationUnitScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(Initializer node, MethodScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(InstanceOfExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(IntLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(Javadoc node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(Javadoc node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocAllocationExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocAllocationExpression node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocArgumentExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocArgumentExpression node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocArrayQualifiedTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocArrayQualifiedTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocArraySingleTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocArraySingleTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocFieldReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocFieldReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocImplicitTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocImplicitTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocMessageSend node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocMessageSend node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocQualifiedTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocQualifiedTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocReturnStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocReturnStatement node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocSingleNameReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocSingleNameReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocSingleTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(JavadocSingleTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(LabeledStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(LocalDeclaration node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(LongLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(MarkerAnnotation node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(MemberValuePair node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(MessageSend node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(MethodDeclaration node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(StringLiteralConcatenation node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(NormalAnnotation node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(NullLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(OR_OR_Expression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ParameterizedQualifiedTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ParameterizedQualifiedTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ParameterizedSingleTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ParameterizedSingleTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(PostfixExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(PrefixExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(QualifiedAllocationExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(QualifiedNameReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(QualifiedNameReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(QualifiedSuperReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(QualifiedSuperReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(QualifiedThisReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(QualifiedThisReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(QualifiedTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(QualifiedTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ReturnStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(SingleMemberAnnotation node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(SingleNameReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(SingleNameReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(SingleTypeReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(SingleTypeReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(StringLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(SuperReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(SwitchStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(SynchronizedStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ThisReference node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ThisReference node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(ThrowStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(TrueLiteral node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(TryStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(TypeDeclaration node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(TypeDeclaration node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(TypeDeclaration node, CompilationUnitScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(TypeParameter node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(TypeParameter node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(UnaryExpression node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(WhileStatement node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(Wildcard node, BlockScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } @Override public boolean visit(Wildcard node, ClassScope scope) { fixPositions(setGeneratedBy(node, source)); return super.visit(node, scope); } // missing methods // public boolean visit(MarkerAnnotation node, ClassScope scope){ return true;} // public boolean visit(MemberValuePair node, ClassScope scope){ return true;} // public boolean visit(NormalAnnotation node, ClassScope scope){ return true;} // public boolean visit(SingleMemberAnnotation node, ClassScope scope){ return true;} // missing methods from later versions // public boolean visit(UnionTypeReference node, BlockScope scope){ return true;} // public boolean visit(UnionTypeReference node, ClassScope scope){ return true;} // public boolean visit(LambdaExpression node, BlockScope scope){ return true;} // public boolean visit(ReferenceExpression node, BlockScope scope){ return true;} // public boolean visit(IntersectionCastTypeReference node, ClassScope scope){ return true;} // public boolean visit(IntersectionCastTypeReference node, BlockScope scope){ return true;} }lombok-1.16.18/src/core/lombok/eclipse/handlers/package-info.java000066400000000000000000000027021312655740700246030ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Contains the classes that implement the transformations for all of lombok's various features on the eclipse platform. * * NB: This package is not public API in the sense that contents of this package, * even public classes / methods / etc, may change in point releases. */ package lombok.eclipse.handlers; lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/000077500000000000000000000000001312655740700234225ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/EclipseGuavaMapSingularizer.java000066400000000000000000000043761312655740700317040ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers.singulars; import org.mangosdk.spi.ProviderFor; import lombok.core.LombokImmutableList; import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; @ProviderFor(EclipseSingularizer.class) public class EclipseGuavaMapSingularizer extends EclipseGuavaSingularizer { // TODO cgcc.ImmutableMultimap, cgcc.ImmutableListMultimap, cgcc.ImmutableSetMultimap // TODO cgcc.ImmutableClassToInstanceMap // TODO cgcc.ImmutableRangeMap private static final LombokImmutableList SUFFIXES = LombokImmutableList.of("key", "value"); private static final LombokImmutableList SUPPORTED_TYPES = LombokImmutableList.of( "com.google.common.collect.ImmutableMap", "com.google.common.collect.ImmutableBiMap", "com.google.common.collect.ImmutableSortedMap" ); @Override public LombokImmutableList getSupportedTypes() { return SUPPORTED_TYPES; } @Override protected LombokImmutableList getArgumentSuffixes() { return SUFFIXES; } @Override protected String getAddMethodName() { return "put"; } @Override protected String getAddAllTypeName() { return "java.util.Map"; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/EclipseGuavaSetListSingularizer.java000066400000000000000000000044511312655740700325500ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers.singulars; import org.mangosdk.spi.ProviderFor; import lombok.core.LombokImmutableList; import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; @ProviderFor(EclipseSingularizer.class) public class EclipseGuavaSetListSingularizer extends EclipseGuavaSingularizer { // TODO com.google.common.collect.ImmutableRangeSet // TODO com.google.common.collect.ImmutableMultiset and com.google.common.collect.ImmutableSortedMultiset private static final LombokImmutableList SUFFIXES = LombokImmutableList.of(""); private static final LombokImmutableList SUPPORTED_TYPES = LombokImmutableList.of( "com.google.common.collect.ImmutableCollection", "com.google.common.collect.ImmutableList", "com.google.common.collect.ImmutableSet", "com.google.common.collect.ImmutableSortedSet" ); @Override public LombokImmutableList getSupportedTypes() { return SUPPORTED_TYPES; } @Override protected LombokImmutableList getArgumentSuffixes() { return SUFFIXES; } @Override protected String getAddMethodName() { return "add"; } @Override protected String getAddAllTypeName() { return "java.lang.Iterable"; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/EclipseGuavaSingularizer.java000066400000000000000000000324111312655740700312350ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers.singulars; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import lombok.core.GuavaTypeMap; import lombok.core.LombokImmutableList; import lombok.core.handlers.HandlerUtil; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; import lombok.eclipse.handlers.EclipseSingularsRecipes.SingularData; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; abstract class EclipseGuavaSingularizer extends EclipseSingularizer { protected String getSimpleTargetTypeName(SingularData data) { return GuavaTypeMap.getGuavaTypeName(data.getTargetFqn()); } protected char[] getBuilderMethodName(SingularData data) { String simpleTypeName = getSimpleTargetTypeName(data); if ("ImmutableSortedSet".equals(simpleTypeName) || "ImmutableSortedMap".equals(simpleTypeName)) return "naturalOrder".toCharArray(); return "builder".toCharArray(); } protected char[][] makeGuavaTypeName(String simpleName, boolean addBuilder) { char[][] tokenizedName = new char[addBuilder ? 6 : 5][]; tokenizedName[0] = new char[] {'c', 'o', 'm'}; tokenizedName[1] = new char[] {'g', 'o', 'o', 'g', 'l', 'e'}; tokenizedName[2] = new char[] {'c', 'o', 'm', 'm', 'o', 'n'}; tokenizedName[3] = new char[] {'c', 'o', 'l', 'l', 'e', 'c', 't'}; tokenizedName[4] = simpleName.toCharArray(); if (addBuilder) tokenizedName[5] = new char[] { 'B', 'u', 'i', 'l', 'd', 'e', 'r'}; return tokenizedName; } @Override public List generateFields(SingularData data, EclipseNode builderType) { String simpleTypeName = getSimpleTargetTypeName(data); char[][] tokenizedName = makeGuavaTypeName(simpleTypeName, true); TypeReference type = new QualifiedTypeReference(tokenizedName, NULL_POSS); type = addTypeArgs(getTypeArgumentsCount(), false, builderType, type, data.getTypeArgs()); FieldDeclaration buildField = new FieldDeclaration(data.getPluralName(), 0, -1); buildField.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; buildField.modifiers = ClassFileConstants.AccPrivate; buildField.declarationSourceEnd = -1; buildField.type = type; data.setGeneratedByRecursive(buildField); return Collections.singletonList(injectFieldAndMarkGenerated(builderType, buildField)); } @Override public void generateMethods(SingularData data, boolean deprecate, EclipseNode builderType, boolean fluent, boolean chain) { TypeReference returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0); Statement returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null; generateSingularMethod(deprecate, returnType, returnStatement, data, builderType, fluent); returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0); returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null; generatePluralMethod(deprecate, returnType, returnStatement, data, builderType, fluent); returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0); returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null; generateClearMethod(deprecate, returnType, returnStatement, data, builderType); } void generateClearMethod(boolean deprecate, TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType) { MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); Assignment a = new Assignment(thisDotField, new NullLiteral(0, 0), 0); md.selector = HandlerUtil.buildAccessorName("clear", new String(data.getPluralName())).toCharArray(); md.statements = returnStatement != null ? new Statement[] {a, returnStatement} : new Statement[] {a}; md.returnType = returnType; md.annotations = deprecate ? new Annotation[] { generateDeprecatedAnnotation(data.getSource()) } : null; injectMethod(builderType, md); } void generateSingularMethod(boolean deprecate, TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) { LombokImmutableList suffixes = getArgumentSuffixes(); char[][] names = new char[suffixes.size()][]; for (int i = 0; i < suffixes.size(); i++) { String s = suffixes.get(i); char[] n = data.getSingularName(); names[i] = s.isEmpty() ? n : s.toCharArray(); } MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; List statements = new ArrayList(); statements.add(createConstructBuilderVarIfNeeded(data, builderType)); FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); MessageSend thisDotFieldDotAdd = new MessageSend(); thisDotFieldDotAdd.arguments = new Expression[suffixes.size()]; for (int i = 0; i < suffixes.size(); i++) { thisDotFieldDotAdd.arguments[i] = new SingleNameReference(names[i], 0L); } thisDotFieldDotAdd.receiver = thisDotField; thisDotFieldDotAdd.selector = getAddMethodName().toCharArray(); statements.add(thisDotFieldDotAdd); if (returnStatement != null) statements.add(returnStatement); md.statements = statements.toArray(new Statement[statements.size()]); md.arguments = new Argument[suffixes.size()]; for (int i = 0; i < suffixes.size(); i++) { TypeReference tr = cloneParamType(i, data.getTypeArgs(), builderType); md.arguments[i] = new Argument(names[i], 0, tr, 0); } md.returnType = returnType; md.selector = fluent ? data.getSingularName() : HandlerUtil.buildAccessorName(getAddMethodName(), new String(data.getSingularName())).toCharArray(); md.annotations = deprecate ? new Annotation[] { generateDeprecatedAnnotation(data.getSource()) } : null; data.setGeneratedByRecursive(md); injectMethod(builderType, md); } void generatePluralMethod(boolean deprecate, TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) { MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; List statements = new ArrayList(); statements.add(createConstructBuilderVarIfNeeded(data, builderType)); FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); MessageSend thisDotFieldDotAddAll = new MessageSend(); thisDotFieldDotAddAll.arguments = new Expression[] {new SingleNameReference(data.getPluralName(), 0L)}; thisDotFieldDotAddAll.receiver = thisDotField; thisDotFieldDotAddAll.selector = (getAddMethodName() + "All").toCharArray(); statements.add(thisDotFieldDotAddAll); if (returnStatement != null) statements.add(returnStatement); md.statements = statements.toArray(new Statement[statements.size()]); TypeReference paramType; paramType = new QualifiedTypeReference(fromQualifiedName(getAddAllTypeName()), NULL_POSS); paramType = addTypeArgs(getTypeArgumentsCount(), true, builderType, paramType, data.getTypeArgs()); Argument param = new Argument(data.getPluralName(), 0, paramType, 0); md.arguments = new Argument[] {param}; md.returnType = returnType; md.selector = fluent ? data.getPluralName() : HandlerUtil.buildAccessorName(getAddMethodName() + "All", new String(data.getPluralName())).toCharArray(); md.annotations = deprecate ? new Annotation[] { generateDeprecatedAnnotation(data.getSource()) } : null; data.setGeneratedByRecursive(md); injectMethod(builderType, md); } @Override public void appendBuildCode(SingularData data, EclipseNode builderType, List statements, char[] targetVariableName) { TypeReference varType = new QualifiedTypeReference(fromQualifiedName(data.getTargetFqn()), NULL_POSS); String simpleTypeName = getSimpleTargetTypeName(data); int agrumentsCount = getTypeArgumentsCount(); varType = addTypeArgs(agrumentsCount, false, builderType, varType, data.getTypeArgs()); MessageSend emptyInvoke; { //ImmutableX.of() emptyInvoke = new MessageSend(); emptyInvoke.selector = new char[] {'o', 'f'}; emptyInvoke.receiver = new QualifiedNameReference(makeGuavaTypeName(simpleTypeName, false), NULL_POSS, 0, 0); emptyInvoke.typeArguments = createTypeArgs(agrumentsCount, false, builderType, data.getTypeArgs()); } MessageSend invokeBuild; { //this.pluralName.build(); invokeBuild = new MessageSend(); invokeBuild.selector = new char[] {'b', 'u', 'i', 'l', 'd'}; FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); invokeBuild.receiver = thisDotField; } Expression isNull; { //this.pluralName == null FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); isNull = new EqualExpression(thisDotField, new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL); } Expression init = new ConditionalExpression(isNull, emptyInvoke, invokeBuild); LocalDeclaration varDefStat = new LocalDeclaration(data.getPluralName(), 0, 0); varDefStat.type = varType; varDefStat.initialization = init; statements.add(varDefStat); } protected Statement createConstructBuilderVarIfNeeded(SingularData data, EclipseNode builderType) { FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); FieldReference thisDotField2 = new FieldReference(data.getPluralName(), 0L); thisDotField2.receiver = new ThisReference(0, 0); Expression cond = new EqualExpression(thisDotField, new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL); MessageSend createBuilderInvoke = new MessageSend(); char[][] tokenizedName = makeGuavaTypeName(getSimpleTargetTypeName(data), false); createBuilderInvoke.receiver = new QualifiedNameReference(tokenizedName, NULL_POSS, 0, 0); createBuilderInvoke.selector = getBuilderMethodName(data); return new IfStatement(cond, new Assignment(thisDotField2, createBuilderInvoke, 0), 0, 0); } protected abstract LombokImmutableList getArgumentSuffixes(); protected abstract String getAddMethodName(); protected abstract String getAddAllTypeName(); protected int getTypeArgumentsCount() { return getArgumentSuffixes().size(); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/EclipseGuavaTableSingularizer.java000066400000000000000000000040341312655740700322050ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers.singulars; import org.mangosdk.spi.ProviderFor; import lombok.core.LombokImmutableList; import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; @ProviderFor(EclipseSingularizer.class) public class EclipseGuavaTableSingularizer extends EclipseGuavaSingularizer { private static final LombokImmutableList SUFFIXES = LombokImmutableList.of("rowKey", "columnKey", "value"); private static final LombokImmutableList SUPPORTED_TYPES = LombokImmutableList.of("com.google.common.collect.ImmutableTable"); @Override public LombokImmutableList getSupportedTypes() { return SUPPORTED_TYPES; } @Override protected LombokImmutableList getArgumentSuffixes() { return SUFFIXES; } @Override protected String getAddMethodName() { return "put"; } @Override protected String getAddAllTypeName() { return "com.google.common.collect.Table"; } } lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilListSetSingularizer.java000066400000000000000000000235431312655740700332270ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers.singulars; import static lombok.eclipse.Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import lombok.core.handlers.HandlerUtil; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseSingularsRecipes.SingularData; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; abstract class EclipseJavaUtilListSetSingularizer extends EclipseJavaUtilSingularizer { @Override public List listFieldsToBeGenerated(SingularData data, EclipseNode builderType) { if (useGuavaInstead(builderType)) { return guavaListSetSingularizer.listFieldsToBeGenerated(data, builderType); } return super.listFieldsToBeGenerated(data, builderType); } @Override public List listMethodsToBeGenerated(SingularData data, EclipseNode builderType) { if (useGuavaInstead(builderType)) { return guavaListSetSingularizer.listMethodsToBeGenerated(data, builderType); } return super.listMethodsToBeGenerated(data, builderType); } @Override public List generateFields(SingularData data, EclipseNode builderType) { if (useGuavaInstead(builderType)) { return guavaListSetSingularizer.generateFields(data, builderType); } TypeReference type = new QualifiedTypeReference(JAVA_UTIL_ARRAYLIST, NULL_POSS); type = addTypeArgs(1, false, builderType, type, data.getTypeArgs()); FieldDeclaration buildField = new FieldDeclaration(data.getPluralName(), 0, -1); buildField.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; buildField.modifiers = ClassFileConstants.AccPrivate; buildField.declarationSourceEnd = -1; buildField.type = type; data.setGeneratedByRecursive(buildField); return Collections.singletonList(injectFieldAndMarkGenerated(builderType, buildField)); } @Override public void generateMethods(SingularData data, boolean deprecate, EclipseNode builderType, boolean fluent, boolean chain) { if (useGuavaInstead(builderType)) { guavaListSetSingularizer.generateMethods(data, deprecate, builderType, fluent, chain); return; } TypeReference returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0); Statement returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null; generateSingularMethod(deprecate, returnType, returnStatement, data, builderType, fluent); returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0); returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null; generatePluralMethod(deprecate, returnType, returnStatement, data, builderType, fluent); returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0); returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null; generateClearMethod(deprecate, returnType, returnStatement, data, builderType); } private void generateClearMethod(boolean deprecate, TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType) { MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); FieldReference thisDotField2 = new FieldReference(data.getPluralName(), 0L); thisDotField2.receiver = new ThisReference(0, 0); md.selector = HandlerUtil.buildAccessorName("clear", new String(data.getPluralName())).toCharArray(); MessageSend clearMsg = new MessageSend(); clearMsg.receiver = thisDotField2; clearMsg.selector = "clear".toCharArray(); Statement clearStatement = new IfStatement(new EqualExpression(thisDotField, new NullLiteral(0, 0), OperatorIds.NOT_EQUAL), clearMsg, 0, 0); md.statements = returnStatement != null ? new Statement[] {clearStatement, returnStatement} : new Statement[] {clearStatement}; md.returnType = returnType; md.annotations = deprecate ? new Annotation[] { generateDeprecatedAnnotation(data.getSource()) } : null; injectMethod(builderType, md); } void generateSingularMethod(boolean deprecate, TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) { MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; List statements = new ArrayList(); statements.add(createConstructBuilderVarIfNeeded(data, builderType, false)); FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); MessageSend thisDotFieldDotAdd = new MessageSend(); thisDotFieldDotAdd.arguments = new Expression[] {new SingleNameReference(data.getSingularName(), 0L)}; thisDotFieldDotAdd.receiver = thisDotField; thisDotFieldDotAdd.selector = "add".toCharArray(); statements.add(thisDotFieldDotAdd); if (returnStatement != null) statements.add(returnStatement); md.statements = statements.toArray(new Statement[statements.size()]); TypeReference paramType = cloneParamType(0, data.getTypeArgs(), builderType); Argument param = new Argument(data.getSingularName(), 0, paramType, 0); md.arguments = new Argument[] {param}; md.returnType = returnType; md.selector = fluent ? data.getSingularName() : HandlerUtil.buildAccessorName("add", new String(data.getSingularName())).toCharArray(); md.annotations = deprecate ? new Annotation[] { generateDeprecatedAnnotation(data.getSource()) } : null; data.setGeneratedByRecursive(md); injectMethod(builderType, md); } void generatePluralMethod(boolean deprecate, TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) { MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; List statements = new ArrayList(); statements.add(createConstructBuilderVarIfNeeded(data, builderType, false)); FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); MessageSend thisDotFieldDotAddAll = new MessageSend(); thisDotFieldDotAddAll.arguments = new Expression[] {new SingleNameReference(data.getPluralName(), 0L)}; thisDotFieldDotAddAll.receiver = thisDotField; thisDotFieldDotAddAll.selector = "addAll".toCharArray(); statements.add(thisDotFieldDotAddAll); if (returnStatement != null) statements.add(returnStatement); md.statements = statements.toArray(new Statement[statements.size()]); TypeReference paramType = new QualifiedTypeReference(TypeConstants.JAVA_UTIL_COLLECTION, NULL_POSS); paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs()); Argument param = new Argument(data.getPluralName(), 0, paramType, 0); md.arguments = new Argument[] {param}; md.returnType = returnType; md.selector = fluent ? data.getPluralName() : HandlerUtil.buildAccessorName("addAll", new String(data.getPluralName())).toCharArray(); md.annotations = deprecate ? new Annotation[] { generateDeprecatedAnnotation(data.getSource()) } : null; data.setGeneratedByRecursive(md); injectMethod(builderType, md); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilListSingularizer.java000066400000000000000000000144561312655740700325560ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers.singulars; import static lombok.eclipse.handlers.EclipseHandlerUtil.makeIntLiteral; import java.util.ArrayList; import java.util.List; import lombok.core.LombokImmutableList; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; import lombok.eclipse.handlers.EclipseSingularsRecipes.SingularData; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.BreakStatement; import org.eclipse.jdt.internal.compiler.ast.CaseStatement; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.SwitchStatement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.mangosdk.spi.ProviderFor; @ProviderFor(EclipseSingularizer.class) public class EclipseJavaUtilListSingularizer extends EclipseJavaUtilListSetSingularizer { @Override public LombokImmutableList getSupportedTypes() { return LombokImmutableList.of("java.util.List", "java.util.Collection", "java.lang.Iterable"); } @Override public void appendBuildCode(SingularData data, EclipseNode builderType, List statements, char[] targetVariableName) { if (useGuavaInstead(builderType)) { guavaListSetSingularizer.appendBuildCode(data, builderType, statements, targetVariableName); return; } List switchContents = new ArrayList(); /* case 0: (empty) break; */ { switchContents.add(new CaseStatement(makeIntLiteral(new char[] {'0'}, null), 0, 0)); MessageSend invoke = new MessageSend(); invoke.receiver = new QualifiedNameReference(JAVA_UTIL_COLLECTIONS, NULL_POSS, 0, 0); invoke.selector = "emptyList".toCharArray(); switchContents.add(new Assignment(new SingleNameReference(data.getPluralName(), 0), invoke, 0)); switchContents.add(new BreakStatement(null, 0, 0)); } /* case 1: (singleton) break; */ { switchContents.add(new CaseStatement(makeIntLiteral(new char[] {'1'}, null), 0, 0)); FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); MessageSend thisDotFieldGet0 = new MessageSend(); thisDotFieldGet0.receiver = thisDotField; thisDotFieldGet0.selector = new char[] {'g', 'e', 't'}; thisDotFieldGet0.arguments = new Expression[] {makeIntLiteral(new char[] {'0'}, null)}; Expression[] args = new Expression[] {thisDotFieldGet0}; MessageSend invoke = new MessageSend(); invoke.receiver = new QualifiedNameReference(JAVA_UTIL_COLLECTIONS, NULL_POSS, 0, 0); invoke.selector = "singletonList".toCharArray(); invoke.arguments = args; switchContents.add(new Assignment(new SingleNameReference(data.getPluralName(), 0), invoke, 0)); switchContents.add(new BreakStatement(null, 0, 0)); } /* default: Create by passing builder field to constructor. */ { switchContents.add(new CaseStatement(null, 0, 0)); Expression argToUnmodifiable; /* new j.u.ArrayList(this.pluralName); */ { FieldReference thisDotPluralName = new FieldReference(data.getPluralName(), 0L); thisDotPluralName.receiver = new ThisReference(0, 0); TypeReference targetTypeExpr = new QualifiedTypeReference(JAVA_UTIL_ARRAYLIST, NULL_POSS); targetTypeExpr = addTypeArgs(1, false, builderType, targetTypeExpr, data.getTypeArgs()); AllocationExpression constructorCall = new AllocationExpression(); constructorCall.type = targetTypeExpr; constructorCall.arguments = new Expression[] {thisDotPluralName}; argToUnmodifiable = constructorCall; } /* pluralname = Collections.unmodifiableList(-newlist-); */ { MessageSend unmodInvoke = new MessageSend(); unmodInvoke.receiver = new QualifiedNameReference(JAVA_UTIL_COLLECTIONS, NULL_POSS, 0, 0); unmodInvoke.selector = "unmodifiableList".toCharArray(); unmodInvoke.arguments = new Expression[] {argToUnmodifiable}; switchContents.add(new Assignment(new SingleNameReference(data.getPluralName(), 0), unmodInvoke, 0)); } } SwitchStatement switchStat = new SwitchStatement(); switchStat.statements = switchContents.toArray(new Statement[switchContents.size()]); switchStat.expression = getSize(builderType, data.getPluralName(), true); TypeReference localShadowerType = new QualifiedTypeReference(Eclipse.fromQualifiedName(data.getTargetFqn()), NULL_POSS); localShadowerType = addTypeArgs(1, false, builderType, localShadowerType, data.getTypeArgs()); LocalDeclaration varDefStat = new LocalDeclaration(data.getPluralName(), 0, 0); varDefStat.type = localShadowerType; statements.add(varDefStat); statements.add(switchStat); } } lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilMapSingularizer.java000066400000000000000000000363651312655740700323630ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers.singulars; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.ForeachStatement; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.mangosdk.spi.ProviderFor; import lombok.core.LombokImmutableList; import lombok.core.handlers.HandlerUtil; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; import lombok.eclipse.handlers.EclipseSingularsRecipes.SingularData; @ProviderFor(EclipseSingularizer.class) public class EclipseJavaUtilMapSingularizer extends EclipseJavaUtilSingularizer { @Override public LombokImmutableList getSupportedTypes() { return LombokImmutableList.of("java.util.Map", "java.util.SortedMap", "java.util.NavigableMap"); } @Override public List listFieldsToBeGenerated(SingularData data, EclipseNode builderType) { if (useGuavaInstead(builderType)) { return guavaMapSingularizer.listFieldsToBeGenerated(data, builderType); } char[] p = data.getPluralName(); int len = p.length; char[] k = new char[len + 4]; char[] v = new char[len + 6]; System.arraycopy(p, 0, k, 0, len); System.arraycopy(p, 0, v, 0, len); k[len] = '$'; k[len + 1] = 'k'; k[len + 2] = 'e'; k[len + 3] = 'y'; v[len] = '$'; v[len + 1] = 'v'; v[len + 2] = 'a'; v[len + 3] = 'l'; v[len + 4] = 'u'; v[len + 5] = 'e'; return Arrays.asList(k, v); } @Override public List listMethodsToBeGenerated(SingularData data, EclipseNode builderType) { if (useGuavaInstead(builderType)) { return guavaMapSingularizer.listFieldsToBeGenerated(data, builderType); } else { return super.listMethodsToBeGenerated(data, builderType); } } @Override public List generateFields(SingularData data, EclipseNode builderType) { if (useGuavaInstead(builderType)) { return guavaMapSingularizer.generateFields(data, builderType); } char[] keyName = (new String(data.getPluralName()) + "$key").toCharArray(); char[] valueName = (new String(data.getPluralName()) + "$value").toCharArray(); FieldDeclaration buildKeyField; { TypeReference type = new QualifiedTypeReference(JAVA_UTIL_ARRAYLIST, NULL_POSS); type = addTypeArgs(1, false, builderType, type, data.getTypeArgs()); buildKeyField = new FieldDeclaration(keyName, 0, -1); buildKeyField.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; buildKeyField.modifiers = ClassFileConstants.AccPrivate; buildKeyField.declarationSourceEnd = -1; buildKeyField.type = type; } FieldDeclaration buildValueField; { TypeReference type = new QualifiedTypeReference(JAVA_UTIL_ARRAYLIST, NULL_POSS); List tArgs = data.getTypeArgs(); if (tArgs != null && tArgs.size() > 1) tArgs = Collections.singletonList(tArgs.get(1)); else tArgs = Collections.emptyList(); type = addTypeArgs(1, false, builderType, type, tArgs); buildValueField = new FieldDeclaration(valueName, 0, -1); buildValueField.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; buildValueField.modifiers = ClassFileConstants.AccPrivate; buildValueField.declarationSourceEnd = -1; buildValueField.type = type; } data.setGeneratedByRecursive(buildKeyField); data.setGeneratedByRecursive(buildValueField); EclipseNode keyFieldNode = injectFieldAndMarkGenerated(builderType, buildKeyField); EclipseNode valueFieldNode = injectFieldAndMarkGenerated(builderType, buildValueField); return Arrays.asList(keyFieldNode, valueFieldNode); } @Override public void generateMethods(SingularData data, boolean deprecate, EclipseNode builderType, boolean fluent, boolean chain) { if (useGuavaInstead(builderType)) { guavaMapSingularizer.generateMethods(data, deprecate, builderType, fluent, chain); return; } TypeReference returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0); Statement returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null; generateSingularMethod(deprecate, returnType, returnStatement, data, builderType, fluent); returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0); returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null; generatePluralMethod(deprecate, returnType, returnStatement, data, builderType, fluent); returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0); returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null; generateClearMethod(deprecate, returnType, returnStatement, data, builderType); } private void generateClearMethod(boolean deprecate, TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType) { MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; String pN = new String(data.getPluralName()); char[] keyFieldName = (pN + "$key").toCharArray(); char[] valueFieldName = (pN + "$value").toCharArray(); FieldReference thisDotField = new FieldReference(keyFieldName, 0L); thisDotField.receiver = new ThisReference(0, 0); FieldReference thisDotField2 = new FieldReference(keyFieldName, 0L); thisDotField2.receiver = new ThisReference(0, 0); FieldReference thisDotField3 = new FieldReference(valueFieldName, 0L); thisDotField3.receiver = new ThisReference(0, 0); md.selector = HandlerUtil.buildAccessorName("clear", new String(data.getPluralName())).toCharArray(); MessageSend clearMsg1 = new MessageSend(); clearMsg1.receiver = thisDotField2; clearMsg1.selector = "clear".toCharArray(); MessageSend clearMsg2 = new MessageSend(); clearMsg2.receiver = thisDotField3; clearMsg2.selector = "clear".toCharArray(); Block clearMsgs = new Block(2); clearMsgs.statements = new Statement[] {clearMsg1, clearMsg2}; Statement clearStatement = new IfStatement(new EqualExpression(thisDotField, new NullLiteral(0, 0), OperatorIds.NOT_EQUAL), clearMsgs, 0, 0); md.statements = returnStatement != null ? new Statement[] {clearStatement, returnStatement} : new Statement[] {clearStatement}; md.returnType = returnType; md.annotations = deprecate ? new Annotation[] { generateDeprecatedAnnotation(data.getSource()) } : null; injectMethod(builderType, md); } private void generateSingularMethod(boolean deprecate, TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) { MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; List statements = new ArrayList(); statements.add(createConstructBuilderVarIfNeeded(data, builderType, true)); String sN = new String(data.getSingularName()); String pN = new String(data.getPluralName()); char[] keyParamName = (sN + "Key").toCharArray(); char[] valueParamName = (sN + "Value").toCharArray(); char[] keyFieldName = (pN + "$key").toCharArray(); char[] valueFieldName = (pN + "$value").toCharArray(); /* this.pluralname$key.add(singularnameKey); */ { FieldReference thisDotKeyField = new FieldReference(keyFieldName, 0L); thisDotKeyField.receiver = new ThisReference(0, 0); MessageSend thisDotKeyFieldDotAdd = new MessageSend(); thisDotKeyFieldDotAdd.arguments = new Expression[] {new SingleNameReference(keyParamName, 0L)}; thisDotKeyFieldDotAdd.receiver = thisDotKeyField; thisDotKeyFieldDotAdd.selector = "add".toCharArray(); statements.add(thisDotKeyFieldDotAdd); } /* this.pluralname$value.add(singularnameValue); */ { FieldReference thisDotValueField = new FieldReference(valueFieldName, 0L); thisDotValueField.receiver = new ThisReference(0, 0); MessageSend thisDotValueFieldDotAdd = new MessageSend(); thisDotValueFieldDotAdd.arguments = new Expression[] {new SingleNameReference(valueParamName, 0L)}; thisDotValueFieldDotAdd.receiver = thisDotValueField; thisDotValueFieldDotAdd.selector = "add".toCharArray(); statements.add(thisDotValueFieldDotAdd); } if (returnStatement != null) statements.add(returnStatement); md.statements = statements.toArray(new Statement[statements.size()]); TypeReference keyParamType = cloneParamType(0, data.getTypeArgs(), builderType); Argument keyParam = new Argument(keyParamName, 0, keyParamType, 0); TypeReference valueParamType = cloneParamType(1, data.getTypeArgs(), builderType); Argument valueParam = new Argument(valueParamName, 0, valueParamType, 0); md.arguments = new Argument[] {keyParam, valueParam}; md.returnType = returnType; md.selector = fluent ? data.getSingularName() : HandlerUtil.buildAccessorName("put", new String(data.getSingularName())).toCharArray(); md.annotations = deprecate ? new Annotation[] { generateDeprecatedAnnotation(data.getSource()) } : null; data.setGeneratedByRecursive(md); injectMethod(builderType, md); } private void generatePluralMethod(boolean deprecate, TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) { MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; String pN = new String(data.getPluralName()); char[] keyFieldName = (pN + "$key").toCharArray(); char[] valueFieldName = (pN + "$value").toCharArray(); List statements = new ArrayList(); statements.add(createConstructBuilderVarIfNeeded(data, builderType, true)); char[] entryName = "$lombokEntry".toCharArray(); TypeReference forEachType = new QualifiedTypeReference(JAVA_UTIL_MAP_ENTRY, NULL_POSS); forEachType = addTypeArgs(2, true, builderType, forEachType, data.getTypeArgs()); MessageSend keyArg = new MessageSend(); keyArg.receiver = new SingleNameReference(entryName, 0L); keyArg.selector = "getKey".toCharArray(); MessageSend addKey = new MessageSend(); FieldReference thisDotKeyField = new FieldReference(keyFieldName, 0L); thisDotKeyField.receiver = new ThisReference(0, 0); addKey.receiver = thisDotKeyField; addKey.selector = new char[] {'a', 'd', 'd'}; addKey.arguments = new Expression[] {keyArg}; MessageSend valueArg = new MessageSend(); valueArg.receiver = new SingleNameReference(entryName, 0L); valueArg.selector = "getValue".toCharArray(); MessageSend addValue = new MessageSend(); FieldReference thisDotValueField = new FieldReference(valueFieldName, 0L); thisDotValueField.receiver = new ThisReference(0, 0); addValue.receiver = thisDotValueField; addValue.selector = new char[] {'a', 'd', 'd'}; addValue.arguments = new Expression[] {valueArg}; LocalDeclaration elementVariable = new LocalDeclaration(entryName, 0, 0); elementVariable.type = forEachType; ForeachStatement forEach = new ForeachStatement(elementVariable, 0); MessageSend invokeEntrySet = new MessageSend(); invokeEntrySet.selector = new char[] { 'e', 'n', 't', 'r', 'y', 'S', 'e', 't'}; invokeEntrySet.receiver = new SingleNameReference(data.getPluralName(), 0L); forEach.collection = invokeEntrySet; Block forEachContent = new Block(0); forEachContent.statements = new Statement[] {addKey, addValue}; forEach.action = forEachContent; statements.add(forEach); if (returnStatement != null) statements.add(returnStatement); md.statements = statements.toArray(new Statement[statements.size()]); TypeReference paramType = new QualifiedTypeReference(JAVA_UTIL_MAP, NULL_POSS); paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs()); Argument param = new Argument(data.getPluralName(), 0, paramType, 0); md.arguments = new Argument[] {param}; md.returnType = returnType; md.selector = fluent ? data.getPluralName() : HandlerUtil.buildAccessorName("putAll", new String(data.getPluralName())).toCharArray(); md.annotations = deprecate ? new Annotation[] { generateDeprecatedAnnotation(data.getSource()) } : null; data.setGeneratedByRecursive(md); injectMethod(builderType, md); } @Override public void appendBuildCode(SingularData data, EclipseNode builderType, List statements, char[] targetVariableName) { if (useGuavaInstead(builderType)) { guavaMapSingularizer.appendBuildCode(data, builderType, statements, targetVariableName); return; } if (data.getTargetFqn().equals("java.util.Map")) { statements.addAll(createJavaUtilSetMapInitialCapacitySwitchStatements(data, builderType, true, "emptyMap", "singletonMap", "LinkedHashMap")); } else { statements.addAll(createJavaUtilSimpleCreationAndFillStatements(data, builderType, true, true, false, true, "TreeMap")); } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilSetSingularizer.java000066400000000000000000000046241312655740700323720ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers.singulars; import java.util.List; import lombok.core.LombokImmutableList; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; import lombok.eclipse.handlers.EclipseSingularsRecipes.SingularData; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.mangosdk.spi.ProviderFor; @ProviderFor(EclipseSingularizer.class) public class EclipseJavaUtilSetSingularizer extends EclipseJavaUtilListSetSingularizer { @Override public LombokImmutableList getSupportedTypes() { return LombokImmutableList.of("java.util.Set", "java.util.SortedSet", "java.util.NavigableSet"); } @Override public void appendBuildCode(SingularData data, EclipseNode builderType, List statements, char[] targetVariableName) { if (useGuavaInstead(builderType)) { guavaListSetSingularizer.appendBuildCode(data, builderType, statements, targetVariableName); return; } if (data.getTargetFqn().equals("java.util.Set")) { statements.addAll(createJavaUtilSetMapInitialCapacitySwitchStatements(data, builderType, false, "emptySet", "singleton", "LinkedHashSet")); } else { statements.addAll(createJavaUtilSimpleCreationAndFillStatements(data, builderType, false, true, false, true, "TreeSet")); } } } lombok-1.16.18/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilSingularizer.java000066400000000000000000000370601312655740700317160ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.handlers.singulars; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.BinaryExpression; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.BreakStatement; import org.eclipse.jdt.internal.compiler.ast.CaseStatement; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.ForStatement; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.PostfixExpression; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.SwitchStatement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import lombok.ConfigurationKeys; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; import lombok.eclipse.handlers.EclipseSingularsRecipes.SingularData; abstract class EclipseJavaUtilSingularizer extends EclipseSingularizer { protected static final char[][] JAVA_UTIL_ARRAYLIST = { {'j', 'a', 'v', 'a'}, {'u', 't', 'i', 'l'}, {'A', 'r', 'r', 'a', 'y', 'L', 'i', 's', 't'} }; protected static final char[][] JAVA_UTIL_LIST = { {'j', 'a', 'v', 'a'}, {'u', 't', 'i', 'l'}, {'L', 'i', 's', 't'} }; protected static final char[][] JAVA_UTIL_MAP = { {'j', 'a', 'v', 'a'}, {'u', 't', 'i', 'l'}, {'M', 'a', 'p'} }; protected static final char[][] JAVA_UTIL_MAP_ENTRY = { {'j', 'a', 'v', 'a'}, {'u', 't', 'i', 'l'}, {'M', 'a', 'p'}, {'E', 'n', 't', 'r', 'y'} }; protected static final char[][] JAVA_UTIL_COLLECTIONS = { {'j', 'a', 'v', 'a'}, {'u', 't', 'i', 'l'}, {'C', 'o', 'l', 'l', 'e', 'c', 't', 'i', 'o', 'n', 's'} }; protected final EclipseSingularizer guavaListSetSingularizer = new EclipseGuavaSetListSingularizer(); protected final EclipseSingularizer guavaMapSingularizer = new EclipseGuavaMapSingularizer(); protected boolean useGuavaInstead(EclipseNode node) { return Boolean.TRUE.equals(node.getAst().readConfiguration(ConfigurationKeys.SINGULAR_USE_GUAVA)); } protected List createJavaUtilSetMapInitialCapacitySwitchStatements(SingularData data, EclipseNode builderType, boolean mapMode, String emptyCollectionMethod, String singletonCollectionMethod, String targetType) { List switchContents = new ArrayList(); char[] keyName = mapMode ? (new String(data.getPluralName()) + "$key").toCharArray() : data.getPluralName(); if (emptyCollectionMethod != null) { // case 0: (empty); break; switchContents.add(new CaseStatement(makeIntLiteral(new char[] {'0'}, null), 0, 0)); /* pluralName = java.util.Collections.emptyCollectionMethod(); */ { MessageSend invoke = new MessageSend(); invoke.receiver = new QualifiedNameReference(JAVA_UTIL_COLLECTIONS, NULL_POSS, 0, 0); invoke.selector = emptyCollectionMethod.toCharArray(); switchContents.add(new Assignment(new SingleNameReference(data.getPluralName(), 0), invoke, 0)); } switchContents.add(new BreakStatement(null, 0, 0)); } if (singletonCollectionMethod != null) { // case 1: (singleton); break; switchContents.add(new CaseStatement(makeIntLiteral(new char[] {'1'}, null), 0, 0)); /* !mapMode: pluralName = java.util.Collections.singletonCollectionMethod(this.pluralName.get(0)); mapMode: pluralName = java.util.Collections.singletonCollectionMethod(this.pluralName$key.get(0), this.pluralName$value.get(0)); */ { FieldReference thisDotKey = new FieldReference(keyName, 0L); thisDotKey.receiver = new ThisReference(0, 0); MessageSend thisDotKeyGet0 = new MessageSend(); thisDotKeyGet0.receiver = thisDotKey; thisDotKeyGet0.selector = new char[] {'g', 'e', 't'}; thisDotKeyGet0.arguments = new Expression[] {makeIntLiteral(new char[] {'0'}, null)}; Expression[] args; if (mapMode) { char[] valueName = (new String(data.getPluralName()) + "$value").toCharArray(); FieldReference thisDotValue = new FieldReference(valueName, 0L); thisDotValue.receiver = new ThisReference(0, 0); MessageSend thisDotValueGet0 = new MessageSend(); thisDotValueGet0.receiver = thisDotValue; thisDotValueGet0.selector = new char[] {'g', 'e', 't'}; thisDotValueGet0.arguments = new Expression[] {makeIntLiteral(new char[] {'0'}, null)}; args = new Expression[] {thisDotKeyGet0, thisDotValueGet0}; } else { args = new Expression[] {thisDotKeyGet0}; } MessageSend invoke = new MessageSend(); invoke.receiver = new QualifiedNameReference(JAVA_UTIL_COLLECTIONS, NULL_POSS, 0, 0); invoke.selector = singletonCollectionMethod.toCharArray(); invoke.arguments = args; switchContents.add(new Assignment(new SingleNameReference(data.getPluralName(), 0), invoke, 0)); } switchContents.add(new BreakStatement(null, 0, 0)); } { // default: switchContents.add(new CaseStatement(null, 0, 0)); switchContents.addAll(createJavaUtilSimpleCreationAndFillStatements(data, builderType, mapMode, false, true, emptyCollectionMethod == null, targetType)); } SwitchStatement switchStat = new SwitchStatement(); switchStat.statements = switchContents.toArray(new Statement[switchContents.size()]); switchStat.expression = getSize(builderType, keyName, true); TypeReference localShadowerType = new QualifiedTypeReference(fromQualifiedName(data.getTargetFqn()), NULL_POSS); localShadowerType = addTypeArgs(mapMode ? 2 : 1, false, builderType, localShadowerType, data.getTypeArgs()); LocalDeclaration varDefStat = new LocalDeclaration(data.getPluralName(), 0, 0); varDefStat.type = localShadowerType; return Arrays.asList(varDefStat, switchStat); } protected List createJavaUtilSimpleCreationAndFillStatements(SingularData data, EclipseNode builderType, boolean mapMode, boolean defineVar, boolean addInitialCapacityArg, boolean nullGuard, String targetType) { char[] varName = mapMode ? (new String(data.getPluralName()) + "$key").toCharArray() : data.getPluralName(); Statement createStat; { // pluralName = new java.util.TargetType(initialCap); Expression[] constructorArgs = null; if (addInitialCapacityArg) { // this.varName.size() < MAX_POWER_OF_2 ? 1 + this.varName.size() + (this.varName.size() - 3) / 3 : Integer.MAX_VALUE; // lessThanCutOff = this.varName.size() < MAX_POWER_OF_2 Expression lessThanCutoff = new BinaryExpression(getSize(builderType, varName, nullGuard), makeIntLiteral("0x40000000".toCharArray(), null), OperatorIds.LESS); FieldReference integerMaxValue = new FieldReference("MAX_VALUE".toCharArray(), 0L); integerMaxValue.receiver = new QualifiedNameReference(TypeConstants.JAVA_LANG_INTEGER, NULL_POSS, 0, 0); Expression sizeFormulaLeft = new BinaryExpression(makeIntLiteral(new char[] {'1'}, null), getSize(builderType, varName, nullGuard), OperatorIds.PLUS); Expression sizeFormulaRightLeft = new BinaryExpression(getSize(builderType, varName, nullGuard), makeIntLiteral(new char[] {'3'}, null), OperatorIds.MINUS); Expression sizeFormulaRight = new BinaryExpression(sizeFormulaRightLeft, makeIntLiteral(new char[] {'3'}, null), OperatorIds.DIVIDE); Expression sizeFormula = new BinaryExpression(sizeFormulaLeft, sizeFormulaRight, OperatorIds.PLUS); Expression cond = new ConditionalExpression(lessThanCutoff, sizeFormula, integerMaxValue); constructorArgs = new Expression[] {cond}; } TypeReference targetTypeRef = new QualifiedTypeReference(new char[][] {TypeConstants.JAVA, TypeConstants.UTIL, targetType.toCharArray()}, NULL_POSS); targetTypeRef = addTypeArgs(mapMode ? 2 : 1, false, builderType, targetTypeRef, data.getTypeArgs()); AllocationExpression constructorCall = new AllocationExpression(); constructorCall.type = targetTypeRef; constructorCall.arguments = constructorArgs; if (defineVar) { TypeReference localShadowerType = new QualifiedTypeReference(fromQualifiedName(data.getTargetFqn()), NULL_POSS); localShadowerType = addTypeArgs(mapMode ? 2 : 1, false, builderType, localShadowerType, data.getTypeArgs()); LocalDeclaration localShadowerDecl = new LocalDeclaration(data.getPluralName(), 0, 0); localShadowerDecl.type = localShadowerType; localShadowerDecl.initialization = constructorCall; createStat = localShadowerDecl; } else { createStat = new Assignment(new SingleNameReference(data.getPluralName(), 0L), constructorCall, 0); } } Statement fillStat; { if (mapMode) { // for (int $i = 0; $i < this.pluralname$key.size(); i++) pluralname.put(this.pluralname$key.get($i), this.pluralname$value.get($i)); char[] iVar = new char[] {'$', 'i'}; MessageSend pluralnameDotPut = new MessageSend(); pluralnameDotPut.selector = new char[] {'p', 'u', 't'}; pluralnameDotPut.receiver = new SingleNameReference(data.getPluralName(), 0L); FieldReference thisDotKey = new FieldReference(varName, 0L); thisDotKey.receiver = new ThisReference(0, 0); FieldReference thisDotValue = new FieldReference((new String(data.getPluralName()) + "$value").toCharArray(), 0L); thisDotValue.receiver = new ThisReference(0, 0); MessageSend keyArg = new MessageSend(); keyArg.receiver = thisDotKey; keyArg.arguments = new Expression[] {new SingleNameReference(iVar, 0L)}; keyArg.selector = new char[] {'g', 'e', 't'}; MessageSend valueArg = new MessageSend(); valueArg.receiver = thisDotValue; valueArg.arguments = new Expression[] {new SingleNameReference(iVar, 0L)}; valueArg.selector = new char[] {'g', 'e', 't'}; pluralnameDotPut.arguments = new Expression[] {keyArg, valueArg}; LocalDeclaration forInit = new LocalDeclaration(iVar, 0, 0); forInit.type = TypeReference.baseTypeReference(TypeIds.T_int, 0); forInit.initialization = makeIntLiteral(new char[] {'0'}, null); Expression checkExpr = new BinaryExpression(new SingleNameReference(iVar, 0L), getSize(builderType, varName, nullGuard), OperatorIds.LESS); Expression incrementExpr = new PostfixExpression(new SingleNameReference(iVar, 0L), IntLiteral.One, OperatorIds.PLUS, 0); fillStat = new ForStatement(new Statement[] {forInit}, checkExpr, new Statement[] {incrementExpr}, pluralnameDotPut, true, 0, 0); } else { // pluralname.addAll(this.pluralname); MessageSend pluralnameDotAddAll = new MessageSend(); pluralnameDotAddAll.selector = new char[] {'a', 'd', 'd', 'A', 'l', 'l'}; pluralnameDotAddAll.receiver = new SingleNameReference(data.getPluralName(), 0L); FieldReference thisDotPluralname = new FieldReference(varName, 0L); thisDotPluralname.receiver = new ThisReference(0, 0); pluralnameDotAddAll.arguments = new Expression[] {thisDotPluralname}; fillStat = pluralnameDotAddAll; } if (nullGuard) { FieldReference thisDotField = new FieldReference(varName, 0L); thisDotField.receiver = new ThisReference(0, 0); Expression cond = new EqualExpression(thisDotField, new NullLiteral(0, 0), OperatorIds.NOT_EQUAL); fillStat = new IfStatement(cond, fillStat, 0, 0); } } Statement unmodifiableStat; { // pluralname = Collections.unmodifiableInterfaceType(pluralname); Expression arg = new SingleNameReference(data.getPluralName(), 0L); MessageSend invoke = new MessageSend(); invoke.arguments = new Expression[] {arg}; invoke.selector = ("unmodifiable" + data.getTargetSimpleType()).toCharArray(); invoke.receiver = new QualifiedNameReference(JAVA_UTIL_COLLECTIONS, NULL_POSS, 0, 0); unmodifiableStat = new Assignment(new SingleNameReference(data.getPluralName(), 0L), invoke, 0); } return Arrays.asList(createStat, fillStat, unmodifiableStat); } protected Statement createConstructBuilderVarIfNeeded(SingularData data, EclipseNode builderType, boolean mapMode) { char[] v1Name, v2Name; if (mapMode) { String n = new String(data.getPluralName()); v1Name = (n + "$key").toCharArray(); v2Name = (n + "$value").toCharArray(); } else { v1Name = data.getPluralName(); v2Name = null; } FieldReference thisDotField = new FieldReference(v1Name, 0L); thisDotField.receiver = new ThisReference(0, 0); Expression cond = new EqualExpression(thisDotField, new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL); thisDotField = new FieldReference(v1Name, 0L); thisDotField.receiver = new ThisReference(0, 0); TypeReference v1Type = new QualifiedTypeReference(JAVA_UTIL_ARRAYLIST, NULL_POSS); v1Type = addTypeArgs(1, false, builderType, v1Type, data.getTypeArgs()); AllocationExpression constructArrayList = new AllocationExpression(); constructArrayList.type = v1Type; Assignment initV1 = new Assignment(thisDotField, constructArrayList, 0); Statement thenPart; if (mapMode) { thisDotField = new FieldReference(v2Name, 0L); thisDotField.receiver = new ThisReference(0, 0); TypeReference v2Type = new QualifiedTypeReference(JAVA_UTIL_ARRAYLIST, NULL_POSS); List tArgs = data.getTypeArgs(); if (tArgs != null && tArgs.size() > 1) tArgs = Collections.singletonList(tArgs.get(1)); else tArgs = Collections.emptyList(); v2Type = addTypeArgs(1, false, builderType, v2Type, tArgs); constructArrayList = new AllocationExpression(); constructArrayList.type = v2Type; Assignment initV2 = new Assignment(thisDotField, constructArrayList, 0); Block b = new Block(0); b.statements = new Statement[] {initV1, initV2}; thenPart = b; } else { thenPart = initV1; } return new IfStatement(cond, thenPart, 0, 0); } } lombok-1.16.18/src/core/lombok/eclipse/package-info.java000066400000000000000000000026561312655740700230130ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Includes the eclipse-specific implementations of the lombok AST and annotation introspection support. * * NB: This package is not public API in the sense that contents of this package, * even public classes / methods / etc, may change in point releases. */ package lombok.eclipse; lombok-1.16.18/src/core/lombok/experimental/000077500000000000000000000000001312655740700206645ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/experimental/Accessors.java000066400000000000000000000061241312655740700234570ustar00rootroot00000000000000/* * Copyright (C) 2012-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A container for settings for the generation of getters and setters. *

* Complete documentation is found at the project lombok features page for @Accessors. *

* Using this annotation does nothing by itself; an annotation that makes lombok generate getters and setters, * such as {@link lombok.Setter} or {@link lombok.Data} is also required. */ @Target({ElementType.TYPE, ElementType.FIELD}) @Retention(RetentionPolicy.SOURCE) public @interface Accessors { /** * If true, accessors will be named after the field and not include a {@code get} or {@code set} * prefix. If true and {@code chain} is omitted, {@code chain} defaults to {@code true}. * default: false * * @return Whether or not to make fluent methods (named {@code fieldName()}, not for example {@code setFieldName}). */ boolean fluent() default false; /** * If true, setters return {@code this} instead of {@code void}. * default: false, unless {@code fluent=true}, then default: true * * @return Whether or not setters should return themselves (chaining) or {@code void} (no chaining). */ boolean chain() default false; /** * If present, only fields with any of the stated prefixes are given the getter/setter treatment. * Note that a prefix only counts if the next character is NOT a lowercase character or the last * letter of the prefix is not a letter (for instance an underscore). If multiple fields * all turn into the same name when the prefix is stripped, an error will be generated. * * @return If you are in the habit of prefixing your fields (for example, you name them {@code fFieldName}, specify such prefixes here). */ String[] prefix() default {}; } lombok-1.16.18/src/core/lombok/experimental/Builder.java000066400000000000000000000132561312655740700231240ustar00rootroot00000000000000/* * Copyright (C) 2013-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * The builder annotation creates a so-called 'builder' aspect to the class that is annotated or the class * that contains a member which is annotated with {@code @Builder}. *

* If a member is annotated, it must be either a constructor or a method. If a class is annotated, * then a private constructor is generated with all fields as arguments * (as if {@code @AllArgsConstructor(AccessLevel.PRIVATE)} is present * on the class), and it is as if this constructor has been annotated with {@code @Builder} instead. *

* The effect of {@code @Builder} is that an inner class is generated named TBuilder, * with a private constructor. Instances of TBuilder are made with the * method named {@code builder()} which is also generated for you in the class itself (not in the builder class). *

* The TBuilder class contains 1 method for each parameter of the annotated * constructor / method (each field, when annotating a class), which returns the builder itself. * The builder also has a build() method which returns a completed instance of the original type, * created by passing all parameters as set via the various other methods in the builder to the constructor * or method that was annotated with {@code @Builder}. The return type of this method will be the same * as the relevant class, unless a method has been annotated, in which case it'll be equal to the * return type of that method. *

* Complete documentation is found at the project lombok features page for @Builder. *
*

* Before: * *

 * @Builder
 * class Example {
 * 	private int foo;
 * 	private final String bar;
 * }
 * 
* * After: * *
 * class Example<T> {
 * 	private T foo;
 * 	private final String bar;
 * 	
 * 	private Example(T foo, String bar) {
 * 		this.foo = foo;
 * 		this.bar = bar;
 * 	}
 * 	
 * 	public static <T> ExampleBuilder<T> builder() {
 * 		return new ExampleBuilder<T>();
 * 	}
 * 	
 * 	public static class ExampleBuilder<T> {
 * 		private T foo;
 * 		private String bar;
 * 		
 * 		private ExampleBuilder() {}
 * 		
 * 		public ExampleBuilder foo(T foo) {
 * 			this.foo = foo;
 * 			return this;
 * 		}
 * 		
 * 		public ExampleBuilder bar(String bar) {
 * 			this.bar = bar;
 * 			return this;
 * 		}
 * 		
 * 		@java.lang.Override public String toString() {
 * 			return "ExampleBuilder(foo = " + foo + ", bar = " + bar + ")";
 * 		}
 * 		
 * 		public Example build() {
 * 			return new Example(foo, bar);
 * 		}
 * 	}
 * }
 * 
* * @deprecated {@link lombok.Builder} has been promoted to the main package, so use that one instead. */ @Target({TYPE, METHOD, CONSTRUCTOR}) @Retention(SOURCE) @Deprecated public @interface Builder { /** @return Name of the method that creates a new builder instance. Default: {@code builder}. */ String builderMethodName() default "builder"; /** @return Name of the method in the builder class that creates an instance of your {@code @Builder}-annotated class. */ String buildMethodName() default "build"; /** * Name of the builder class. * * Default for {@code @Builder} on types and constructors: {@code (TypeName)Builder}. *

* Default for {@code @Builder} on methods: {@code (ReturnTypeName)Builder}. * * @return Name of the builder class that will be generated (or if it already exists, will be filled with builder elements). */ String builderClassName() default ""; /** * Normally the builder's 'set' methods are fluent, meaning, they have the same name as the field. Set this * to {@code false} to name the setter method for field {@code someField}: {@code setSomeField}. *

* Default: true * * @return Whether to generate fluent methods (just {@code fieldName()} instead of {@code setFieldName()}). */ boolean fluent() default true; /** * Normally the builder's 'set' methods are chaining, meaning, they return the builder so that you can chain * calls to set methods. Set this to {@code false} to have these 'set' methods return {@code void} instead. *

* Default: true * * @return Whether to generate chaining methods (each build call returns itself instead of returning {@code void}). */ boolean chain() default true; } lombok-1.16.18/src/core/lombok/experimental/Delegate.java000066400000000000000000000067651312655740700232570ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Put on any field to make lombok generate delegate methods that forward the call to this field. * * Example: *

 *     private @Delegate List<String> foo;
 * 
* * will generate for example an {@code boolean add(String)} method, which contains: {@code return foo.add(arg);}, as well as all other methods in {@code List}. * * All public instance methods of the field's type, as well as all public instance methods of all the field's type's superfields are delegated, except for all methods * that exist in {@link Object}, the {@code canEqual(Object)} method, and any methods that appear in types * that are listed in the {@code excludes} property. *

* Complete documentation is found at the project lombok features page for @Delegate. */ @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.SOURCE) public @interface Delegate { /** * Normally the type of the field is used as delegate type. However, to choose a different type to delegate, you can list one (or more) types here. Note that types with * type arguments can only be done as a field type. A solution for this is to create a private inner interface/class with the appropriate types extended, and possibly * with all methods you'd like to delegate listed, and then supply that class here. The field does not actually have to implement the type you're delegating; the * type listed here is used only to determine which delegate methods to generate. * * NB: All methods in {@code Object}, as well as {@code canEqual(Object other)} will never be delegated. * * @return For each method (not already in {@code java.lang.Object}) in these types, generate a delegate method. */ Class[] types() default {}; /** * Each method in any of the types listed here (include supertypes) will not be delegated. * * NB: All methods in {@code Object}, as well as {@code canEqual(Object other)} will never be delegated. * * @return For each method (not already in {@code java.lang.Object}) in these types, skip generating a delegate method (overrides {@code types()}). */ Class[] excludes() default {}; } lombok-1.16.18/src/core/lombok/experimental/ExtensionMethod.java000066400000000000000000000053741312655740700246550ustar00rootroot00000000000000/* * Copyright (C) 2012-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import java.lang.annotation.*; /** * Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or * otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as * if they were instance methods on the extended type. *

* Complete documentation is found at the project lombok features page for @ExtensionMethod. *
*

* Before: * *

 * @ExtensionMethod(java.util.Arrays.class)
 * class Example {
 * 	private void example() {
 * 		long[] values = new long[] { 2, 5, 7, 9 };
 * 		values.copyOf(3).sort();
 * 	}
 * }
 * 
* * After: * *
 * class Example {
 * 	private void example() {
 * 		long[] values = new long[] { 2, 5, 7, 9 };
 * 		java.util.Arrays.sort(java.util.Arrays.copyOf(values, 3));
 * 	}
 * }
 * 
*/ @Target(TYPE) @Retention(SOURCE) public @interface ExtensionMethod { /** @return All types whose static methods will be exposed as extension methods. */ Class[] value(); /** * If {@code true}, an applicable extension method is used (if found) even if the method call already was compilable (this is the default). * If {@code false}, an extension method is only used if the method call is not also defined by the type itself. * * @return Whether or not to override already existing methods with the extension. */ boolean suppressBaseMethods() default true; } lombok-1.16.18/src/core/lombok/experimental/FieldDefaults.java000066400000000000000000000042071312655740700242450ustar00rootroot00000000000000/* * Copyright (C) 2012-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import lombok.AccessLevel; /** * Adds modifiers to each field in the type with this annotation. *

* Complete documentation is found at the project lombok features page for @FieldDefaults. *

* If {@code makeFinal} is {@code true}, then each (instance) field that is not annotated with {@code @NonFinal} will have the {@code final} modifier added. *

* If {@code level} is set, then each (instance) field that is package private (i.e. no access modifier) and does not have the {@code @PackagePrivate} annotation will * have the appropriate access level modifier added. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface FieldDefaults { AccessLevel level() default AccessLevel.NONE; boolean makeFinal() default false; } lombok-1.16.18/src/core/lombok/experimental/Helper.java000066400000000000000000000030421312655740700227450ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Use on a method local class to indicate that all methods inside should be exposed to the rest of * the method as if they were helper methods. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface Helper {} lombok-1.16.18/src/core/lombok/experimental/NonFinal.java000066400000000000000000000033251312655740700232360ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to indicate the explicit intention for the annotated entity to not be {@code final}. * Currently used by {@code FieldDefaults} and {@code Value} to avoid having it make a field final. */ @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.SOURCE) public @interface NonFinal {} lombok-1.16.18/src/core/lombok/experimental/PackagePrivate.java000066400000000000000000000034111312655740700244140ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to indicate the explicit intention for the annotated entity to have the package private access level. * Currently used by {@code FieldDefaults} and {@code Value} to avoid having it make a field one of {@code public}, {@code protected}, or {@code private}. */ @Target({ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.SOURCE) public @interface PackagePrivate {} lombok-1.16.18/src/core/lombok/experimental/Tolerate.java000066400000000000000000000031271312655740700233110ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Put on any method or constructor to make lombok pretend it doesn't exist, * i.e., to generate a method which would otherwise be skipped due to possible conflicts. */ @Target({ElementType.METHOD, ElementType.CONSTRUCTOR}) @Retention(RetentionPolicy.SOURCE) public @interface Tolerate { } lombok-1.16.18/src/core/lombok/experimental/UtilityClass.java000066400000000000000000000035301312655740700241610ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation to create utility classes. * * If a class is annotated with {@code @UtilityClass}, the following things happen to it:

    *
  • It is marked final.
  • *
  • If any constructors are declared in it, an error is generated. Otherwise, a private no-args constructor is generated; it throws a {@code UnsupportedOperationException}.
  • *
  • All methods, inner classes, and fields in the class are marked static.
  • *
*/ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.SOURCE) public @interface UtilityClass { } lombok-1.16.18/src/core/lombok/experimental/Value.java000066400000000000000000000051651312655740700226120ustar00rootroot00000000000000/* * Copyright (C) 2012-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Generates a lot of code which fits with a class that is a representation of an immutable entity. *

* Equivalent to {@code @Getter @FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE) @RequiredArgsConstructor @ToString @EqualsAndHashCode}. *

* Complete documentation is found at the project lombok features page for @Value. * * @see lombok.Getter * @see Wither * @see lombok.RequiredArgsConstructor * @see lombok.ToString * @see lombok.EqualsAndHashCode * @see lombok.Data * @deprecated {@link lombok.Value} has been promoted to the main package, so use that one instead. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Deprecated public @interface Value { /** * If you specify a static constructor name, then the generated constructor will be private, and * instead a static factory method is created that other classes can use to create instances. * We suggest the name: "of", like so: * *

	 *     public @Data(staticConstructor = "of") class Point { final int x, y; }
	 * 
* * Default: No static constructor, instead the normal constructor is public. * * @return Name of static 'constructor' method to generate (blank = generate a normal constructor). */ String staticConstructor() default ""; } lombok-1.16.18/src/core/lombok/experimental/Wither.java000066400000000000000000000075561312655740700230060ustar00rootroot00000000000000/* * Copyright (C) 2012-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import lombok.AccessLevel; /** * Put on any field to make lombok build a 'wither' - a withX method which produces a clone of this object (except for 1 field which gets a new value). *

* Complete documentation is found at the project lombok features page for @Wither. *

* Even though it is not listed, this annotation also has the {@code onParam} and {@code onMethod} parameter. See the full documentation for more details. *

* Example: *

 *     private @Wither final int foo;
 * 
* * will generate: * *
 *     public SELF_TYPE withFoo(int foo) {
 *         return this.foo == foo ? this : new SELF_TYPE(otherField1, otherField2, foo);
 *     }
 * 
*

* This annotation can also be applied to a class, in which case it'll be as if all non-static fields that don't already have * a {@code Wither} annotation have the annotation. */ @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.SOURCE) public @interface Wither { /** * If you want your wither to be non-public, you can specify an alternate access level here. * * @return The method will be generated with this access modifier. */ AccessLevel value() default AccessLevel.PUBLIC; /** * Any annotations listed here are put on the generated method. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
* up to JDK7:
* {@code @Wither(onMethod=@__({@AnnotationsGoHere}))}
* from JDK8:
* {@code @Wither(onMethod_={@AnnotationsGohere})} // note the underscore after {@code onMethod}. * * @return List of annotations to apply to the generated method. */ AnyAnnotation[] onMethod() default {}; /** * Any annotations listed here are put on the generated method's parameter. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
* up to JDK7:
* {@code @Wither(onParam=@__({@AnnotationsGoHere}))}
* from JDK8:
* {@code @Wither(onParam_={@AnnotationsGohere})} // note the underscore after {@code onParam}. * * @return List of annotations to apply to the generated parameter in the method. */ AnyAnnotation[] onParam() default {}; /** * Placeholder annotation to enable the placement of annotations on the generated code. * @deprecated Don't use this annotation, ever - Read the documentation. */ @Deprecated @Retention(RetentionPolicy.SOURCE) @Target({}) @interface AnyAnnotation {} } lombok-1.16.18/src/core/lombok/experimental/package-info.java000066400000000000000000000033221312655740700240530ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * This package contains the annotations and support classes you need as a user of lombok, for * all features which aren't (yet) supported as a first class feature. Features that involve the * annotations and support classes in this package may change or may be removed entirely in future versions, * and bugs may not be solved as expediently. For the status and likely future of any feature, refer * to the official feature documentation. * * @see lombok * @see Lombok features (experimental) */ package lombok.experimental; lombok-1.16.18/src/core/lombok/experimental/var.java000066400000000000000000000023161312655740700223210ustar00rootroot00000000000000/* * Copyright (C) 2010-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.experimental; /** * like val but not final */ public @interface var { } lombok-1.16.18/src/core/lombok/extern/000077500000000000000000000000001312655740700174745ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/extern/apachecommons/000077500000000000000000000000001312655740700223115ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/extern/apachecommons/CommonsLog.java000066400000000000000000000053561312655740700252420ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.extern.apachecommons; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Causes lombok to generate a logger field. *

* Complete documentation is found at the project lombok features page for lombok log annotations. *

* Example: *

 * @CommonsLog
 * public class LogExample {
 * }
 * 
* * will generate: * *
 * public class LogExample {
 *     private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);
 * }
 * 
* * This annotation is valid for classes and enumerations.
* * @see org.apache.commons.logging.Log * @see org.apache.commons.logging.LogFactory#getLog(java.lang.Class) * @see lombok.extern.java.Log @Log * @see lombok.extern.log4j.Log4j @Log4j * @see lombok.extern.log4j.Log4j2 @Log4j2 * @see lombok.extern.slf4j.Slf4j @Slf4j * @see lombok.extern.slf4j.XSlf4j @XSlf4j * @see lombok.extern.jbosslog.JBossLog @JBossLog */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface CommonsLog { /** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */ String topic() default ""; } lombok-1.16.18/src/core/lombok/extern/java/000077500000000000000000000000001312655740700204155ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/extern/java/Log.java000066400000000000000000000052461312655740700220100ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.extern.java; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Causes lombok to generate a logger field. *

* Complete documentation is found at the project lombok features page for lombok log annotations. *

* Example: *

 * @Log
 * public class LogExample {
 * }
 * 
* * will generate: * *
 * public class LogExample {
 *     private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
 * }
 * 
* * This annotation is valid for classes and enumerations.
* @see java.util.logging.Logger * @see java.util.logging.Logger#getLogger(java.lang.String) * @see lombok.extern.apachecommons.CommonsLog @CommonsLog * @see lombok.extern.log4j.Log4j @Log4j * @see lombok.extern.log4j.Log4j2 @Log4j2 * @see lombok.extern.slf4j.Slf4j @Slf4j * @see lombok.extern.slf4j.XSlf4j @XSlf4j * @see lombok.extern.jbosslog.JBossLog @JBossLog */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface Log { /** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */ String topic() default ""; } lombok-1.16.18/src/core/lombok/extern/jbosslog/000077500000000000000000000000001312655740700213165ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/extern/jbosslog/JBossLog.java000066400000000000000000000052501312655740700236450ustar00rootroot00000000000000/* * Copyright (C) 2016-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.extern.jbosslog; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Causes lombok to generate a logger field. *

* Complete documentation is found at the project lombok features page for lombok log annotations. *

* Example: *

 * @JBossLog
 * public class LogExample {
 * }
 * 
* * will generate: * *
 * public class LogExample {
 *     private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(LogExample.class);
 * }
 * 
* * This annotation is valid for classes and enumerations.
* @see org.jboss.logging.Logger * @see org.jboss.logging.Logger#getLogger(java.lang.Class) * @see lombok.extern.apachecommons.CommonsLog @CommonsLog * @see lombok.extern.java.Log @Log * @see lombok.extern.log4j.Log4j @Log4j * @see lombok.extern.log4j.Log4j2 @Log4j2 * @see lombok.extern.slf4j.XSlf4j @XSlf4j * @see lombok.extern.jbosslog.JBossLog @JBossLog * */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface JBossLog { /** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */ String topic() default ""; } lombok-1.16.18/src/core/lombok/extern/log4j/000077500000000000000000000000001312655740700205135ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/extern/log4j/Log4j.java000066400000000000000000000052361312655740700223430ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.extern.log4j; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Causes lombok to generate a logger field. *

* Complete documentation is found at the project lombok features page for lombok log annotations. *

* Example: *

 * @Log4j
 * public class LogExample {
 * }
 * 
* * will generate: * *
 * public class LogExample {
 *     private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogExample.class);
 * }
 * 
* * This annotation is valid for classes and enumerations.
* * @see org.apache.log4j.Logger * @see org.apache.log4j.Logger#getLogger(java.lang.Class) * @see lombok.extern.log4j.Log4j2 @Log4j2 * @see lombok.extern.apachecommons.CommonsLog @CommonsLog * @see lombok.extern.java.Log @Log * @see lombok.extern.slf4j.Slf4j @Slf4j * @see lombok.extern.slf4j.XSlf4j @XSlf4j * @see lombok.extern.jbosslog.JBossLog @JBossLog */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface Log4j { /** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */ String topic() default ""; } lombok-1.16.18/src/core/lombok/extern/log4j/Log4j2.java000066400000000000000000000053561312655740700224300ustar00rootroot00000000000000/* * Copyright (C) 2013-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.extern.log4j; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Causes lombok to generate a logger field. *

* Complete documentation is found at the project lombok features page for lombok log annotations. *

* Example: *

 * @Log4j2
 * public class LogExample {
 * }
 * 
* * will generate: * *
 * public class LogExample {
 *     private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
 * }
 * 
* * This annotation is valid for classes and enumerations.
* * @see org.apache.logging.log4j.Logger * @see org.apache.logging.log4j.LogManager#getLogger(java.lang.Class) * @see lombok.extern.log4j.Log4j @Log4j * @see lombok.extern.apachecommons.CommonsLog @CommonsLog * @see lombok.extern.java.Log @Log * @see lombok.extern.slf4j.Slf4j @Slf4j * @see lombok.extern.slf4j.XSlf4j @XSlf4j * @see lombok.extern.jbosslog.JBossLog @JBossLog */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface Log4j2 { /** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */ String topic() default ""; } lombok-1.16.18/src/core/lombok/extern/slf4j/000077500000000000000000000000001312655740700205165ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/extern/slf4j/Slf4j.java000066400000000000000000000051401312655740700223430ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.extern.slf4j; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Causes lombok to generate a logger field. *

* Complete documentation is found at the project lombok features page for lombok log annotations. *

* Example: *

 * @Slf4j
 * public class LogExample {
 * }
 * 
* * will generate: * *
 * public class LogExample {
 *     private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
 * }
 * 
* * This annotation is valid for classes and enumerations.
* @see org.slf4j.Logger * @see org.slf4j.LoggerFactory#getLogger(java.lang.Class) * @see lombok.extern.apachecommons.CommonsLog @CommonsLog * @see lombok.extern.java.Log @Log * @see lombok.extern.log4j.Log4j @Log4j * @see lombok.extern.log4j.Log4j2 @Log4j2 * @see lombok.extern.slf4j.XSlf4j @XSlf4j * @see lombok.extern.jbosslog.JBossLog @JBossLog */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface Slf4j { /** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */ String topic() default ""; } lombok-1.16.18/src/core/lombok/extern/slf4j/XSlf4j.java000066400000000000000000000051771312655740700225050ustar00rootroot00000000000000/* * Copyright (C) 2012-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.extern.slf4j; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Causes lombok to generate a logger field. *

* Complete documentation is found at the project lombok features page for lombok log annotations. *

* Example: *

 * @XSlf4j
 * public class LogExample {
 * }
 * 
* * will generate: * *
 * public class LogExample {
 *     private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
 * }
 * 
* * This annotation is valid for classes and enumerations.
* @see org.slf4j.ext.XLogger * @see org.slf4j.ext.XLoggerFactory#getLogger(java.lang.Class) * @see lombok.extern.apachecommons.CommonsLog @CommonsLog * @see lombok.extern.java.Log @Log * @see lombok.extern.log4j.Log4j @Log4j * @see lombok.extern.log4j.Log4j2 @Log4j2 * @see lombok.extern.slf4j.Slf4j @Slf4j * @see lombok.extern.jbosslog.JBossLog @JBossLog */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface XSlf4j { /** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */ String topic() default ""; } lombok-1.16.18/src/core/lombok/javac/000077500000000000000000000000001312655740700172535ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/javac/CapturingDiagnosticListener.java000066400000000000000000000100301312655740700255570ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.io.File; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; import javax.tools.DiagnosticListener; import javax.tools.JavaFileObject; /** * This class stores any reported errors as {@code CompilerMessage} objects and supports removing some of these. * Currently this class is only used for testing purposes. */ public class CapturingDiagnosticListener implements DiagnosticListener { private final File file; private final Collection messages; public CapturingDiagnosticListener(File file, Collection messages) { this.file = file; this.messages = messages; } @Override public void report(Diagnostic d) { String msg = d.getMessage(Locale.ENGLISH); Matcher m = Pattern.compile( "^" + Pattern.quote(file.getAbsolutePath()) + "\\s*:\\s*\\d+\\s*:\\s*(?:warning:\\s*)?(.*)$", Pattern.DOTALL).matcher(msg); if (m.matches()) msg = m.group(1); messages.add(new CompilerMessage(d.getLineNumber(), d.getStartPosition(), d.getKind() == Kind.ERROR, msg)); } public void suppress(int start, int end) { Iterator it = messages.iterator(); while (it.hasNext()) { long pos = it.next().getPosition(); if (pos >= start && pos < end) it.remove(); } } public static final class CompilerMessage { /** Line Number (starting at 1) */ private final long line; private final long position; private final boolean isError; private final String message; public CompilerMessage(long line, long position, boolean isError, String message) { this.line = line; this.position = position; this.isError = isError; this.message = message; } public long getLine() { return line; } public long getPosition() { return position; } public boolean isError() { return isError; } public String getMessage() { return message; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (isError ? 1231 : 1237); result = prime * result + (int) (line ^ (line >>> 32)); result = prime * result + ((message == null) ? 0 : message.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CompilerMessage other = (CompilerMessage) obj; if (isError != other.isError) return false; if (line != other.line) return false; if (message == null) { if (other.message != null) return false; } else if (!message.equals(other.message)) return false; return true; } @Override public String toString() { return String.format("%d %s %s", line, isError ? "ERROR" : "WARNING", message); } } } lombok-1.16.18/src/core/lombok/javac/CompilerMessageSuppressor.java000066400000000000000000000257341312655740700253160ustar00rootroot00000000000000/* * Copyright (C) 2011-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.tools.DiagnosticListener; import javax.tools.JavaFileObject; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.JCDiagnostic; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Log; /** * During resolution, the resolver will emit resolution errors, but without appropriate file names and line numbers. If these resolution errors stick around * then they will be generated AGAIN, this time with proper names and line numbers, at the end. Therefore, we want to suppress the logger. */ public final class CompilerMessageSuppressor { private final Log log; private static final WriterField errWriterField, warnWriterField, noticeWriterField; private static final Field dumpOnErrorField, promptOnErrorField, diagnosticListenerField; private static final Field deferDiagnosticsField, deferredDiagnosticsField, diagnosticHandlerField; private static final ConcurrentMap, Field> handlerDeferredFields = new ConcurrentHashMap, Field>(); private static final Field NULL_FIELD; private Boolean dumpOnError, promptOnError; private DiagnosticListener contextDiagnosticListener, logDiagnosticListener; private final Context context; private static final ThreadLocal> queueCache = new ThreadLocal>(); enum Writers { ERROR("errWriter", "ERROR"), WARNING("warnWriter", "WARNING"), NOTICE("noticeWriter", "NOTICE"); final String fieldName; final String keyName; Writers(String fieldName, String keyName) { this.fieldName = fieldName; this.keyName = keyName; } } static { errWriterField = createWriterField(Writers.ERROR); warnWriterField = createWriterField(Writers.WARNING); noticeWriterField = createWriterField(Writers.NOTICE); dumpOnErrorField = getDeclaredField(Log.class, "dumpOnError"); promptOnErrorField = getDeclaredField(Log.class, "promptOnError"); diagnosticListenerField = getDeclaredField(Log.class, "diagListener"); deferDiagnosticsField = getDeclaredField(Log.class, "deferDiagnostics"); deferredDiagnosticsField = getDeclaredField(Log.class, "deferredDiagnostics"); // javac8 diagnosticHandlerField = getDeclaredField(Log.class, "diagnosticHandler"); NULL_FIELD = getDeclaredField(JavacResolution.class, "NULL_FIELD"); } static Field getDeclaredField(Class c, String fieldName) { try { Field field = c.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (Throwable t) { return null; } } public CompilerMessageSuppressor(Context context) { this.log = Log.instance(context); this.context = context; } public void disableLoggers() { contextDiagnosticListener = context.get(DiagnosticListener.class); context.put(DiagnosticListener.class, (DiagnosticListener) null); errWriterField.pauze(log); warnWriterField.pauze(log); noticeWriterField.pauze(log); if (deferDiagnosticsField != null) try { if (Boolean.TRUE.equals(deferDiagnosticsField.get(log))) { queueCache.set((Queue) deferredDiagnosticsField.get(log)); Queue empty = new LinkedList(); deferredDiagnosticsField.set(log, empty); } } catch (Exception e) {} if (diagnosticHandlerField != null) try { Object handler = diagnosticHandlerField.get(log); Field field = getDeferredField(handler); if (field != null) { queueCache.set((Queue) field.get(handler)); Queue empty = new LinkedList(); field.set(handler, empty); } } catch (Exception e) {} if (dumpOnErrorField != null) try { dumpOnError = (Boolean) dumpOnErrorField.get(log); dumpOnErrorField.set(log, false); } catch (Exception e) { } if (promptOnErrorField != null) try { promptOnError = (Boolean) promptOnErrorField.get(log); promptOnErrorField.set(log, false); } catch (Exception e) { } if (diagnosticListenerField != null) try { logDiagnosticListener = (DiagnosticListener) diagnosticListenerField.get(log); diagnosticListenerField.set(log, null); } catch (Exception e) { } } private static Field getDeferredField(Object handler) { Class key = handler.getClass(); Field field = handlerDeferredFields.get(key); if (field != null) { return field == NULL_FIELD ? null : field; } Field value = getDeclaredField(key, "deferred"); handlerDeferredFields.put(key, value == null ? NULL_FIELD : value); return getDeferredField(handler); } public void enableLoggers() { if (contextDiagnosticListener != null) { context.put(DiagnosticListener.class, contextDiagnosticListener); contextDiagnosticListener = null; } errWriterField.resume(log); warnWriterField.resume(log); noticeWriterField.resume(log); if (dumpOnError != null) try { dumpOnErrorField.set(log, dumpOnError); dumpOnError = null; } catch (Exception e) {} if (promptOnError != null) try { promptOnErrorField.set(log, promptOnError); promptOnError = null; } catch (Exception e) {} if (logDiagnosticListener != null) try { diagnosticListenerField.set(log, logDiagnosticListener); logDiagnosticListener = null; } catch (Exception e) {} if (diagnosticHandlerField != null && queueCache.get() != null) try { Object handler = diagnosticHandlerField.get(log); Field field = getDeferredField(handler); if (field != null) { field.set(handler, queueCache.get()); queueCache.set(null); } } catch (Exception e) {} if (deferDiagnosticsField != null && queueCache.get() != null) try { deferredDiagnosticsField.set(log, queueCache.get()); queueCache.set(null); } catch (Exception e) {} } public void removeAllBetween(JavaFileObject sourcefile, int startPos, int endPos) { DiagnosticListener listener = context.get(DiagnosticListener.class); if (listener instanceof CapturingDiagnosticListener) { ((CapturingDiagnosticListener) listener).suppress(startPos, endPos); } Field field = null; Object receiver = null; if (deferDiagnosticsField != null) try { if (Boolean.TRUE.equals(deferDiagnosticsField.get(log))) { field = deferredDiagnosticsField; receiver = log; } } catch (Exception e) {} if (diagnosticHandlerField != null) try { Object handler = diagnosticHandlerField.get(log); field = getDeferredField(handler); receiver = handler; } catch (Exception e) {} if (field == null || receiver == null) return; try { ListBuffer deferredDiagnostics = (ListBuffer) field.get(receiver); ListBuffer newDeferredDiagnostics = new ListBuffer(); for (Object diag_ : deferredDiagnostics) { if (!(diag_ instanceof JCDiagnostic)) { newDeferredDiagnostics.add(diag_); continue; } JCDiagnostic diag = (JCDiagnostic) diag_; long here = diag.getStartPosition(); if (here >= startPos && here < endPos && diag.getSource() == sourcefile) { // We eliminate it } else { newDeferredDiagnostics.add(diag); } } field.set(receiver, newDeferredDiagnostics); } catch (Exception e) { // We do not expect failure here; if failure does occur, the best course of action is to silently continue; the result will be that the error output of // javac will contain rather a lot of messages, but this is a lot better than just crashing during compilation! } } private static WriterField createWriterField(Writers w) { // jdk9 try { Field writers = getDeclaredField(Log.class, "writer"); if (writers != null) { Class kindsClass = Class.forName("com.sun.tools.javac.util.Log$WriterKind"); for (Object enumConstant : kindsClass.getEnumConstants()) { if (enumConstant.toString().equals(w.keyName)) { return new Java9WriterField(writers, enumConstant); } } return WriterField.NONE; } } catch (Exception e) { } // jdk8 Field writerField = getDeclaredField(Log.class, w.fieldName); if (writerField != null) return new Java8WriterField(writerField); // other jdk return WriterField.NONE; } interface WriterField { final PrintWriter NO_WRITER = new PrintWriter(new OutputStream() { @Override public void write(int b) throws IOException { // Do nothing on purpose } }); final WriterField NONE = new WriterField() { @Override public void pauze(Log log) { // do nothing } @Override public void resume(Log log) { // no nothing } }; void pauze(Log log); void resume(Log log); } static class Java8WriterField implements WriterField { private final Field field; private PrintWriter writer; public Java8WriterField(Field field) { this.field = field; } @Override public void pauze(Log log) { try { writer = (PrintWriter) field.get(log); field.set(log, NO_WRITER); } catch (Exception e) { } } @Override public void resume(Log log) { if (writer != null) { try { field.set(log, writer); } catch (Exception e) { } } writer = null; } } static class Java9WriterField implements WriterField { private final Field field; private final Object key; private PrintWriter writer; public Java9WriterField(Field field, Object key) { this.field = field; this.key = key; } @Override public void pauze(Log log) { try { @SuppressWarnings("unchecked") Map map = (Map)field.get(log); writer = map.get(key); map.put(key, NO_WRITER); } catch (Exception e) { } } @Override public void resume(Log log) { if (writer != null) { try { @SuppressWarnings("unchecked") Map map = (Map)field.get(log); map.put(key, writer); } catch (Exception e) { } } writer = null; } } }lombok-1.16.18/src/core/lombok/javac/FindTypeVarScanner.java000066400000000000000000000073171312655740700236330ustar00rootroot00000000000000/* * Copyright (C) 2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.util.HashSet; import java.util.Set; import javax.lang.model.element.Name; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ErrorType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.NoType; import javax.lang.model.type.NullType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.type.WildcardType; import javax.lang.model.util.AbstractTypeVisitor6; import com.sun.tools.javac.code.Type; /** * scanner (i.e. visits child nodes all the way to the leaves) that accumulates type variables. Call {@code visit} on any {@code TypeMirror} object with an instance * to add all used type variable names such as {@code T} or {@code E} to the set that is returned by the {@link #getTypeVariables} method. */ public class FindTypeVarScanner extends AbstractTypeVisitor6 { private Set typeVariables = new HashSet(); public Set getTypeVariables() { return typeVariables; } private Void subVisit(TypeMirror mirror) { if (mirror == null) return null; return mirror.accept(this, null); } @Override public Void visitPrimitive(PrimitiveType t, Void p) { return null; } @Override public Void visitNull(NullType t, Void p) { return null; } @Override public Void visitNoType(NoType t, Void p) { return null; } @Override public Void visitUnknown(TypeMirror t, Void p) { return null; } @Override public Void visitError(ErrorType t, Void p) { return null; } @Override public Void visitArray(ArrayType t, Void p) { return subVisit(t.getComponentType()); } @Override public Void visitDeclared(DeclaredType t, Void p) { for (TypeMirror subT : t.getTypeArguments()) subVisit(subT); return null; } @Override public Void visitTypeVariable(TypeVariable t, Void p) { Name name = null; try { name = ((Type) t).tsym.name; } catch (NullPointerException e) {} if (name != null) typeVariables.add(name.toString()); subVisit(t.getLowerBound()); subVisit(t.getUpperBound()); return null; } @Override public Void visitWildcard(WildcardType t, Void p) { subVisit(t.getSuperBound()); subVisit(t.getExtendsBound()); return null; } @Override public Void visitExecutable(ExecutableType t, Void p) { subVisit(t.getReturnType()); for (TypeMirror subT : t.getParameterTypes()) subVisit(subT); for (TypeMirror subT : t.getThrownTypes()) subVisit(subT); for (TypeVariable subT : t.getTypeVariables()) subVisit(subT); return null; } } lombok-1.16.18/src/core/lombok/javac/HandlerLibrary.java000066400000000000000000000255001312655740700230220ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import static lombok.javac.JavacAugments.JCTree_handled; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.processing.Messager; import javax.tools.Diagnostic; import lombok.core.AnnotationValues.AnnotationValueDecodeFail; import lombok.core.HandlerPriority; import lombok.core.SpiLoadUtil; import lombok.core.TypeLibrary; import lombok.core.TypeResolver; import lombok.core.configuration.ConfigurationKeysLoader; import lombok.javac.handlers.JavacHandlerUtil; import com.sun.source.util.Trees; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; /** * This class tracks 'handlers' and knows how to invoke them for any given AST node. * * This class can find the handlers (via SPI discovery) and will set up the given AST node, such as * building an AnnotationValues instance. */ public class HandlerLibrary { private final TypeLibrary typeLibrary = new TypeLibrary(); private final Map> annotationHandlers = new HashMap>(); private final Collection visitorHandlers = new ArrayList(); private final Messager messager; /** * Creates a new HandlerLibrary that will report any problems or errors to the provided messager. * You probably want to use {@link #load(Messager)} instead. */ public HandlerLibrary(Messager messager) { ConfigurationKeysLoader.LoaderLoader.loadAllConfigurationKeys(); this.messager = messager; } private static class VisitorContainer { private final JavacASTVisitor visitor; private final long priority; private final boolean resolutionResetNeeded; VisitorContainer(JavacASTVisitor visitor) { this.visitor = visitor; HandlerPriority hp = visitor.getClass().getAnnotation(HandlerPriority.class); this.priority = hp == null ? 0L : (((long)hp.value()) << 32) + hp.subValue(); this.resolutionResetNeeded = visitor.getClass().isAnnotationPresent(ResolutionResetNeeded.class); } public long getPriority() { return priority; } public boolean isResolutionResetNeeded() { return resolutionResetNeeded; } } private static class AnnotationHandlerContainer { private final JavacAnnotationHandler handler; private final Class annotationClass; private final long priority; private final boolean resolutionResetNeeded; AnnotationHandlerContainer(JavacAnnotationHandler handler, Class annotationClass) { this.handler = handler; this.annotationClass = annotationClass; HandlerPriority hp = handler.getClass().getAnnotation(HandlerPriority.class); this.priority = hp == null ? 0L : (((long)hp.value()) << 32) + hp.subValue(); this.resolutionResetNeeded = handler.getClass().isAnnotationPresent(ResolutionResetNeeded.class); } public void handle(final JavacNode node) { handler.handle(JavacHandlerUtil.createAnnotation(annotationClass, node), (JCAnnotation)node.get(), node); } public long getPriority() { return priority; } public boolean isResolutionResetNeeded() { return resolutionResetNeeded; } } private SortedSet priorities; private SortedSet prioritiesRequiringResolutionReset; public SortedSet getPriorities() { return priorities; } public SortedSet getPrioritiesRequiringResolutionReset() { return prioritiesRequiringResolutionReset; } private void calculatePriorities() { SortedSet set = new TreeSet(); SortedSet resetNeeded = new TreeSet(); for (AnnotationHandlerContainer container : annotationHandlers.values()) { set.add(container.getPriority()); if (container.isResolutionResetNeeded()) resetNeeded.add(container.getPriority()); } for (VisitorContainer container : visitorHandlers) { set.add(container.getPriority()); if (container.isResolutionResetNeeded()) resetNeeded.add(container.getPriority()); } this.priorities = Collections.unmodifiableSortedSet(set); this.prioritiesRequiringResolutionReset = Collections.unmodifiableSortedSet(resetNeeded); } /** * Creates a new HandlerLibrary that will report any problems or errors to the provided messager, * then uses SPI discovery to load all annotation and visitor based handlers so that future calls * to the handle methods will defer to these handlers. */ public static HandlerLibrary load(Messager messager, Trees trees) { HandlerLibrary library = new HandlerLibrary(messager); try { loadAnnotationHandlers(library, trees); loadVisitorHandlers(library, trees); } catch (IOException e) { System.err.println("Lombok isn't running due to misconfigured SPI files: " + e); } library.calculatePriorities(); return library; } /** Uses SPI Discovery to find implementations of {@link JavacAnnotationHandler}. */ @SuppressWarnings({"rawtypes", "unchecked"}) private static void loadAnnotationHandlers(HandlerLibrary lib, Trees trees) throws IOException { //No, that seemingly superfluous reference to JavacAnnotationHandler's classloader is not in fact superfluous! for (JavacAnnotationHandler handler : SpiLoadUtil.findServices(JavacAnnotationHandler.class, JavacAnnotationHandler.class.getClassLoader())) { handler.setTrees(trees); Class annotationClass = handler.getAnnotationHandledByThisHandler(); AnnotationHandlerContainer container = new AnnotationHandlerContainer(handler, annotationClass); String annotationClassName = container.annotationClass.getName().replace("$", "."); if (lib.annotationHandlers.put(annotationClassName, container) != null) { lib.javacWarning("Duplicate handlers for annotation type: " + annotationClassName); } lib.typeLibrary.addType(container.annotationClass.getName()); } } /** Uses SPI Discovery to find implementations of {@link JavacASTVisitor}. */ private static void loadVisitorHandlers(HandlerLibrary lib, Trees trees) throws IOException { //No, that seemingly superfluous reference to JavacASTVisitor's classloader is not in fact superfluous! for (JavacASTVisitor visitor : SpiLoadUtil.findServices(JavacASTVisitor.class, JavacASTVisitor.class.getClassLoader())) { visitor.setTrees(trees); lib.visitorHandlers.add(new VisitorContainer(visitor)); } } /** Generates a warning in the Messager that was used to initialize this HandlerLibrary. */ public void javacWarning(String message) { javacWarning(message, null); } /** Generates a warning in the Messager that was used to initialize this HandlerLibrary. */ public void javacWarning(String message, Throwable t) { messager.printMessage(Diagnostic.Kind.WARNING, message + (t == null ? "" : (": " + t))); } /** Generates an error in the Messager that was used to initialize this HandlerLibrary. */ public void javacError(String message) { javacError(message, null); } /** Generates an error in the Messager that was used to initialize this HandlerLibrary. */ public void javacError(String message, Throwable t) { messager.printMessage(Diagnostic.Kind.ERROR, message + (t == null ? "" : (": " + t))); if (t != null) t.printStackTrace(); } private boolean checkAndSetHandled(JCTree node) { return !JCTree_handled.getAndSet(node, true); } /** * Handles the provided annotation node by first finding a qualifying instance of * {@link JavacAnnotationHandler} and if one exists, calling it with a freshly cooked up * instance of {@link lombok.core.AnnotationValues}. * * Note that depending on the printASTOnly flag, the {@link lombok.core.PrintAST} annotation * will either be silently skipped, or everything that isn't {@code PrintAST} will be skipped. * * The HandlerLibrary will attempt to guess if the given annotation node represents a lombok annotation. * For example, if {@code lombok.*} is in the import list, then this method will guess that * {@code Getter} refers to {@code lombok.Getter}, presuming that {@link lombok.javac.handlers.HandleGetter} * has been loaded. * * @param unit The Compilation Unit that contains the Annotation AST Node. * @param node The Lombok AST Node representing the Annotation AST Node. * @param annotation 'node.get()' - convenience parameter. */ public void handleAnnotation(JCCompilationUnit unit, JavacNode node, JCAnnotation annotation, long priority) { TypeResolver resolver = new TypeResolver(node.getImportList()); String rawType = annotation.annotationType.toString(); String fqn = resolver.typeRefToFullyQualifiedName(node, typeLibrary, rawType); if (fqn == null) return; AnnotationHandlerContainer container = annotationHandlers.get(fqn); if (container == null) return; try { if (container.getPriority() == priority) { if (checkAndSetHandled(annotation)) container.handle(node); } } catch (AnnotationValueDecodeFail fail) { fail.owner.setError(fail.getMessage(), fail.idx); } catch (Throwable t) { String sourceName = "(unknown).java"; if (unit != null && unit.sourcefile != null) sourceName = unit.sourcefile.getName(); javacError(String.format("Lombok annotation handler %s failed on " + sourceName, container.handler.getClass()), t); } } /** * Will call all registered {@link JavacASTVisitor} instances. */ public void callASTVisitors(JavacAST ast, long priority) { for (VisitorContainer container : visitorHandlers) try { if (container.getPriority() == priority) ast.traverse(container.visitor); } catch (Throwable t) { javacError(String.format("Lombok visitor handler %s failed", container.visitor.getClass()), t); } } } lombok-1.16.18/src/core/lombok/javac/Javac6BasedLombokOptions.java000066400000000000000000000052551312655740700247160ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import lombok.Lombok; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Options; public class Javac6BasedLombokOptions extends LombokOptions { private static final Method optionName_valueOf; private static final Method options_put; static { try { Class optionNameClass = Class.forName("com.sun.tools.javac.main.OptionName"); optionName_valueOf = optionNameClass.getMethod("valueOf", String.class); options_put = Class.forName("com.sun.tools.javac.util.Options").getMethod("put", optionNameClass, String.class); } catch (Exception e) { throw new IllegalArgumentException("Can't initialize Javac6-based lombok options due to reflection issue.", e); } } public static Javac6BasedLombokOptions replaceWithDelombokOptions(Context context) { Options options = Options.instance(context); context.put(optionsKey, (Options)null); Javac6BasedLombokOptions result = new Javac6BasedLombokOptions(context); result.putAll(options); return result; } private Javac6BasedLombokOptions(Context context) { super(context); } @Override public void putJavacOption(String optionName, String value) { try { options_put.invoke(this, optionName_valueOf.invoke(null, optionName), value); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Can't initialize Javac6-based lombok options due to reflection issue.", e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } } } lombok-1.16.18/src/core/lombok/javac/Javac8BasedLombokOptions.java000066400000000000000000000035241312655740700247150ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import com.sun.tools.javac.main.Option; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Options; public class Javac8BasedLombokOptions extends LombokOptions { public static Javac8BasedLombokOptions replaceWithDelombokOptions(Context context) { Options options = Options.instance(context); context.put(optionsKey, (Options)null); Javac8BasedLombokOptions result = new Javac8BasedLombokOptions(context); result.putAll(options); return result; } private Javac8BasedLombokOptions(Context context) { super(context); } @Override public void putJavacOption(String optionName, String value) { String optionText = Option.valueOf(optionName).text; put(optionText, value); } } lombok-1.16.18/src/core/lombok/javac/JavacAST.java000066400000000000000000000521461312655740700215220ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.annotation.processing.Messager; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import lombok.core.AST; import com.sun.tools.javac.code.Source; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.model.JavacElements; import com.sun.tools.javac.model.JavacTypes; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCCatch; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTry; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Name; /** * Wraps around javac's internal AST view to add useful features as well as the ability to visit parents from children, * something javac's own AST system does not offer. */ public class JavacAST extends AST { private final JavacElements elements; private final JavacTreeMaker treeMaker; private final Symtab symtab; private final JavacTypes javacTypes; private final Log log; private final ErrorLog errorLogger; private final Context context; /** * Creates a new JavacAST of the provided Compilation Unit. * * @param messager A Messager for warning and error reporting. * @param context A Context object for interfacing with the compiler. * @param top The compilation unit, which serves as the top level node in the tree to be built. */ public JavacAST(Messager messager, Context context, JCCompilationUnit top) { super(sourceName(top), PackageName.getPackageName(top), new JavacImportList(top), statementTypes()); setTop(buildCompilationUnit(top)); this.context = context; this.log = Log.instance(context); this.errorLogger = ErrorLog.create(messager, log); this.elements = JavacElements.instance(context); this.treeMaker = new JavacTreeMaker(TreeMaker.instance(context)); this.symtab = Symtab.instance(context); this.javacTypes = JavacTypes.instance(context); clearChanged(); } @Override public URI getAbsoluteFileLocation() { try { JCCompilationUnit cu = (JCCompilationUnit) top().get(); return cu.sourcefile.toUri(); } catch (Exception e) { return null; } } private static String sourceName(JCCompilationUnit cu) { return cu.sourcefile == null ? null : cu.sourcefile.toString(); } // jdk9 support, types have changed, names stay the same static class PackageName { private static final Method packageNameMethod; static { Method m = null; try { m = JCCompilationUnit.class.getDeclaredMethod("getPackageName"); } catch (Exception e) {} packageNameMethod = m; } static String getPackageName(JCCompilationUnit cu) { try { Object pkg = packageNameMethod.invoke(cu); return (pkg instanceof JCFieldAccess || pkg instanceof JCIdent) ? pkg.toString() : null; } catch (Exception e) {} return null; } } public Context getContext() { return context; } /** * Runs through the entire AST, starting at the compilation unit, calling the provided visitor's visit methods * for each node, depth first. */ public void traverse(JavacASTVisitor visitor) { top().traverse(visitor); } void traverseChildren(JavacASTVisitor visitor, JavacNode node) { for (JavacNode child : node.down()) child.traverse(visitor); } @Override public int getSourceVersion() { try { String nm = Source.instance(context).name(); int underscoreIdx = nm.indexOf('_'); if (underscoreIdx > -1) return Integer.parseInt(nm.substring(underscoreIdx + 1)); } catch (Exception ignore) {} return 6; } @Override public int getLatestJavaSpecSupported() { return Javac.getJavaCompilerVersion(); } /** @return A Name object generated for the proper name table belonging to this AST. */ public Name toName(String name) { return elements.getName(name); } /** @return A TreeMaker instance that you can use to create new AST nodes. */ public JavacTreeMaker getTreeMaker() { treeMaker.at(-1); return treeMaker; } /** @return The symbol table used by this AST for symbols. */ public Symtab getSymbolTable() { return symtab; } /** * @return The implementation of {@link javax.lang.model.util.Types} of javac. Contains a few extra methods beyond * the ones listed in the official annotation API interface. */ public JavacTypes getTypesUtil() { return javacTypes; } /** {@inheritDoc} */ @Override protected JavacNode buildTree(JCTree node, Kind kind) { switch (kind) { case COMPILATION_UNIT: return buildCompilationUnit((JCCompilationUnit) node); case TYPE: return buildType((JCClassDecl) node); case FIELD: return buildField((JCVariableDecl) node); case INITIALIZER: return buildInitializer((JCBlock) node); case METHOD: return buildMethod((JCMethodDecl) node); case ARGUMENT: return buildLocalVar((JCVariableDecl) node, kind); case LOCAL: return buildLocalVar((JCVariableDecl) node, kind); case STATEMENT: return buildStatementOrExpression(node); case ANNOTATION: return buildAnnotation((JCAnnotation) node, false); default: throw new AssertionError("Did not expect: " + kind); } } private JavacNode buildCompilationUnit(JCCompilationUnit top) { List childNodes = new ArrayList(); for (JCTree s : top.defs) { if (s instanceof JCClassDecl) { addIfNotNull(childNodes, buildType((JCClassDecl) s)); } // else they are import statements, which we don't care about. Or Skip objects, whatever those are. } return new JavacNode(this, top, childNodes, Kind.COMPILATION_UNIT); } private JavacNode buildType(JCClassDecl type) { if (setAndGetAsHandled(type)) return null; List childNodes = new ArrayList(); for (JCAnnotation annotation : type.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation, false)); for (JCTree def : type.defs) { /* A def can be: * JCClassDecl for inner types * JCMethodDecl for constructors and methods * JCVariableDecl for fields * JCBlock for (static) initializers */ if (def instanceof JCMethodDecl) addIfNotNull(childNodes, buildMethod((JCMethodDecl) def)); else if (def instanceof JCClassDecl) addIfNotNull(childNodes, buildType((JCClassDecl) def)); else if (def instanceof JCVariableDecl) addIfNotNull(childNodes, buildField((JCVariableDecl) def)); else if (def instanceof JCBlock) addIfNotNull(childNodes, buildInitializer((JCBlock) def)); } return putInMap(new JavacNode(this, type, childNodes, Kind.TYPE)); } private JavacNode buildField(JCVariableDecl field) { if (setAndGetAsHandled(field)) return null; List childNodes = new ArrayList(); for (JCAnnotation annotation : field.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation, true)); addIfNotNull(childNodes, buildExpression(field.init)); return putInMap(new JavacNode(this, field, childNodes, Kind.FIELD)); } private JavacNode buildLocalVar(JCVariableDecl local, Kind kind) { if (setAndGetAsHandled(local)) return null; List childNodes = new ArrayList(); for (JCAnnotation annotation : local.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation, true)); addIfNotNull(childNodes, buildExpression(local.init)); return putInMap(new JavacNode(this, local, childNodes, kind)); } private static boolean JCTRY_RESOURCES_FIELD_INITIALIZED; private static Field JCTRY_RESOURCES_FIELD; @SuppressWarnings("unchecked") private static List getResourcesForTryNode(JCTry tryNode) { if (!JCTRY_RESOURCES_FIELD_INITIALIZED) { try { JCTRY_RESOURCES_FIELD = JCTry.class.getField("resources"); } catch (NoSuchFieldException ignore) { // Java 1.6 or lower won't have this at all. } catch (Exception ignore) { // Shouldn't happen. Best thing we can do is just carry on and break on try/catch. } JCTRY_RESOURCES_FIELD_INITIALIZED = true; } if (JCTRY_RESOURCES_FIELD == null) return Collections.emptyList(); Object rv = null; try { rv = JCTRY_RESOURCES_FIELD.get(tryNode); } catch (Exception ignore) {} if (rv instanceof List) return (List) rv; return Collections.emptyList(); } private JavacNode buildTry(JCTry tryNode) { if (setAndGetAsHandled(tryNode)) return null; List childNodes = new ArrayList(); for (JCTree varDecl : getResourcesForTryNode(tryNode)) { if (varDecl instanceof JCVariableDecl) { addIfNotNull(childNodes, buildLocalVar((JCVariableDecl) varDecl, Kind.LOCAL)); } } addIfNotNull(childNodes, buildStatement(tryNode.body)); for (JCCatch jcc : tryNode.catchers) addIfNotNull(childNodes, buildTree(jcc, Kind.STATEMENT)); addIfNotNull(childNodes, buildStatement(tryNode.finalizer)); return putInMap(new JavacNode(this, tryNode, childNodes, Kind.STATEMENT)); } private JavacNode buildInitializer(JCBlock initializer) { if (setAndGetAsHandled(initializer)) return null; List childNodes = new ArrayList(); for (JCStatement statement: initializer.stats) addIfNotNull(childNodes, buildStatement(statement)); return putInMap(new JavacNode(this, initializer, childNodes, Kind.INITIALIZER)); } private JavacNode buildMethod(JCMethodDecl method) { if (setAndGetAsHandled(method)) return null; List childNodes = new ArrayList(); for (JCAnnotation annotation : method.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation, false)); for (JCVariableDecl param : method.params) addIfNotNull(childNodes, buildLocalVar(param, Kind.ARGUMENT)); if (method.body != null && method.body.stats != null) { for (JCStatement statement : method.body.stats) addIfNotNull(childNodes, buildStatement(statement)); } return putInMap(new JavacNode(this, method, childNodes, Kind.METHOD)); } private JavacNode buildAnnotation(JCAnnotation annotation, boolean varDecl) { boolean handled = setAndGetAsHandled(annotation); if (!varDecl && handled) { // @Foo int x, y; is handled in javac by putting the same annotation node on 2 JCVariableDecls. return null; } return putInMap(new JavacNode(this, annotation, null, Kind.ANNOTATION)); } private JavacNode buildExpression(JCExpression expression) { return buildStatementOrExpression(expression); } private JavacNode buildStatement(JCStatement statement) { return buildStatementOrExpression(statement); } private JavacNode buildStatementOrExpression(JCTree statement) { if (statement == null) return null; if (statement instanceof JCAnnotation) return null; if (statement instanceof JCClassDecl) return buildType((JCClassDecl)statement); if (statement instanceof JCVariableDecl) return buildLocalVar((JCVariableDecl)statement, Kind.LOCAL); if (statement instanceof JCTry) return buildTry((JCTry) statement); if (statement.getClass().getSimpleName().equals("JCLambda")) return buildLambda(statement); if (setAndGetAsHandled(statement)) return null; return drill(statement); } private JavacNode buildLambda(JCTree jcTree) { return buildStatementOrExpression(getBody(jcTree)); } private JCTree getBody(JCTree jcTree) { try { return (JCTree) getBodyMethod(jcTree.getClass()).invoke(jcTree); } catch (Exception e) { throw Javac.sneakyThrow(e); } } private final static ConcurrentMap, Method> getBodyMethods = new ConcurrentHashMap, Method>(); private Method getBodyMethod(Class c) { Method m = getBodyMethods.get(c); if (m != null) { return m; } try { m = c.getMethod("getBody"); } catch (NoSuchMethodException e) { throw Javac.sneakyThrow(e); } getBodyMethods.putIfAbsent(c, m); return getBodyMethods.get(c); } private JavacNode drill(JCTree statement) { try { List childNodes = new ArrayList(); for (FieldAccess fa : fieldsOf(statement.getClass())) childNodes.addAll(buildWithField(JavacNode.class, statement, fa)); return putInMap(new JavacNode(this, statement, childNodes, Kind.STATEMENT)); } catch (OutOfMemoryError oome) { String msg = oome.getMessage(); if (msg == null) msg = "(no original message)"; OutOfMemoryError newError = new OutOfMemoryError(getFileName() + "@pos" + statement.getPreferredPosition() + ": " + msg); // We could try to set the stack trace of the new exception to the same one as the old exception, but this costs memory, // and we're already in an extremely fragile situation in regards to remaining heap space, so let's not do that. throw newError; } } /* For javac, both JCExpression and JCStatement are considered as valid children types. */ private static Collection> statementTypes() { Collection> collection = new ArrayList>(3); collection.add(JCStatement.class); collection.add(JCExpression.class); collection.add(JCCatch.class); return collection; } private static void addIfNotNull(Collection nodes, JavacNode node) { if (node != null) nodes.add(node); } /** * Attempts to remove any compiler errors generated by java whose reporting position is located anywhere between the start and end of the supplied node. */ void removeDeferredErrors(JavacNode node) { DiagnosticPosition pos = node.get().pos(); JCCompilationUnit top = (JCCompilationUnit) top().get(); removeFromDeferredDiagnostics(pos.getStartPosition(), Javac.getEndPosition(pos, top)); } /** Supply either a position or a node (in that case, position of the node is used) */ void printMessage(Diagnostic.Kind kind, String message, JavacNode node, DiagnosticPosition pos, boolean attemptToRemoveErrorsInRange) { JavaFileObject oldSource = null; JavaFileObject newSource = null; JCTree astObject = node == null ? null : node.get(); JCCompilationUnit top = (JCCompilationUnit) top().get(); newSource = top.sourcefile; if (newSource != null) { oldSource = log.useSource(newSource); if (pos == null) pos = astObject.pos(); } if (pos != null && attemptToRemoveErrorsInRange) { removeFromDeferredDiagnostics(pos.getStartPosition(), node.getEndPosition(pos)); } try { switch (kind) { case ERROR: errorLogger.error(pos, message); break; case MANDATORY_WARNING: errorLogger.mandatoryWarning(pos, message); break; case WARNING: errorLogger.warning(pos, message); break; default: case NOTE: errorLogger.note(pos, message); break; } } finally { if (newSource != null) log.useSource(oldSource); } } public void removeFromDeferredDiagnostics(int startPos, int endPos) { JCCompilationUnit self = (JCCompilationUnit) top().get(); new CompilerMessageSuppressor(getContext()).removeAllBetween(self.sourcefile, startPos, endPos); } /** {@inheritDoc} */ @Override protected void setElementInASTCollection(Field field, Object refField, List> chain, Collection collection, int idx, JCTree newN) throws IllegalAccessException { com.sun.tools.javac.util.List list = setElementInConsList(chain, collection, ((List)collection).get(idx), newN); field.set(refField, list); } private com.sun.tools.javac.util.List setElementInConsList(List> chain, Collection current, Object oldO, Object newO) { com.sun.tools.javac.util.List oldL = (com.sun.tools.javac.util.List) current; com.sun.tools.javac.util.List newL = replaceInConsList(oldL, oldO, newO); if (chain.isEmpty()) return newL; List> reducedChain = new ArrayList>(chain); Collection newCurrent = reducedChain.remove(reducedChain.size() -1); return setElementInConsList(reducedChain, newCurrent, oldL, newL); } private com.sun.tools.javac.util.List replaceInConsList(com.sun.tools.javac.util.List oldL, Object oldO, Object newO) { boolean repl = false; Object[] a = oldL.toArray(); for (int i = 0; i < a.length; i++) { if (a[i] == oldO) { a[i] = newO; repl = true; } } if (repl) return com.sun.tools.javac.util.List.from(a); return oldL; } abstract static class ErrorLog { final Log log; private final Messager messager; private final Field errorCount; private final Field warningCount; private ErrorLog(Log log, Messager messager, Field errorCount, Field warningCount) { this.log = log; this.messager = messager; this.errorCount = errorCount; this.warningCount = warningCount; } final void error(DiagnosticPosition pos, String message) { increment(errorCount); error1(pos, message); } final void warning(DiagnosticPosition pos, String message) { increment(warningCount); log.warning(pos, "proc.messager", message); } final void mandatoryWarning(DiagnosticPosition pos, String message) { increment(warningCount); log.mandatoryWarning(pos, "proc.messager", message); } final void note(DiagnosticPosition pos, String message) { log.note(pos, "proc.messager", message); } abstract void error1(DiagnosticPosition pos, String message); private void increment(Field field) { if (field == null) return; try { int val = ((Number)field.get(messager)).intValue(); field.set(messager, val +1); } catch (Throwable t) { //Very unfortunate, but in most cases it still works fine, so we'll silently swallow it. } } static ErrorLog create(Messager messager, Log log) { Field errorCount = null; try { Field f = messager.getClass().getDeclaredField("errorCount"); f.setAccessible(true); errorCount = f; } catch (Throwable t) {} boolean hasMultipleErrors = false; for (Field field : log.getClass().getFields()) { if (field.getName().equals("multipleErrors")) { hasMultipleErrors = true; break; } } if (hasMultipleErrors) return new JdkBefore9(log, messager, errorCount); Field warningCount = null; try { Field f = messager.getClass().getDeclaredField("warningCount"); f.setAccessible(true); warningCount = f; } catch (Throwable t) {} Method logMethod = null; Object multiple = null; try { Class df = Class.forName("com.sun.tools.javac.util.JCDiagnostic$DiagnosticFlag"); for (Object constant : df.getEnumConstants()) { if (constant.toString().equals("MULTIPLE")) multiple = constant; } logMethod = log.getClass().getMethod("error", new Class[] {df, DiagnosticPosition.class, String.class, Object[].class}); } catch (Throwable t) {} return new Jdk9Plus(log, messager, errorCount, warningCount, logMethod, multiple); } } static class JdkBefore9 extends ErrorLog { private JdkBefore9(Log log, Messager messager, Field errorCount) { super(log, messager, errorCount, null); } @Override void error1(DiagnosticPosition pos, String message) { boolean prev = log.multipleErrors; log.multipleErrors = true; try { log.error(pos, "proc.messager", message); } finally { log.multipleErrors = prev; } } } static class Jdk9Plus extends ErrorLog { private final Object multiple; private final Method logMethod; private Jdk9Plus(Log log, Messager messager, Field errorCount, Field warningCount, Method logMethod, Object multiple) { super(log, messager, errorCount, warningCount); this.logMethod = logMethod; this.multiple = multiple; } @Override void error1(DiagnosticPosition pos, String message) { try { logMethod.invoke(multiple, pos, "proc.messager", message); } catch (Throwable t) {} } } } lombok-1.16.18/src/core/lombok/javac/JavacASTAdapter.java000066400000000000000000000105041312655740700230130ustar00rootroot00000000000000/* * Copyright (C) 2009-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import com.sun.source.util.Trees; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; /** * Standard adapter for the {@link JavacASTVisitor} interface. Every method on that interface * has been implemented with an empty body. Override whichever methods you need. */ public class JavacASTAdapter implements JavacASTVisitor { /** {@inheritDoc} */ @Override public void setTrees(Trees trees) {} /** {@inheritDoc} */ @Override public void visitCompilationUnit(JavacNode top, JCCompilationUnit unit) {} /** {@inheritDoc} */ @Override public void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit) {} /** {@inheritDoc} */ @Override public void visitType(JavacNode typeNode, JCClassDecl type) {} /** {@inheritDoc} */ @Override public void visitAnnotationOnType(JCClassDecl type, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ @Override public void endVisitType(JavacNode typeNode, JCClassDecl type) {} /** {@inheritDoc} */ @Override public void visitField(JavacNode fieldNode, JCVariableDecl field) {} /** {@inheritDoc} */ @Override public void visitAnnotationOnField(JCVariableDecl field, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ @Override public void endVisitField(JavacNode fieldNode, JCVariableDecl field) {} /** {@inheritDoc} */ @Override public void visitInitializer(JavacNode initializerNode, JCBlock initializer) {} /** {@inheritDoc} */ @Override public void endVisitInitializer(JavacNode initializerNode, JCBlock initializer) {} /** {@inheritDoc} */ @Override public void visitMethod(JavacNode methodNode, JCMethodDecl method) {} /** {@inheritDoc} */ @Override public void visitAnnotationOnMethod(JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ @Override public void endVisitMethod(JavacNode methodNode, JCMethodDecl method) {} /** {@inheritDoc} */ @Override public void visitMethodArgument(JavacNode argumentNode, JCVariableDecl argument, JCMethodDecl method) {} /** {@inheritDoc} */ @Override public void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ @Override public void endVisitMethodArgument(JavacNode argumentNode, JCVariableDecl argument, JCMethodDecl method) {} /** {@inheritDoc} */ @Override public void visitLocal(JavacNode localNode, JCVariableDecl local) {} /** {@inheritDoc} */ @Override public void visitAnnotationOnLocal(JCVariableDecl local, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ @Override public void endVisitLocal(JavacNode localNode, JCVariableDecl local) {} /** {@inheritDoc} */ @Override public void visitStatement(JavacNode statementNode, JCTree statement) {} /** {@inheritDoc} */ @Override public void endVisitStatement(JavacNode statementNode, JCTree statement) {} } lombok-1.16.18/src/core/lombok/javac/JavacASTVisitor.java000066400000000000000000000230321312655740700230720ustar00rootroot00000000000000/* * Copyright (C) 2009-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.io.PrintStream; import com.sun.source.util.Trees; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; /** * Implement so you can ask any JavacAST.LombokNode to traverse depth-first through all children, * calling the appropriate visit and endVisit methods. */ public interface JavacASTVisitor { void setTrees(Trees trees); /** * Called at the very beginning and end. */ void visitCompilationUnit(JavacNode top, JCCompilationUnit unit); void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit); /** * Called when visiting a type (a class, interface, annotation, enum, etcetera). */ void visitType(JavacNode typeNode, JCClassDecl type); void visitAnnotationOnType(JCClassDecl type, JavacNode annotationNode, JCAnnotation annotation); void endVisitType(JavacNode typeNode, JCClassDecl type); /** * Called when visiting a field of a class. */ void visitField(JavacNode fieldNode, JCVariableDecl field); void visitAnnotationOnField(JCVariableDecl field, JavacNode annotationNode, JCAnnotation annotation); void endVisitField(JavacNode fieldNode, JCVariableDecl field); /** * Called for static and instance initializers. You can tell the difference via the isStatic() method. */ void visitInitializer(JavacNode initializerNode, JCBlock initializer); void endVisitInitializer(JavacNode initializerNode, JCBlock initializer); /** * Called for both methods and constructors. */ void visitMethod(JavacNode methodNode, JCMethodDecl method); void visitAnnotationOnMethod(JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation); void endVisitMethod(JavacNode methodNode, JCMethodDecl method); /** * Visits a method argument. */ void visitMethodArgument(JavacNode argumentNode, JCVariableDecl argument, JCMethodDecl method); void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation); void endVisitMethodArgument(JavacNode argumentNode, JCVariableDecl argument, JCMethodDecl method); /** * Visits a local declaration - that is, something like 'int x = 10;' on the method level. Also called * for method parameters. */ void visitLocal(JavacNode localNode, JCVariableDecl local); void visitAnnotationOnLocal(JCVariableDecl local, JavacNode annotationNode, JCAnnotation annotation); void endVisitLocal(JavacNode localNode, JCVariableDecl local); /** * Visits a statement that isn't any of the other visit methods (e.g. JCClassDecl). * The statement object is guaranteed to be either a JCStatement or a JCExpression. */ void visitStatement(JavacNode statementNode, JCTree statement); void endVisitStatement(JavacNode statementNode, JCTree statement); /** * Prints the structure of an AST. */ public static class Printer implements JavacASTVisitor { private final PrintStream out; private final boolean printContent; private int disablePrinting = 0; private int indent = 0; /** * @param printContent if true, bodies are printed directly, as java code, * instead of a tree listing of every AST node inside it. */ public Printer(boolean printContent) { this(printContent, System.out); } /** * @param printContent if true, bodies are printed directly, as java code, * instead of a tree listing of every AST node inside it. * @param out write output to this stream. You must close it yourself. flush() is called after every line. * * @see java.io.PrintStream#flush() */ public Printer(boolean printContent, PrintStream out) { this.printContent = printContent; this.out = out; } @Override public void setTrees(Trees trees) {} private void forcePrint(String text, Object... params) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; i++) sb.append(" "); out.printf(sb.append(text).append('\n').toString(), params); out.flush(); } private void print(String text, Object... params) { if (disablePrinting == 0) forcePrint(text, params); } @Override public void visitCompilationUnit(JavacNode LombokNode, JCCompilationUnit unit) { out.println("---------------------------------------------------------"); print("", LombokNode.getFileName()); indent++; } @Override public void endVisitCompilationUnit(JavacNode node, JCCompilationUnit unit) { indent--; print(""); } @Override public void visitType(JavacNode node, JCClassDecl type) { print("", type.name); indent++; if (printContent) { print("%s", type); disablePrinting++; } } @Override public void visitAnnotationOnType(JCClassDecl type, JavacNode node, JCAnnotation annotation) { forcePrint("", annotation); } @Override public void endVisitType(JavacNode node, JCClassDecl type) { if (printContent) disablePrinting--; indent--; print("", type.name); } @Override public void visitInitializer(JavacNode node, JCBlock initializer) { print("<%s INITIALIZER>", initializer.isStatic() ? "static" : "instance"); indent++; if (printContent) { print("%s", initializer); disablePrinting++; } } @Override public void endVisitInitializer(JavacNode node, JCBlock initializer) { if (printContent) disablePrinting--; indent--; print("", initializer.isStatic() ? "static" : "instance"); } @Override public void visitField(JavacNode node, JCVariableDecl field) { print("", field.vartype, field.name); indent++; if (printContent) { if (field.init != null) print("%s", field.init); disablePrinting++; } } @Override public void visitAnnotationOnField(JCVariableDecl field, JavacNode node, JCAnnotation annotation) { forcePrint("", annotation); } @Override public void endVisitField(JavacNode node, JCVariableDecl field) { if (printContent) disablePrinting--; indent--; print("", field.vartype, field.name); } @Override public void visitMethod(JavacNode node, JCMethodDecl method) { final String type; if (method.name.contentEquals("")) { if ((method.mods.flags & Flags.GENERATEDCONSTR) != 0) { type = "DEFAULTCONSTRUCTOR"; } else type = "CONSTRUCTOR"; } else type = "METHOD"; print("<%s %s> returns: %s", type, method.name, method.restype); indent++; if (printContent) { if (method.body == null) print("(ABSTRACT)"); else print("%s", method.body); disablePrinting++; } } @Override public void visitAnnotationOnMethod(JCMethodDecl method, JavacNode node, JCAnnotation annotation) { forcePrint("", annotation); } @Override public void endVisitMethod(JavacNode node, JCMethodDecl method) { if (printContent) disablePrinting--; indent--; print("", "XMETHOD", method.name); } @Override public void visitMethodArgument(JavacNode node, JCVariableDecl arg, JCMethodDecl method) { print("", arg.vartype, arg.name); indent++; } @Override public void visitAnnotationOnMethodArgument(JCVariableDecl arg, JCMethodDecl method, JavacNode nodeAnnotation, JCAnnotation annotation) { forcePrint("", annotation); } @Override public void endVisitMethodArgument(JavacNode node, JCVariableDecl arg, JCMethodDecl method) { indent--; print("", arg.vartype, arg.name); } @Override public void visitLocal(JavacNode node, JCVariableDecl local) { print("", local.vartype, local.name); indent++; } @Override public void visitAnnotationOnLocal(JCVariableDecl local, JavacNode node, JCAnnotation annotation) { print("", annotation); } @Override public void endVisitLocal(JavacNode node, JCVariableDecl local) { indent--; print("", local.vartype, local.name); } @Override public void visitStatement(JavacNode node, JCTree statement) { print("<%s>", statement.getClass()); indent++; print("%s", statement); } @Override public void endVisitStatement(JavacNode node, JCTree statement) { indent--; print("", statement.getClass()); } } } lombok-1.16.18/src/core/lombok/javac/JavacAnnotationHandler.java000066400000000000000000000064331312655740700245010ustar00rootroot00000000000000/* * Copyright (C) 2009-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.lang.annotation.Annotation; import lombok.core.AnnotationValues; import lombok.core.SpiLoadUtil; import com.sun.source.util.Trees; import com.sun.tools.javac.tree.JCTree.JCAnnotation; /** * Implement this interface if you want to be triggered for a specific annotation. * * You MUST replace 'T' with a specific annotation type, such as: * * {@code public class HandleGetter extends JavacAnnotationHandler} * * Because this generics parameter is inspected to figure out which class you're interested in. * * You also need to register yourself via SPI discovery as being an implementation of {@code JavacAnnotationHandler}. */ public abstract class JavacAnnotationHandler { protected Trees trees; /** * Called when an annotation is found that is likely to match the annotation you're interested in. * * Be aware that you'll be called for ANY annotation node in the source that looks like a match. There is, * for example, no guarantee that the annotation node belongs to a method, even if you set your * TargetType in the annotation to methods only. * * @param annotation The actual annotation - use this object to retrieve the annotation parameters. * @param ast The javac AST node representing the annotation. * @param annotationNode The Lombok AST wrapper around the 'ast' parameter. You can use this object * to travel back up the chain (something javac AST can't do) to the parent of the annotation, as well * as access useful methods such as generating warnings or errors focused on the annotation. */ public abstract void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode); /** * This handler is a handler for the given annotation; you don't normally need to override this class * as the annotation type is extracted from your {@code extends EclipseAnnotationHandler} * signature. */ @SuppressWarnings("unchecked") public Class getAnnotationHandledByThisHandler() { return (Class) SpiLoadUtil.findAnnotationClass(getClass(), JavacAnnotationHandler.class); } public void setTrees(Trees trees) { this.trees = trees; } } lombok-1.16.18/src/core/lombok/javac/JavacAugments.java000066400000000000000000000031311312655740700226440ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import lombok.core.FieldAugment; import com.sun.tools.javac.tree.JCTree; public final class JavacAugments { private JavacAugments() { // Prevent instantiation } public static final FieldAugment JCTree_handled = FieldAugment.augment(JCTree.class, boolean.class, "lombok$handled"); public static final FieldAugment JCTree_generatedNode = FieldAugment.circularSafeAugment(JCTree.class, JCTree.class, "lombok$generatedNode"); } lombok-1.16.18/src/core/lombok/javac/JavacImportList.java000066400000000000000000000106501312655740700231730ustar00rootroot00000000000000/* * Copyright (C) 2013-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.util.ArrayList; import java.util.Collection; import lombok.core.ImportList; import lombok.core.LombokInternalAliasing; import lombok.javac.JavacAST.PackageName; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCImport; import com.sun.tools.javac.util.List; public class JavacImportList implements ImportList { private final String pkgStr; private final List defs; public JavacImportList(JCCompilationUnit cud) { this.pkgStr = PackageName.getPackageName(cud); this.defs = cud.defs; } @Override public String getFullyQualifiedNameForSimpleName(String unqualified) { for (JCTree def : defs) { if (!(def instanceof JCImport)) continue; JCTree qual = ((JCImport) def).qualid; if (!(qual instanceof JCFieldAccess)) continue; String simpleName = ((JCFieldAccess) qual).name.toString(); if (simpleName.equals(unqualified)) { return LombokInternalAliasing.processAliases(qual.toString()); } } return null; } @Override public boolean hasStarImport(String packageName) { if (pkgStr != null && pkgStr.equals(packageName)) return true; if ("java.lang".equals(packageName)) return true; if (pkgStr != null) { Collection extra = LombokInternalAliasing.IMPLIED_EXTRA_STAR_IMPORTS.get(pkgStr); if (extra != null && extra.contains(packageName)) return true; } for (JCTree def : defs) { if (!(def instanceof JCImport)) continue; if (((JCImport) def).staticImport) continue; JCTree qual = ((JCImport) def).qualid; if (!(qual instanceof JCFieldAccess)) continue; String simpleName = ((JCFieldAccess) qual).name.toString(); if (!"*".equals(simpleName)) continue; String starImport = ((JCFieldAccess) qual).selected.toString(); if (packageName.equals(starImport)) return true; Collection extra = LombokInternalAliasing.IMPLIED_EXTRA_STAR_IMPORTS.get(starImport); if (extra != null && extra.contains(packageName)) return true; } return false; } @Override public Collection applyNameToStarImports(String startsWith, String name) { ArrayList out = new ArrayList(); if (pkgStr != null && topLevelName(pkgStr).equals(startsWith)) out.add(pkgStr + "." + name); for (JCTree def : defs) { if (!(def instanceof JCImport)) continue; if (((JCImport) def).staticImport) continue; JCTree qual = ((JCImport) def).qualid; if (!(qual instanceof JCFieldAccess)) continue; String simpleName = ((JCFieldAccess) qual).name.toString(); if (!"*".equals(simpleName)) continue; String topLevelName = topLevelName(qual); if (topLevelName.equals(startsWith)) { out.add(((JCFieldAccess) qual).selected.toString() + "." + name); } } return out; } private String topLevelName(JCTree tree) { while (tree instanceof JCFieldAccess) tree = ((JCFieldAccess) tree).selected; return tree.toString(); } private String topLevelName(String packageName) { int idx = packageName.indexOf("."); if (idx == -1) return packageName; return packageName.substring(0, idx); } @Override public String applyUnqualifiedNameToPackage(String unqualified) { if (pkgStr == null) return unqualified; return pkgStr + "." + unqualified; } } lombok-1.16.18/src/core/lombok/javac/JavacNode.java000066400000000000000000000206551312655740700217600ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.util.List; import javax.lang.model.element.Element; import javax.tools.Diagnostic; import lombok.core.AST.Kind; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.model.JavacTypes; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; /** * Javac specific version of the LombokNode class. */ public class JavacNode extends lombok.core.LombokNode { /** * Passes through to the parent constructor. */ public JavacNode(JavacAST ast, JCTree node, List children, Kind kind) { super(ast, node, children, kind); } public Element getElement() { if (node instanceof JCClassDecl) return ((JCClassDecl) node).sym; if (node instanceof JCMethodDecl) return ((JCMethodDecl) node).sym; if (node instanceof JCVariableDecl) return ((JCVariableDecl) node).sym; return null; } public int getEndPosition(DiagnosticPosition pos) { JCCompilationUnit cu = (JCCompilationUnit) top().get(); return Javac.getEndPosition(pos, cu); } public int getEndPosition() { return getEndPosition(node); } /** * Visits this node and all child nodes depth-first, calling the provided visitor's visit methods. */ public void traverse(JavacASTVisitor visitor) { switch (this.getKind()) { case COMPILATION_UNIT: visitor.visitCompilationUnit(this, (JCCompilationUnit) get()); ast.traverseChildren(visitor, this); visitor.endVisitCompilationUnit(this, (JCCompilationUnit) get()); break; case TYPE: visitor.visitType(this, (JCClassDecl) get()); ast.traverseChildren(visitor, this); visitor.endVisitType(this, (JCClassDecl) get()); break; case FIELD: visitor.visitField(this, (JCVariableDecl) get()); ast.traverseChildren(visitor, this); visitor.endVisitField(this, (JCVariableDecl) get()); break; case METHOD: visitor.visitMethod(this, (JCMethodDecl) get()); ast.traverseChildren(visitor, this); visitor.endVisitMethod(this, (JCMethodDecl) get()); break; case INITIALIZER: visitor.visitInitializer(this, (JCBlock) get()); ast.traverseChildren(visitor, this); visitor.endVisitInitializer(this, (JCBlock) get()); break; case ARGUMENT: JCMethodDecl parentMethod = (JCMethodDecl) up().get(); visitor.visitMethodArgument(this, (JCVariableDecl) get(), parentMethod); ast.traverseChildren(visitor, this); visitor.endVisitMethodArgument(this, (JCVariableDecl) get(), parentMethod); break; case LOCAL: visitor.visitLocal(this, (JCVariableDecl) get()); ast.traverseChildren(visitor, this); visitor.endVisitLocal(this, (JCVariableDecl) get()); break; case STATEMENT: visitor.visitStatement(this, get()); ast.traverseChildren(visitor, this); visitor.endVisitStatement(this, get()); break; case ANNOTATION: switch (up().getKind()) { case TYPE: visitor.visitAnnotationOnType((JCClassDecl) up().get(), this, (JCAnnotation) get()); break; case FIELD: visitor.visitAnnotationOnField((JCVariableDecl) up().get(), this, (JCAnnotation) get()); break; case METHOD: visitor.visitAnnotationOnMethod((JCMethodDecl) up().get(), this, (JCAnnotation) get()); break; case ARGUMENT: JCVariableDecl argument = (JCVariableDecl) up().get(); JCMethodDecl method = (JCMethodDecl) up().up().get(); visitor.visitAnnotationOnMethodArgument(argument, method, this, (JCAnnotation) get()); break; case LOCAL: visitor.visitAnnotationOnLocal((JCVariableDecl) up().get(), this, (JCAnnotation) get()); break; default: throw new AssertionError("Annotion not expected as child of a " + up().getKind()); } break; default: throw new AssertionError("Unexpected kind during node traversal: " + getKind()); } } /** {@inheritDoc} */ @Override public String getName() { final Name n; if (node instanceof JCClassDecl) n = ((JCClassDecl) node).name; else if (node instanceof JCMethodDecl) n = ((JCMethodDecl) node).name; else if (node instanceof JCVariableDecl) n = ((JCVariableDecl) node).name; else n = null; return n == null ? null : n.toString(); } /** {@inheritDoc} */ @Override protected boolean calculateIsStructurallySignificant(JCTree parent) { if (node instanceof JCClassDecl) return true; if (node instanceof JCMethodDecl) return true; if (node instanceof JCVariableDecl) return true; if (node instanceof JCCompilationUnit) return true; //Static and instance initializers if (node instanceof JCBlock) return parent instanceof JCClassDecl; return false; } @Override protected boolean fieldContainsAnnotation(JCTree field, JCTree annotation) { if (!(field instanceof JCVariableDecl)) return false; JCVariableDecl f = (JCVariableDecl) field; if (f.mods.annotations == null) return false; for (JCAnnotation childAnnotation : f.mods.annotations) { if (childAnnotation == annotation) return true; } return false; } /** * Convenient shortcut to the owning JavacAST object's getTreeMaker method. * * @see JavacAST#getTreeMaker() */ public JavacTreeMaker getTreeMaker() { return ast.getTreeMaker(); } /** * Convenient shortcut to the owning JavacAST object's getSymbolTable method. * * @see JavacAST#getSymbolTable() */ public Symtab getSymbolTable() { return ast.getSymbolTable(); } /** * Convenient shortcut to the owning JavacAST object's getTypesUtil method. * * @see JavacAST#getTypesUtil() */ public JavacTypes getTypesUtil() { return ast.getTypesUtil(); } /** * Convenient shortcut to the owning JavacAST object's getContext method. * * @see JavacAST#getContext() */ public Context getContext() { return ast.getContext(); } public boolean shouldDeleteLombokAnnotations() { return LombokOptions.shouldDeleteLombokAnnotations(ast.getContext()); } /** * Convenient shortcut to the owning JavacAST object's toName method. * * @see JavacAST#toName(String) */ public Name toName(String name) { return ast.toName(name); } public void removeDeferredErrors() { ast.removeDeferredErrors(this); } /** * Generates an compiler error focused on the AST node represented by this node object. */ @Override public void addError(String message) { ast.printMessage(Diagnostic.Kind.ERROR, message, this, null, true); } /** * Generates an compiler error focused on the AST node represented by this node object. */ public void addError(String message, DiagnosticPosition pos) { ast.printMessage(Diagnostic.Kind.ERROR, message, null, pos, true); } /** * Generates a compiler warning focused on the AST node represented by this node object. */ @Override public void addWarning(String message) { ast.printMessage(Diagnostic.Kind.WARNING, message, this, null, false); } /** * Generates a compiler warning focused on the AST node represented by this node object. */ public void addWarning(String message, DiagnosticPosition pos) { ast.printMessage(Diagnostic.Kind.WARNING, message, null, pos, false); } } lombok-1.16.18/src/core/lombok/javac/JavacResolution.java000066400000000000000000000350271312655740700232350ustar00rootroot00000000000000/* * Copyright (C) 2011-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import static lombok.javac.Javac.*; import static lombok.javac.JavacTreeMaker.TypeTag.typeTag; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayDeque; import java.util.Map; import javax.lang.model.type.TypeKind; import lombok.Lombok; import lombok.core.debug.AssertionLogger; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ArrayType; import com.sun.tools.javac.code.Type.CapturedType; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Type.WildcardType; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.comp.Attr; import com.sun.tools.javac.comp.AttrContext; import com.sun.tools.javac.comp.Enter; import com.sun.tools.javac.comp.Env; import com.sun.tools.javac.comp.MemberEnter; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; public class JavacResolution { private final Attr attr; private final CompilerMessageSuppressor messageSuppressor; public JavacResolution(Context context) { attr = Attr.instance(context); messageSuppressor = new CompilerMessageSuppressor(context); } /* * We need to dig down to the level of the method or field declaration or (static) initializer block, then attribute that entire method/field/block using * the appropriate environment. So, we start from the top and walk down the node tree until we hit that method/field/block and stop there, recording both * the environment object (`env`) and the exact tree node (`copyAt`) at which to begin the attr process. */ private static final class EnvFinder extends JCTree.Visitor { private Env env = null; private Enter enter; private MemberEnter memberEnter; private JCTree copyAt = null; EnvFinder(Context context) { this.enter = Enter.instance(context); this.memberEnter = MemberEnter.instance(context); } Env get() { return env; } JCTree copyAt() { return copyAt; } @Override public void visitTopLevel(JCCompilationUnit tree) { if (copyAt != null) return; env = enter.getTopLevelEnv(tree); } @Override public void visitClassDef(JCClassDecl tree) { if (copyAt != null) return; if (tree.sym != null) env = enter.getClassEnv(tree.sym); } @Override public void visitMethodDef(JCMethodDecl tree) { if (copyAt != null) return; env = memberEnter.getMethodEnv(tree, env); copyAt = tree; } public void visitVarDef(JCVariableDecl tree) { if (copyAt != null) return; env = memberEnter.getInitEnv(tree, env); copyAt = tree; } @Override public void visitBlock(JCBlock tree) { if (copyAt != null) return; copyAt = tree; } @Override public void visitTree(JCTree that) { } } public Map resolveMethodMember(JavacNode node) { ArrayDeque stack = new ArrayDeque(); { JavacNode n = node; while (n != null) { stack.push(n.get()); n = n.up(); } } messageSuppressor.disableLoggers(); try { EnvFinder finder = new EnvFinder(node.getContext()); while (!stack.isEmpty()) stack.pop().accept(finder); TreeMirrorMaker mirrorMaker = new TreeMirrorMaker(node.getTreeMaker(), node.getContext()); JCTree copy = mirrorMaker.copy(finder.copyAt()); memberEnterAndAttribute(copy, finder.get(), node.getContext()); return mirrorMaker.getOriginalToCopyMap(); } finally { messageSuppressor.enableLoggers(); } } private static Field memberEnterDotEnv; private static Field getMemberEnterDotEnv() { if (memberEnterDotEnv != null) return memberEnterDotEnv; try { Field f = MemberEnter.class.getDeclaredField("env"); f.setAccessible(true); memberEnterDotEnv = f; } catch (NoSuchFieldException e) { return null; } return memberEnterDotEnv; } @SuppressWarnings("unchecked") private static Env getEnvOfMemberEnter(MemberEnter memberEnter) { Field f = getMemberEnterDotEnv(); try { return (Env) f.get(memberEnter); } catch (Exception e) { return null; } } private static void setEnvOfMemberEnter(MemberEnter memberEnter, Env env) { Field f = getMemberEnterDotEnv(); try { f.set(memberEnter, env); } catch (Exception e) { return; } } private void memberEnterAndAttribute(JCTree copy, Env env, Context context) { MemberEnter memberEnter = MemberEnter.instance(context); Env oldEnv = getEnvOfMemberEnter(memberEnter); setEnvOfMemberEnter(memberEnter, env); try { copy.accept(memberEnter); } catch (Exception ignore) { // intentionally ignored; usually even if this step fails, val will work (but not for val in method local inner classes and anonymous inner classes). AssertionLogger.assertLog("member enter failed.", ignore); } finally { setEnvOfMemberEnter(memberEnter, oldEnv); } attrib(copy, env); } public void resolveClassMember(JavacNode node) { ArrayDeque stack = new ArrayDeque(); { JavacNode n = node; while (n != null) { stack.push(n.get()); n = n.up(); } } messageSuppressor.disableLoggers(); try { EnvFinder finder = new EnvFinder(node.getContext()); while (!stack.isEmpty()) stack.pop().accept(finder); attrib(node.get(), finder.get()); } finally { messageSuppressor.enableLoggers(); } } private void attrib(JCTree tree, Env env) { if (tree instanceof JCBlock) attr.attribStat(tree, env); else if (tree instanceof JCMethodDecl) attr.attribStat(((JCMethodDecl)tree).body, env); else if (tree instanceof JCVariableDecl) attr.attribStat(tree, env); else throw new IllegalStateException("Called with something that isn't a block, method decl, or variable decl"); } public static class TypeNotConvertibleException extends Exception { public TypeNotConvertibleException(String msg) { super(msg); } } private static class ReflectiveAccess { private static Method UPPER_BOUND; static { Method upperBound = null; try { upperBound = Types.class.getMethod("upperBound", Type.class); } catch (Throwable ignore) {} if (upperBound == null) try { upperBound = Types.class.getMethod("wildUpperBound", Type.class); } catch (Throwable ignore) {} UPPER_BOUND = upperBound; } public static Type Types_upperBound(Types types, Type type) { try { return (Type) UPPER_BOUND.invoke(types, type); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (Exception e) { throw Lombok.sneakyThrow(e); } } } public static Type ifTypeIsIterableToComponent(Type type, JavacAST ast) { Types types = Types.instance(ast.getContext()); Symtab syms = Symtab.instance(ast.getContext()); Type boundType = ReflectiveAccess.Types_upperBound(types, type); // Type boundType = types.upperBound(type); Type elemTypeIfArray = types.elemtype(boundType); if (elemTypeIfArray != null) return elemTypeIfArray; Type base = types.asSuper(boundType, syms.iterableType.tsym); if (base == null) return syms.objectType; List iterableParams = base.allparams(); return iterableParams.isEmpty() ? syms.objectType : ReflectiveAccess.Types_upperBound(types, iterableParams.head); } public static JCExpression typeToJCTree(Type type, JavacAST ast, boolean allowVoid) throws TypeNotConvertibleException { return typeToJCTree(type, ast, false, allowVoid); } public static JCExpression createJavaLangObject(JavacAST ast) { JavacTreeMaker maker = ast.getTreeMaker(); JCExpression out = maker.Ident(ast.toName("java")); out = maker.Select(out, ast.toName("lang")); out = maker.Select(out, ast.toName("Object")); return out; } private static JCExpression typeToJCTree(Type type, JavacAST ast, boolean allowCompound, boolean allowVoid) throws TypeNotConvertibleException { int dims = 0; Type type0 = type; while (type0 instanceof ArrayType) { dims++; type0 = ((ArrayType) type0).elemtype; } JCExpression result = typeToJCTree0(type0, ast, allowCompound, allowVoid); while (dims > 0) { result = ast.getTreeMaker().TypeArray(result); dims--; } return result; } private static JCExpression typeToJCTree0(Type type, JavacAST ast, boolean allowCompound, boolean allowVoid) throws TypeNotConvertibleException { // NB: There's such a thing as maker.Type(type), but this doesn't work very well; it screws up anonymous classes, captures, and adds an extra prefix dot for some reason too. // -- so we write our own take on that here. JavacTreeMaker maker = ast.getTreeMaker(); if (CTC_BOT.equals(typeTag(type))) return createJavaLangObject(ast); if (CTC_VOID.equals(typeTag(type))) return allowVoid ? primitiveToJCTree(type.getKind(), maker) : createJavaLangObject(ast); if (type.isPrimitive()) return primitiveToJCTree(type.getKind(), maker); if (type.isErroneous()) throw new TypeNotConvertibleException("Type cannot be resolved"); TypeSymbol symbol = type.asElement(); List generics = type.getTypeArguments(); JCExpression replacement = null; if (symbol == null) throw new TypeNotConvertibleException("Null or compound type"); if (symbol.name.length() == 0) { // Anonymous inner class if (type instanceof ClassType) { List ifaces = ((ClassType) type).interfaces_field; Type supertype = ((ClassType) type).supertype_field; if (ifaces != null && ifaces.length() == 1) { return typeToJCTree(ifaces.get(0), ast, allowCompound, allowVoid); } if (supertype != null) return typeToJCTree(supertype, ast, allowCompound, allowVoid); } throw new TypeNotConvertibleException("Anonymous inner class"); } if (type instanceof CapturedType || type instanceof WildcardType) { Type lower, upper; if (type instanceof WildcardType) { upper = ((WildcardType)type).getExtendsBound(); lower = ((WildcardType)type).getSuperBound(); } else { lower = type.getLowerBound(); upper = type.getUpperBound(); } if (allowCompound) { if (lower == null || CTC_BOT.equals(typeTag(lower))) { if (upper == null || upper.toString().equals("java.lang.Object")) { return maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null); } if (upper.getTypeArguments().contains(type)) { return maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null); } return maker.Wildcard(maker.TypeBoundKind(BoundKind.EXTENDS), typeToJCTree(upper, ast, false, false)); } else { return maker.Wildcard(maker.TypeBoundKind(BoundKind.SUPER), typeToJCTree(lower, ast, false, false)); } } if (upper != null) { if (upper.getTypeArguments().contains(type)) { return maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null); } return typeToJCTree(upper, ast, allowCompound, allowVoid); } return createJavaLangObject(ast); } String qName; if (symbol.isLocal()) { qName = symbol.getSimpleName().toString(); } else if (symbol.type != null && symbol.type.getEnclosingType() != null && typeTag(symbol.type.getEnclosingType()).equals(typeTag("CLASS"))) { replacement = typeToJCTree0(type.getEnclosingType(), ast, false, false); qName = symbol.getSimpleName().toString(); } else { qName = symbol.getQualifiedName().toString(); } if (qName.isEmpty()) throw new TypeNotConvertibleException("unknown type"); if (qName.startsWith("<")) throw new TypeNotConvertibleException(qName); String[] baseNames = qName.split("\\."); int i = 0; if (replacement == null) { replacement = maker.Ident(ast.toName(baseNames[0])); i = 1; } for (; i < baseNames.length; i++) { replacement = maker.Select(replacement, ast.toName(baseNames[i])); } return genericsToJCTreeNodes(generics, ast, replacement); } private static JCExpression genericsToJCTreeNodes(List generics, JavacAST ast, JCExpression rawTypeNode) throws TypeNotConvertibleException { if (generics != null && !generics.isEmpty()) { ListBuffer args = new ListBuffer(); for (Type t : generics) args.append(typeToJCTree(t, ast, true, false)); return ast.getTreeMaker().TypeApply(rawTypeNode, args.toList()); } return rawTypeNode; } private static JCExpression primitiveToJCTree(TypeKind kind, JavacTreeMaker maker) throws TypeNotConvertibleException { switch (kind) { case BYTE: return maker.TypeIdent(CTC_BYTE); case CHAR: return maker.TypeIdent( CTC_CHAR); case SHORT: return maker.TypeIdent(CTC_SHORT); case INT: return maker.TypeIdent(CTC_INT); case LONG: return maker.TypeIdent(CTC_LONG); case FLOAT: return maker.TypeIdent(CTC_FLOAT); case DOUBLE: return maker.TypeIdent(CTC_DOUBLE); case BOOLEAN: return maker.TypeIdent(CTC_BOOLEAN); case VOID: return maker.TypeIdent(CTC_VOID); case NULL: case NONE: case OTHER: default: throw new TypeNotConvertibleException("Nulltype"); } } public static boolean platformHasTargetTyping() { return Javac.getJavaCompilerVersion() >= 8; } } lombok-1.16.18/src/core/lombok/javac/JavacTransformer.java000066400000000000000000000107611312655740700233720ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.util.ArrayList; import java.util.SortedSet; import javax.annotation.processing.Messager; import com.sun.source.util.Trees; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; public class JavacTransformer { private final HandlerLibrary handlers; private final Messager messager; public JavacTransformer(Messager messager, Trees trees) { this.messager = messager; this.handlers = HandlerLibrary.load(messager, trees); } public SortedSet getPriorities() { return handlers.getPriorities(); } public SortedSet getPrioritiesRequiringResolutionReset() { return handlers.getPrioritiesRequiringResolutionReset(); } public void transform(long priority, Context context, java.util.List compilationUnitsRaw) { List compilationUnits; if (compilationUnitsRaw instanceof List) { compilationUnits = (List) compilationUnitsRaw; } else { compilationUnits = List.nil(); for (int i = compilationUnitsRaw.size() -1; i >= 0; i--) { compilationUnits = compilationUnits.prepend(compilationUnitsRaw.get(i)); } } java.util.List asts = new ArrayList(); for (JCCompilationUnit unit : compilationUnits) asts.add(new JavacAST(messager, context, unit)); for (JavacAST ast : asts) { ast.traverse(new AnnotationVisitor(priority)); handlers.callASTVisitors(ast, priority); } for (JavacAST ast : asts) if (ast.isChanged()) LombokOptions.markChanged(context, (JCCompilationUnit) ast.top().get()); } private class AnnotationVisitor extends JavacASTAdapter { private final long priority; AnnotationVisitor(long priority) { this.priority = priority; } @Override public void visitAnnotationOnType(JCClassDecl type, JavacNode annotationNode, JCAnnotation annotation) { JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnField(JCVariableDecl field, JavacNode annotationNode, JCAnnotation annotation) { JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnMethod(JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation) { JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation) { JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnLocal(JCVariableDecl local, JavacNode annotationNode, JCAnnotation annotation) { JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } } } lombok-1.16.18/src/core/lombok/javac/LombokOptions.java000066400000000000000000000050611312655740700227170ustar00rootroot00000000000000/* * Copyright (C) 2010-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.util.HashSet; import java.util.Set; import lombok.delombok.FormatPreferences; import lombok.delombok.LombokOptionsFactory; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Options; public abstract class LombokOptions extends Options { private boolean deleteLombokAnnotations = false; private final Set changed = new HashSet(); private FormatPreferences formatPreferences = new FormatPreferences(null); public boolean isChanged(JCCompilationUnit ast) { return changed.contains(ast); } public void setFormatPreferences(FormatPreferences formatPreferences) { this.formatPreferences = formatPreferences; } public FormatPreferences getFormatPreferences() { return this.formatPreferences; } public static void markChanged(Context context, JCCompilationUnit ast) { LombokOptions options = LombokOptionsFactory.getDelombokOptions(context); options.changed.add(ast); } public static boolean shouldDeleteLombokAnnotations(Context context) { LombokOptions options = LombokOptionsFactory.getDelombokOptions(context); return options.deleteLombokAnnotations; } protected LombokOptions(Context context) { super(context); } public abstract void putJavacOption(String optionName, String value); public void deleteLombokAnnotations() { this.deleteLombokAnnotations = true; } } lombok-1.16.18/src/core/lombok/javac/ResolutionResetNeeded.java000066400000000000000000000031721312655740700243740ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks the annotated handler as needing a reset on the resolved model (resulting in generated methods' signatures from becoming part of the symbol table and such) before * the priority level of this handler is reached. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ResolutionResetNeeded { } lombok-1.16.18/src/core/lombok/javac/apt/000077500000000000000000000000001312655740700200375ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/javac/apt/EmptyLombokFileObject.java000066400000000000000000000077321312655740700251040ustar00rootroot00000000000000/* * Copyright (C) 2010-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.net.URI; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; // Can't use SimpleJavaFileObject so we copy/paste most of its content here, because javac doesn't follow the interface, // and casts to its own BaseFileObject type. D'oh! class EmptyLombokFileObject implements LombokFileObject { private final String name; private final Kind kind; public EmptyLombokFileObject(String name, Kind kind) { this.name = name; this.kind = kind; } @Override public boolean isNameCompatible(String simpleName, Kind kind) { String baseName = simpleName + kind.extension; return kind.equals(getKind()) && (baseName.equals(toUri().getPath()) || toUri().getPath().endsWith("/" + baseName)); } @Override public URI toUri() { return URI.create(name); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return ""; } @Override public InputStream openInputStream() throws IOException { return new ByteArrayInputStream(new byte[0]); } @Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException { return new StringReader(""); } @Override public Writer openWriter() throws IOException { return new OutputStreamWriter(openOutputStream()); } @Override public OutputStream openOutputStream() throws IOException { return new ByteArrayOutputStream(); } @Override public long getLastModified() { return 0L; } @Override public boolean delete() { return false; } @Override public Kind getKind() { return kind; } @SuppressWarnings("all") @Override public String getName() { return toUri().getPath(); } @Override public NestingKind getNestingKind() { return null; } @Override public Modifier getAccessLevel() { return null; } @Override public CharsetDecoder getDecoder(boolean ignoreEncodingErrors) { CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); CodingErrorAction action = ignoreEncodingErrors ? CodingErrorAction.REPLACE : CodingErrorAction.REPORT; return decoder.onMalformedInput(action).onUnmappableCharacter(action); } @Override public boolean equals(Object obj) { if (!(obj instanceof EmptyLombokFileObject)) { return false; } if (obj == this) { return true; } EmptyLombokFileObject other = (EmptyLombokFileObject) obj; return name.equals(other.name) && kind.equals(other.kind); } @Override public int hashCode() { return name.hashCode() ^ kind.hashCode(); } }lombok-1.16.18/src/core/lombok/javac/apt/InterceptingJavaFileManager.java000066400000000000000000000045701312655740700262400ustar00rootroot00000000000000/* * Copyright (C) 2010-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import java.io.IOException; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import lombok.core.DiagnosticsReceiver; final class InterceptingJavaFileManager extends ForwardingJavaFileManager { private final DiagnosticsReceiver diagnostics; private final LombokFileObjects.Compiler compiler; InterceptingJavaFileManager(JavaFileManager original, DiagnosticsReceiver diagnostics) { super(original); this.compiler = LombokFileObjects.getCompiler(original); this.diagnostics = diagnostics; } @Override public JavaFileObject getJavaFileForOutput(Location location, String className, final Kind kind, FileObject sibling) throws IOException { if (className.startsWith("lombok.dummy.ForceNewRound")) { final String name = className.replace(".", "/") + kind.extension; return LombokFileObjects.createEmpty(compiler, name, kind); } JavaFileObject fileObject = fileManager.getJavaFileForOutput(location, className, kind, sibling); if (kind != Kind.CLASS) { return fileObject; } return LombokFileObjects.createIntercepting(compiler, fileObject, className, diagnostics); } }lombok-1.16.18/src/core/lombok/javac/apt/InterceptingJavaFileObject.java000066400000000000000000000107251312655740700260730ustar00rootroot00000000000000/* * Copyright (C) 2010-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.nio.charset.CharsetDecoder; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.tools.JavaFileObject; import lombok.Lombok; import lombok.core.DiagnosticsReceiver; import lombok.core.PostCompiler; final class InterceptingJavaFileObject implements LombokFileObject { private final JavaFileObject delegate; private final String fileName; private final DiagnosticsReceiver diagnostics; private final Method decoderMethod; public InterceptingJavaFileObject(JavaFileObject original, String fileName, DiagnosticsReceiver diagnostics, Method decoderMethod) { this.delegate = original; this.fileName = fileName; this.diagnostics = diagnostics; this.decoderMethod = decoderMethod; } @Override public OutputStream openOutputStream() throws IOException { return PostCompiler.wrapOutputStream(delegate.openOutputStream(), fileName, diagnostics); } @Override public Writer openWriter() throws IOException { throw new UnsupportedOperationException("Can't use a write for class files"); } @Override public CharsetDecoder getDecoder(boolean ignoreEncodingErrors) { if (decoderMethod == null) { throw new UnsupportedOperationException(); } try { return (CharsetDecoder) decoderMethod.invoke(delegate, ignoreEncodingErrors); } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e); } } @Override public boolean equals(Object obj) { if (!(obj instanceof InterceptingJavaFileObject)) { return false; } if (obj == this) { return true; } InterceptingJavaFileObject other = (InterceptingJavaFileObject) obj; return fileName.equals(other.fileName) && delegate.equals(other.delegate); } @Override public int hashCode() { return fileName.hashCode() ^ delegate.hashCode(); } /////////////////////// NOTHING CHANGED BELOW ////////////////////////////////////// @Override public boolean delete() { return delegate.delete(); } @Override public Modifier getAccessLevel() { return delegate.getAccessLevel(); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return delegate.getCharContent(ignoreEncodingErrors); } @Override public Kind getKind() { return delegate.getKind(); } @Override public long getLastModified() { return delegate.getLastModified(); } @Override @SuppressWarnings("all") public String getName() { return delegate.getName(); } @Override public NestingKind getNestingKind() { return delegate.getNestingKind(); } @Override public boolean isNameCompatible(String simpleName, Kind kind) { return delegate.isNameCompatible(simpleName, kind); } @Override public InputStream openInputStream() throws IOException { return delegate.openInputStream(); } @Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException { return delegate.openReader(ignoreEncodingErrors); } @Override public URI toUri() { return delegate.toUri(); } @Override public String toString() { return delegate.toString(); } } lombok-1.16.18/src/core/lombok/javac/apt/Javac6BaseFileObjectWrapper.java000066400000000000000000000070421312655740700261020ustar00rootroot00000000000000/* * Copyright (C) 2010-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URI; import java.nio.charset.CharsetDecoder; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; // Weird SuppressWarnings, but javac doesn't understand 'all' and eclipse doesn't understand that this file contains deprecation references. @SuppressWarnings({"all", "deprecation"}) class Javac6BaseFileObjectWrapper extends com.sun.tools.javac.util.BaseFileObject { private final LombokFileObject delegate; public Javac6BaseFileObjectWrapper(LombokFileObject delegate) { this.delegate = delegate; } @Override public boolean isNameCompatible(String simpleName, Kind kind) { return delegate.isNameCompatible(simpleName, kind); } @Override public URI toUri() { return delegate.toUri(); } @Override public String getName() { return delegate.getName(); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return delegate.getCharContent(ignoreEncodingErrors); } @Override public InputStream openInputStream() throws IOException { return delegate.openInputStream(); } @Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException { return delegate.openReader(ignoreEncodingErrors); } @Override public Writer openWriter() throws IOException { return delegate.openWriter(); } @Override public OutputStream openOutputStream() throws IOException { return delegate.openOutputStream(); } @Override public long getLastModified() { return delegate.getLastModified(); } @Override public boolean delete() { return delegate.delete(); } @Override public Kind getKind() { return delegate.getKind(); } @Override public NestingKind getNestingKind() { return delegate.getNestingKind(); } @Override public Modifier getAccessLevel() { return delegate.getAccessLevel(); } protected CharsetDecoder getDecoder(boolean ignoreEncodingErrors) { return delegate.getDecoder(ignoreEncodingErrors); } @Override public boolean equals(Object obj) { if (!(obj instanceof Javac6BaseFileObjectWrapper)) { return false; } return delegate.equals(((Javac6BaseFileObjectWrapper)obj).delegate); } @Override public int hashCode() { return delegate.hashCode(); } @Override public String toString() { return delegate.toString(); } }lombok-1.16.18/src/core/lombok/javac/apt/Javac7BaseFileObjectWrapper.java000066400000000000000000000066241312655740700261100ustar00rootroot00000000000000/* * Copyright (C) 2010-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URI; import java.nio.charset.CharsetDecoder; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; class Javac7BaseFileObjectWrapper extends com.sun.tools.javac.file.BaseFileObject { private final LombokFileObject delegate; public Javac7BaseFileObjectWrapper(LombokFileObject delegate) { super(null); this.delegate = delegate; } @Override public boolean isNameCompatible(String simpleName, Kind kind) { return delegate.isNameCompatible(simpleName, kind); } @Override public URI toUri() { return delegate.toUri(); } @SuppressWarnings("all") @Override public String getName() { return delegate.getName(); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return delegate.getCharContent(ignoreEncodingErrors); } @Override public InputStream openInputStream() throws IOException { return delegate.openInputStream(); } @Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException { return delegate.openReader(ignoreEncodingErrors); } @Override public Writer openWriter() throws IOException { return delegate.openWriter(); } @Override public OutputStream openOutputStream() throws IOException { return delegate.openOutputStream(); } @Override public long getLastModified() { return delegate.getLastModified(); } @Override public boolean delete() { return delegate.delete(); } @Override public Kind getKind() { return delegate.getKind(); } @Override public NestingKind getNestingKind() { return delegate.getNestingKind(); } @Override public Modifier getAccessLevel() { return delegate.getAccessLevel(); } protected CharsetDecoder getDecoder(boolean ignoreEncodingErrors) { return delegate.getDecoder(ignoreEncodingErrors); } @Override public boolean equals(Object obj) { if (!(obj instanceof Javac7BaseFileObjectWrapper)) { return false; } return delegate.equals(((Javac7BaseFileObjectWrapper)obj).delegate); } @Override public int hashCode() { return delegate.hashCode(); } @Override public String toString() { return delegate.toString(); } }lombok-1.16.18/src/core/lombok/javac/apt/Javac9BaseFileObjectWrapper.java000066400000000000000000000065601312655740700261110ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URI; import java.nio.file.Path; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import com.sun.tools.javac.file.BaseFileManager; class Javac9BaseFileObjectWrapper extends com.sun.tools.javac.file.PathFileObject { private final LombokFileObject delegate; public Javac9BaseFileObjectWrapper(BaseFileManager fileManager, Path path, LombokFileObject delegate) { super(fileManager, path); this.delegate = delegate; } @Override public boolean isNameCompatible(String simpleName, Kind kind) { return delegate.isNameCompatible(simpleName, kind); } @Override public URI toUri() { return delegate.toUri(); } @SuppressWarnings("all") @Override public String getName() { return delegate.getName(); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return delegate.getCharContent(ignoreEncodingErrors); } @Override public InputStream openInputStream() throws IOException { return delegate.openInputStream(); } @Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException { return delegate.openReader(ignoreEncodingErrors); } @Override public Writer openWriter() throws IOException { return delegate.openWriter(); } @Override public OutputStream openOutputStream() throws IOException { return delegate.openOutputStream(); } @Override public long getLastModified() { return delegate.getLastModified(); } @Override public boolean delete() { return delegate.delete(); } @Override public Kind getKind() { return delegate.getKind(); } @Override public NestingKind getNestingKind() { return delegate.getNestingKind(); } @Override public Modifier getAccessLevel() { return delegate.getAccessLevel(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Javac9BaseFileObjectWrapper)) { return false; } return delegate.equals(((Javac9BaseFileObjectWrapper)obj).delegate); } @Override public int hashCode() { return delegate.hashCode(); } @Override public String toString() { return delegate.toString(); } }lombok-1.16.18/src/core/lombok/javac/apt/LombokFileObject.java000066400000000000000000000025151312655740700240570ustar00rootroot00000000000000/* * Copyright (C) 2010-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import java.nio.charset.CharsetDecoder; import javax.tools.JavaFileObject; interface LombokFileObject extends JavaFileObject { CharsetDecoder getDecoder(boolean ignoreEncodingErrors); } lombok-1.16.18/src/core/lombok/javac/apt/LombokFileObjects.java000066400000000000000000000140171312655740700242420ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import java.lang.reflect.Method; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.atomic.AtomicBoolean; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import lombok.core.DiagnosticsReceiver; import com.sun.tools.javac.file.BaseFileManager; //Can't use SimpleJavaFileObject so we copy/paste most of its content here, because javac doesn't follow the interface, //and casts to its own BaseFileObject type. D'oh! final class LombokFileObjects { interface Compiler { Compiler JAVAC6 = new Compiler() { private Method decoderMethod = null; private final AtomicBoolean decoderIsSet = new AtomicBoolean(); @Override public JavaFileObject wrap(LombokFileObject fileObject) { return new Javac6BaseFileObjectWrapper(fileObject); } @Override public Method getDecoderMethod() { synchronized (decoderIsSet) { if (decoderIsSet.get()) return decoderMethod; decoderMethod = LombokFileObjects.getDecoderMethod("com.sun.tools.javac.util.BaseFileObject"); decoderIsSet.set(true); return decoderMethod; } } }; Compiler JAVAC7 = new Compiler() { private Method decoderMethod = null; private final AtomicBoolean decoderIsSet = new AtomicBoolean(); @Override public JavaFileObject wrap(LombokFileObject fileObject) { return new Javac7BaseFileObjectWrapper(fileObject); } @Override public Method getDecoderMethod() { synchronized (decoderIsSet) { if (decoderIsSet.get()) return decoderMethod; decoderMethod = LombokFileObjects.getDecoderMethod("com.sun.tools.javac.file.BaseFileObject"); decoderIsSet.set(true); return decoderMethod; } } }; JavaFileObject wrap(LombokFileObject fileObject); Method getDecoderMethod(); } static Method getDecoderMethod(String className) { Method m = null; try { m = Class.forName(className).getDeclaredMethod("getDecoder", boolean.class); m.setAccessible(true); } catch (NoSuchMethodException e) { // Intentional fallthrough - getDecoder(boolean) is not always present. } catch (ClassNotFoundException e) { // Intentional fallthrough - getDecoder(boolean) is not always present. } return m; } private LombokFileObjects() {} static Compiler getCompiler(JavaFileManager jfm) { String jfmClassName = jfm != null ? jfm.getClass().getName() : "null"; if (jfmClassName.equals("com.sun.tools.javac.util.DefaultFileManager")) return Compiler.JAVAC6; if (jfmClassName.equals("com.sun.tools.javac.util.JavacFileManager")) return Compiler.JAVAC6; if (jfmClassName.equals("com.sun.tools.javac.file.JavacFileManager") || jfmClassName.equals("com.google.errorprone.MaskedClassLoader$MaskedFileManager") || jfmClassName.equals("com.google.devtools.build.buildjar.javac.BlazeJavacMain$ClassloaderMaskingFileManager")) { try { Class superType = Class.forName("com.sun.tools.javac.file.BaseFileManager"); if (superType.isInstance(jfm)) { return new Java9Compiler(jfm); } } catch (Exception e) {} return Compiler.JAVAC7; } try { if (Class.forName("com.sun.tools.javac.file.BaseFileObject") == null) throw new NullPointerException(); return Compiler.JAVAC7; } catch (Exception e) {} try { if (Class.forName("com.sun.tools.javac.util.BaseFileObject") == null) throw new NullPointerException(); return Compiler.JAVAC6; } catch (Exception e) {} StringBuilder sb = new StringBuilder(jfmClassName); if (jfm != null) { sb.append(" extends ").append(jfm.getClass().getSuperclass().getName()); for (Class cls : jfm.getClass().getInterfaces()) { sb.append(" implements ").append(cls.getName()); } } throw new IllegalArgumentException(sb.toString()); } static JavaFileObject createEmpty(Compiler compiler, String name, Kind kind) { return compiler.wrap(new EmptyLombokFileObject(name, kind)); } static JavaFileObject createIntercepting(Compiler compiler, JavaFileObject delegate, String fileName, DiagnosticsReceiver diagnostics) { return compiler.wrap(new InterceptingJavaFileObject(delegate, fileName, diagnostics, compiler.getDecoderMethod())); } static class Java9Compiler implements Compiler { private final BaseFileManager fileManager; public Java9Compiler(JavaFileManager jfm) { fileManager = (BaseFileManager) jfm; } @Override public JavaFileObject wrap(LombokFileObject fileObject) { URI uri = fileObject.toUri(); if (uri.getScheme() == null) { uri = URI.create("file:///" + uri); } Path path; try { path = Paths.get(uri); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Problems in URI '" + uri + "' (" + fileObject.toUri() + ")", e); } return new Javac9BaseFileObjectWrapper(fileManager, path, fileObject); } @Override public Method getDecoderMethod() { throw new UnsupportedOperationException(); } } } lombok-1.16.18/src/core/lombok/javac/apt/LombokProcessor.java000066400000000000000000000327021312655740700240310ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic.Kind; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import lombok.Lombok; import lombok.core.DiagnosticsReceiver; import lombok.javac.JavacTransformer; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import com.sun.tools.javac.processing.JavacFiler; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; /** * This Annotation Processor is the standard injection mechanism for lombok-enabling the javac compiler. * * To actually enable lombok in a javac compilation run, this class should be in the classpath when * running javac; that's the only requirement. */ @SupportedAnnotationTypes("*") public class LombokProcessor extends AbstractProcessor { private JavacProcessingEnvironment processingEnv; private JavacTransformer transformer; private Trees trees; private boolean lombokDisabled = false; /** {@inheritDoc} */ @Override public void init(ProcessingEnvironment procEnv) { super.init(procEnv); if (System.getProperty("lombok.disable") != null) { lombokDisabled = true; return; } this.processingEnv = (JavacProcessingEnvironment) procEnv; placePostCompileAndDontMakeForceRoundDummiesHook(); trees = Trees.instance(procEnv); transformer = new JavacTransformer(procEnv.getMessager(), trees); SortedSet p = transformer.getPriorities(); if (p.isEmpty()) { this.priorityLevels = new long[] {0L}; this.priorityLevelsRequiringResolutionReset = new HashSet(); } else { this.priorityLevels = new long[p.size()]; int i = 0; for (Long prio : p) this.priorityLevels[i++] = prio; this.priorityLevelsRequiringResolutionReset = transformer.getPrioritiesRequiringResolutionReset(); } } private static final String JPE = "com.sun.tools.javac.processing.JavacProcessingEnvironment"; private static final Field javacProcessingEnvironment_discoveredProcs = getFieldAccessor(JPE, "discoveredProcs"); private static final Field discoveredProcessors_procStateList = getFieldAccessor(JPE + "$DiscoveredProcessors", "procStateList"); private static final Field processorState_processor = getFieldAccessor(JPE + "$processor", "processor"); private static final Field getFieldAccessor(String typeName, String fieldName) { try { Class c = Class.forName(typeName); Field f = c.getDeclaredField(fieldName); f.setAccessible(true); return f; } catch (ClassNotFoundException e) { return null; } catch (NoSuchFieldException e) { return null; } } // The intent of this method is to have lombok emit a warning if it's not 'first in line'. However, pragmatically speaking, you're always looking at one of two cases: // (A) The other processor(s) running before lombok require lombok to have run or they crash. So, they crash, and unfortunately we are never even init-ed; the warning is never emitted. // (B) The other processor(s) don't care about it at all. So, it doesn't actually matter that lombok isn't first. // Hence, for now, no warnings. @SuppressWarnings("unused") private String listAnnotationProcessorsBeforeOurs() { try { Object discoveredProcessors = javacProcessingEnvironment_discoveredProcs.get(this.processingEnv); ArrayList states = (ArrayList) discoveredProcessors_procStateList.get(discoveredProcessors); if (states == null || states.isEmpty()) return null; if (states.size() == 1) return processorState_processor.get(states.get(0)).getClass().getName(); int idx = 0; StringBuilder out = new StringBuilder(); for (Object processState : states) { idx++; String name = processorState_processor.get(processState).getClass().getName(); if (out.length() > 0) out.append(", "); out.append("[").append(idx).append("] ").append(name); } return out.toString(); } catch (Exception e) { return null; } } private void placePostCompileAndDontMakeForceRoundDummiesHook() { stopJavacProcessingEnvironmentFromClosingOurClassloader(); forceMultipleRoundsInNetBeansEditor(); Context context = processingEnv.getContext(); disablePartialReparseInNetBeansEditor(context); try { Method keyMethod = Context.class.getDeclaredMethod("key", Class.class); keyMethod.setAccessible(true); Object key = keyMethod.invoke(context, JavaFileManager.class); Field htField = Context.class.getDeclaredField("ht"); htField.setAccessible(true); @SuppressWarnings("unchecked") Map ht = (Map) htField.get(context); final JavaFileManager originalFiler = (JavaFileManager) ht.get(key); if (!(originalFiler instanceof InterceptingJavaFileManager)) { final Messager messager = processingEnv.getMessager(); DiagnosticsReceiver receiver = new MessagerDiagnosticsReceiver(messager); JavaFileManager newFiler = new InterceptingJavaFileManager(originalFiler, receiver); ht.put(key, newFiler); Field filerFileManagerField = JavacFiler.class.getDeclaredField("fileManager"); filerFileManagerField.setAccessible(true); filerFileManagerField.set(processingEnv.getFiler(), newFiler); } } catch (Exception e) { throw Lombok.sneakyThrow(e); } } private void forceMultipleRoundsInNetBeansEditor() { try { Field f = JavacProcessingEnvironment.class.getDeclaredField("isBackgroundCompilation"); f.setAccessible(true); f.set(processingEnv, true); } catch (NoSuchFieldException e) { // only NetBeans has it } catch (Throwable t) { throw Lombok.sneakyThrow(t); } } private void disablePartialReparseInNetBeansEditor(Context context) { try { Class cancelServiceClass = Class.forName("com.sun.tools.javac.util.CancelService"); Method cancelServiceInstace = cancelServiceClass.getDeclaredMethod("instance", Context.class); Object cancelService = cancelServiceInstace.invoke(null, context); if (cancelService == null) return; Field parserField = cancelService.getClass().getDeclaredField("parser"); parserField.setAccessible(true); Object parser = parserField.get(cancelService); Field supportsReparseField = parser.getClass().getDeclaredField("supportsReparse"); supportsReparseField.setAccessible(true); supportsReparseField.set(parser, false); } catch (ClassNotFoundException e) { // only NetBeans has it } catch (NoSuchFieldException e) { // only NetBeans has it } catch (Throwable t) { throw Lombok.sneakyThrow(t); } } private static ClassLoader wrapClassLoader(final ClassLoader parent) { return new ClassLoader() { public Class loadClass(String name) throws ClassNotFoundException { return parent.loadClass(name); } public String toString() { return parent.toString(); } public URL getResource(String name) { return parent.getResource(name); } public Enumeration getResources(String name) throws IOException { return parent.getResources(name); } public InputStream getResourceAsStream(String name) { return parent.getResourceAsStream(name); } public void setDefaultAssertionStatus(boolean enabled) { parent.setDefaultAssertionStatus(enabled); } public void setPackageAssertionStatus(String packageName, boolean enabled) { parent.setPackageAssertionStatus(packageName, enabled); } public void setClassAssertionStatus(String className, boolean enabled) { parent.setClassAssertionStatus(className, enabled); } public void clearAssertionStatus() { parent.clearAssertionStatus(); } }; } private void stopJavacProcessingEnvironmentFromClosingOurClassloader() { try { Field f = JavacProcessingEnvironment.class.getDeclaredField("processorClassLoader"); f.setAccessible(true); ClassLoader unwrapped = (ClassLoader) f.get(processingEnv); if (unwrapped == null) return; ClassLoader wrapped = wrapClassLoader(unwrapped); f.set(processingEnv, wrapped); } catch (NoSuchFieldException e) { // Some versions of javac have this (and call close on it), some don't. I guess this one doesn't have it. } catch (Throwable t) { throw Lombok.sneakyThrow(t); } } private final IdentityHashMap roots = new IdentityHashMap(); private long[] priorityLevels; private Set priorityLevelsRequiringResolutionReset; /** {@inheritDoc} */ @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { if (lombokDisabled) return false; if (roundEnv.processingOver()) return false; // We have: A sorted set of all priority levels: 'priorityLevels' // Step 1: Take all CUs which aren't already in the map. Give them the first priority level. for (Element element : roundEnv.getRootElements()) { JCCompilationUnit unit = toUnit(element); if (unit == null) continue; if (roots.containsKey(unit)) continue; roots.put(unit, priorityLevels[0]); } while (true) { // Step 2: For all CUs (in the map, not the roundEnv!), run them across all handlers at their current prio level. for (long prio : priorityLevels) { List cusForThisRound = new ArrayList(); for (Map.Entry entry : roots.entrySet()) { Long prioOfCu = entry.getValue(); if (prioOfCu == null || prioOfCu != prio) continue; cusForThisRound.add(entry.getKey()); } transformer.transform(prio, processingEnv.getContext(), cusForThisRound); } // Step 3: Push up all CUs to the next level. Set level to null if there is no next level. Set newLevels = new HashSet(); for (int i = priorityLevels.length - 1; i >= 0; i--) { Long curLevel = priorityLevels[i]; Long nextLevel = (i == priorityLevels.length - 1) ? null : priorityLevels[i + 1]; List cusToAdvance = new ArrayList(); for (Map.Entry entry : roots.entrySet()) { if (curLevel.equals(entry.getValue())) { cusToAdvance.add(entry.getKey()); newLevels.add(nextLevel); } } for (JCCompilationUnit unit : cusToAdvance) { roots.put(unit, nextLevel); } } newLevels.remove(null); // Step 4: If ALL values are null, quit. Else, either do another loop right now or force a resolution reset by forcing a new round in the annotation processor. if (newLevels.isEmpty()) return false; newLevels.retainAll(priorityLevelsRequiringResolutionReset); if (!newLevels.isEmpty()){ // Force a new round to reset resolution. The next round will cause this method (process) to be called again. forceNewRound((JavacFiler) processingEnv.getFiler()); return false; } // None of the new levels need resolution, so just keep going. } } private int dummyCount = 0; private void forceNewRound(JavacFiler filer) { if (!filer.newFiles()) { try { JavaFileObject dummy = filer.createSourceFile("lombok.dummy.ForceNewRound" + (dummyCount++)); Writer w = dummy.openWriter(); w.close(); } catch (Exception e) { e.printStackTrace(); processingEnv.getMessager().printMessage(Kind.WARNING, "Can't force a new processing round. Lombok won't work."); } } } private JCCompilationUnit toUnit(Element element) { TreePath path = trees == null ? null : trees.getPath(element); if (path == null) return null; return (JCCompilationUnit) path.getCompilationUnit(); } /** * We just return the latest version of whatever JDK we run on. Stupid? Yeah, but it's either that or warnings on all versions but 1. */ @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } } lombok-1.16.18/src/core/lombok/javac/apt/MessagerDiagnosticsReceiver.java000066400000000000000000000032371312655740700263320ustar00rootroot00000000000000/* * Copyright (C) 2009-2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import javax.annotation.processing.Messager; import javax.tools.Diagnostic.Kind; import lombok.core.DiagnosticsReceiver; public class MessagerDiagnosticsReceiver implements DiagnosticsReceiver { private final Messager messager; public MessagerDiagnosticsReceiver(Messager messager) { this.messager = messager; } @Override public void addWarning(String message) { messager.printMessage(Kind.WARNING, message); } @Override public void addError(String message) { messager.printMessage(Kind.ERROR, message); } }lombok-1.16.18/src/core/lombok/javac/apt/Processor.java000066400000000000000000000202561312655740700226660ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.apt; import static javax.tools.StandardLocation.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import javax.tools.JavaFileManager; import com.sun.tools.javac.processing.JavacFiler; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.util.Options; /** * This processor should not be used. It used to be THE processor. This class is only there to warn people that something went wrong, and for the * lombok developers to see if what the reason for those failures is. */ @Deprecated @SupportedAnnotationTypes("*") public class Processor extends AbstractProcessor { /** {@inheritDoc} */ @Override public void init(ProcessingEnvironment procEnv) { super.init(procEnv); if (System.getProperty("lombok.disable") != null) { return; } procEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Wrong usage of 'lombok.javac.apt.Processor'. " + report(procEnv)); } private String report(ProcessingEnvironment procEnv) { String data = collectData(procEnv); try { return writeFile(data); } catch (Exception e) { return "Report:\n\n" + data; } } private String writeFile(String data) throws IOException { File file = File.createTempFile("lombok-processor-report-", ".txt"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file)); writer.write(data); writer.close(); return "Report written to '" + file.getCanonicalPath() + "'\n"; } private String collectData(ProcessingEnvironment procEnv) { StringBuilder message = new StringBuilder(); message.append("Problem report for usages of 'lombok.javac.apt.Processor'\n\n"); listOptions(message, procEnv); findServices(message, procEnv.getFiler()); addStacktrace(message); listProperties(message); return message.toString(); } private void listOptions(StringBuilder message, ProcessingEnvironment procEnv) { try { JavacProcessingEnvironment environment = (JavacProcessingEnvironment) procEnv; Options instance = Options.instance(environment.getContext()); Field field = Options.class.getDeclaredField("values"); field.setAccessible(true); @SuppressWarnings("unchecked") Map values = (Map) field.get(instance); if (values.isEmpty()) { message.append("Options: empty\n\n"); return; } message.append("Compiler Options:\n"); for (Map.Entry value : values.entrySet()) { message.append("- "); string(message, value.getKey()); message.append(" = "); string(message, value.getValue()); message.append("\n"); } message.append("\n"); } catch (Exception e) { message.append("No options available\n\n"); } } private void findServices(StringBuilder message, Filer filer) { try { Field filerFileManagerField = JavacFiler.class.getDeclaredField("fileManager"); filerFileManagerField.setAccessible(true); JavaFileManager jfm = (JavaFileManager) filerFileManagerField.get(filer); ClassLoader processorClassLoader = jfm.hasLocation(ANNOTATION_PROCESSOR_PATH) ? jfm.getClassLoader(ANNOTATION_PROCESSOR_PATH) : jfm.getClassLoader(CLASS_PATH); Enumeration resources = processorClassLoader.getResources("META-INF/services/javax.annotation.processing.Processor"); if (!resources.hasMoreElements()) { message.append("No processors discovered\n\n"); return; } message.append("Discovered processors:\n"); while (resources.hasMoreElements()) { URL processorUrl = resources.nextElement(); message.append("- '").append(processorUrl).append("'"); InputStream content = (InputStream) processorUrl.getContent(); if (content != null) try { InputStreamReader reader = new InputStreamReader(content, "UTF-8"); StringWriter sw = new StringWriter(); char[] buffer = new char[8192]; int read = 0; while ((read = reader.read(buffer))!= -1) { sw.write(buffer, 0, read); } String wholeFile = sw.toString(); if (wholeFile.contains("lombok.javac.apt.Processor")) { message.append(" <= problem\n"); } else { message.append(" (ok)\n"); } message.append(" ").append(wholeFile.replace("\n", "\n ")).append("\n"); } finally { content.close(); } } } catch (Exception e) { message.append("Filer information unavailable\n"); } message.append("\n"); } private void addStacktrace(StringBuilder message) { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); if (stackTraceElements != null) { message.append("Called from\n"); for (int i = 1; i < stackTraceElements.length; i++) { StackTraceElement element = stackTraceElements[i]; if (!element.getClassName().equals("lombok.javac.apt.Processor")) message.append("- ").append(element).append("\n"); } } else { message.append("No stacktrace available\n"); } message.append("\n"); } private void listProperties(StringBuilder message) { Properties properties = System.getProperties(); ArrayList propertyNames = new ArrayList(properties.stringPropertyNames()); Collections.sort(propertyNames); message.append("Properties: \n"); for (String propertyName : propertyNames) { if (propertyName.startsWith("user.")) continue; message.append("- ").append(propertyName).append(" = "); string(message, System.getProperty(propertyName)); message.append("\n"); } message.append("\n"); } private static void string(StringBuilder sb, String s) { if (s == null) { sb.append("null"); return; } sb.append("\""); for (int i = 0; i < s.length(); i++) sb.append(escape(s.charAt(i))); sb.append("\""); } private static String escape(char ch) { switch (ch) { case '\b': return "\\b"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; case '\'': return "\\'"; case '\"': return "\\\""; case '\\': return "\\\\"; default: if (ch < 32) return String.format("\\%03o", (int) ch); return String.valueOf(ch); } } /** * We just return the latest version of whatever JDK we run on. Stupid? Yeah, but it's either that or warnings on all versions but 1. */ @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.values()[SourceVersion.values().length - 1]; } @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { return false; } } lombok-1.16.18/src/core/lombok/javac/apt/package-info.java000066400000000000000000000026171312655740700232340ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Contains the mechanism that instruments javac as an annotation processor. * * NB: This package is not public API in the sense that contents of this package, * even public classes / methods / etc, may change in point releases. */ package lombok.javac.apt; lombok-1.16.18/src/core/lombok/javac/handlers/000077500000000000000000000000001312655740700210535ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/javac/handlers/HandleAccessors.java000066400000000000000000000041731312655740700247640ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.experimental.Accessors; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(65536) public class HandleAccessors extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { // Accessors itself is handled by HandleGetter/Setter; this is just to ensure that the annotation is removed // from the AST when delomboking. handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.ACCESSORS_FLAG_USAGE, "@Accessors"); deleteAnnotationIfNeccessary(annotationNode, Accessors.class); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleBuilder.java000066400000000000000000001020261312655740700244210ustar00rootroot00000000000000/* * Copyright (C) 2013-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import java.lang.annotation.Annotation; import java.util.ArrayList; import javax.lang.model.element.Modifier; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCIf; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeApply; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import lombok.AccessLevel; import lombok.Builder; import lombok.Builder.ObtainVia; import lombok.ConfigurationKeys; import lombok.Singular; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.core.handlers.HandlerUtil; import lombok.experimental.NonFinal; import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.HandleConstructor.SkipIfConstructorExists; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; import lombok.javac.handlers.JavacSingularsRecipes.SingularData; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import static lombok.javac.Javac.*; import static lombok.javac.JavacTreeMaker.TypeTag.*; @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(-1024) //-2^10; to ensure we've picked up @FieldDefault's changes (-2048) but @Value hasn't removed itself yet (-512), so that we can error on presence of it on the builder classes. public class HandleBuilder extends JavacAnnotationHandler { private static final boolean toBoolean(Object expr, boolean defaultValue) { if (expr == null) return defaultValue; if (expr instanceof JCLiteral) return ((Integer) ((JCLiteral) expr).value) != 0; return ((Boolean) expr).booleanValue(); } private static class BuilderFieldData { JCExpression type; Name rawName; Name name; Name nameOfDefaultProvider; Name nameOfSetFlag; SingularData singularData; ObtainVia obtainVia; JavacNode obtainViaNode; JavacNode originalFieldNode; java.util.List createdFields = new ArrayList(); } @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { Builder builderInstance = annotation.getInstance(); // These exist just to support the 'old' lombok.experimental.Builder, which had these properties. lombok.Builder no longer has them. boolean fluent = toBoolean(annotation.getActualExpression("fluent"), true); boolean chain = toBoolean(annotation.getActualExpression("chain"), true); String builderMethodName = builderInstance.builderMethodName(); String buildMethodName = builderInstance.buildMethodName(); String builderClassName = builderInstance.builderClassName(); String toBuilderMethodName = "toBuilder"; boolean toBuilder = builderInstance.toBuilder(); java.util.List typeArgsForToBuilder = null; if (builderMethodName == null) builderMethodName = "builder"; if (buildMethodName == null) buildMethodName = "build"; if (builderClassName == null) builderClassName = ""; if (!checkName("builderMethodName", builderMethodName, annotationNode)) return; if (!checkName("buildMethodName", buildMethodName, annotationNode)) return; if (!builderClassName.isEmpty()) { if (!checkName("builderClassName", builderClassName, annotationNode)) return; } @SuppressWarnings("deprecation") Class oldExperimentalBuilder = lombok.experimental.Builder.class; deleteAnnotationIfNeccessary(annotationNode, Builder.class, oldExperimentalBuilder); JavacNode parent = annotationNode.up(); java.util.List builderFields = new ArrayList(); JCExpression returnType; List typeParams = List.nil(); List thrownExceptions = List.nil(); Name nameOfBuilderMethod; JavacNode tdParent; JavacNode fillParametersFrom = parent.get() instanceof JCMethodDecl ? parent : null; boolean addCleaning = false; boolean isStatic = true; if (parent.get() instanceof JCClassDecl) { tdParent = parent; JCClassDecl td = (JCClassDecl) tdParent.get(); ListBuffer allFields = new ListBuffer(); @SuppressWarnings("deprecation") boolean valuePresent = (hasAnnotation(lombok.Value.class, parent) || hasAnnotation(lombok.experimental.Value.class, parent)); for (JavacNode fieldNode : HandleConstructor.findAllFields(tdParent, true)) { JCVariableDecl fd = (JCVariableDecl) fieldNode.get(); JavacNode isDefault = findAnnotation(Builder.Default.class, fieldNode, true); boolean isFinal = (fd.mods.flags & Flags.FINAL) != 0 || (valuePresent && !hasAnnotation(NonFinal.class, fieldNode)); BuilderFieldData bfd = new BuilderFieldData(); bfd.rawName = fd.name; bfd.name = removePrefixFromField(fieldNode); bfd.type = fd.vartype; bfd.singularData = getSingularData(fieldNode); bfd.originalFieldNode = fieldNode; if (bfd.singularData != null && isDefault != null) { isDefault.addError("@Builder.Default and @Singular cannot be mixed."); isDefault = null; } if (fd.init == null && isDefault != null) { isDefault.addWarning("@Builder.Default requires an initializing expression (' = something;')."); isDefault = null; } if (fd.init != null && isDefault == null) { if (isFinal) continue; fieldNode.addWarning("@Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final."); } if (isDefault != null) { bfd.nameOfDefaultProvider = parent.toName("$default$" + bfd.name); bfd.nameOfSetFlag = parent.toName(bfd.name + "$set"); JCMethodDecl md = generateDefaultProvider(bfd.nameOfDefaultProvider, fieldNode); recursiveSetGeneratedBy(md, ast, annotationNode.getContext()); if (md != null) injectMethod(tdParent, md); } addObtainVia(bfd, fieldNode); builderFields.add(bfd); allFields.append(fieldNode); } new HandleConstructor().generateConstructor(tdParent, AccessLevel.PACKAGE, List.nil(), allFields.toList(), false, null, SkipIfConstructorExists.I_AM_BUILDER, annotationNode); returnType = namePlusTypeParamsToTypeReference(tdParent.getTreeMaker(), td.name, td.typarams); typeParams = td.typarams; thrownExceptions = List.nil(); nameOfBuilderMethod = null; if (builderClassName.isEmpty()) builderClassName = td.name.toString() + "Builder"; } else if (fillParametersFrom != null && fillParametersFrom.getName().toString().equals("")) { JCMethodDecl jmd = (JCMethodDecl) fillParametersFrom.get(); if (!jmd.typarams.isEmpty()) { annotationNode.addError("@Builder is not supported on constructors with constructor type parameters."); return; } tdParent = parent.up(); JCClassDecl td = (JCClassDecl) tdParent.get(); returnType = namePlusTypeParamsToTypeReference(tdParent.getTreeMaker(), td.name, td.typarams); typeParams = td.typarams; thrownExceptions = jmd.thrown; nameOfBuilderMethod = null; if (builderClassName.isEmpty()) builderClassName = td.name.toString() + "Builder"; } else if (fillParametersFrom != null) { tdParent = parent.up(); JCClassDecl td = (JCClassDecl) tdParent.get(); JCMethodDecl jmd = (JCMethodDecl) fillParametersFrom.get(); isStatic = (jmd.mods.flags & Flags.STATIC) != 0; JCExpression fullReturnType = jmd.restype; returnType = fullReturnType; typeParams = jmd.typarams; thrownExceptions = jmd.thrown; nameOfBuilderMethod = jmd.name; if (returnType instanceof JCTypeApply) { returnType = ((JCTypeApply) returnType).clazz; } if (builderClassName.isEmpty()) { if (returnType instanceof JCFieldAccess) { builderClassName = ((JCFieldAccess) returnType).name.toString() + "Builder"; } else if (returnType instanceof JCIdent) { Name n = ((JCIdent) returnType).name; for (JCTypeParameter tp : typeParams) { if (tp.name.equals(n)) { annotationNode.addError("@Builder requires specifying 'builderClassName' if used on methods with a type parameter as return type."); return; } } builderClassName = n.toString() + "Builder"; } else if (returnType instanceof JCPrimitiveTypeTree) { builderClassName = returnType.toString() + "Builder"; if (Character.isLowerCase(builderClassName.charAt(0))) { builderClassName = Character.toTitleCase(builderClassName.charAt(0)) + builderClassName.substring(1); } } else { // This shouldn't happen. System.err.println("Lombok bug ID#20140614-1651: javac HandleBuilder: return type to name conversion failed: " + returnType.getClass()); builderClassName = td.name.toString() + "Builder"; } } if (toBuilder) { final String TO_BUILDER_NOT_SUPPORTED = "@Builder(toBuilder=true) is only supported if you return your own type."; if (returnType instanceof JCArrayTypeTree) { annotationNode.addError(TO_BUILDER_NOT_SUPPORTED); return; } Name simpleName; String pkg; List tpOnRet = List.nil(); if (fullReturnType instanceof JCTypeApply) { tpOnRet = ((JCTypeApply) fullReturnType).arguments; } if (returnType instanceof JCIdent) { simpleName = ((JCIdent) returnType).name; pkg = null; } else if (returnType instanceof JCFieldAccess) { JCFieldAccess jcfa = (JCFieldAccess) returnType; simpleName = jcfa.name; pkg = unpack(jcfa.selected); if (pkg.startsWith("ERR:")) { String err = pkg.substring(4, pkg.indexOf("__ERR__")); annotationNode.addError(err); return; } } else { annotationNode.addError("Expected a (parameterized) type here instead of a " + returnType.getClass().getName()); return; } if (pkg != null && !parent.getPackageDeclaration().equals(pkg)) { annotationNode.addError(TO_BUILDER_NOT_SUPPORTED); return; } if (!tdParent.getName().contentEquals(simpleName)) { annotationNode.addError(TO_BUILDER_NOT_SUPPORTED); return; } List tpOnMethod = jmd.typarams; List tpOnType = ((JCClassDecl) tdParent.get()).typarams; typeArgsForToBuilder = new ArrayList(); for (JCTypeParameter tp : tpOnMethod) { int pos = -1; int idx = -1; for (JCExpression tOnRet : tpOnRet) { idx++; if (!(tOnRet instanceof JCIdent)) continue; if (((JCIdent) tOnRet).name != tp.name) continue; pos = idx; } if (pos == -1 || tpOnType.size() <= pos) { annotationNode.addError("@Builder(toBuilder=true) requires that each type parameter on the static method is part of the typeargs of the return value. Type parameter " + tp.name + " is not part of the return type."); return; } typeArgsForToBuilder.add(tpOnType.get(pos).name); } } } else { annotationNode.addError("@Builder is only supported on types, constructors, and methods."); return; } if (fillParametersFrom != null) { for (JavacNode param : fillParametersFrom.down()) { if (param.getKind() != Kind.ARGUMENT) continue; BuilderFieldData bfd = new BuilderFieldData(); JCVariableDecl raw = (JCVariableDecl) param.get(); bfd.name = raw.name; bfd.rawName = raw.name; bfd.type = raw.vartype; bfd.singularData = getSingularData(param); bfd.originalFieldNode = param; addObtainVia(bfd, param); builderFields.add(bfd); } } JavacNode builderType = findInnerClass(tdParent, builderClassName); if (builderType == null) { builderType = makeBuilderClass(isStatic, annotationNode, tdParent, builderClassName, typeParams, ast); } else { JCClassDecl builderTypeDeclaration = (JCClassDecl) builderType.get(); if (isStatic && !builderTypeDeclaration.getModifiers().getFlags().contains(Modifier.STATIC)) { annotationNode.addError("Existing Builder must be a static inner class."); return; } else if (!isStatic && builderTypeDeclaration.getModifiers().getFlags().contains(Modifier.STATIC)) { annotationNode.addError("Existing Builder must be a non-static inner class."); return; } sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(builderType, annotationNode); /* generate errors for @Singular BFDs that have one already defined node. */ { for (BuilderFieldData bfd : builderFields) { SingularData sd = bfd.singularData; if (sd == null) continue; JavacSingularizer singularizer = sd.getSingularizer(); if (singularizer == null) continue; if (singularizer.checkForAlreadyExistingNodesAndGenerateError(builderType, sd)) { bfd.singularData = null; } } } } for (BuilderFieldData bfd : builderFields) { if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { if (bfd.singularData.getSingularizer().requiresCleaning()) { addCleaning = true; break; } } if (bfd.obtainVia != null) { if (bfd.obtainVia.field().isEmpty() == bfd.obtainVia.method().isEmpty()) { bfd.obtainViaNode.addError("The syntax is either @ObtainVia(field = \"fieldName\") or @ObtainVia(method = \"methodName\")."); return; } if (bfd.obtainVia.method().isEmpty() && bfd.obtainVia.isStatic()) { bfd.obtainViaNode.addError("@ObtainVia(isStatic = true) is not valid unless 'method' has been set."); return; } } } generateBuilderFields(builderType, builderFields, ast); if (addCleaning) { JavacTreeMaker maker = builderType.getTreeMaker(); JCVariableDecl uncleanField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), builderType.toName("$lombokUnclean"), maker.TypeIdent(CTC_BOOLEAN), null); injectFieldAndMarkGenerated(builderType, uncleanField); } if (constructorExists(builderType) == MemberExistsResult.NOT_EXISTS) { JCMethodDecl cd = HandleConstructor.createConstructor(AccessLevel.PACKAGE, List.nil(), builderType, List.nil(), false, annotationNode); if (cd != null) injectMethod(builderType, cd); } for (BuilderFieldData bfd : builderFields) { makeSetterMethodsForBuilder(builderType, bfd, annotationNode, fluent, chain); } if (methodExists(buildMethodName, builderType, -1) == MemberExistsResult.NOT_EXISTS) { JCMethodDecl md = generateBuildMethod(tdParent, isStatic, buildMethodName, nameOfBuilderMethod, returnType, builderFields, builderType, thrownExceptions, ast, addCleaning); if (md != null) injectMethod(builderType, md); } if (methodExists("toString", builderType, 0) == MemberExistsResult.NOT_EXISTS) { java.util.List fieldNodes = new ArrayList(); for (BuilderFieldData bfd : builderFields) { fieldNodes.addAll(bfd.createdFields); } JCMethodDecl md = HandleToString.createToString(builderType, fieldNodes, true, false, FieldAccess.ALWAYS_FIELD, ast); if (md != null) injectMethod(builderType, md); } if (addCleaning) injectMethod(builderType, generateCleanMethod(builderFields, builderType, ast)); if (methodExists(builderMethodName, tdParent, -1) == MemberExistsResult.NOT_EXISTS) { JCMethodDecl md = generateBuilderMethod(isStatic, builderMethodName, builderClassName, annotationNode, tdParent, typeParams); recursiveSetGeneratedBy(md, ast, annotationNode.getContext()); if (md != null) injectMethod(tdParent, md); } if (toBuilder) { switch (methodExists(toBuilderMethodName, tdParent, 0)) { case EXISTS_BY_USER: annotationNode.addWarning("Not generating toBuilder() as it already exists."); return; case NOT_EXISTS: List tps = typeParams; if (typeArgsForToBuilder != null) { ListBuffer lb = new ListBuffer(); JavacTreeMaker maker = tdParent.getTreeMaker(); for (Name n : typeArgsForToBuilder) { lb.append(maker.TypeParameter(n, List.nil())); } tps = lb.toList(); } JCMethodDecl md = generateToBuilderMethod(toBuilderMethodName, builderClassName, tdParent, tps, builderFields, fluent, ast); if (md != null) injectMethod(tdParent, md); } } recursiveSetGeneratedBy(builderType.get(), ast, annotationNode.getContext()); } private static String unpack(JCExpression expr) { StringBuilder sb = new StringBuilder(); unpack(sb, expr); return sb.toString(); } private static void unpack(StringBuilder sb, JCExpression expr) { if (expr instanceof JCIdent) { sb.append(((JCIdent) expr).name.toString()); return; } if (expr instanceof JCFieldAccess) { JCFieldAccess jcfa = (JCFieldAccess) expr; unpack(sb, jcfa.selected); sb.append(".").append(jcfa.name.toString()); return; } if (expr instanceof JCTypeApply) { sb.setLength(0); sb.append("ERR:"); sb.append("@Builder(toBuilder=true) is not supported if returning a type with generics applied to an intermediate."); sb.append("__ERR__"); return; } sb.setLength(0); sb.append("ERR:"); sb.append("Expected a type of some sort, not a " + expr.getClass().getName()); sb.append("__ERR__"); } private JCMethodDecl generateToBuilderMethod(String toBuilderMethodName, String builderClassName, JavacNode type, List typeParams, java.util.List builderFields, boolean fluent, JCAnnotation ast) { // return new ThingieBuilder().setA(this.a).setB(this.b); JavacTreeMaker maker = type.getTreeMaker(); ListBuffer typeArgs = new ListBuffer(); for (JCTypeParameter typeParam : typeParams) { typeArgs.append(maker.Ident(typeParam.name)); } JCExpression call = maker.NewClass(null, List.nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.nil(), null); JCExpression invoke = call; for (BuilderFieldData bfd : builderFields) { Name setterName = fluent ? bfd.name : type.toName(HandlerUtil.buildAccessorName("set", bfd.name.toString())); JCExpression arg; if (bfd.obtainVia == null || !bfd.obtainVia.field().isEmpty()) { arg = maker.Select(maker.Ident(type.toName("this")), bfd.obtainVia == null ? bfd.rawName : type.toName(bfd.obtainVia.field())); } else { if (bfd.obtainVia.isStatic()) { JCExpression c = maker.Select(maker.Ident(type.toName(type.getName())), type.toName(bfd.obtainVia.method())); arg = maker.Apply(List.nil(), c, List.of(maker.Ident(type.toName("this")))); } else { JCExpression c = maker.Select(maker.Ident(type.toName("this")), type.toName(bfd.obtainVia.method())); arg = maker.Apply(List.nil(), c, List.nil()); } } invoke = maker.Apply(List.nil(), maker.Select(invoke, setterName), List.of(arg)); } JCStatement statement = maker.Return(invoke); JCBlock body = maker.Block(0, List.of(statement)); return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName(toBuilderMethodName), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.nil(), List.nil(), List.nil(), body, null); } private JCMethodDecl generateCleanMethod(java.util.List builderFields, JavacNode type, JCTree source) { JavacTreeMaker maker = type.getTreeMaker(); ListBuffer statements = new ListBuffer(); for (BuilderFieldData bfd : builderFields) { if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, type, source, statements); } } statements.append(maker.Exec(maker.Assign(maker.Select(maker.Ident(type.toName("this")), type.toName("$lombokUnclean")), maker.Literal(CTC_BOOLEAN, 0)))); JCBlock body = maker.Block(0, statements.toList()); return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName("$lombokClean"), maker.Type(Javac.createVoidType(type.getSymbolTable(), CTC_VOID)), List.nil(), List.nil(), List.nil(), body, null); /* * if (shouldReturnThis) { methodType = cloneSelfType(field); } if (methodType == null) { //WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6. methodType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID)); shouldReturnThis = false; } */ } private JCMethodDecl generateBuildMethod(JavacNode tdParent, boolean isStatic, String buildName, Name builderName, JCExpression returnType, java.util.List builderFields, JavacNode type, List thrownExceptions, JCTree source, boolean addCleaning) { JavacTreeMaker maker = type.getTreeMaker(); JCExpression call; ListBuffer statements = new ListBuffer(); if (addCleaning) { JCExpression notClean = maker.Unary(CTC_NOT, maker.Select(maker.Ident(type.toName("this")), type.toName("$lombokUnclean"))); JCStatement invokeClean = maker.Exec(maker.Apply(List.nil(), maker.Ident(type.toName("$lombokClean")), List.nil())); JCIf ifUnclean = maker.If(notClean, invokeClean, null); statements.append(ifUnclean); } for (BuilderFieldData bfd : builderFields) { if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { bfd.singularData.getSingularizer().appendBuildCode(bfd.singularData, type, source, statements, bfd.name); } } ListBuffer args = new ListBuffer(); for (BuilderFieldData bfd : builderFields) { if (bfd.nameOfSetFlag != null) { args.append(maker.Conditional(maker.Ident(bfd.nameOfSetFlag), maker.Ident(bfd.name), maker.Apply(List.nil(), maker.Select(maker.Ident(((JCClassDecl) tdParent.get()).name), bfd.nameOfDefaultProvider), List.nil()))); } else { args.append(maker.Ident(bfd.name)); } } if (addCleaning) { statements.append(maker.Exec(maker.Assign(maker.Select(maker.Ident(type.toName("this")), type.toName("$lombokUnclean")), maker.Literal(CTC_BOOLEAN, 1)))); } if (builderName == null) { call = maker.NewClass(null, List.nil(), returnType, args.toList(), null); statements.append(maker.Return(call)); } else { ListBuffer typeParams = new ListBuffer(); for (JCTypeParameter tp : ((JCClassDecl) type.get()).typarams) { typeParams.append(maker.Ident(tp.name)); } JCExpression callee = maker.Ident(((JCClassDecl) type.up().get()).name); if (!isStatic) callee = maker.Select(callee, type.up().toName("this")); JCExpression fn = maker.Select(callee, builderName); call = maker.Apply(typeParams.toList(), fn, args.toList()); if (returnType instanceof JCPrimitiveTypeTree && CTC_VOID.equals(typeTag(returnType))) { statements.append(maker.Exec(call)); } else { statements.append(maker.Return(call)); } } JCBlock body = maker.Block(0, statements.toList()); return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName(buildName), returnType, List.nil(), List.nil(), thrownExceptions, body, null); } public JCMethodDecl generateDefaultProvider(Name methodName, JavacNode fieldNode) { JavacTreeMaker maker = fieldNode.getTreeMaker(); JCVariableDecl field = (JCVariableDecl) fieldNode.get(); JCStatement statement = maker.Return(field.init); field.init = null; JCBlock body = maker.Block(0, List.of(statement)); int modifiers = Flags.PRIVATE | Flags.STATIC; return maker.MethodDef(maker.Modifiers(modifiers), methodName, cloneType(maker, field.vartype, field, fieldNode.getContext()), List.nil(), List.nil(), List.nil(), body, null); } public JCMethodDecl generateBuilderMethod(boolean isStatic, String builderMethodName, String builderClassName, JavacNode source, JavacNode type, List typeParams) { JavacTreeMaker maker = type.getTreeMaker(); ListBuffer typeArgs = new ListBuffer(); for (JCTypeParameter typeParam : typeParams) { typeArgs.append(maker.Ident(typeParam.name)); } JCExpression call = maker.NewClass(null, List.nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.nil(), null); JCStatement statement = maker.Return(call); JCBlock body = maker.Block(0, List.of(statement)); int modifiers = Flags.PUBLIC; if (isStatic) modifiers |= Flags.STATIC; return maker.MethodDef(maker.Modifiers(modifiers), type.toName(builderMethodName), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), copyTypeParams(source, typeParams), List.nil(), List.nil(), body, null); } public void generateBuilderFields(JavacNode builderType, java.util.List builderFields, JCTree source) { int len = builderFields.size(); java.util.List existing = new ArrayList(); for (JavacNode child : builderType.down()) { if (child.getKind() == Kind.FIELD) existing.add(child); } for (int i = len - 1; i >= 0; i--) { BuilderFieldData bfd = builderFields.get(i); if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { bfd.createdFields.addAll(bfd.singularData.getSingularizer().generateFields(bfd.singularData, builderType, source)); } else { JavacNode field = null, setFlag = null; for (JavacNode exists : existing) { Name n = ((JCVariableDecl) exists.get()).name; if (n.equals(bfd.name)) field = exists; if (n.equals(bfd.nameOfSetFlag)) setFlag = exists; } JavacTreeMaker maker = builderType.getTreeMaker(); if (field == null) { JCModifiers mods = maker.Modifiers(Flags.PRIVATE); JCVariableDecl newField = maker.VarDef(mods, bfd.name, cloneType(maker, bfd.type, source, builderType.getContext()), null); field = injectFieldAndMarkGenerated(builderType, newField); } if (setFlag == null && bfd.nameOfSetFlag != null) { JCModifiers mods = maker.Modifiers(Flags.PRIVATE); JCVariableDecl newField = maker.VarDef(mods, bfd.nameOfSetFlag, maker.TypeIdent(CTC_BOOLEAN), null); injectFieldAndMarkGenerated(builderType, newField); } bfd.createdFields.add(field); } } } public void makeSetterMethodsForBuilder(JavacNode builderType, BuilderFieldData fieldNode, JavacNode source, boolean fluent, boolean chain) { boolean deprecate = isFieldDeprecated(fieldNode.originalFieldNode); if (fieldNode.singularData == null || fieldNode.singularData.getSingularizer() == null) { makeSimpleSetterMethodForBuilder(builderType, deprecate, fieldNode.createdFields.get(0), fieldNode.nameOfSetFlag, source, fluent, chain); } else { fieldNode.singularData.getSingularizer().generateMethods(fieldNode.singularData, deprecate, builderType, source.get(), fluent, chain); } } private void makeSimpleSetterMethodForBuilder(JavacNode builderType, boolean deprecate, JavacNode fieldNode, Name nameOfSetFlag, JavacNode source, boolean fluent, boolean chain) { Name fieldName = ((JCVariableDecl) fieldNode.get()).name; for (JavacNode child : builderType.down()) { if (child.getKind() != Kind.METHOD) continue; JCMethodDecl methodDecl = (JCMethodDecl) child.get(); Name existingName = methodDecl.name; if (existingName.equals(fieldName) && !isTolerate(fieldNode, methodDecl)) return; } String setterName = fluent ? fieldNode.getName() : HandlerUtil.buildAccessorName("set", fieldNode.getName()); JavacTreeMaker maker = fieldNode.getTreeMaker(); JCMethodDecl newMethod = HandleSetter.createSetter(Flags.PUBLIC, deprecate, fieldNode, maker, setterName, nameOfSetFlag, chain, source, List.nil(), List.nil()); injectMethod(builderType, newMethod); } public JavacNode findInnerClass(JavacNode parent, String name) { for (JavacNode child : parent.down()) { if (child.getKind() != Kind.TYPE) continue; JCClassDecl td = (JCClassDecl) child.get(); if (td.name.contentEquals(name)) return child; } return null; } public JavacNode makeBuilderClass(boolean isStatic, JavacNode source, JavacNode tdParent, String builderClassName, List typeParams, JCAnnotation ast) { JavacTreeMaker maker = tdParent.getTreeMaker(); int modifiers = Flags.PUBLIC; if (isStatic) modifiers |= Flags.STATIC; JCModifiers mods = maker.Modifiers(modifiers); JCClassDecl builder = maker.ClassDef(mods, tdParent.toName(builderClassName), copyTypeParams(source, typeParams), null, List.nil(), List.nil()); return injectType(tdParent, builder); } private void addObtainVia(BuilderFieldData bfd, JavacNode node) { for (JavacNode child : node.down()) { if (!annotationTypeMatches(ObtainVia.class, child)) continue; AnnotationValues ann = createAnnotation(ObtainVia.class, child); bfd.obtainVia = ann.getInstance(); bfd.obtainViaNode = child; deleteAnnotationIfNeccessary(child, ObtainVia.class); return; } } /** * Returns the explicitly requested singular annotation on this node (field * or parameter), or null if there's no {@code @Singular} annotation on it. * * @param node The node (field or method param) to inspect for its name and potential {@code @Singular} annotation. */ private SingularData getSingularData(JavacNode node) { for (JavacNode child : node.down()) { if (!annotationTypeMatches(Singular.class, child)) continue; Name pluralName = node.getKind() == Kind.FIELD ? removePrefixFromField(node) : ((JCVariableDecl) node.get()).name; AnnotationValues ann = createAnnotation(Singular.class, child); deleteAnnotationIfNeccessary(child, Singular.class); String explicitSingular = ann.getInstance().value(); if (explicitSingular.isEmpty()) { if (Boolean.FALSE.equals(node.getAst().readConfiguration(ConfigurationKeys.SINGULAR_AUTO))) { node.addError("The singular must be specified explicitly (e.g. @Singular(\"task\")) because auto singularization is disabled."); explicitSingular = pluralName.toString(); } else { explicitSingular = autoSingularize(pluralName.toString()); if (explicitSingular == null) { node.addError("Can't singularize this name; please specify the singular explicitly (i.e. @Singular(\"sheep\"))"); explicitSingular = pluralName.toString(); } } } Name singularName = node.toName(explicitSingular); JCExpression type = null; if (node.get() instanceof JCVariableDecl) { type = ((JCVariableDecl) node.get()).vartype; } String name = null; List typeArgs = List.nil(); if (type instanceof JCTypeApply) { typeArgs = ((JCTypeApply) type).arguments; type = ((JCTypeApply) type).clazz; } name = type.toString(); String targetFqn = JavacSingularsRecipes.get().toQualified(name); JavacSingularizer singularizer = JavacSingularsRecipes.get().getSingularizer(targetFqn); if (singularizer == null) { node.addError("Lombok does not know how to create the singular-form builder methods for type '" + name + "'; they won't be generated."); return null; } return new SingularData(child, singularName, pluralName, typeArgs, targetFqn, singularizer); } return null; } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleBuilderDefault.java000066400000000000000000000023011312655740700257210ustar00rootroot00000000000000package lombok.javac.handlers; import static lombok.javac.handlers.JavacHandlerUtil.*; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import lombok.Builder; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(-1025) //HandleBuilder's level, minus one. public class HandleBuilderDefault extends JavacAnnotationHandler { @SuppressWarnings("deprecation") @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { JavacNode annotatedField = annotationNode.up(); if (annotatedField.getKind() != Kind.FIELD) return; JavacNode classWithAnnotatedField = annotatedField.up(); if (!hasAnnotation(Builder.class, classWithAnnotatedField) && !hasAnnotation(lombok.experimental.Builder.class, classWithAnnotatedField)) { annotationNode.addWarning("@Builder.Default requires @Builder on the class for it to mean anything."); deleteAnnotationIfNeccessary(annotationNode, Builder.Default.class); } } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleCleanup.java000066400000000000000000000171651312655740700244330ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import static lombok.javac.Javac.*; import lombok.Cleanup; import lombok.ConfigurationKeys; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.delombok.LombokOptionsFactory; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCCase; import com.sun.tools.javac.tree.JCTree.JCCatch; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCIf; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeCast; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; /** * Handles the {@code lombok.Cleanup} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public class HandleCleanup extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.CLEANUP_FLAG_USAGE, "@Cleanup"); if (inNetbeansEditor(annotationNode)) return; deleteAnnotationIfNeccessary(annotationNode, Cleanup.class); String cleanupName = annotation.getInstance().value(); if (cleanupName.length() == 0) { annotationNode.addError("cleanupName cannot be the empty string."); return; } if (annotationNode.up().getKind() != Kind.LOCAL) { annotationNode.addError("@Cleanup is legal only on local variable declarations."); return; } JCVariableDecl decl = (JCVariableDecl)annotationNode.up().get(); if (decl.init == null) { annotationNode.addError("@Cleanup variable declarations need to be initialized."); return; } JavacNode ancestor = annotationNode.up().directUp(); JCTree blockNode = ancestor.get(); final List statements; if (blockNode instanceof JCBlock) { statements = ((JCBlock)blockNode).stats; } else if (blockNode instanceof JCCase) { statements = ((JCCase)blockNode).stats; } else if (blockNode instanceof JCMethodDecl) { statements = ((JCMethodDecl)blockNode).body.stats; } else { annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block."); return; } boolean seenDeclaration = false; ListBuffer newStatements = new ListBuffer(); ListBuffer tryBlock = new ListBuffer(); for (JCStatement statement : statements) { if (!seenDeclaration) { if (statement == decl) seenDeclaration = true; newStatements.append(statement); } else { tryBlock.append(statement); } } if (!seenDeclaration) { annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent."); return; } doAssignmentCheck(annotationNode, tryBlock.toList(), decl.name); JavacTreeMaker maker = annotationNode.getTreeMaker(); JCFieldAccess cleanupMethod = maker.Select(maker.Ident(decl.name), annotationNode.toName(cleanupName)); List cleanupCall = List.of(maker.Exec( maker.Apply(List.nil(), cleanupMethod, List.nil()))); JCExpression preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name)); JCBinary isNull = maker.Binary(CTC_NOT_EQUAL, preventNullAnalysis, maker.Literal(CTC_BOT, null)); JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null); Context context = annotationNode.getContext(); JCBlock finalizer = recursiveSetGeneratedBy(maker.Block(0, List.of(ifNotNullCleanup)), ast, context); newStatements.append(setGeneratedBy(maker.Try(setGeneratedBy(maker.Block(0, tryBlock.toList()), ast, context), List.nil(), finalizer), ast, context)); if (blockNode instanceof JCBlock) { ((JCBlock)blockNode).stats = newStatements.toList(); } else if (blockNode instanceof JCCase) { ((JCCase)blockNode).stats = newStatements.toList(); } else if (blockNode instanceof JCMethodDecl) { ((JCMethodDecl)blockNode).body.stats = newStatements.toList(); } else throw new AssertionError("Should not get here"); ancestor.rebuild(); } public JCExpression preventNullAnalysis(JavacTreeMaker maker, JavacNode node, JCExpression expression) { if (LombokOptionsFactory.getDelombokOptions(node.getContext()).getFormatPreferences().danceAroundIdeChecks()) { JCMethodInvocation singletonList = maker.Apply(List.nil(), chainDotsString(node, "java.util.Collections.singletonList"), List.of(expression)); JCMethodInvocation cleanedExpr = maker.Apply(List.nil(), maker.Select(singletonList, node.toName("get")) , List.of(maker.Literal(CTC_INT, 0))); return cleanedExpr; } else { return expression; } } public void doAssignmentCheck(JavacNode node, List statements, Name name) { for (JCStatement statement : statements) doAssignmentCheck0(node, statement, name); } public void doAssignmentCheck0(JavacNode node, JCTree statement, Name name) { if (statement instanceof JCAssign) doAssignmentCheck0(node, ((JCAssign)statement).rhs, name); if (statement instanceof JCExpressionStatement) doAssignmentCheck0(node, ((JCExpressionStatement)statement).expr, name); if (statement instanceof JCVariableDecl) doAssignmentCheck0(node, ((JCVariableDecl)statement).init, name); if (statement instanceof JCTypeCast) doAssignmentCheck0(node, ((JCTypeCast)statement).expr, name); if (statement instanceof JCIdent) { if (((JCIdent)statement).name.contentEquals(name)) { JavacNode problemNode = node.getNodeFor(statement); if (problemNode != null) problemNode.addWarning( "You're assigning an auto-cleanup variable to something else. This is a bad idea."); } } } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleConstructor.java000066400000000000000000000460131312655740700253630ustar00rootroot00000000000000/* * Copyright (C) 2010-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import static lombok.javac.Javac.*; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.ConfigurationKeys; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.delombok.LombokOptionsFactory; import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCReturn; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; public class HandleConstructor { @ProviderFor(JavacAnnotationHandler.class) public static class HandleNoArgsConstructor extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.NO_ARGS_CONSTRUCTOR_FLAG_USAGE, "@NoArgsConstructor", ConfigurationKeys.ANY_CONSTRUCTOR_FLAG_USAGE, "any @xArgsConstructor"); deleteAnnotationIfNeccessary(annotationNode, NoArgsConstructor.class); deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); JavacNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode, NoArgsConstructor.class.getSimpleName())) return; List onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@NoArgsConstructor(onConstructor", annotationNode); NoArgsConstructor ann = annotation.getInstance(); AccessLevel level = ann.access(); if (level == AccessLevel.NONE) return; String staticName = ann.staticName(); boolean force = ann.force(); List fields = force ? findFinalFields(typeNode) : List.nil(); new HandleConstructor().generateConstructor(typeNode, level, onConstructor, fields, force, staticName, SkipIfConstructorExists.NO, annotationNode); } } @ProviderFor(JavacAnnotationHandler.class) public static class HandleRequiredArgsConstructor extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.REQUIRED_ARGS_CONSTRUCTOR_FLAG_USAGE, "@RequiredArgsConstructor", ConfigurationKeys.ANY_CONSTRUCTOR_FLAG_USAGE, "any @xArgsConstructor"); deleteAnnotationIfNeccessary(annotationNode, RequiredArgsConstructor.class); deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); JavacNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode, RequiredArgsConstructor.class.getSimpleName())) return; List onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@RequiredArgsConstructor(onConstructor", annotationNode); RequiredArgsConstructor ann = annotation.getInstance(); AccessLevel level = ann.access(); if (level == AccessLevel.NONE) return; String staticName = ann.staticName(); if (annotation.isExplicit("suppressConstructorProperties")) { annotationNode.addError("This deprecated feature is no longer supported. Remove it; you can create a lombok.config file with 'lombok.anyConstructor.suppressConstructorProperties = true'."); } new HandleConstructor().generateConstructor(typeNode, level, onConstructor, findRequiredFields(typeNode), false, staticName, SkipIfConstructorExists.NO, annotationNode); } } public static List findRequiredFields(JavacNode typeNode) { return findFields(typeNode, true); } public static List findFinalFields(JavacNode typeNode) { return findFields(typeNode, false); } public static List findFields(JavacNode typeNode, boolean nullMarked) { ListBuffer fields = new ListBuffer(); for (JavacNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); //Skip fields that start with $ if (fieldDecl.name.toString().startsWith("$")) continue; long fieldFlags = fieldDecl.mods.flags; //Skip static fields. if ((fieldFlags & Flags.STATIC) != 0) continue; boolean isFinal = (fieldFlags & Flags.FINAL) != 0; boolean isNonNull = nullMarked && !findAnnotations(child, NON_NULL_PATTERN).isEmpty(); if ((isFinal || isNonNull) && fieldDecl.init == null) fields.append(child); } return fields.toList(); } @ProviderFor(JavacAnnotationHandler.class) public static class HandleAllArgsConstructor extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.ALL_ARGS_CONSTRUCTOR_FLAG_USAGE, "@AllArgsConstructor", ConfigurationKeys.ANY_CONSTRUCTOR_FLAG_USAGE, "any @xArgsConstructor"); deleteAnnotationIfNeccessary(annotationNode, AllArgsConstructor.class); deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); JavacNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode, AllArgsConstructor.class.getSimpleName())) return; List onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@AllArgsConstructor(onConstructor", annotationNode); AllArgsConstructor ann = annotation.getInstance(); AccessLevel level = ann.access(); if (level == AccessLevel.NONE) return; String staticName = ann.staticName(); if (annotation.isExplicit("suppressConstructorProperties")) { annotationNode.addError("This deprecated feature is no longer supported. Remove it; you can create a lombok.config file with 'lombok.anyConstructor.suppressConstructorProperties = true'."); } new HandleConstructor().generateConstructor(typeNode, level, onConstructor, findAllFields(typeNode), false, staticName, SkipIfConstructorExists.NO, annotationNode); } } public static List findAllFields(JavacNode typeNode) { return findAllFields(typeNode, false); } public static List findAllFields(JavacNode typeNode, boolean evenFinalInitialized) { ListBuffer fields = new ListBuffer(); for (JavacNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); //Skip fields that start with $ if (fieldDecl.name.toString().startsWith("$")) continue; long fieldFlags = fieldDecl.mods.flags; //Skip static fields. if ((fieldFlags & Flags.STATIC) != 0) continue; //Skip initialized final fields boolean isFinal = (fieldFlags & Flags.FINAL) != 0; if (evenFinalInitialized || !isFinal || fieldDecl.init == null) fields.append(child); } return fields.toList(); } public static boolean checkLegality(JavacNode typeNode, JavacNode errorNode, String name) { JCClassDecl typeDecl = null; if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION)) != 0; if (typeDecl == null || notAClass) { errorNode.addError(name + " is only supported on a class or an enum."); return false; } return true; } public void generateRequiredArgsConstructor(JavacNode typeNode, AccessLevel level, String staticName, SkipIfConstructorExists skipIfConstructorExists, JavacNode source) { generateConstructor(typeNode, level, List.nil(), findRequiredFields(typeNode), false, staticName, skipIfConstructorExists, source); } public enum SkipIfConstructorExists { YES, NO, I_AM_BUILDER; } public void generateAllArgsConstructor(JavacNode typeNode, AccessLevel level, String staticName, SkipIfConstructorExists skipIfConstructorExists, JavacNode source) { generateConstructor(typeNode, level, List.nil(), findAllFields(typeNode), false, staticName, skipIfConstructorExists, source); } public void generateConstructor(JavacNode typeNode, AccessLevel level, List onConstructor, List fields, boolean allToDefault, String staticName, SkipIfConstructorExists skipIfConstructorExists, JavacNode source) { boolean staticConstrRequired = staticName != null && !staticName.equals(""); if (skipIfConstructorExists != SkipIfConstructorExists.NO && constructorExists(typeNode) != MemberExistsResult.NOT_EXISTS) return; if (skipIfConstructorExists != SkipIfConstructorExists.NO) { for (JavacNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { boolean skipGeneration = annotationTypeMatches(NoArgsConstructor.class, child) || annotationTypeMatches(AllArgsConstructor.class, child) || annotationTypeMatches(RequiredArgsConstructor.class, child); if (!skipGeneration && skipIfConstructorExists == SkipIfConstructorExists.YES) { skipGeneration = annotationTypeMatches(Builder.class, child); } if (skipGeneration) { if (staticConstrRequired) { // @Data has asked us to generate a constructor, but we're going to skip this instruction, as an explicit 'make a constructor' annotation // will take care of it. However, @Data also wants a specific static name; this will be ignored; the appropriate way to do this is to use // the 'staticName' parameter of the @XArgsConstructor you've stuck on your type. // We should warn that we're ignoring @Data's 'staticConstructor' param. source.addWarning("Ignoring static constructor name: explicit @XxxArgsConstructor annotation present; its `staticName` parameter will be used."); } return; } } } } JCMethodDecl constr = createConstructor(staticConstrRequired ? AccessLevel.PRIVATE : level, onConstructor, typeNode, fields, allToDefault, source); ListBuffer argTypes = new ListBuffer(); for (JavacNode fieldNode : fields) { Type mirror = getMirrorForFieldType(fieldNode); if (mirror == null) { argTypes = null; break; } argTypes.append(mirror); } List argTypes_ = argTypes == null ? null : argTypes.toList(); injectMethod(typeNode, constr, argTypes_, Javac.createVoidType(typeNode.getSymbolTable(), CTC_VOID)); if (staticConstrRequired) { ClassSymbol sym = ((JCClassDecl) typeNode.get()).sym; Type returnType = sym == null ? null : sym.type; JCMethodDecl staticConstr = createStaticConstructor(staticName, level, typeNode, allToDefault ? List.nil() : fields, source.get()); injectMethod(typeNode, staticConstr, argTypes_, returnType); } } public static void addConstructorProperties(JCModifiers mods, JavacNode node, List fields) { if (fields.isEmpty()) return; JavacTreeMaker maker = node.getTreeMaker(); JCExpression constructorPropertiesType = chainDots(node, "java", "beans", "ConstructorProperties"); ListBuffer fieldNames = new ListBuffer(); for (JavacNode field : fields) { Name fieldName = removePrefixFromField(field); fieldNames.append(maker.Literal(fieldName.toString())); } JCExpression fieldNamesArray = maker.NewArray(null, List.nil(), fieldNames.toList()); JCAnnotation annotation = maker.Annotation(constructorPropertiesType, List.of(fieldNamesArray)); mods.annotations = mods.annotations.append(annotation); } public static JCMethodDecl createConstructor(AccessLevel level, List onConstructor, JavacNode typeNode, List fields, boolean allToDefault, JavacNode source) { JavacTreeMaker maker = typeNode.getTreeMaker(); boolean isEnum = (((JCClassDecl) typeNode.get()).mods.flags & Flags.ENUM) != 0; if (isEnum) level = AccessLevel.PRIVATE; boolean suppressConstructorProperties; if (fields.isEmpty()) { suppressConstructorProperties = false; } else { suppressConstructorProperties = Boolean.TRUE.equals(typeNode.getAst().readConfiguration(ConfigurationKeys.ANY_CONSTRUCTOR_SUPPRESS_CONSTRUCTOR_PROPERTIES)); } ListBuffer nullChecks = new ListBuffer(); ListBuffer assigns = new ListBuffer(); ListBuffer params = new ListBuffer(); for (JavacNode fieldNode : fields) { JCVariableDecl field = (JCVariableDecl) fieldNode.get(); Name fieldName = removePrefixFromField(fieldNode); Name rawName = field.name; List nonNulls = findAnnotations(fieldNode, NON_NULL_PATTERN); if (!allToDefault) { List nullables = findAnnotations(fieldNode, NULLABLE_PATTERN); long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext()); JCVariableDecl param = maker.VarDef(maker.Modifiers(flags, nonNulls.appendList(nullables)), fieldName, field.vartype, null); params.append(param); if (!nonNulls.isEmpty()) { JCStatement nullCheck = generateNullCheck(maker, fieldNode, source); if (nullCheck != null) nullChecks.append(nullCheck); } } JCFieldAccess thisX = maker.Select(maker.Ident(fieldNode.toName("this")), rawName); JCExpression assign = maker.Assign(thisX, allToDefault ? getDefaultExpr(maker, field.vartype) : maker.Ident(fieldName)); assigns.append(maker.Exec(assign)); } JCModifiers mods = maker.Modifiers(toJavacModifier(level), List.nil()); if (!allToDefault && !suppressConstructorProperties && !isLocalType(typeNode) && LombokOptionsFactory.getDelombokOptions(typeNode.getContext()).getFormatPreferences().generateConstructorProperties()) { addConstructorProperties(mods, typeNode, fields); } if (onConstructor != null) mods.annotations = mods.annotations.appendList(copyAnnotations(onConstructor)); return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName(""), null, List.nil(), params.toList(), List.nil(), maker.Block(0L, nullChecks.appendList(assigns).toList()), null), source.get(), typeNode.getContext()); } private static JCExpression getDefaultExpr(JavacTreeMaker maker, JCExpression type) { if (type instanceof JCPrimitiveTypeTree) { switch (((JCPrimitiveTypeTree) type).getPrimitiveTypeKind()) { case BOOLEAN: return maker.Literal(CTC_BOOLEAN, 0); case CHAR: return maker.Literal(CTC_CHAR, 0); default: case BYTE: case SHORT: case INT: return maker.Literal(CTC_INT, 0); case LONG: return maker.Literal(CTC_LONG, 0L); case FLOAT: return maker.Literal(CTC_FLOAT, 0F); case DOUBLE: return maker.Literal(CTC_DOUBLE, 0D); } } return maker.Literal(CTC_BOT, null); } public static boolean isLocalType(JavacNode type) { Kind kind = type.up().getKind(); if (kind == Kind.COMPILATION_UNIT) return false; if (kind == Kind.TYPE) return isLocalType(type.up()); return true; } public JCMethodDecl createStaticConstructor(String name, AccessLevel level, JavacNode typeNode, List fields, JCTree source) { JavacTreeMaker maker = typeNode.getTreeMaker(); JCClassDecl type = (JCClassDecl) typeNode.get(); JCModifiers mods = maker.Modifiers(Flags.STATIC | toJavacModifier(level)); JCExpression returnType, constructorType; ListBuffer typeParams = new ListBuffer(); ListBuffer params = new ListBuffer(); ListBuffer typeArgs1 = new ListBuffer(); ListBuffer typeArgs2 = new ListBuffer(); ListBuffer args = new ListBuffer(); if (!type.typarams.isEmpty()) { for (JCTypeParameter param : type.typarams) { typeArgs1.append(maker.Ident(param.name)); typeArgs2.append(maker.Ident(param.name)); typeParams.append(maker.TypeParameter(param.name, param.bounds)); } returnType = maker.TypeApply(maker.Ident(type.name), typeArgs1.toList()); constructorType = maker.TypeApply(maker.Ident(type.name), typeArgs2.toList()); } else { returnType = maker.Ident(type.name); constructorType = maker.Ident(type.name); } for (JavacNode fieldNode : fields) { JCVariableDecl field = (JCVariableDecl) fieldNode.get(); Name fieldName = removePrefixFromField(fieldNode); JCExpression pType = cloneType(maker, field.vartype, source, typeNode.getContext()); List nonNulls = findAnnotations(fieldNode, NON_NULL_PATTERN); List nullables = findAnnotations(fieldNode, NULLABLE_PATTERN); long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext()); JCVariableDecl param = maker.VarDef(maker.Modifiers(flags, nonNulls.appendList(nullables)), fieldName, pType, null); params.append(param); args.append(maker.Ident(fieldName)); } JCReturn returnStatement = maker.Return(maker.NewClass(null, List.nil(), constructorType, args.toList(), null)); JCBlock body = maker.Block(0, List.of(returnStatement)); return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName(name), returnType, typeParams.toList(), params.toList(), List.nil(), body, null), source, typeNode.getContext()); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleData.java000066400000000000000000000055471312655740700237160ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.Data; import lombok.core.AnnotationValues; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.handlers.HandleConstructor.SkipIfConstructorExists; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.tree.JCTree.JCAnnotation; /** * Handles the {@code lombok.Data} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public class HandleData extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.DATA_FLAG_USAGE, "@Data"); deleteAnnotationIfNeccessary(annotationNode, Data.class); JavacNode typeNode = annotationNode.up(); boolean notAClass = !isClass(typeNode); if (notAClass) { annotationNode.addError("@Data is only supported on a class."); return; } String staticConstructorName = annotation.getInstance().staticConstructor(); // TODO move this to the end OR move it to the top in eclipse. new HandleConstructor().generateRequiredArgsConstructor(typeNode, AccessLevel.PUBLIC, staticConstructorName, SkipIfConstructorExists.YES, annotationNode); new HandleGetter().generateGetterForType(typeNode, annotationNode, AccessLevel.PUBLIC, true); new HandleSetter().generateSetterForType(typeNode, annotationNode, AccessLevel.PUBLIC, true); new HandleEqualsAndHashCode().generateEqualsAndHashCodeForType(typeNode, annotationNode); new HandleToString().generateToStringForType(typeNode, annotationNode); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleDelegate.java000066400000000000000000000457121312655740700245550ustar00rootroot00000000000000/* * Copyright (C) 2010-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import static com.sun.tools.javac.code.Flags.*; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import lombok.ConfigurationKeys; import lombok.experimental.Delegate; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.javac.FindTypeVarScanner; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacResolution; import lombok.javac.JavacTreeMaker; import lombok.javac.ResolutionResetNeeded; import lombok.javac.JavacResolution.TypeNotConvertibleException; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Attribute.Compound; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Type.TypeVar; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.model.JavacTypes; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(65536) //2^16; to make sure that we also delegate generated methods. @ResolutionResetNeeded public class HandleDelegate extends JavacAnnotationHandler { private static final List METHODS_IN_OBJECT = Collections.unmodifiableList(Arrays.asList( "hashCode()", "canEqual(java.lang.Object)", //Not in j.l.Object, but it goes with hashCode and equals so if we ignore those two, we should ignore this one. "equals(java.lang.Object)", "wait()", "wait(long)", "wait(long, int)", "notify()", "notifyAll()", "toString()", "getClass()", "clone()", "finalize()")); private static final String LEGALITY_OF_DELEGATE = "@Delegate is legal only on instance fields or no-argument instance methods."; private static final String RECURSION_NOT_ALLOWED = "@Delegate does not support recursion (delegating to a type that itself has @Delegate members). Member \"%s\" is @Delegate in type \"%s\""; @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.DELEGATE_FLAG_USAGE, "@Delegate"); @SuppressWarnings("deprecation") Class oldDelegate = lombok.Delegate.class; deleteAnnotationIfNeccessary(annotationNode, Delegate.class, oldDelegate); Type delegateType; Name delegateName = annotationNode.toName(annotationNode.up().getName()); DelegateReceiver delegateReceiver; JavacResolution reso = new JavacResolution(annotationNode.getContext()); JCTree member = annotationNode.up().get(); if (annotationNode.up().getKind() == Kind.FIELD) { if ((((JCVariableDecl) member).mods.flags & Flags.STATIC) != 0) { annotationNode.addError(LEGALITY_OF_DELEGATE); return; } delegateReceiver = DelegateReceiver.FIELD; delegateType = member.type; if (delegateType == null) reso.resolveClassMember(annotationNode.up()); delegateType = member.type; } else if (annotationNode.up().getKind() == Kind.METHOD) { if (!(member instanceof JCMethodDecl)) { annotationNode.addError(LEGALITY_OF_DELEGATE); return; } JCMethodDecl methodDecl = (JCMethodDecl) member; if (!methodDecl.params.isEmpty() || (methodDecl.mods.flags & Flags.STATIC) != 0) { annotationNode.addError(LEGALITY_OF_DELEGATE); return; } delegateReceiver = DelegateReceiver.METHOD; delegateType = methodDecl.restype.type; if (delegateType == null) reso.resolveClassMember(annotationNode.up()); delegateType = methodDecl.restype.type; } else { // As the annotation is legal on fields and methods only, javac itself will take care of printing an error message for this. return; } List delegateTypes = annotation.getActualExpressions("types"); List excludeTypes = annotation.getActualExpressions("excludes"); List toDelegate = new ArrayList(); List toExclude = new ArrayList(); if (delegateTypes.isEmpty()) { if (delegateType != null) toDelegate.add(delegateType); } else { for (Object dt : delegateTypes) { if (dt instanceof JCFieldAccess && ((JCFieldAccess)dt).name.toString().equals("class")) { Type type = ((JCFieldAccess)dt).selected.type; if (type == null) reso.resolveClassMember(annotationNode); type = ((JCFieldAccess)dt).selected.type; if (type != null) toDelegate.add(type); } } } for (Object et : excludeTypes) { if (et instanceof JCFieldAccess && ((JCFieldAccess)et).name.toString().equals("class")) { Type type = ((JCFieldAccess)et).selected.type; if (type == null) reso.resolveClassMember(annotationNode); type = ((JCFieldAccess)et).selected.type; if (type != null) toExclude.add(type); } } List signaturesToDelegate = new ArrayList(); List signaturesToExclude = new ArrayList(); Set banList = new HashSet(); banList.addAll(METHODS_IN_OBJECT); /* To exclude all methods in the class itself, try this: for (Symbol member : ((JCClassDecl)typeNode.get()).sym.getEnclosedElements()) { if (member instanceof MethodSymbol) { MethodSymbol method = (MethodSymbol) member; banList.add(printSig((ExecutableType) method.asType(), method.name, annotationNode.getTypesUtil())); } } */ try { for (Type t : toExclude) { if (t instanceof ClassType) { ClassType ct = (ClassType) t; addMethodBindings(signaturesToExclude, ct, annotationNode.getTypesUtil(), banList); } else { annotationNode.addError("@Delegate can only use concrete class types, not wildcards, arrays, type variables, or primitives."); return; } } for (MethodSig sig : signaturesToExclude) { banList.add(printSig(sig.type, sig.name, annotationNode.getTypesUtil())); } for (Type t : toDelegate) { if (t instanceof ClassType) { ClassType ct = (ClassType) t; addMethodBindings(signaturesToDelegate, ct, annotationNode.getTypesUtil(), banList); } else { annotationNode.addError("@Delegate can only use concrete class types, not wildcards, arrays, type variables, or primitives."); return; } } for (MethodSig sig : signaturesToDelegate) generateAndAdd(sig, annotationNode, delegateName, delegateReceiver); } catch (DelegateRecursion e) { annotationNode.addError(String.format(RECURSION_NOT_ALLOWED, e.member, e.type)); } } public void generateAndAdd(MethodSig sig, JavacNode annotation, Name delegateName, DelegateReceiver delegateReceiver) { List toAdd = new ArrayList(); try { toAdd.add(createDelegateMethod(sig, annotation, delegateName, delegateReceiver)); } catch (TypeNotConvertibleException e) { annotation.addError("Can't create delegate method for " + sig.name + ": " + e.getMessage()); return; } catch (CantMakeDelegates e) { annotation.addError("There's a conflict in the names of type parameters. Fix it by renaming the following type parameters of your class: " + e.conflicted); return; } for (JCMethodDecl method : toAdd) { injectMethod(annotation.up().up(), method); } } public static class CantMakeDelegates extends Exception { Set conflicted; } /** * There's a rare but problematic case if a delegate method has its own type variables, and the delegated type does too, and the method uses both. * If for example the delegated type has {@code }, and the method has {@code }, but in our class we have a {@code } at the class level, then we have two different * type variables both named {@code T}. We detect this situation and error out asking the programmer to rename their type variable. * * @throws CantMakeDelegates If there's a conflict. Conflict list is in ex.conflicted. */ public void checkConflictOfTypeVarNames(MethodSig sig, JavacNode annotation) throws CantMakeDelegates { // As first step, we check if there's a conflict between the delegate method's type vars and our own class. if (sig.elem.getTypeParameters().isEmpty()) return; Set usedInOurType = new HashSet(); JavacNode enclosingType = annotation; while (enclosingType != null) { if (enclosingType.getKind() == Kind.TYPE) { List typarams = ((JCClassDecl)enclosingType.get()).typarams; if (typarams != null) for (JCTypeParameter param : typarams) { if (param.name != null) usedInOurType.add(param.name.toString()); } } enclosingType = enclosingType.up(); } Set usedInMethodSig = new HashSet(); for (TypeParameterElement param : sig.elem.getTypeParameters()) { usedInMethodSig.add(param.getSimpleName().toString()); } usedInMethodSig.retainAll(usedInOurType); if (usedInMethodSig.isEmpty()) return; // We might be delegating a List, and we are making method toArray(). A conflict is possible. // But only if the toArray method also uses type vars from its class, otherwise we're only shadowing, // which is okay as we'll add a @SuppressWarnings. FindTypeVarScanner scanner = new FindTypeVarScanner(); sig.elem.asType().accept(scanner, null); Set names = new HashSet(scanner.getTypeVariables()); names.removeAll(usedInMethodSig); if (!names.isEmpty()) { // We have a confirmed conflict. We could dig deeper as this may still be a false alarm, but its already an exceedingly rare case. CantMakeDelegates cmd = new CantMakeDelegates(); cmd.conflicted = usedInMethodSig; throw cmd; } } public JCMethodDecl createDelegateMethod(MethodSig sig, JavacNode annotation, Name delegateName, DelegateReceiver delegateReceiver) throws TypeNotConvertibleException, CantMakeDelegates { /* public ReturnType methodName(ParamType1 name1, ParamType2 name2, ...) throws T1, T2, ... { * (return) delegate.methodName(name1, name2); * } */ checkConflictOfTypeVarNames(sig, annotation); JavacTreeMaker maker = annotation.getTreeMaker(); com.sun.tools.javac.util.List annotations; if (sig.isDeprecated) { annotations = com.sun.tools.javac.util.List.of(maker.Annotation( genJavaLangTypeRef(annotation, "Deprecated"), com.sun.tools.javac.util.List.nil())); } else { annotations = com.sun.tools.javac.util.List.nil(); } JCModifiers mods = maker.Modifiers(PUBLIC, annotations); JCExpression returnType = JavacResolution.typeToJCTree((Type) sig.type.getReturnType(), annotation.getAst(), true); boolean useReturn = sig.type.getReturnType().getKind() != TypeKind.VOID; ListBuffer params = sig.type.getParameterTypes().isEmpty() ? null : new ListBuffer(); ListBuffer args = sig.type.getParameterTypes().isEmpty() ? null : new ListBuffer(); ListBuffer thrown = sig.type.getThrownTypes().isEmpty() ? null : new ListBuffer(); ListBuffer typeParams = sig.type.getTypeVariables().isEmpty() ? null : new ListBuffer(); ListBuffer typeArgs = sig.type.getTypeVariables().isEmpty() ? null : new ListBuffer(); Types types = Types.instance(annotation.getContext()); for (TypeMirror param : sig.type.getTypeVariables()) { Name name = ((TypeVar) param).tsym.name; ListBuffer bounds = new ListBuffer(); for (Type type : types.getBounds((TypeVar) param)) { bounds.append(JavacResolution.typeToJCTree(type, annotation.getAst(), true)); } typeParams.append(maker.TypeParameter(name, bounds.toList())); typeArgs.append(maker.Ident(name)); } for (TypeMirror ex : sig.type.getThrownTypes()) { thrown.append(JavacResolution.typeToJCTree((Type) ex, annotation.getAst(), true)); } int idx = 0; String[] paramNames = sig.getParameterNames(); boolean varargs = sig.elem.isVarArgs(); for (TypeMirror param : sig.type.getParameterTypes()) { long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, annotation.getContext()); JCModifiers paramMods = maker.Modifiers(flags); Name name = annotation.toName(paramNames[idx++]); if (varargs && idx == paramNames.length) { paramMods.flags |= VARARGS; } params.append(maker.VarDef(paramMods, name, JavacResolution.typeToJCTree((Type) param, annotation.getAst(), true), null)); args.append(maker.Ident(name)); } JCExpression delegateCall = maker.Apply(toList(typeArgs), maker.Select(delegateReceiver.get(annotation, delegateName), sig.name), toList(args)); JCStatement body = useReturn ? maker.Return(delegateCall) : maker.Exec(delegateCall); JCBlock bodyBlock = maker.Block(0, com.sun.tools.javac.util.List.of(body)); return recursiveSetGeneratedBy(maker.MethodDef(mods, sig.name, returnType, toList(typeParams), toList(params), toList(thrown), bodyBlock, null), annotation.get(), annotation.getContext()); } public static com.sun.tools.javac.util.List toList(ListBuffer collection) { return collection == null ? com.sun.tools.javac.util.List.nil() : collection.toList(); } private static class DelegateRecursion extends Throwable { final String type, member; public DelegateRecursion(String type, String member) { this.type = type; this.member = member; } } public void addMethodBindings(List signatures, ClassType ct, JavacTypes types, Set banList) throws DelegateRecursion { TypeSymbol tsym = ct.asElement(); if (tsym == null) return; for (Symbol member : tsym.getEnclosedElements()) { for (Compound am : member.getAnnotationMirrors()) { String name = null; try { name = am.type.tsym.flatName().toString(); } catch (Exception ignore) {} if ("lombok.Delegate".equals(name) || "lombok.experimental.Delegate".equals(name)) { throw new DelegateRecursion(ct.tsym.name.toString(), member.name.toString()); } } if (member.getKind() != ElementKind.METHOD) continue; if (member.isStatic()) continue; if (member.isConstructor()) continue; ExecutableElement exElem = (ExecutableElement)member; if (!exElem.getModifiers().contains(Modifier.PUBLIC)) continue; ExecutableType methodType = (ExecutableType) types.asMemberOf(ct, member); String sig = printSig(methodType, member.name, types); if (!banList.add(sig)) continue; //If add returns false, it was already in there boolean isDeprecated = (member.flags() & DEPRECATED) != 0; signatures.add(new MethodSig(member.name, methodType, isDeprecated, exElem)); } if (ct.supertype_field instanceof ClassType) addMethodBindings(signatures, (ClassType) ct.supertype_field, types, banList); if (ct.interfaces_field != null) for (Type iface : ct.interfaces_field) { if (iface instanceof ClassType) addMethodBindings(signatures, (ClassType) iface, types, banList); } } public static class MethodSig { final Name name; final ExecutableType type; final boolean isDeprecated; final ExecutableElement elem; MethodSig(Name name, ExecutableType type, boolean isDeprecated, ExecutableElement elem) { this.name = name; this.type = type; this.isDeprecated = isDeprecated; this.elem = elem; } String[] getParameterNames() { List paramList = elem.getParameters(); String[] paramNames = new String[paramList.size()]; for (int i = 0; i < paramNames.length; i++) { paramNames[i] = paramList.get(i).getSimpleName().toString(); } return paramNames; } @Override public String toString() { return (isDeprecated ? "@Deprecated " : "") + name + " " + type; } } public static String printSig(ExecutableType method, Name name, JavacTypes types) { StringBuilder sb = new StringBuilder(); sb.append(name.toString()).append("("); boolean first = true; for (TypeMirror param : method.getParameterTypes()) { if (!first) sb.append(", "); first = false; sb.append(typeBindingToSignature(param, types)); } return sb.append(")").toString(); } public static String typeBindingToSignature(TypeMirror binding, JavacTypes types) { binding = types.erasure(binding); return binding.toString(); } public enum DelegateReceiver { METHOD { public JCExpression get(final JavacNode node, final Name name) { com.sun.tools.javac.util.List nilExprs = com.sun.tools.javac.util.List.nil(); final JavacTreeMaker maker = node.getTreeMaker(); return maker.Apply(nilExprs, maker.Select(maker.Ident(node.toName("this")), name), nilExprs); } }, FIELD { public JCExpression get(final JavacNode node, final Name name) { final JavacTreeMaker maker = node.getTreeMaker(); return maker.Select(maker.Ident(node.toName("this")), name); } }; public abstract JCExpression get(final JavacNode node, final Name name); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java000066400000000000000000000645371312655740700263250ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import lombok.ConfigurationKeys; import lombok.EqualsAndHashCode; import lombok.core.AST.Kind; import lombok.core.configuration.CallSuperType; import lombok.core.AnnotationValues; import lombok.core.handlers.HandlerUtil; import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; import lombok.javac.handlers.JavacHandlerUtil.MemberExistsResult; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCUnary; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; /** * Handles the {@code lombok.EqualsAndHashCode} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public class HandleEqualsAndHashCode extends JavacAnnotationHandler { private static final String RESULT_NAME = "result"; private static final String PRIME_NAME = "PRIME"; public void checkForBogusFieldNames(JavacNode type, AnnotationValues annotation) { if (annotation.isExplicit("exclude")) { for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().exclude()), type, true, true)) { annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); } } if (annotation.isExplicit("of")) { for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().of()), type, false, false)) { annotation.setWarning("of", "This field does not exist.", i); } } } @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.EQUALS_AND_HASH_CODE_FLAG_USAGE, "@EqualsAndHashCode"); deleteAnnotationIfNeccessary(annotationNode, EqualsAndHashCode.class); EqualsAndHashCode ann = annotation.getInstance(); List excludes = List.from(ann.exclude()); List includes = List.from(ann.of()); JavacNode typeNode = annotationNode.up(); List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@EqualsAndHashCode(onParam", annotationNode); checkForBogusFieldNames(typeNode, annotation); Boolean callSuper = ann.callSuper(); if (!annotation.isExplicit("callSuper")) callSuper = null; if (!annotation.isExplicit("exclude")) excludes = null; if (!annotation.isExplicit("of")) includes = null; if (excludes != null && includes != null) { excludes = null; annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored."); } Boolean doNotUseGettersConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.EQUALS_AND_HASH_CODE_DO_NOT_USE_GETTERS); boolean doNotUseGetters = annotation.isExplicit("doNotUseGetters") || doNotUseGettersConfiguration == null ? ann.doNotUseGetters() : doNotUseGettersConfiguration; FieldAccess fieldAccess = doNotUseGetters ? FieldAccess.PREFER_FIELD : FieldAccess.GETTER; generateMethods(typeNode, annotationNode, excludes, includes, callSuper, true, fieldAccess, onParam); } public void generateEqualsAndHashCodeForType(JavacNode typeNode, JavacNode source) { if (hasAnnotation(EqualsAndHashCode.class, typeNode)) { //The annotation will make it happen, so we can skip it. return; } Boolean doNotUseGettersConfiguration = typeNode.getAst().readConfiguration(ConfigurationKeys.EQUALS_AND_HASH_CODE_DO_NOT_USE_GETTERS); FieldAccess access = doNotUseGettersConfiguration == null || !doNotUseGettersConfiguration ? FieldAccess.GETTER : FieldAccess.PREFER_FIELD; generateMethods(typeNode, source, null, null, null, false, access, List.nil()); } public void generateMethods(JavacNode typeNode, JavacNode source, List excludes, List includes, Boolean callSuper, boolean whineIfExists, FieldAccess fieldAccess, List onParam) { boolean notAClass = true; if (typeNode.get() instanceof JCClassDecl) { long flags = ((JCClassDecl) typeNode.get()).mods.flags; notAClass = (flags & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; } if (notAClass) { source.addError("@EqualsAndHashCode is only supported on a class."); return; } boolean isDirectDescendantOfObject = true; boolean implicitCallSuper = callSuper == null; if (callSuper == null) { try { callSuper = ((Boolean) EqualsAndHashCode.class.getMethod("callSuper").getDefaultValue()).booleanValue(); } catch (Exception ignore) { throw new InternalError("Lombok bug - this cannot happen - can't find callSuper field in EqualsAndHashCode annotation."); } } JCTree extending = Javac.getExtendsClause((JCClassDecl)typeNode.get()); if (extending != null) { String p = extending.toString(); isDirectDescendantOfObject = p.equals("Object") || p.equals("java.lang.Object"); } if (isDirectDescendantOfObject && callSuper) { source.addError("Generating equals/hashCode with a supercall to java.lang.Object is pointless."); return; } if (implicitCallSuper && !isDirectDescendantOfObject) { CallSuperType cst = typeNode.getAst().readConfiguration(ConfigurationKeys.EQUALS_AND_HASH_CODE_CALL_SUPER); if (cst == null) cst = CallSuperType.WARN; switch (cst) { default: case WARN: source.addWarning("Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.lang.Object. If this is intentional, add '@EqualsAndHashCode(callSuper=false)' to your type."); callSuper = false; break; case SKIP: callSuper = false; break; case CALL: callSuper = true; break; } } ListBuffer nodesForEquality = new ListBuffer(); if (includes != null) { for (JavacNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); if (includes.contains(fieldDecl.name.toString())) nodesForEquality.append(child); } } else { for (JavacNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); //Skip static fields. if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue; //Skip transient fields. if ((fieldDecl.mods.flags & Flags.TRANSIENT) != 0) continue; //Skip excluded fields. if (excludes != null && excludes.contains(fieldDecl.name.toString())) continue; //Skip fields that start with $ if (fieldDecl.name.toString().startsWith("$")) continue; nodesForEquality.append(child); } } boolean isFinal = (((JCClassDecl) typeNode.get()).mods.flags & Flags.FINAL) != 0; boolean needsCanEqual = !isFinal || !isDirectDescendantOfObject; MemberExistsResult equalsExists = methodExists("equals", typeNode, 1); MemberExistsResult hashCodeExists = methodExists("hashCode", typeNode, 0); MemberExistsResult canEqualExists = methodExists("canEqual", typeNode, 1); switch (Collections.max(Arrays.asList(equalsExists, hashCodeExists))) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: if (whineIfExists) { String msg = "Not generating equals and hashCode: A method with one of those names already exists. (Either both or none of these methods will be generated)."; source.addWarning(msg); } else if (equalsExists == MemberExistsResult.NOT_EXISTS || hashCodeExists == MemberExistsResult.NOT_EXISTS) { // This means equals OR hashCode exists and not both. // Even though we should suppress the message about not generating these, this is such a weird and surprising situation we should ALWAYS generate a warning. // The user code couldn't possibly (barring really weird subclassing shenanigans) be in a shippable state anyway; the implementations of these 2 methods are // all inter-related and should be written by the same entity. String msg = String.format("Not generating %s: One of equals or hashCode exists. " + "You should either write both of these or none of these (in the latter case, lombok generates them).", equalsExists == MemberExistsResult.NOT_EXISTS ? "equals" : "hashCode"); source.addWarning(msg); } return; case NOT_EXISTS: default: //fallthrough } JCMethodDecl equalsMethod = createEquals(typeNode, nodesForEquality.toList(), callSuper, fieldAccess, needsCanEqual, source.get(), onParam); injectMethod(typeNode, equalsMethod); if (needsCanEqual && canEqualExists == MemberExistsResult.NOT_EXISTS) { JCMethodDecl canEqualMethod = createCanEqual(typeNode, source.get(), onParam); injectMethod(typeNode, canEqualMethod); } JCMethodDecl hashCodeMethod = createHashCode(typeNode, nodesForEquality.toList(), callSuper, fieldAccess, source.get()); injectMethod(typeNode, hashCodeMethod); } public JCMethodDecl createHashCode(JavacNode typeNode, List fields, boolean callSuper, FieldAccess fieldAccess, JCTree source) { JavacTreeMaker maker = typeNode.getTreeMaker(); JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.nil()); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); JCExpression returnType = maker.TypeIdent(CTC_INT); ListBuffer statements = new ListBuffer(); Name primeName = typeNode.toName(PRIME_NAME); Name resultName = typeNode.toName(RESULT_NAME); long finalFlag = JavacHandlerUtil.addFinalIfNeeded(0L, typeNode.getContext()); /* final int PRIME = X; */ { if (!fields.isEmpty() || callSuper) { statements.append(maker.VarDef(maker.Modifiers(finalFlag), primeName, maker.TypeIdent(CTC_INT), maker.Literal(HandlerUtil.primeForHashcode()))); } } /* int result = 1; */ { statements.append(maker.VarDef(maker.Modifiers(0), resultName, maker.TypeIdent(CTC_INT), maker.Literal(1))); } if (callSuper) { JCMethodInvocation callToSuper = maker.Apply(List.nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("hashCode")), List.nil()); statements.append(createResultCalculation(typeNode, callToSuper)); } Name dollar = typeNode.toName("$"); for (JavacNode fieldNode : fields) { JCExpression fType = getFieldType(fieldNode, fieldAccess); JCExpression fieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess); if (fType instanceof JCPrimitiveTypeTree) { switch (((JCPrimitiveTypeTree) fType).getPrimitiveTypeKind()) { case BOOLEAN: /* this.fieldName ? X : Y */ statements.append(createResultCalculation(typeNode, maker.Parens(maker.Conditional(fieldAccessor, maker.Literal(HandlerUtil.primeForTrue()), maker.Literal(HandlerUtil.primeForFalse()))))); break; case LONG: { Name dollarFieldName = dollar.append(((JCVariableDecl) fieldNode.get()).name); statements.append(maker.VarDef(maker.Modifiers(finalFlag), dollarFieldName, maker.TypeIdent(CTC_LONG), fieldAccessor)); statements.append(createResultCalculation(typeNode, longToIntForHashCode(maker, maker.Ident(dollarFieldName), maker.Ident(dollarFieldName)))); } break; case FLOAT: /* Float.floatToIntBits(this.fieldName) */ statements.append(createResultCalculation(typeNode, maker.Apply( List.nil(), genJavaLangTypeRef(typeNode, "Float", "floatToIntBits"), List.of(fieldAccessor)))); break; case DOUBLE: { /* longToIntForHashCode(Double.doubleToLongBits(this.fieldName)) */ Name dollarFieldName = dollar.append(((JCVariableDecl) fieldNode.get()).name); JCExpression init = maker.Apply( List.nil(), genJavaLangTypeRef(typeNode, "Double", "doubleToLongBits"), List.of(fieldAccessor)); statements.append(maker.VarDef(maker.Modifiers(finalFlag), dollarFieldName, maker.TypeIdent(CTC_LONG), init)); statements.append(createResultCalculation(typeNode, longToIntForHashCode(maker, maker.Ident(dollarFieldName), maker.Ident(dollarFieldName)))); } break; default: case BYTE: case SHORT: case INT: case CHAR: /* just the field */ statements.append(createResultCalculation(typeNode, fieldAccessor)); break; } } else if (fType instanceof JCArrayTypeTree) { /* java.util.Arrays.deepHashCode(this.fieldName) //use just hashCode() for primitive arrays. */ boolean multiDim = ((JCArrayTypeTree) fType).elemtype instanceof JCArrayTypeTree; boolean primitiveArray = ((JCArrayTypeTree) fType).elemtype instanceof JCPrimitiveTypeTree; boolean useDeepHC = multiDim || !primitiveArray; JCExpression hcMethod = chainDots(typeNode, "java", "util", "Arrays", useDeepHC ? "deepHashCode" : "hashCode"); statements.append(createResultCalculation(typeNode, maker.Apply(List.nil(), hcMethod, List.of(fieldAccessor)))); } else /* objects */ { /* final java.lang.Object $fieldName = this.fieldName; */ /* ($fieldName == null ? NULL_PRIME : $fieldName.hashCode()) */ Name dollarFieldName = dollar.append(((JCVariableDecl) fieldNode.get()).name); statements.append(maker.VarDef(maker.Modifiers(finalFlag), dollarFieldName, genJavaLangTypeRef(typeNode, "Object"), fieldAccessor)); JCExpression hcCall = maker.Apply(List.nil(), maker.Select(maker.Ident(dollarFieldName), typeNode.toName("hashCode")), List.nil()); JCExpression thisEqualsNull = maker.Binary(CTC_EQUAL, maker.Ident(dollarFieldName), maker.Literal(CTC_BOT, null)); statements.append(createResultCalculation(typeNode, maker.Parens(maker.Conditional(thisEqualsNull, maker.Literal(HandlerUtil.primeForNull()), hcCall)))); } } /* return result; */ { statements.append(maker.Return(maker.Ident(resultName))); } JCBlock body = maker.Block(0, statements.toList()); return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("hashCode"), returnType, List.nil(), List.nil(), List.nil(), body, null), source, typeNode.getContext()); } public JCExpressionStatement createResultCalculation(JavacNode typeNode, JCExpression expr) { /* result = result * PRIME + expr; */ JavacTreeMaker maker = typeNode.getTreeMaker(); Name resultName = typeNode.toName(RESULT_NAME); JCExpression mult = maker.Binary(CTC_MUL, maker.Ident(resultName), maker.Ident(typeNode.toName(PRIME_NAME))); JCExpression add = maker.Binary(CTC_PLUS, mult, expr); return maker.Exec(maker.Assign(maker.Ident(resultName), add)); } /** The 2 references must be clones of each other. */ public JCExpression longToIntForHashCode(JavacTreeMaker maker, JCExpression ref1, JCExpression ref2) { /* (int) (ref >>> 32 ^ ref) */ JCExpression shift = maker.Binary(CTC_UNSIGNED_SHIFT_RIGHT, ref1, maker.Literal(32)); JCExpression xorBits = maker.Binary(CTC_BITXOR, shift, ref2); return maker.TypeCast(maker.TypeIdent(CTC_INT), maker.Parens(xorBits)); } public JCExpression createTypeReference(JavacNode type, boolean addWildcards) { java.util.List list = new ArrayList(); list.add(type.getName()); JavacNode tNode = type.up(); while (tNode != null && tNode.getKind() == Kind.TYPE) { list.add(tNode.getName()); tNode = tNode.up(); } Collections.reverse(list); JCClassDecl typeDecl = (JCClassDecl) type.get(); JavacTreeMaker maker = type.getTreeMaker(); JCExpression chain = maker.Ident(type.toName(list.get(0))); for (int i = 1; i < list.size(); i++) { chain = maker.Select(chain, type.toName(list.get(i))); } if (!addWildcards || typeDecl.typarams.length() == 0) return chain; ListBuffer wildcards = new ListBuffer(); for (int i = 0 ; i < typeDecl.typarams.length() ; i++) { wildcards.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null)); } return maker.TypeApply(chain, wildcards.toList()); } public JCMethodDecl createEquals(JavacNode typeNode, List fields, boolean callSuper, FieldAccess fieldAccess, boolean needsCanEqual, JCTree source, List onParam) { JavacTreeMaker maker = typeNode.getTreeMaker(); Name oName = typeNode.toName("o"); Name otherName = typeNode.toName("other"); Name thisName = typeNode.toName("this"); JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.nil()); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); JCExpression objectType = genJavaLangTypeRef(typeNode, "Object"); JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN); long finalFlag = JavacHandlerUtil.addFinalIfNeeded(0L, typeNode.getContext()); ListBuffer statements = new ListBuffer(); final List params = List.of(maker.VarDef(maker.Modifiers(finalFlag | Flags.PARAMETER, onParam), oName, objectType, null)); /* if (o == this) return true; */ { statements.append(maker.If(maker.Binary(CTC_EQUAL, maker.Ident(oName), maker.Ident(thisName)), returnBool(maker, true), null)); } /* if (!(o instanceof Outer.Inner.MyType)) return false; */ { JCUnary notInstanceOf = maker.Unary(CTC_NOT, maker.Parens(maker.TypeTest(maker.Ident(oName), createTypeReference(typeNode, false)))); statements.append(maker.If(notInstanceOf, returnBool(maker, false), null)); } /* Outer.Inner.MyType other = (Outer.Inner.MyType) o; */ { if (!fields.isEmpty() || needsCanEqual) { final JCExpression selfType1 = createTypeReference(typeNode, true), selfType2 = createTypeReference(typeNode, true); statements.append( maker.VarDef(maker.Modifiers(finalFlag), otherName, selfType1, maker.TypeCast(selfType2, maker.Ident(oName)))); } } /* if (!other.canEqual((java.lang.Object) this)) return false; */ { if (needsCanEqual) { List exprNil = List.nil(); JCExpression thisRef = maker.Ident(thisName); JCExpression castThisRef = maker.TypeCast(genJavaLangTypeRef(typeNode, "Object"), thisRef); JCExpression equalityCheck = maker.Apply(exprNil, maker.Select(maker.Ident(otherName), typeNode.toName("canEqual")), List.of(castThisRef)); statements.append(maker.If(maker.Unary(CTC_NOT, equalityCheck), returnBool(maker, false), null)); } } /* if (!super.equals(o)) return false; */ if (callSuper) { JCMethodInvocation callToSuper = maker.Apply(List.nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("equals")), List.of(maker.Ident(oName))); JCUnary superNotEqual = maker.Unary(CTC_NOT, callToSuper); statements.append(maker.If(superNotEqual, returnBool(maker, false), null)); } Name thisDollar = typeNode.toName("this$"); Name otherDollar = typeNode.toName("other$"); for (JavacNode fieldNode : fields) { JCExpression fType = getFieldType(fieldNode, fieldAccess); JCExpression thisFieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess); JCExpression otherFieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess, maker.Ident(otherName)); if (fType instanceof JCPrimitiveTypeTree) { switch (((JCPrimitiveTypeTree)fType).getPrimitiveTypeKind()) { case FLOAT: /* if (Float.compare(this.fieldName, other.fieldName) != 0) return false; */ statements.append(generateCompareFloatOrDouble(thisFieldAccessor, otherFieldAccessor, maker, typeNode, false)); break; case DOUBLE: /* if (Double.compare(this.fieldName, other.fieldName) != 0) return false; */ statements.append(generateCompareFloatOrDouble(thisFieldAccessor, otherFieldAccessor, maker, typeNode, true)); break; default: /* if (this.fieldName != other.fieldName) return false; */ statements.append( maker.If(maker.Binary(CTC_NOT_EQUAL, thisFieldAccessor, otherFieldAccessor), returnBool(maker, false), null)); break; } } else if (fType instanceof JCArrayTypeTree) { /* if (!java.util.Arrays.deepEquals(this.fieldName, other.fieldName)) return false; //use equals for primitive arrays. */ boolean multiDim = ((JCArrayTypeTree) fType).elemtype instanceof JCArrayTypeTree; boolean primitiveArray = ((JCArrayTypeTree) fType).elemtype instanceof JCPrimitiveTypeTree; boolean useDeepEquals = multiDim || !primitiveArray; JCExpression eqMethod = chainDots(typeNode, "java", "util", "Arrays", useDeepEquals ? "deepEquals" : "equals"); List args = List.of(thisFieldAccessor, otherFieldAccessor); statements.append(maker.If(maker.Unary(CTC_NOT, maker.Apply(List.nil(), eqMethod, args)), returnBool(maker, false), null)); } else /* objects */ { /* final java.lang.Object this$fieldName = this.fieldName; */ /* final java.lang.Object other$fieldName = other.fieldName; */ /* if (this$fieldName == null ? other$fieldName != null : !this$fieldName.equals(other$fieldName)) return false; */ Name fieldName = ((JCVariableDecl) fieldNode.get()).name; Name thisDollarFieldName = thisDollar.append(fieldName); Name otherDollarFieldName = otherDollar.append(fieldName); statements.append(maker.VarDef(maker.Modifiers(finalFlag), thisDollarFieldName, genJavaLangTypeRef(typeNode, "Object"), thisFieldAccessor)); statements.append(maker.VarDef(maker.Modifiers(finalFlag), otherDollarFieldName, genJavaLangTypeRef(typeNode, "Object"), otherFieldAccessor)); JCExpression thisEqualsNull = maker.Binary(CTC_EQUAL, maker.Ident(thisDollarFieldName), maker.Literal(CTC_BOT, null)); JCExpression otherNotEqualsNull = maker.Binary(CTC_NOT_EQUAL, maker.Ident(otherDollarFieldName), maker.Literal(CTC_BOT, null)); JCExpression thisEqualsThat = maker.Apply(List.nil(), maker.Select(maker.Ident(thisDollarFieldName), typeNode.toName("equals")), List.of(maker.Ident(otherDollarFieldName))); JCExpression fieldsAreNotEqual = maker.Conditional(thisEqualsNull, otherNotEqualsNull, maker.Unary(CTC_NOT, thisEqualsThat)); statements.append(maker.If(fieldsAreNotEqual, returnBool(maker, false), null)); } } /* return true; */ { statements.append(returnBool(maker, true)); } JCBlock body = maker.Block(0, statements.toList()); return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("equals"), returnType, List.nil(), params, List.nil(), body, null), source, typeNode.getContext()); } public JCMethodDecl createCanEqual(JavacNode typeNode, JCTree source, List onParam) { /* protected boolean canEqual(final java.lang.Object other) { * return other instanceof Outer.Inner.MyType; * } */ JavacTreeMaker maker = typeNode.getTreeMaker(); JCModifiers mods = maker.Modifiers(Flags.PROTECTED, List.nil()); JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN); Name canEqualName = typeNode.toName("canEqual"); JCExpression objectType = genJavaLangTypeRef(typeNode, "Object"); Name otherName = typeNode.toName("other"); long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext()); List params = List.of(maker.VarDef(maker.Modifiers(flags, onParam), otherName, objectType, null)); JCBlock body = maker.Block(0, List.of( maker.Return(maker.TypeTest(maker.Ident(otherName), createTypeReference(typeNode, false))))); return recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.nil(), params, List.nil(), body, null), source, typeNode.getContext()); } public JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField, JavacTreeMaker maker, JavacNode node, boolean isDouble) { /* if (Float.compare(fieldName, other.fieldName) != 0) return false; */ JCExpression clazz = genJavaLangTypeRef(node, isDouble ? "Double" : "Float"); List args = List.of(thisDotField, otherDotField); JCBinary compareCallEquals0 = maker.Binary(CTC_NOT_EQUAL, maker.Apply( List.nil(), maker.Select(clazz, node.toName("compare")), args), maker.Literal(0)); return maker.If(compareCallEquals0, returnBool(maker, false), null); } public JCStatement returnBool(JavacTreeMaker maker, boolean bool) { return maker.Return(maker.Literal(CTC_BOOLEAN, bool ? 1 : 0)); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleExtensionMethod.java000066400000000000000000000212531312655740700261520ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static com.sun.tools.javac.code.Flags.*; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import static lombok.javac.handlers.JavacResolver.*; import java.util.ArrayList; import java.util.List; import javax.lang.model.element.ElementKind; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.experimental.ExtensionMethod; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import org.mangosdk.spi.ProviderFor; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Type.ErrorType; import com.sun.tools.javac.code.Type.ForAll; import com.sun.tools.javac.code.Type.MethodType; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; /** * Handles the {@link ExtensionMethod} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(66560) // 2^16 + 2^10; we must run AFTER HandleVal which is at 2^16 public class HandleExtensionMethod extends JavacAnnotationHandler { @Override public void handle(final AnnotationValues annotation, final JCAnnotation source, final JavacNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.EXTENSION_METHOD_FLAG_USAGE, "@ExtensionMethod"); deleteAnnotationIfNeccessary(annotationNode, ExtensionMethod.class); JavacNode typeNode = annotationNode.up(); boolean isClassOrEnum = isClassOrEnum(typeNode); if (!isClassOrEnum) { annotationNode.addError("@ExtensionMethod can only be used on a class or an enum"); return; } boolean suppressBaseMethods = annotation.getInstance().suppressBaseMethods(); List extensionProviders = annotation.getActualExpressions("value"); if (extensionProviders.isEmpty()) { annotationNode.addError(String.format("@%s has no effect since no extension types were specified.", ExtensionMethod.class.getName())); return; } final List extensions = getExtensions(annotationNode, extensionProviders); if (extensions.isEmpty()) return; new ExtensionMethodReplaceVisitor(annotationNode, extensions, suppressBaseMethods).replace(); annotationNode.rebuild(); } public List getExtensions(final JavacNode typeNode, final List extensionProviders) { List extensions = new ArrayList(); for (Object extensionProvider : extensionProviders) { if (!(extensionProvider instanceof JCFieldAccess)) continue; JCFieldAccess provider = (JCFieldAccess) extensionProvider; if (!("class".equals(provider.name.toString()))) continue; Type providerType = CLASS.resolveMember(typeNode, provider.selected); if (providerType == null) continue; if ((providerType.tsym.flags() & (INTERFACE | ANNOTATION)) != 0) continue; extensions.add(getExtension(typeNode, (ClassType) providerType)); } return extensions; } public Extension getExtension(final JavacNode typeNode, final ClassType extensionMethodProviderType) { List extensionMethods = new ArrayList(); TypeSymbol tsym = extensionMethodProviderType.asElement(); if (tsym != null) for (Symbol member : tsym.getEnclosedElements()) { if (member.getKind() != ElementKind.METHOD) continue; MethodSymbol method = (MethodSymbol) member; if ((method.flags() & (STATIC | PUBLIC)) == 0) continue; if (method.params().isEmpty()) continue; extensionMethods.add(method); } return new Extension(extensionMethods, tsym); } private static class Extension { final List extensionMethods; final TypeSymbol extensionProvider; public Extension(List extensionMethods, TypeSymbol extensionProvider) { this.extensionMethods = extensionMethods; this.extensionProvider = extensionProvider; } } private static class ExtensionMethodReplaceVisitor extends TreeScanner { final JavacNode annotationNode; final List extensions; final boolean suppressBaseMethods; public ExtensionMethodReplaceVisitor(JavacNode annotationNode, List extensions, boolean suppressBaseMethods) { this.annotationNode = annotationNode; this.extensions = extensions; this.suppressBaseMethods = suppressBaseMethods; } public void replace() { annotationNode.up().get().accept(this, null); } @Override public Void visitMethodInvocation(final MethodInvocationTree tree, final Void p) { handleMethodCall((JCMethodInvocation) tree); return super.visitMethodInvocation(tree, p); } private void handleMethodCall(final JCMethodInvocation methodCall) { JavacNode methodCallNode = annotationNode.getAst().get(methodCall); if (methodCallNode == null) { // This should mean the node does not exist in the source at all. This is the case for generated nodes, such as implicit super() calls. return; } JavacNode surroundingType = upToTypeNode(methodCallNode); TypeSymbol surroundingTypeSymbol = ((JCClassDecl)surroundingType.get()).sym; JCExpression receiver = receiverOf(methodCall); String methodName = methodNameOf(methodCall); if ("this".equals(methodName) || "super".equals(methodName)) return; Type resolvedMethodCall = CLASS_AND_METHOD.resolveMember(methodCallNode, methodCall); if (resolvedMethodCall == null) return; if (!suppressBaseMethods && !(resolvedMethodCall instanceof ErrorType)) return; Type receiverType = CLASS_AND_METHOD.resolveMember(methodCallNode, receiver); if (receiverType == null) return; if (receiverType.tsym.toString().endsWith(receiver.toString())) return; Types types = Types.instance(annotationNode.getContext()); for (Extension extension : extensions) { TypeSymbol extensionProvider = extension.extensionProvider; if (surroundingTypeSymbol == extensionProvider) continue; for (MethodSymbol extensionMethod : extension.extensionMethods) { if (!methodName.equals(extensionMethod.name.toString())) continue; Type extensionMethodType = extensionMethod.type; if (!MethodType.class.isInstance(extensionMethodType) && !ForAll.class.isInstance(extensionMethodType)) continue; Type firstArgType = types.erasure(extensionMethodType.asMethodType().argtypes.get(0)); if (!types.isAssignable(receiverType, firstArgType)) continue; methodCall.args = methodCall.args.prepend(receiver); methodCall.meth = chainDotsString(annotationNode, extensionProvider.toString() + "." + methodName); return; } } } private String methodNameOf(final JCMethodInvocation methodCall) { if (methodCall.meth instanceof JCIdent) { return ((JCIdent) methodCall.meth).name.toString(); } else { return ((JCFieldAccess) methodCall.meth).name.toString(); } } private JCExpression receiverOf(final JCMethodInvocation methodCall) { if (methodCall.meth instanceof JCIdent) { return annotationNode.getTreeMaker().Ident(annotationNode.toName("this")); } else { return ((JCFieldAccess) methodCall.meth).selected; } } } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleFieldDefaults.java000066400000000000000000000144651312655740700255570ustar00rootroot00000000000000/* * Copyright (C) 2012-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.experimental.FieldDefaults; import lombok.experimental.NonFinal; import lombok.experimental.PackagePrivate; import lombok.javac.JavacASTAdapter; import lombok.javac.JavacASTVisitor; import lombok.javac.JavacNode; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; /** * Handles the {@code lombok.FieldDefaults} annotation for eclipse. */ @ProviderFor(JavacASTVisitor.class) @HandlerPriority(-2048) //-2^11; to ensure @Value picks up on messing with the fields' 'final' state, run earlier. public class HandleFieldDefaults extends JavacASTAdapter { public boolean generateFieldDefaultsForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean makeFinal, boolean checkForTypeLevelFieldDefaults) { if (checkForTypeLevelFieldDefaults) { if (hasAnnotation(FieldDefaults.class, typeNode)) { //The annotation will make it happen, so we can skip it. return true; } } JCClassDecl typeDecl = null; if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION)) != 0; if (typeDecl == null || notAClass) { errorNode.addError("@FieldDefaults is only supported on a class or an enum."); return false; } for (JavacNode field : typeNode.down()) { if (field.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); //Skip fields that start with $ if (fieldDecl.name.toString().startsWith("$")) continue; setFieldDefaultsForField(field, level, makeFinal); } return true; } public void setFieldDefaultsForField(JavacNode fieldNode, AccessLevel level, boolean makeFinal) { JCVariableDecl field = (JCVariableDecl) fieldNode.get(); if (level != null && level != AccessLevel.NONE) { if ((field.mods.flags & (Flags.PUBLIC | Flags.PRIVATE | Flags.PROTECTED)) == 0) { if (!hasAnnotationAndDeleteIfNeccessary(PackagePrivate.class, fieldNode)) { if ((field.mods.flags & Flags.STATIC) == 0) { field.mods.flags |= toJavacModifier(level); } } } } if (makeFinal && (field.mods.flags & Flags.FINAL) == 0) { if (!hasAnnotationAndDeleteIfNeccessary(NonFinal.class, fieldNode)) { if ((field.mods.flags & Flags.STATIC) == 0) { field.mods.flags |= Flags.FINAL; } } } fieldNode.rebuild(); } @Override public void visitType(JavacNode typeNode, JCClassDecl type) { AnnotationValues fieldDefaults = null; JavacNode source = typeNode; boolean levelIsExplicit = false; boolean makeFinalIsExplicit = false; FieldDefaults fd = null; for (JavacNode jn : typeNode.down()) { if (jn.getKind() != Kind.ANNOTATION) continue; JCAnnotation ann = (JCAnnotation) jn.get(); JCTree typeTree = ann.annotationType; if (typeTree == null) continue; String typeTreeToString = typeTree.toString(); if (!typeTreeToString.equals("FieldDefaults") && !typeTreeToString.equals("lombok.experimental.FieldDefaults")) continue; if (!typeMatches(FieldDefaults.class, jn, typeTree)) continue; source = jn; fieldDefaults = createAnnotation(FieldDefaults.class, jn); levelIsExplicit = fieldDefaults.isExplicit("level"); makeFinalIsExplicit = fieldDefaults.isExplicit("makeFinal"); handleExperimentalFlagUsage(jn, ConfigurationKeys.FIELD_DEFAULTS_FLAG_USAGE, "@FieldDefaults"); fd = fieldDefaults.getInstance(); if (!levelIsExplicit && !makeFinalIsExplicit) { jn.addError("This does nothing; provide either level or makeFinal or both."); } if (levelIsExplicit && fd.level() == AccessLevel.NONE) { jn.addError("AccessLevel.NONE doesn't mean anything here. Pick another value."); levelIsExplicit = false; } deleteAnnotationIfNeccessary(jn, FieldDefaults.class); deleteImportFromCompilationUnit(jn, "lombok.AccessLevel"); break; } if (fd == null && (type.mods.flags & (Flags.INTERFACE | Flags.ANNOTATION)) != 0) return; boolean defaultToPrivate = levelIsExplicit ? false : Boolean.TRUE.equals(typeNode.getAst().readConfiguration(ConfigurationKeys.FIELD_DEFAULTS_PRIVATE_EVERYWHERE)); boolean defaultToFinal = makeFinalIsExplicit ? false : Boolean.TRUE.equals(typeNode.getAst().readConfiguration(ConfigurationKeys.FIELD_DEFAULTS_FINAL_EVERYWHERE)); if (!defaultToPrivate && !defaultToFinal && fieldDefaults == null) return; AccessLevel fdAccessLevel = (fieldDefaults != null && levelIsExplicit) ? fd.level() : defaultToPrivate ? AccessLevel.PRIVATE : null; boolean fdToFinal = (fieldDefaults != null && makeFinalIsExplicit) ? fd.makeFinal() : defaultToFinal; generateFieldDefaultsForType(typeNode, source, fdAccessLevel, fdToFinal, false); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleGetter.java000066400000000000000000000446031312655740700242730ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.Javac.*; import static lombok.javac.JavacTreeMaker.TypeTag.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.experimental.Delegate; import lombok.Getter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.JavacTreeMaker.TypeTag; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCIf; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCSynchronized; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; /** * Handles the {@code lombok.Getter} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public class HandleGetter extends JavacAnnotationHandler { public void generateGetterForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean checkForTypeLevelGetter) { if (checkForTypeLevelGetter) { if (hasAnnotation(Getter.class, typeNode)) { //The annotation will make it happen, so we can skip it. return; } } JCClassDecl typeDecl = null; if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION)) != 0; if (typeDecl == null || notAClass) { errorNode.addError("@Getter is only supported on a class, an enum, or a field."); return; } for (JavacNode field : typeNode.down()) { if (fieldQualifiesForGetterGeneration(field)) generateGetterForField(field, errorNode.get(), level, false); } } public boolean fieldQualifiesForGetterGeneration(JavacNode field) { if (field.getKind() != Kind.FIELD) return false; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); //Skip fields that start with $ if (fieldDecl.name.toString().startsWith("$")) return false; //Skip static fields. if ((fieldDecl.mods.flags & Flags.STATIC) != 0) return false; return true; } /** * Generates a getter on the stated field. * * Used by {@link HandleData}. * * The difference between this call and the handle method is as follows: * * If there is a {@code lombok.Getter} annotation on the field, it is used and the * same rules apply (e.g. warning if the method already exists, stated access level applies). * If not, the getter is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. * * @param fieldNode The node representing the field you want a getter for. * @param pos The node responsible for generating the getter (the {@code @Data} or {@code @Getter} annotation). */ public void generateGetterForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level, boolean lazy) { if (hasAnnotation(Getter.class, fieldNode)) { //The annotation will make it happen, so we can skip it. return; } createGetterForField(level, fieldNode, fieldNode, false, lazy, List.nil()); } @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.GETTER_FLAG_USAGE, "@Getter"); Collection fields = annotationNode.upFromAnnotationToFields(); deleteAnnotationIfNeccessary(annotationNode, Getter.class); deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); JavacNode node = annotationNode.up(); Getter annotationInstance = annotation.getInstance(); AccessLevel level = annotationInstance.value(); boolean lazy = annotationInstance.lazy(); if (lazy) handleFlagUsage(annotationNode, ConfigurationKeys.GETTER_LAZY_FLAG_USAGE, "@Getter(lazy=true)"); if (level == AccessLevel.NONE) { if (lazy) annotationNode.addWarning("'lazy' does not work with AccessLevel.NONE."); return; } if (node == null) return; List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Getter(onMethod", annotationNode); switch (node.getKind()) { case FIELD: createGetterForFields(level, fields, annotationNode, true, lazy, onMethod); break; case TYPE: if (!onMethod.isEmpty()) { annotationNode.addError("'onMethod' is not supported for @Getter on a type."); } if (lazy) annotationNode.addError("'lazy' is not supported for @Getter on a type."); generateGetterForType(node, annotationNode, level, false); break; } } public void createGetterForFields(AccessLevel level, Collection fieldNodes, JavacNode errorNode, boolean whineIfExists, boolean lazy, List onMethod) { for (JavacNode fieldNode : fieldNodes) { createGetterForField(level, fieldNode, errorNode, whineIfExists, lazy, onMethod); } } public void createGetterForField(AccessLevel level, JavacNode fieldNode, JavacNode source, boolean whineIfExists, boolean lazy, List onMethod) { if (fieldNode.getKind() != Kind.FIELD) { source.addError("@Getter is only supported on a class or a field."); return; } JCVariableDecl fieldDecl = (JCVariableDecl)fieldNode.get(); if (lazy) { if ((fieldDecl.mods.flags & Flags.PRIVATE) == 0 || (fieldDecl.mods.flags & Flags.FINAL) == 0) { source.addError("'lazy' requires the field to be private and final."); return; } if ((fieldDecl.mods.flags & Flags.TRANSIENT) != 0) { source.addError("'lazy' is not supported on transient fields."); return; } if (fieldDecl.init == null) { source.addError("'lazy' requires field initialization."); return; } } String methodName = toGetterName(fieldNode); if (methodName == null) { source.addWarning("Not generating getter for this field: It does not fit your @Accessors prefix list."); return; } for (String altName : toAllGetterNames(fieldNode)) { switch (methodExists(altName, fieldNode, false, 0)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: if (whineIfExists) { String altNameExpl = ""; if (!altName.equals(methodName)) altNameExpl = String.format(" (%s)", altName); source.addWarning( String.format("Not generating %s(): A method with that name already exists%s", methodName, altNameExpl)); } return; default: case NOT_EXISTS: //continue scanning the other alt names. } } long access = toJavacModifier(level) | (fieldDecl.mods.flags & Flags.STATIC); injectMethod(fieldNode.up(), createGetter(access, fieldNode, fieldNode.getTreeMaker(), source.get(), lazy, onMethod), List.nil(), getMirrorForFieldType(fieldNode)); } public JCMethodDecl createGetter(long access, JavacNode field, JavacTreeMaker treeMaker, JCTree source, boolean lazy, List onMethod) { JCVariableDecl fieldNode = (JCVariableDecl) field.get(); // Remember the type; lazy will change it JCExpression methodType = copyType(treeMaker, fieldNode); // Generate the methodName; lazy will change the field type Name methodName = field.toName(toGetterName(field)); List statements; JCTree toClearOfMarkers = null; if (lazy && !inNetbeansEditor(field)) { toClearOfMarkers = fieldNode.init; statements = createLazyGetterBody(treeMaker, field, source); } else { statements = createSimpleGetterBody(treeMaker, field); } JCBlock methodBody = treeMaker.Block(0, statements); List methodGenericParams = List.nil(); List parameters = List.nil(); List throwsClauses = List.nil(); JCExpression annotationMethodDefaultValue = null; List nonNulls = findAnnotations(field, NON_NULL_PATTERN); List nullables = findAnnotations(field, NULLABLE_PATTERN); List delegates = findDelegatesAndRemoveFromField(field); List annsOnMethod = copyAnnotations(onMethod).appendList(nonNulls).appendList(nullables); if (isFieldDeprecated(field)) { annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.nil())); } JCMethodDecl decl = recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType, methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source, field.getContext()); if (toClearOfMarkers != null) recursiveSetGeneratedBy(toClearOfMarkers, null, null); decl.mods.annotations = decl.mods.annotations.appendList(delegates); copyJavadoc(field, decl, CopyJavadoc.GETTER); return decl; } public static List findDelegatesAndRemoveFromField(JavacNode field) { JCVariableDecl fieldNode = (JCVariableDecl) field.get(); List delegates = List.nil(); for (JCAnnotation annotation : fieldNode.mods.annotations) { if (typeMatches(Delegate.class, field, annotation.annotationType)) { delegates = delegates.append(annotation); } } if (!delegates.isEmpty()) { ListBuffer withoutDelegates = new ListBuffer(); for (JCAnnotation annotation : fieldNode.mods.annotations) { if (!delegates.contains(annotation)) { withoutDelegates.append(annotation); } } fieldNode.mods.annotations = withoutDelegates.toList(); field.rebuild(); } return delegates; } public List createSimpleGetterBody(JavacTreeMaker treeMaker, JavacNode field) { return List.of(treeMaker.Return(createFieldAccessor(treeMaker, field, FieldAccess.ALWAYS_FIELD))); } private static final String AR = "java.util.concurrent.atomic.AtomicReference"; private static final List NIL_EXPRESSION = List.nil(); public static final java.util.Map TYPE_MAP; static { Map m = new HashMap(); m.put(CTC_INT, "Integer"); m.put(CTC_DOUBLE, "Double"); m.put(CTC_FLOAT, "Float"); m.put(CTC_SHORT, "Short"); m.put(CTC_BYTE, "Byte"); m.put(CTC_LONG, "Long"); m.put(CTC_BOOLEAN, "Boolean"); m.put(CTC_CHAR, "Character"); TYPE_MAP = Collections.unmodifiableMap(m); } public List createLazyGetterBody(JavacTreeMaker maker, JavacNode fieldNode, JCTree source) { /* java.lang.Object value = this.fieldName.get(); if (value == null) { synchronized (this.fieldName) { value = this.fieldName.get(); if (value == null) { final RawValueType actualValue = INITIALIZER_EXPRESSION; [IF PRIMITIVE] value = actualValue; [ELSE] value = actualValue == null ? this.fieldName : actualValue; [END IF] this.fieldName.set(value); } } } [IF PRIMITIVE] return (BoxedValueType) value; [ELSE] return (BoxedValueType) (value == this.fieldName ? null : value); [END IF] */ ListBuffer statements = new ListBuffer(); JCVariableDecl field = (JCVariableDecl) fieldNode.get(); JCExpression copyOfRawFieldType = copyType(maker, field); JCExpression copyOfBoxedFieldType = null; field.type = null; boolean isPrimitive = false; if (field.vartype instanceof JCPrimitiveTypeTree) { String boxed = TYPE_MAP.get(typeTag(field.vartype)); if (boxed != null) { isPrimitive = true; field.vartype = genJavaLangTypeRef(fieldNode, boxed); copyOfBoxedFieldType = genJavaLangTypeRef(fieldNode, boxed); } } if (copyOfBoxedFieldType == null) copyOfBoxedFieldType = copyType(maker, field); Name valueName = fieldNode.toName("value"); Name actualValueName = fieldNode.toName("actualValue"); /* java.lang.Object value = this.fieldName.get();*/ { JCExpression valueVarType = genJavaLangTypeRef(fieldNode, "Object"); statements.append(maker.VarDef(maker.Modifiers(0), valueName, valueVarType, callGet(fieldNode, createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD)))); } /* if (value == null) { */ { JCSynchronized synchronizedStatement; /* synchronized (this.fieldName) { */ { ListBuffer synchronizedStatements = new ListBuffer(); /* value = this.fieldName.get(); */ { JCExpressionStatement newAssign = maker.Exec(maker.Assign(maker.Ident(valueName), callGet(fieldNode, createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD)))); synchronizedStatements.append(newAssign); } /* if (value == null) { */ { ListBuffer innerIfStatements = new ListBuffer(); /* final RawValueType actualValue = INITIALIZER_EXPRESSION; */ { innerIfStatements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), actualValueName, copyOfRawFieldType, field.init)); } /* [IF primitive] value = actualValue; */ { if (isPrimitive) { JCStatement statement = maker.Exec(maker.Assign(maker.Ident(valueName), maker.Ident(actualValueName))); innerIfStatements.append(statement); } } /* [ELSE] value = actualValue == null ? this.fieldName : actualValue; */ { if (!isPrimitive) { JCExpression actualValueIsNull = maker.Binary(CTC_EQUAL, maker.Ident(actualValueName), maker.Literal(CTC_BOT, null)); JCExpression thisDotFieldName = createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD); JCExpression ternary = maker.Conditional(actualValueIsNull, thisDotFieldName, maker.Ident(actualValueName)); JCStatement statement = maker.Exec(maker.Assign(maker.Ident(valueName), ternary)); innerIfStatements.append(statement); } } /* this.fieldName.set(value); */ { JCStatement statement = callSet(fieldNode, createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD), maker.Ident(valueName)); innerIfStatements.append(statement); } JCBinary isNull = maker.Binary(CTC_EQUAL, maker.Ident(valueName), maker.Literal(CTC_BOT, null)); JCIf ifStatement = maker.If(isNull, maker.Block(0, innerIfStatements.toList()), null); synchronizedStatements.append(ifStatement); } synchronizedStatement = maker.Synchronized(createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD), maker.Block(0, synchronizedStatements.toList())); } JCBinary isNull = maker.Binary(CTC_EQUAL, maker.Ident(valueName), maker.Literal(CTC_BOT, null)); JCIf ifStatement = maker.If(isNull, maker.Block(0, List.of(synchronizedStatement)), null); statements.append(ifStatement); } /* [IF PRIMITIVE] return (BoxedValueType) value; */ { if (isPrimitive) { statements.append(maker.Return(maker.TypeCast(copyOfBoxedFieldType, maker.Ident(valueName)))); } } /* [ELSE] return (BoxedValueType) (value == this.fieldName ? null : value); */ { if (!isPrimitive) { JCExpression valueEqualsSelf = maker.Binary(CTC_EQUAL, maker.Ident(valueName), createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD)); JCExpression ternary = maker.Conditional(valueEqualsSelf, maker.Literal(CTC_BOT, null), maker.Ident(valueName)); JCExpression typeCast = maker.TypeCast(copyOfBoxedFieldType, maker.Parens(ternary)); statements.append(maker.Return(typeCast)); } } // update the field type and init last /* private final java.util.concurrent.atomic.AtomicReference fieldName = new java.util.concurrent.atomic.AtomicReference(); */ { field.vartype = recursiveSetGeneratedBy( maker.TypeApply(chainDotsString(fieldNode, AR), List.of(genJavaLangTypeRef(fieldNode, "Object"))), source, fieldNode.getContext()); field.init = recursiveSetGeneratedBy(maker.NewClass(null, NIL_EXPRESSION, copyType(maker, field), NIL_EXPRESSION, null), source, fieldNode.getContext()); } return statements.toList(); } public JCMethodInvocation callGet(JavacNode source, JCExpression receiver) { JavacTreeMaker maker = source.getTreeMaker(); return maker.Apply(NIL_EXPRESSION, maker.Select(receiver, source.toName("get")), NIL_EXPRESSION); } public JCStatement callSet(JavacNode source, JCExpression receiver, JCExpression value) { JavacTreeMaker maker = source.getTreeMaker(); return maker.Exec(maker.Apply(NIL_EXPRESSION, maker.Select(receiver, source.toName("set")), List.of(value))); } public JCExpression copyType(JavacTreeMaker treeMaker, JCVariableDecl fieldNode) { return fieldNode.type != null ? treeMaker.Type(fieldNode.type) : fieldNode.vartype; } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleHelper.java000066400000000000000000000137661312655740700242660ustar00rootroot00000000000000/* * Copyright (C) 2015-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import org.mangosdk.spi.ProviderFor; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.TreeVisitor; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCCase; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import lombok.ConfigurationKeys; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.experimental.Helper; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; @ProviderFor(JavacAnnotationHandler.class) public class HandleHelper extends JavacAnnotationHandler { private List getStatementsFromJcNode(JCTree tree) { if (tree instanceof JCBlock) return ((JCBlock) tree).stats; if (tree instanceof JCCase) return ((JCCase) tree).stats; return null; } private void setStatementsOfJcNode(JCTree tree, List statements) { if (tree instanceof JCBlock) ((JCBlock) tree).stats = statements; else if (tree instanceof JCCase) ((JCCase) tree).stats = statements; else throw new IllegalArgumentException("Can't set statements on node type: " + tree.getClass()); } @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.HELPER_FLAG_USAGE, "@Helper"); deleteAnnotationIfNeccessary(annotationNode, Helper.class); JavacNode annotatedType = annotationNode.up(); JavacNode containingBlock = annotatedType == null ? null : annotatedType.directUp(); List origStatements = getStatementsFromJcNode(containingBlock == null ? null : containingBlock.get()); if (annotatedType == null || annotatedType.getKind() != Kind.TYPE || origStatements == null) { annotationNode.addError("@Helper is legal only on method-local classes."); return; } JCClassDecl annotatedType_ = (JCClassDecl) annotatedType.get(); Iterator it = origStatements.iterator(); while (it.hasNext()) { if (it.next() == annotatedType_) { break; } } java.util.List knownMethodNames = new ArrayList(); for (JavacNode ch : annotatedType.down()) { if (ch.getKind() != Kind.METHOD) continue; String n = ch.getName(); if (n == null || n.isEmpty() || n.charAt(0) == '<') continue; knownMethodNames.add(n); } Collections.sort(knownMethodNames); final String[] knownMethodNames_ = knownMethodNames.toArray(new String[knownMethodNames.size()]); final Name helperName = annotationNode.toName("$" + annotatedType_.name); final boolean[] helperUsed = new boolean[1]; final JavacTreeMaker maker = annotationNode.getTreeMaker(); TreeVisitor visitor = new TreeScanner() { @Override public Void visitMethodInvocation(MethodInvocationTree node, Void p) { JCMethodInvocation jcmi = (JCMethodInvocation) node; apply(jcmi); return super.visitMethodInvocation(node, p); } private void apply(JCMethodInvocation jcmi) { if (!(jcmi.meth instanceof JCIdent)) return; JCIdent jci = (JCIdent) jcmi.meth; if (Arrays.binarySearch(knownMethodNames_, jci.name.toString()) < 0) return; jcmi.meth = maker.Select(maker.Ident(helperName), jci.name); helperUsed[0] = true; } }; while (it.hasNext()) { JCStatement stat = it.next(); stat.accept(visitor, null); } if (!helperUsed[0]) { annotationNode.addWarning("No methods of this helper class are ever used."); return; } ListBuffer newStatements = new ListBuffer(); boolean mark = false; for (JCStatement stat : origStatements) { newStatements.append(stat); if (mark || stat != annotatedType_) continue; mark = true; JCExpression init = maker.NewClass(null, List.nil(), maker.Ident(annotatedType_.name), List.nil(), null); JCExpression varType = maker.Ident(annotatedType_.name); JCVariableDecl decl = maker.VarDef(maker.Modifiers(Flags.FINAL), helperName, varType, init); newStatements.append(decl); } setStatementsOfJcNode(containingBlock.get(), newStatements.toList()); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleLog.java000066400000000000000000000271231312655740700235600ustar00rootroot00000000000000/* * Copyright (C) 2010-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.lang.annotation.Annotation; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Name; public class HandleLog { private HandleLog() { throw new UnsupportedOperationException(); } public static void processAnnotation(LoggingFramework framework, AnnotationValues annotation, JavacNode annotationNode, String loggerTopic) { deleteAnnotationIfNeccessary(annotationNode, framework.getAnnotationClass()); JavacNode typeNode = annotationNode.up(); switch (typeNode.getKind()) { case TYPE: String logFieldName = annotationNode.getAst().readConfiguration(ConfigurationKeys.LOG_ANY_FIELD_NAME); if (logFieldName == null) logFieldName = "log"; boolean useStatic = !Boolean.FALSE.equals(annotationNode.getAst().readConfiguration(ConfigurationKeys.LOG_ANY_FIELD_IS_STATIC)); if ((((JCClassDecl)typeNode.get()).mods.flags & Flags.INTERFACE) != 0) { annotationNode.addError("@Log is legal only on classes and enums."); return; } if (fieldExists(logFieldName, typeNode) != MemberExistsResult.NOT_EXISTS) { annotationNode.addWarning("Field '" + logFieldName + "' already exists."); return; } JCFieldAccess loggingType = selfType(typeNode); createField(framework, typeNode, loggingType, annotationNode.get(), logFieldName, useStatic, loggerTopic); break; default: annotationNode.addError("@Log is legal only on types."); break; } } public static JCFieldAccess selfType(JavacNode typeNode) { JavacTreeMaker maker = typeNode.getTreeMaker(); Name name = ((JCClassDecl) typeNode.get()).name; return maker.Select(maker.Ident(name), typeNode.toName("class")); } private static boolean createField(LoggingFramework framework, JavacNode typeNode, JCFieldAccess loggingType, JCTree source, String logFieldName, boolean useStatic, String loggerTopic) { JavacTreeMaker maker = typeNode.getTreeMaker(); // private static final log = (); JCExpression loggerType = chainDotsString(typeNode, framework.getLoggerTypeName()); JCExpression factoryMethod = chainDotsString(typeNode, framework.getLoggerFactoryMethodName()); JCExpression loggerName; if (loggerTopic == null || loggerTopic.trim().length() == 0) { loggerName = framework.createFactoryParameter(typeNode, loggingType); } else { loggerName = maker.Literal(loggerTopic); } JCMethodInvocation factoryMethodCall = maker.Apply(List.nil(), factoryMethod, List.of(loggerName)); JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef( maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (useStatic ? Flags.STATIC : 0)), typeNode.toName(logFieldName), loggerType, factoryMethodCall), source, typeNode.getContext()); injectFieldAndMarkGenerated(typeNode, fieldDecl); return true; } /** * Handles the {@link lombok.extern.apachecommons.CommonsLog} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public static class HandleCommonsLog extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_COMMONS_FLAG_USAGE, "@apachecommons.CommonsLog", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.COMMONS, annotation, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.java.Log} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public static class HandleJulLog extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_JUL_FLAG_USAGE, "@java.Log", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.JUL, annotation, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.log4j.Log4j} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public static class HandleLog4jLog extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_LOG4J_FLAG_USAGE, "@Log4j", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.LOG4J, annotation, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.log4j.Log4j2} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public static class HandleLog4j2Log extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_LOG4J2_FLAG_USAGE, "@Log4j2", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.LOG4J2, annotation, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.slf4j.Slf4j} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public static class HandleSlf4jLog extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_SLF4J_FLAG_USAGE, "@Slf4j", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.SLF4J, annotation, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.slf4j.XSlf4j} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public static class HandleXSlf4jLog extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_XSLF4J_FLAG_USAGE, "@XSlf4j", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.XSLF4J, annotation, annotationNode, annotation.getInstance().topic()); } } /** * Handles the {@link lombok.extern.jbosslog.JBossLog} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public static class HandleJBossLog extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.LOG_JBOSSLOG_FLAG_USAGE, "@JBossLog", ConfigurationKeys.LOG_ANY_FLAG_USAGE, "any @Log"); processAnnotation(LoggingFramework.JBOSSLOG, annotation, annotationNode, annotation.getInstance().topic()); } } enum LoggingFramework { // private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(TargetType.class); COMMONS(lombok.extern.apachecommons.CommonsLog.class, "org.apache.commons.logging.Log", "org.apache.commons.logging.LogFactory.getLog"), // private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(TargetType.class.getName()); JUL(lombok.extern.java.Log.class, "java.util.logging.Logger", "java.util.logging.Logger.getLogger") { @Override public JCExpression createFactoryParameter(JavacNode typeNode, JCFieldAccess loggingType) { JavacTreeMaker maker = typeNode.getTreeMaker(); JCExpression method = maker.Select(loggingType, typeNode.toName("getName")); return maker.Apply(List.nil(), method, List.nil()); } }, // private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(TargetType.class); LOG4J(lombok.extern.log4j.Log4j.class, "org.apache.log4j.Logger", "org.apache.log4j.Logger.getLogger"), // private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(TargetType.class); LOG4J2(lombok.extern.log4j.Log4j2.class, "org.apache.logging.log4j.Logger", "org.apache.logging.log4j.LogManager.getLogger"), // private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TargetType.class); SLF4J(lombok.extern.slf4j.Slf4j.class, "org.slf4j.Logger", "org.slf4j.LoggerFactory.getLogger"), // private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(TargetType.class); XSLF4J(lombok.extern.slf4j.XSlf4j.class, "org.slf4j.ext.XLogger", "org.slf4j.ext.XLoggerFactory.getXLogger"), // private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(TargetType.class); JBOSSLOG(lombok.extern.jbosslog.JBossLog.class, "org.jboss.logging.Logger", "org.jboss.logging.Logger.getLogger") ; private final Class annotationClass; private final String loggerTypeName; private final String loggerFactoryName; LoggingFramework(Class annotationClass, String loggerTypeName, String loggerFactoryName) { this.annotationClass = annotationClass; this.loggerTypeName = loggerTypeName; this.loggerFactoryName = loggerFactoryName; } final Class getAnnotationClass() { return annotationClass; } final String getLoggerTypeName() { return loggerTypeName; } final String getLoggerFactoryMethodName() { return loggerFactoryName; } JCExpression createFactoryParameter(JavacNode typeNode, JCFieldAccess loggingType) { return loggingType; } } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleNonNull.java000066400000000000000000000163621312655740700244270ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCIf; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCParens; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCSynchronized; import com.sun.tools.javac.tree.JCTree.JCThrow; import com.sun.tools.javac.tree.JCTree.JCTry; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import lombok.ConfigurationKeys; import lombok.NonNull; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.core.AST.Kind; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import static lombok.javac.JavacTreeMaker.TypeTag.*; import static lombok.javac.JavacTreeMaker.TreeTag.*; @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(value = 512) // 2^9; onParameter=@__(@NonNull) has to run first. public class HandleNonNull extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.NON_NULL_FLAG_USAGE, "@NonNull"); if (annotationNode.up().getKind() == Kind.FIELD) { // This is meaningless unless the field is used to generate a method (@Setter, @RequiredArgsConstructor, etc), // but in that case those handlers will take care of it. However, we DO check if the annotation is applied to // a primitive, because those handlers trigger on any annotation named @NonNull and we only want the warning // behaviour on _OUR_ 'lombok.NonNull'. try { if (isPrimitive(((JCVariableDecl) annotationNode.up().get()).vartype)) { annotationNode.addWarning("@NonNull is meaningless on a primitive."); } } catch (Exception ignore) {} return; } if (annotationNode.up().getKind() != Kind.ARGUMENT) return; JCMethodDecl declaration; try { declaration = (JCMethodDecl) annotationNode.up().up().get(); } catch (Exception e) { return; } if (declaration.body == null) { // This used to be a warning, but as @NonNull also has a documentary purpose, better to not warn about this. Since 1.16.7 return; } // Possibly, if 'declaration instanceof ConstructorDeclaration', fetch declaration.constructorCall, search it for any references to our parameter, // and if they exist, create a new method in the class: 'private static T lombok$nullCheck(T expr, String msg) {if (expr == null) throw NPE; return expr;}' and // wrap all references to it in the super/this to a call to this method. JCStatement nullCheck = recursiveSetGeneratedBy(generateNullCheck(annotationNode.getTreeMaker(), annotationNode.up(), annotationNode), ast, annotationNode.getContext()); if (nullCheck == null) { // @NonNull applied to a primitive. Kinda pointless. Let's generate a warning. annotationNode.addWarning("@NonNull is meaningless on a primitive."); return; } List statements = declaration.body.stats; String expectedName = annotationNode.up().getName(); /* Abort if the null check is already there, delving into try and synchronized statements */ { List stats = statements; int idx = 0; while (stats.size() > idx) { JCStatement stat = stats.get(idx++); if (JavacHandlerUtil.isConstructorCall(stat)) continue; if (stat instanceof JCTry) { stats = ((JCTry) stat).body.stats; idx = 0; continue; } if (stat instanceof JCSynchronized) { stats = ((JCSynchronized) stat).body.stats; idx = 0; continue; } String varNameOfNullCheck = returnVarNameIfNullCheck(stat); if (varNameOfNullCheck == null) break; if (varNameOfNullCheck.equals(expectedName)) return; } } List tail = statements; List head = List.nil(); for (JCStatement stat : statements) { if (JavacHandlerUtil.isConstructorCall(stat) || (JavacHandlerUtil.isGenerated(stat) && isNullCheck(stat))) { tail = tail.tail; head = head.prepend(stat); continue; } break; } List newList = tail.prepend(nullCheck); for (JCStatement stat : head) newList = newList.prepend(stat); declaration.body.stats = newList; annotationNode.getAst().setChanged(); } public boolean isNullCheck(JCStatement stat) { return returnVarNameIfNullCheck(stat) != null; } /** * Checks if the statement is of the form 'if (x == null) {throw WHATEVER;}, * where the block braces are optional. If it is of this form, returns "x". * If it is not of this form, returns null. */ public String returnVarNameIfNullCheck(JCStatement stat) { if (!(stat instanceof JCIf)) return null; /* Check that the if's statement is a throw statement, possibly in a block. */ { JCStatement then = ((JCIf) stat).thenpart; if (then instanceof JCBlock) { List stats = ((JCBlock) then).stats; if (stats.length() == 0) return null; then = stats.get(0); } if (!(then instanceof JCThrow)) return null; } /* Check that the if's conditional is like 'x == null'. Return from this method (don't generate a nullcheck) if 'x' is equal to our own variable's name: There's already a nullcheck here. */ { JCExpression cond = ((JCIf) stat).cond; while (cond instanceof JCParens) cond = ((JCParens) cond).expr; if (!(cond instanceof JCBinary)) return null; JCBinary bin = (JCBinary) cond; if (!CTC_EQUAL.equals(treeTag(bin))) return null; if (!(bin.lhs instanceof JCIdent)) return null; if (!(bin.rhs instanceof JCLiteral)) return null; if (!CTC_BOT.equals(typeTag(bin.rhs))) return null; return ((JCIdent) bin.lhs).name.toString(); } } } lombok-1.16.18/src/core/lombok/javac/handlers/HandlePrintAST.java000066400000000000000000000047131312655740700245030ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import lombok.Lombok; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.core.PrintAST; import lombok.javac.JavacASTVisitor; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; /** * Handles the {@code lombok.core.PrintAST} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(536870912) // 2^29; this handler is customarily run at the very end. public class HandlePrintAST extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { PrintStream stream = System.out; String fileName = annotation.getInstance().outfile(); if (fileName.length() > 0) try { stream = new PrintStream(new File(fileName)); } catch (FileNotFoundException e) { throw Lombok.sneakyThrow(e); } try { annotationNode.up().traverse(new JavacASTVisitor.Printer(annotation.getInstance().printContent(), stream)); } finally { if (stream != System.out) { try { stream.close(); } catch (Exception e) { throw Lombok.sneakyThrow(e); } } } } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleSetter.java000066400000000000000000000271051312655740700243050ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.javac.Javac.*; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.Collection; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.Setter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCReturn; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; /** * Handles the {@code lombok.Setter} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public class HandleSetter extends JavacAnnotationHandler { public void generateSetterForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean checkForTypeLevelSetter) { if (checkForTypeLevelSetter) { if (hasAnnotation(Setter.class, typeNode)) { //The annotation will make it happen, so we can skip it. return; } } JCClassDecl typeDecl = null; if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; if (typeDecl == null || notAClass) { errorNode.addError("@Setter is only supported on a class or a field."); return; } for (JavacNode field : typeNode.down()) { if (field.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); //Skip fields that start with $ if (fieldDecl.name.toString().startsWith("$")) continue; //Skip static fields. if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue; //Skip final fields. if ((fieldDecl.mods.flags & Flags.FINAL) != 0) continue; generateSetterForField(field, errorNode, level); } } /** * Generates a setter on the stated field. * * Used by {@link HandleData}. * * The difference between this call and the handle method is as follows: * * If there is a {@code lombok.Setter} annotation on the field, it is used and the * same rules apply (e.g. warning if the method already exists, stated access level applies). * If not, the setter is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. * * @param fieldNode The node representing the field you want a setter for. * @param pos The node responsible for generating the setter (the {@code @Data} or {@code @Setter} annotation). */ public void generateSetterForField(JavacNode fieldNode, JavacNode sourceNode, AccessLevel level) { if (hasAnnotation(Setter.class, fieldNode)) { //The annotation will make it happen, so we can skip it. return; } createSetterForField(level, fieldNode, sourceNode, false, List.nil(), List.nil()); } @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.SETTER_FLAG_USAGE, "@Setter"); Collection fields = annotationNode.upFromAnnotationToFields(); deleteAnnotationIfNeccessary(annotationNode, Setter.class); deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); JavacNode node = annotationNode.up(); AccessLevel level = annotation.getInstance().value(); if (level == AccessLevel.NONE || node == null) return; List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Setter(onMethod", annotationNode); List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Setter(onParam", annotationNode); switch (node.getKind()) { case FIELD: createSetterForFields(level, fields, annotationNode, true, onMethod, onParam); break; case TYPE: if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @Setter on a type."); if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @Setter on a type."); generateSetterForType(node, annotationNode, level, false); break; } } public void createSetterForFields(AccessLevel level, Collection fieldNodes, JavacNode errorNode, boolean whineIfExists, List onMethod, List onParam) { for (JavacNode fieldNode : fieldNodes) { createSetterForField(level, fieldNode, errorNode, whineIfExists, onMethod, onParam); } } public void createSetterForField(AccessLevel level, JavacNode fieldNode, JavacNode sourceNode, boolean whineIfExists, List onMethod, List onParam) { if (fieldNode.getKind() != Kind.FIELD) { fieldNode.addError("@Setter is only supported on a class or a field."); return; } JCVariableDecl fieldDecl = (JCVariableDecl) fieldNode.get(); String methodName = toSetterName(fieldNode); if (methodName == null) { fieldNode.addWarning("Not generating setter for this field: It does not fit your @Accessors prefix list."); return; } if ((fieldDecl.mods.flags & Flags.FINAL) != 0) { fieldNode.addWarning("Not generating setter for this field: Setters cannot be generated for final fields."); return; } for (String altName : toAllSetterNames(fieldNode)) { switch (methodExists(altName, fieldNode, false, 1)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: if (whineIfExists) { String altNameExpl = ""; if (!altName.equals(methodName)) altNameExpl = String.format(" (%s)", altName); fieldNode.addWarning( String.format("Not generating %s(): A method with that name already exists%s", methodName, altNameExpl)); } return; default: case NOT_EXISTS: //continue scanning the other alt names. } } long access = toJavacModifier(level) | (fieldDecl.mods.flags & Flags.STATIC); JCMethodDecl createdSetter = createSetter(access, fieldNode, fieldNode.getTreeMaker(), sourceNode, onMethod, onParam); Type fieldType = getMirrorForFieldType(fieldNode); Type returnType; if (shouldReturnThis(fieldNode)) { ClassSymbol sym = ((JCClassDecl) fieldNode.up().get()).sym; returnType = sym == null ? null : sym.type; } else { returnType = Javac.createVoidType(fieldNode.getSymbolTable(), CTC_VOID); } injectMethod(fieldNode.up(), createdSetter, fieldType == null ? null : List.of(fieldType), returnType); } public static JCMethodDecl createSetter(long access, JavacNode field, JavacTreeMaker treeMaker, JavacNode source, List onMethod, List onParam) { String setterName = toSetterName(field); boolean returnThis = shouldReturnThis(field); return createSetter(access, false, field, treeMaker, setterName, null, returnThis, source, onMethod, onParam); } public static JCMethodDecl createSetter(long access, boolean deprecate, JavacNode field, JavacTreeMaker treeMaker, String setterName, Name booleanFieldToSet, boolean shouldReturnThis, JavacNode source, List onMethod, List onParam) { if (setterName == null) return null; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); JCExpression fieldRef = createFieldAccessor(treeMaker, field, FieldAccess.ALWAYS_FIELD); JCAssign assign = treeMaker.Assign(fieldRef, treeMaker.Ident(fieldDecl.name)); ListBuffer statements = new ListBuffer(); List nonNulls = findAnnotations(field, NON_NULL_PATTERN); List nullables = findAnnotations(field, NULLABLE_PATTERN); Name methodName = field.toName(setterName); List annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables); long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext()); JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); if (nonNulls.isEmpty()) { statements.append(treeMaker.Exec(assign)); } else { JCStatement nullCheck = generateNullCheck(treeMaker, field, source); if (nullCheck != null) statements.append(nullCheck); statements.append(treeMaker.Exec(assign)); } if (booleanFieldToSet != null) { JCAssign setBool = treeMaker.Assign(treeMaker.Ident(booleanFieldToSet), treeMaker.Literal(CTC_BOOLEAN, 1)); statements.append(treeMaker.Exec(setBool)); } JCExpression methodType = null; if (shouldReturnThis) { methodType = cloneSelfType(field); } if (methodType == null) { //WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6. methodType = treeMaker.Type(Javac.createVoidType(field.getSymbolTable(), CTC_VOID)); shouldReturnThis = false; } if (shouldReturnThis) { JCReturn returnStatement = treeMaker.Return(treeMaker.Ident(field.toName("this"))); statements.append(returnStatement); } JCBlock methodBody = treeMaker.Block(0, statements.toList()); List methodGenericParams = List.nil(); List parameters = List.of(param); List throwsClauses = List.nil(); JCExpression annotationMethodDefaultValue = null; List annsOnMethod = copyAnnotations(onMethod); if (isFieldDeprecated(field) || deprecate) { annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.nil())); } JCMethodDecl decl = recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType, methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext()); copyJavadoc(field, decl, CopyJavadoc.SETTER); return decl; } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleSneakyThrows.java000066400000000000000000000146721312655740700255050ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import lombok.ConfigurationKeys; import lombok.SneakyThrows; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTry; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import lombok.javac.Javac; /** * Handles the {@code lombok.SneakyThrows} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(value = 1024) // 2^10; @NonNull must have run first, so that we wrap around the statements generated by it. public class HandleSneakyThrows extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.SNEAKY_THROWS_FLAG_USAGE, "@SneakyThrows"); deleteAnnotationIfNeccessary(annotationNode, SneakyThrows.class); Collection exceptionNames = annotation.getRawExpressions("value"); if (exceptionNames.isEmpty()) { exceptionNames = Collections.singleton("java.lang.Throwable"); } java.util.List exceptions = new ArrayList(); for (String exception : exceptionNames) { if (exception.endsWith(".class")) exception = exception.substring(0, exception.length() - 6); exceptions.add(exception); } JavacNode owner = annotationNode.up(); switch (owner.getKind()) { case METHOD: handleMethod(annotationNode, (JCMethodDecl)owner.get(), exceptions); break; default: annotationNode.addError("@SneakyThrows is legal only on methods and constructors."); break; } } public void handleMethod(JavacNode annotation, JCMethodDecl method, Collection exceptions) { JavacNode methodNode = annotation.up(); if ( (method.mods.flags & Flags.ABSTRACT) != 0) { annotation.addError("@SneakyThrows can only be used on concrete methods."); return; } if (method.body == null || method.body.stats.isEmpty()) { generateEmptyBlockWarning(methodNode, annotation, false); return; } final JCStatement constructorCall = method.body.stats.get(0); final boolean isConstructorCall = isConstructorCall(constructorCall); List contents = isConstructorCall ? method.body.stats.tail : method.body.stats; if (contents == null || contents.isEmpty()) { generateEmptyBlockWarning(methodNode, annotation, true); return; } for (String exception : exceptions) { contents = List.of(buildTryCatchBlock(methodNode, contents, exception, annotation.get())); } method.body.stats = isConstructorCall ? List.of(constructorCall).appendList(contents) : contents; methodNode.rebuild(); } public void generateEmptyBlockWarning(JavacNode methodNode, JavacNode annotation, boolean hasConstructorCall) { if (hasConstructorCall) { annotation.addWarning("Calls to sibling / super constructors are always excluded from @SneakyThrows; @SneakyThrows has been ignored because there is no other code in this constructor."); } else { annotation.addWarning("This method or constructor is empty; @SneakyThrows has been ignored."); } } public JCStatement buildTryCatchBlock(JavacNode node, List contents, String exception, JCTree source) { JavacTreeMaker maker = node.getTreeMaker(); Context context = node.getContext(); JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents), source, context); JCExpression varType = chainDots(node, exception.split("\\.")); JCVariableDecl catchParam = maker.VarDef(maker.Modifiers(Flags.FINAL | Flags.PARAMETER), node.toName("$ex"), varType, null); JCExpression lombokLombokSneakyThrowNameRef = chainDots(node, "lombok", "Lombok", "sneakyThrow"); JCBlock catchBody = maker.Block(0, List.of(maker.Throw(maker.Apply( List.nil(), lombokLombokSneakyThrowNameRef, List.of(maker.Ident(node.toName("$ex"))))))); JCTry tryStatement = maker.Try(tryBlock, List.of(recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source, context)), null); if (JavacHandlerUtil.inNetbeansEditor(node)) { //set span (start and end position) of the try statement and the main block //this allows NetBeans to dive into the statement correctly: JCCompilationUnit top = (JCCompilationUnit) node.top().get(); int startPos = contents.head.pos; int endPos = Javac.getEndPosition(contents.last().pos(), top); tryBlock.pos = startPos; tryStatement.pos = startPos; Javac.storeEnd(tryBlock, endPos, top); Javac.storeEnd(tryStatement, endPos, top); } return setGeneratedBy(tryStatement, source, context); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleSynchronized.java000066400000000000000000000117331312655740700255160ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import lombok.ConfigurationKeys; import lombok.Synchronized; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacHandlerUtil.MemberExistsResult; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; /** * Handles the {@code lombok.Synchronized} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(value = 1024) // 2^10; @NonNull must have run first, so that we wrap around the statements generated by it. public class HandleSynchronized extends JavacAnnotationHandler { private static final String INSTANCE_LOCK_NAME = "$lock"; private static final String STATIC_LOCK_NAME = "$LOCK"; @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.SYNCHRONIZED_FLAG_USAGE, "@Synchronized"); if (inNetbeansEditor(annotationNode)) return; deleteAnnotationIfNeccessary(annotationNode, Synchronized.class); JavacNode methodNode = annotationNode.up(); if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof JCMethodDecl)) { annotationNode.addError("@Synchronized is legal only on methods."); return; } JCMethodDecl method = (JCMethodDecl)methodNode.get(); if ((method.mods.flags & Flags.ABSTRACT) != 0) { annotationNode.addError("@Synchronized is legal only on concrete methods."); return; } boolean isStatic = (method.mods.flags & Flags.STATIC) != 0; String lockName = annotation.getInstance().value(); boolean autoMake = false; if (lockName.length() == 0) { autoMake = true; lockName = isStatic ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME; } JavacTreeMaker maker = methodNode.getTreeMaker().at(ast.pos); Context context = methodNode.getContext(); if (fieldExists(lockName, methodNode) == MemberExistsResult.NOT_EXISTS) { if (!autoMake) { annotationNode.addError("The field " + lockName + " does not exist."); return; } JCExpression objectType = genJavaLangTypeRef(methodNode, ast.pos, "Object"); //We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable! JCNewArray newObjectArray = maker.NewArray(genJavaLangTypeRef(methodNode, ast.pos, "Object"), List.of(maker.Literal(CTC_INT, 0)), null); JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef( maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (isStatic ? Flags.STATIC : 0)), methodNode.toName(lockName), objectType, newObjectArray), ast, context); injectFieldAndMarkGenerated(methodNode.up(), fieldDecl); } if (method.body == null) return; JCExpression lockNode; if (isStatic) { lockNode = chainDots(methodNode, ast.pos, methodNode.up().getName(), lockName); } else { lockNode = maker.Select(maker.Ident(methodNode.toName("this")), methodNode.toName(lockName)); } recursiveSetGeneratedBy(lockNode, ast, context); method.body = setGeneratedBy(maker.Block(0, List.of(setGeneratedBy(maker.Synchronized(lockNode, method.body), ast, context))), ast, context); methodNode.rebuild(); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleToString.java000066400000000000000000000261721312655740700246130ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import static lombok.javac.Javac.*; import java.util.Collection; import lombok.ConfigurationKeys; import lombok.ToString; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; /** * Handles the {@code ToString} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public class HandleToString extends JavacAnnotationHandler { public void checkForBogusFieldNames(JavacNode type, AnnotationValues annotation) { if (annotation.isExplicit("exclude")) { for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().exclude()), type, true, false)) { annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); } } if (annotation.isExplicit("of")) { for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().of()), type, false, false)) { annotation.setWarning("of", "This field does not exist.", i); } } } @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.TO_STRING_FLAG_USAGE, "@ToString"); deleteAnnotationIfNeccessary(annotationNode, ToString.class); ToString ann = annotation.getInstance(); List excludes = List.from(ann.exclude()); List includes = List.from(ann.of()); JavacNode typeNode = annotationNode.up(); checkForBogusFieldNames(typeNode, annotation); Boolean callSuper = ann.callSuper(); if (!annotation.isExplicit("callSuper")) callSuper = null; if (!annotation.isExplicit("exclude")) excludes = null; if (!annotation.isExplicit("of")) includes = null; if (excludes != null && includes != null) { excludes = null; annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored."); } Boolean doNotUseGettersConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_DO_NOT_USE_GETTERS); boolean doNotUseGetters = annotation.isExplicit("doNotUseGetters") || doNotUseGettersConfiguration == null ? ann.doNotUseGetters() : doNotUseGettersConfiguration; FieldAccess fieldAccess = doNotUseGetters ? FieldAccess.PREFER_FIELD : FieldAccess.GETTER; Boolean fieldNamesConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_INCLUDE_FIELD_NAMES); boolean includeFieldNames = annotation.isExplicit("includeFieldNames") || fieldNamesConfiguration == null ? ann.includeFieldNames() : fieldNamesConfiguration; generateToString(typeNode, annotationNode, excludes, includes, includeFieldNames, callSuper, true, fieldAccess); } public void generateToStringForType(JavacNode typeNode, JavacNode errorNode) { if (hasAnnotation(ToString.class, typeNode)) { //The annotation will make it happen, so we can skip it. return; } boolean includeFieldNames = true; try { Boolean configuration = typeNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_INCLUDE_FIELD_NAMES); includeFieldNames = configuration != null ? configuration : ((Boolean)ToString.class.getMethod("includeFieldNames").getDefaultValue()).booleanValue(); } catch (Exception ignore) {} Boolean doNotUseGettersConfiguration = typeNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_DO_NOT_USE_GETTERS); FieldAccess access = doNotUseGettersConfiguration == null || !doNotUseGettersConfiguration ? FieldAccess.GETTER : FieldAccess.PREFER_FIELD; generateToString(typeNode, errorNode, null, null, includeFieldNames, null, false, access); } public void generateToString(JavacNode typeNode, JavacNode source, List excludes, List includes, boolean includeFieldNames, Boolean callSuper, boolean whineIfExists, FieldAccess fieldAccess) { boolean notAClass = true; if (typeNode.get() instanceof JCClassDecl) { long flags = ((JCClassDecl)typeNode.get()).mods.flags; notAClass = (flags & (Flags.INTERFACE | Flags.ANNOTATION)) != 0; } if (callSuper == null) { try { callSuper = ((Boolean)ToString.class.getMethod("callSuper").getDefaultValue()).booleanValue(); } catch (Exception ignore) {} } if (notAClass) { source.addError("@ToString is only supported on a class or enum."); return; } ListBuffer nodesForToString = new ListBuffer(); if (includes != null) { for (JavacNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); if (includes.contains(fieldDecl.name.toString())) nodesForToString.append(child); } } else { for (JavacNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); //Skip static fields. if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue; //Skip excluded fields. if (excludes != null && excludes.contains(fieldDecl.name.toString())) continue; //Skip fields that start with $. if (fieldDecl.name.toString().startsWith("$")) continue; nodesForToString.append(child); } } switch (methodExists("toString", typeNode, 0)) { case NOT_EXISTS: JCMethodDecl method = createToString(typeNode, nodesForToString.toList(), includeFieldNames, callSuper, fieldAccess, source.get()); injectMethod(typeNode, method); break; case EXISTS_BY_LOMBOK: break; default: case EXISTS_BY_USER: if (whineIfExists) { source.addWarning("Not generating toString(): A method with that name already exists"); } break; } } static JCMethodDecl createToString(JavacNode typeNode, Collection fields, boolean includeFieldNames, boolean callSuper, FieldAccess fieldAccess, JCTree source) { JavacTreeMaker maker = typeNode.getTreeMaker(); JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.nil()); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); JCExpression returnType = genJavaLangTypeRef(typeNode, "String"); boolean first = true; String typeName = getTypeName(typeNode); String infix = ", "; String suffix = ")"; String prefix; if (callSuper) { prefix = typeName + "(super="; } else if (fields.isEmpty()) { prefix = typeName + "()"; } else if (includeFieldNames) { prefix = typeName + "(" + ((JCVariableDecl)fields.iterator().next().get()).name.toString() + "="; } else { prefix = typeName + "("; } JCExpression current = maker.Literal(prefix); if (callSuper) { JCMethodInvocation callToSuper = maker.Apply(List.nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("toString")), List.nil()); current = maker.Binary(CTC_PLUS, current, callToSuper); first = false; } for (JavacNode fieldNode : fields) { JCExpression expr; JCExpression fieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess); JCExpression fieldType = getFieldType(fieldNode, fieldAccess); // The distinction between primitive and object will be useful if we ever add a 'hideNulls' option. boolean fieldIsPrimitive = fieldType instanceof JCPrimitiveTypeTree; boolean fieldIsPrimitiveArray = fieldType instanceof JCArrayTypeTree && ((JCArrayTypeTree) fieldType).elemtype instanceof JCPrimitiveTypeTree; boolean fieldIsObjectArray = !fieldIsPrimitiveArray && fieldType instanceof JCArrayTypeTree; @SuppressWarnings("unused") boolean fieldIsObject = !fieldIsPrimitive && !fieldIsPrimitiveArray && !fieldIsObjectArray; if (fieldIsPrimitiveArray || fieldIsObjectArray) { JCExpression tsMethod = chainDots(typeNode, "java", "util", "Arrays", fieldIsObjectArray ? "deepToString" : "toString"); expr = maker.Apply(List.nil(), tsMethod, List.of(fieldAccessor)); } else expr = fieldAccessor; if (first) { current = maker.Binary(CTC_PLUS, current, expr); first = false; continue; } if (includeFieldNames) { current = maker.Binary(CTC_PLUS, current, maker.Literal(infix + fieldNode.getName() + "=")); } else { current = maker.Binary(CTC_PLUS, current, maker.Literal(infix)); } current = maker.Binary(CTC_PLUS, current, expr); } if (!first) current = maker.Binary(CTC_PLUS, current, maker.Literal(suffix)); JCStatement returnStatement = maker.Return(current); JCBlock body = maker.Block(0, List.of(returnStatement)); return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("toString"), returnType, List.nil(), List.nil(), List.nil(), body, null), source, typeNode.getContext()); } public static String getTypeName(JavacNode typeNode) { String typeName = ((JCClassDecl) typeNode.get()).name.toString(); JavacNode upType = typeNode.up(); while (upType.getKind() == Kind.TYPE) { typeName = ((JCClassDecl) upType.get()).name.toString() + "." + typeName; upType = upType.up(); } return typeName; } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleUtilityClass.java000066400000000000000000000161371312655740700254730ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.handleExperimentalFlagUsage; import static lombok.javac.Javac.CTC_VOID; import static lombok.javac.handlers.JavacHandlerUtil.*; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Name; import lombok.ConfigurationKeys; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.experimental.UtilityClass; import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; /** * Handles the {@code @UtilityClass} annotation for javac. */ @HandlerPriority(-4096) //-2^12; to ensure @FieldDefaults picks up on the 'static' we set here. @ProviderFor(JavacAnnotationHandler.class) public class HandleUtilityClass extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.UTILITY_CLASS_FLAG_USAGE, "@UtilityClass"); deleteAnnotationIfNeccessary(annotationNode, UtilityClass.class); JavacNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode)) return; changeModifiersAndGenerateConstructor(annotationNode.up(), annotationNode); } private static boolean checkLegality(JavacNode typeNode, JavacNode errorNode) { JCClassDecl typeDecl = null; if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; if (typeDecl == null || notAClass) { errorNode.addError("@UtilityClass is only supported on a class (can't be an interface, enum, or annotation)."); return false; } // It might be an inner class. This is okay, but only if it is / can be a static inner class. Thus, all of its parents have to be static inner classes until the top-level. JavacNode typeWalk = typeNode; while (true) { typeWalk = typeWalk.up(); switch (typeWalk.getKind()) { case TYPE: JCClassDecl typeDef = (JCClassDecl) typeWalk.get(); if ((typeDef.mods.flags & (Flags.STATIC | Flags.ANNOTATION | Flags.ENUM | Flags.INTERFACE)) != 0) continue; if (typeWalk.up().getKind() == Kind.COMPILATION_UNIT) return true; errorNode.addError("@UtilityClass automatically makes the class static, however, this class cannot be made static."); return false; case COMPILATION_UNIT: return true; default: errorNode.addError("@UtilityClass cannot be placed on a method local or anonymous inner class, or any class nested in such a class."); return false; } } } private void changeModifiersAndGenerateConstructor(JavacNode typeNode, JavacNode errorNode) { JCClassDecl classDecl = (JCClassDecl) typeNode.get(); boolean makeConstructor = true; classDecl.mods.flags |= Flags.FINAL; boolean markStatic = true; if (typeNode.up().getKind() == Kind.COMPILATION_UNIT) markStatic = false; if (markStatic && typeNode.up().getKind() == Kind.TYPE) { JCClassDecl typeDecl = (JCClassDecl) typeNode.up().get(); if ((typeDecl.mods.flags & Flags.INTERFACE) != 0) markStatic = false; } if (markStatic) classDecl.mods.flags |= Flags.STATIC; for (JavacNode element : typeNode.down()) { if (element.getKind() == Kind.FIELD) { JCVariableDecl fieldDecl = (JCVariableDecl) element.get(); fieldDecl.mods.flags |= Flags.STATIC; } else if (element.getKind() == Kind.METHOD) { JCMethodDecl methodDecl = (JCMethodDecl) element.get(); if (methodDecl.name.contentEquals("")) { if (getGeneratedBy(methodDecl) == null && (methodDecl.mods.flags & Flags.GENERATEDCONSTR) == 0) { element.addError("@UtilityClasses cannot have declared constructors."); makeConstructor = false; continue; } } methodDecl.mods.flags |= Flags.STATIC; } else if (element.getKind() == Kind.TYPE) { JCClassDecl innerClassDecl = (JCClassDecl) element.get(); innerClassDecl.mods.flags |= Flags.STATIC; } } if (makeConstructor) createPrivateDefaultConstructor(typeNode); } private void createPrivateDefaultConstructor(JavacNode typeNode) { JavacTreeMaker maker = typeNode.getTreeMaker(); JCModifiers mods = maker.Modifiers(Flags.PRIVATE, List.nil()); Name name = typeNode.toName(""); JCBlock block = maker.Block(0L, createThrowStatement(typeNode, maker)); JCMethodDecl methodDef = maker.MethodDef(mods, name, null, List.nil(), List.nil(), List.nil(), block, null); JCMethodDecl constructor = recursiveSetGeneratedBy(methodDef, typeNode.get(), typeNode.getContext()); JavacHandlerUtil.injectMethod(typeNode, constructor, List.nil(), Javac.createVoidType(typeNode.getSymbolTable(), CTC_VOID)); } private List createThrowStatement(JavacNode typeNode, JavacTreeMaker maker) { JCExpression exceptionType = genJavaLangTypeRef(typeNode, "UnsupportedOperationException"); List jceBlank = List.nil(); JCExpression message = maker.Literal("This is a utility class and cannot be instantiated"); JCExpression exceptionInstance = maker.NewClass(null, jceBlank, exceptionType, List.of(message), null); JCStatement throwStatement = maker.Throw(exceptionInstance); return List.of(throwStatement); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleVal.java000066400000000000000000000166731312655740700235710ustar00rootroot00000000000000/* * Copyright (C) 2010-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.handleFlagUsage; import static lombok.javac.handlers.JavacHandlerUtil.*; import lombok.ConfigurationKeys; import lombok.val; import lombok.core.HandlerPriority; import lombok.experimental.var; import lombok.javac.JavacASTAdapter; import lombok.javac.JavacASTVisitor; import lombok.javac.JavacNode; import lombok.javac.JavacResolution; import lombok.javac.ResolutionResetNeeded; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCForLoop; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; @ProviderFor(JavacASTVisitor.class) @HandlerPriority(65536) // 2^16; resolution needs to work, so if the RHS expression is i.e. a call to a generated getter, we have to run after that getter has been generated. @ResolutionResetNeeded public class HandleVal extends JavacASTAdapter { private static boolean eq(String typeTreeToString, String key) { return (typeTreeToString.equals(key) || typeTreeToString.equals("lombok." + key)); } @Override public void visitLocal(JavacNode localNode, JCVariableDecl local) { JCTree typeTree = local.vartype; if (typeTree == null) return; String typeTreeToString = typeTree.toString(); if (!(eq(typeTreeToString, "val") || eq(typeTreeToString, "var"))) return; boolean isVal = typeMatches(val.class, localNode, typeTree); boolean isVar = typeMatches(var.class, localNode, typeTree); if (!(isVal || isVar)) return; if (isVal) handleFlagUsage(localNode, ConfigurationKeys.VAL_FLAG_USAGE, "val"); if (isVar) handleFlagUsage(localNode, ConfigurationKeys.VAR_FLAG_USAGE, "var"); JCTree parentRaw = localNode.directUp().get(); if (isVal && parentRaw instanceof JCForLoop) { localNode.addError("'val' is not allowed in old-style for loops"); return; } JCExpression rhsOfEnhancedForLoop = null; if (local.init == null) { if (parentRaw instanceof JCEnhancedForLoop) { JCEnhancedForLoop efl = (JCEnhancedForLoop) parentRaw; if (efl.var == local) rhsOfEnhancedForLoop = efl.expr; } } final String annotation = typeTreeToString; if (rhsOfEnhancedForLoop == null && local.init == null) { localNode.addError("'" + annotation + "' on a local variable requires an initializer expression"); return; } if (local.init instanceof JCNewArray && ((JCNewArray)local.init).elemtype == null) { localNode.addError("'" + annotation + "' is not compatible with array initializer expressions. Use the full form (new int[] { ... } instead of just { ... })"); return; } if (localNode.shouldDeleteLombokAnnotations()) { JavacHandlerUtil.deleteImportFromCompilationUnit(localNode, val.class.getName()); JavacHandlerUtil.deleteImportFromCompilationUnit(localNode, var.class.getName()); } if (isVal) local.mods.flags |= Flags.FINAL; if (!localNode.shouldDeleteLombokAnnotations()) { JCAnnotation valAnnotation = recursiveSetGeneratedBy(localNode.getTreeMaker().Annotation(local.vartype, List.nil()), typeTree, localNode.getContext()); local.mods.annotations = local.mods.annotations == null ? List.of(valAnnotation) : local.mods.annotations.append(valAnnotation); } if (JavacResolution.platformHasTargetTyping()) { local.vartype = localNode.getAst().getTreeMaker().Ident(localNode.getAst().toName("___Lombok_VAL_Attrib__")); } else { local.vartype = JavacResolution.createJavaLangObject(localNode.getAst()); } Type type; try { if (rhsOfEnhancedForLoop == null) { if (local.init.type == null) { if (isVar && local.init instanceof JCLiteral && ((JCLiteral) local.init).value == null) { localNode.addError("variable initializer is 'null'"); } JavacResolution resolver = new JavacResolution(localNode.getContext()); try { type = ((JCExpression) resolver.resolveMethodMember(localNode).get(local.init)).type; } catch (RuntimeException e) { System.err.println("Exception while resolving: " + localNode); throw e; } } else { type = local.init.type; if (type.isErroneous()) { try { JavacResolution resolver = new JavacResolution(localNode.getContext()); local.type = Symtab.instance(localNode.getContext()).unknownType; type = ((JCExpression) resolver.resolveMethodMember(localNode).get(local.init)).type; } catch (RuntimeException e) { System.err.println("Exception while resolving: " + localNode); throw e; } } } } else { if (rhsOfEnhancedForLoop.type == null) { JavacResolution resolver = new JavacResolution(localNode.getContext()); type = ((JCExpression) resolver.resolveMethodMember(localNode.directUp()).get(rhsOfEnhancedForLoop)).type; } else { type = rhsOfEnhancedForLoop.type; } } try { JCExpression replacement; if (rhsOfEnhancedForLoop != null) { Type componentType = JavacResolution.ifTypeIsIterableToComponent(type, localNode.getAst()); if (componentType == null) replacement = JavacResolution.createJavaLangObject(localNode.getAst()); else replacement = JavacResolution.typeToJCTree(componentType, localNode.getAst(), false); } else { replacement = JavacResolution.typeToJCTree(type, localNode.getAst(), false); } if (replacement != null) { local.vartype = replacement; } else { local.vartype = JavacResolution.createJavaLangObject(localNode.getAst()); } localNode.getAst().setChanged(); } catch (JavacResolution.TypeNotConvertibleException e) { localNode.addError("Cannot use '" + annotation + "' here because initializer expression does not have a representable type: " + e.getMessage()); local.vartype = JavacResolution.createJavaLangObject(localNode.getAst()); } } catch (RuntimeException e) { local.vartype = JavacResolution.createJavaLangObject(localNode.getAst()); throw e; } finally { recursiveSetGeneratedBy(local.vartype, typeTree, localNode.getContext()); } } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleValue.java000066400000000000000000000072551312655740700241170ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.lang.annotation.Annotation; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.experimental.NonFinal; import lombok.Value; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.handlers.HandleConstructor.SkipIfConstructorExists; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; /** * Handles the {@code lombok.Value} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(-512) //-2^9; to ensure @EqualsAndHashCode and such pick up on this handler making the class final and messing with the fields' access levels, run earlier. public class HandleValue extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { @SuppressWarnings("deprecation") Class oldExperimentalValue = lombok.experimental.Value.class; handleFlagUsage(annotationNode, ConfigurationKeys.VALUE_FLAG_USAGE, "@Value"); deleteAnnotationIfNeccessary(annotationNode, Value.class, oldExperimentalValue); JavacNode typeNode = annotationNode.up(); boolean notAClass = !isClass(typeNode); if (notAClass) { annotationNode.addError("@Value is only supported on a class."); return; } String staticConstructorName = annotation.getInstance().staticConstructor(); if (!hasAnnotationAndDeleteIfNeccessary(NonFinal.class, typeNode)) { JCModifiers jcm = ((JCClassDecl) typeNode.get()).mods; if ((jcm.flags & Flags.FINAL) == 0) { jcm.flags |= Flags.FINAL; typeNode.rebuild(); } } new HandleFieldDefaults().generateFieldDefaultsForType(typeNode, annotationNode, AccessLevel.PRIVATE, true, true); // TODO move this to the end OR move it to the top in eclipse. new HandleConstructor().generateAllArgsConstructor(typeNode, AccessLevel.PUBLIC, staticConstructorName, SkipIfConstructorExists.YES, annotationNode); new HandleGetter().generateGetterForType(typeNode, annotationNode, AccessLevel.PUBLIC, true); new HandleEqualsAndHashCode().generateEqualsAndHashCodeForType(typeNode, annotationNode); new HandleToString().generateToStringForType(typeNode, annotationNode); } } lombok-1.16.18/src/core/lombok/javac/handlers/HandleWither.java000066400000000000000000000304311312655740700242750ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.Collection; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.experimental.Wither; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacHandlerUtil.CopyJavadoc; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCConditional; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCNewClass; import com.sun.tools.javac.tree.JCTree.JCReturn; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; /** * Handles the {@code lombok.experimental.Wither} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public class HandleWither extends JavacAnnotationHandler { public void generateWitherForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean checkForTypeLevelWither) { if (checkForTypeLevelWither) { if (hasAnnotation(Wither.class, typeNode)) { //The annotation will make it happen, so we can skip it. return; } } JCClassDecl typeDecl = null; if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; if (typeDecl == null || notAClass) { errorNode.addError("@Wither is only supported on a class or a field."); return; } for (JavacNode field : typeNode.down()) { if (field.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); //Skip fields that start with $ if (fieldDecl.name.toString().startsWith("$")) continue; //Skip static fields. if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue; //Skip final initialized fields. if ((fieldDecl.mods.flags & Flags.FINAL) != 0 && fieldDecl.init != null) continue; generateWitherForField(field, errorNode.get(), level); } } /** * Generates a wither on the stated field. * * Used by {@link HandleValue}. * * The difference between this call and the handle method is as follows: * * If there is a {@code lombok.experimental.Wither} annotation on the field, it is used and the * same rules apply (e.g. warning if the method already exists, stated access level applies). * If not, the wither is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. * * @param fieldNode The node representing the field you want a wither for. * @param pos The node responsible for generating the wither (the {@code @Value} or {@code @Wither} annotation). */ public void generateWitherForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level) { if (hasAnnotation(Wither.class, fieldNode)) { //The annotation will make it happen, so we can skip it. return; } createWitherForField(level, fieldNode, fieldNode, false, List.nil(), List.nil()); } @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.WITHER_FLAG_USAGE, "@Wither"); Collection fields = annotationNode.upFromAnnotationToFields(); deleteAnnotationIfNeccessary(annotationNode, Wither.class); deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); JavacNode node = annotationNode.up(); AccessLevel level = annotation.getInstance().value(); if (level == AccessLevel.NONE || node == null) return; List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Wither(onMethod", annotationNode); List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Wither(onParam", annotationNode); switch (node.getKind()) { case FIELD: createWitherForFields(level, fields, annotationNode, true, onMethod, onParam); break; case TYPE: if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @Wither on a type."); if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @Wither on a type."); generateWitherForType(node, annotationNode, level, false); break; } } public void createWitherForFields(AccessLevel level, Collection fieldNodes, JavacNode errorNode, boolean whineIfExists, List onMethod, List onParam) { for (JavacNode fieldNode : fieldNodes) { createWitherForField(level, fieldNode, errorNode, whineIfExists, onMethod, onParam); } } public void createWitherForField(AccessLevel level, JavacNode fieldNode, JavacNode source, boolean strictMode, List onMethod, List onParam) { JavacNode typeNode = fieldNode.up(); boolean makeAbstract = typeNode != null && typeNode.getKind() == Kind.TYPE && (((JCClassDecl) typeNode.get()).mods.flags & Flags.ABSTRACT) != 0; if (fieldNode.getKind() != Kind.FIELD) { fieldNode.addError("@Wither is only supported on a class or a field."); return; } JCVariableDecl fieldDecl = (JCVariableDecl)fieldNode.get(); String methodName = toWitherName(fieldNode); if (methodName == null) { fieldNode.addWarning("Not generating wither for this field: It does not fit your @Accessors prefix list."); return; } if ((fieldDecl.mods.flags & Flags.STATIC) != 0) { if (strictMode) { fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for static fields."); } return; } if ((fieldDecl.mods.flags & Flags.FINAL) != 0 && fieldDecl.init != null) { if (strictMode) { fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for final, initialized fields."); } return; } if (fieldDecl.name.toString().startsWith("$")) { if (strictMode) { fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for fields starting with $."); } return; } for (String altName : toAllWitherNames(fieldNode)) { switch (methodExists(altName, fieldNode, false, 1)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: if (strictMode) { String altNameExpl = ""; if (!altName.equals(methodName)) altNameExpl = String.format(" (%s)", altName); fieldNode.addWarning( String.format("Not generating %s(): A method with that name already exists%s", methodName, altNameExpl)); } return; default: case NOT_EXISTS: //continue scanning the other alt names. } } long access = toJavacModifier(level); JCMethodDecl createdWither = createWither(access, fieldNode, fieldNode.getTreeMaker(), source, onMethod, onParam, makeAbstract); ClassSymbol sym = ((JCClassDecl) fieldNode.up().get()).sym; Type returnType = sym == null ? null : sym.type; injectMethod(typeNode, createdWither, List.of(getMirrorForFieldType(fieldNode)), returnType); } public JCMethodDecl createWither(long access, JavacNode field, JavacTreeMaker maker, JavacNode source, List onMethod, List onParam, boolean makeAbstract) { String witherName = toWitherName(field); if (witherName == null) return null; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); List nonNulls = findAnnotations(field, NON_NULL_PATTERN); List nullables = findAnnotations(field, NULLABLE_PATTERN); Name methodName = field.toName(witherName); JCExpression returnType = cloneSelfType(field); JCBlock methodBody = null; long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext()); List annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables); JCVariableDecl param = maker.VarDef(maker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); if (!makeAbstract) { ListBuffer statements = new ListBuffer(); JCExpression selfType = cloneSelfType(field); if (selfType == null) return null; ListBuffer args = new ListBuffer(); for (JavacNode child : field.up().down()) { if (child.getKind() != Kind.FIELD) continue; JCVariableDecl childDecl = (JCVariableDecl) child.get(); // Skip fields that start with $ if (childDecl.name.toString().startsWith("$")) continue; long fieldFlags = childDecl.mods.flags; // Skip static fields. if ((fieldFlags & Flags.STATIC) != 0) continue; // Skip initialized final fields. if (((fieldFlags & Flags.FINAL) != 0) && childDecl.init != null) continue; if (child.get() == field.get()) { args.append(maker.Ident(fieldDecl.name)); } else { args.append(createFieldAccessor(maker, child, FieldAccess.ALWAYS_FIELD)); } } JCNewClass newClass = maker.NewClass(null, List.nil(), selfType, args.toList(), null); JCExpression identityCheck = maker.Binary(CTC_EQUAL, createFieldAccessor(maker, field, FieldAccess.ALWAYS_FIELD), maker.Ident(fieldDecl.name)); JCConditional conditional = maker.Conditional(identityCheck, maker.Ident(field.toName("this")), newClass); JCReturn returnStatement = maker.Return(conditional); if (nonNulls.isEmpty()) { statements.append(returnStatement); } else { JCStatement nullCheck = generateNullCheck(maker, field, source); if (nullCheck != null) statements.append(nullCheck); statements.append(returnStatement); } methodBody = maker.Block(0, statements.toList()); } List methodGenericParams = List.nil(); List parameters = List.of(param); List throwsClauses = List.nil(); JCExpression annotationMethodDefaultValue = null; List annsOnMethod = copyAnnotations(onMethod); if (isFieldDeprecated(field)) { annsOnMethod = annsOnMethod.prepend(maker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.nil())); } if (makeAbstract) access = access | Flags.ABSTRACT; JCMethodDecl decl = recursiveSetGeneratedBy(maker.MethodDef(maker.Modifiers(access, annsOnMethod), methodName, returnType, methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext()); copyJavadoc(field, decl, CopyJavadoc.WITHER); return decl; } } lombok-1.16.18/src/core/lombok/javac/handlers/JavacHandlerUtil.java000066400000000000000000001745261312655740700251150ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static com.sun.tools.javac.code.Flags.GENERATEDCONSTR; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.Javac.*; import static lombok.javac.JavacAugments.JCTree_generatedNode; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.lang.model.element.Element; import lombok.AccessLevel; import lombok.ConfigurationKeys; import lombok.Data; import lombok.Getter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.LombokImmutableList; import lombok.core.AnnotationValues.AnnotationValue; import lombok.core.TypeResolver; import lombok.core.configuration.NullCheckExceptionType; import lombok.core.handlers.HandlerUtil; import lombok.delombok.LombokOptionsFactory; import lombok.experimental.Accessors; import lombok.experimental.Tolerate; import lombok.javac.Javac; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Scope; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type.MethodType; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.tree.DocCommentTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCImport; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeApply; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.tree.JCTree.TypeBoundKind; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.Options; /** * Container for static utility methods useful to handlers written for javac. */ public class JavacHandlerUtil { private JavacHandlerUtil() { //Prevent instantiation } private static class MarkingScanner extends TreeScanner { private final JCTree source; private final Context context; MarkingScanner(JCTree source, Context context) { this.source = source; this.context = context; } @Override public void scan(JCTree tree) { if (tree == null) return; setGeneratedBy(tree, source, context); super.scan(tree); } } /** * Contributed by Jan Lahoda; many lombok transformations should not be run (or a lite version should be run) when the netbeans editor * is running javac on the open source file to find inline errors and such. As class files are compiled separately this does not affect * actual runtime behaviour or file output of the netbeans IDE. */ public static boolean inNetbeansEditor(JavacNode node) { return inNetbeansEditor(node.getContext()); } private static boolean inNetbeansEditor(Context context) { Options options = Options.instance(context); return (options.keySet().contains("ide") && !options.keySet().contains("backgroundCompilation")); } public static JCTree getGeneratedBy(JCTree node) { return JCTree_generatedNode.get(node); } public static boolean isGenerated(JCTree node) { return getGeneratedBy(node) != null; } public static T recursiveSetGeneratedBy(T node, JCTree source, Context context) { if (node == null) return null; setGeneratedBy(node, source, context); node.accept(new MarkingScanner(source, context)); return node; } public static T setGeneratedBy(T node, JCTree source, Context context) { if (node == null) return null; if (source == null) JCTree_generatedNode.clear(node); else JCTree_generatedNode.set(node, source); if (source != null && (!inNetbeansEditor(context) || (node instanceof JCVariableDecl && (((JCVariableDecl) node).mods.flags & Flags.PARAMETER) != 0))) node.pos = source.pos; return node; } public static boolean hasAnnotation(Class type, JavacNode node) { return hasAnnotation(type, node, false); } public static boolean hasAnnotationAndDeleteIfNeccessary(Class type, JavacNode node) { return hasAnnotation(type, node, true); } private static boolean hasAnnotation(Class type, JavacNode node, boolean delete) { if (node == null) return false; if (type == null) return false; switch (node.getKind()) { case ARGUMENT: case FIELD: case LOCAL: case TYPE: case METHOD: for (JavacNode child : node.down()) { if (annotationTypeMatches(type, child)) { if (delete) deleteAnnotationIfNeccessary(child, type); return true; } } // intentional fallthrough default: return false; } } static JavacNode findAnnotation(Class type, JavacNode node, boolean delete) { if (node == null) return null; if (type == null) return null; switch (node.getKind()) { case ARGUMENT: case FIELD: case LOCAL: case TYPE: case METHOD: for (JavacNode child : node.down()) { if (annotationTypeMatches(type, child)) { if (delete) deleteAnnotationIfNeccessary(child, type); return child; } } // intentional fallthrough default: return null; } } /** * Checks if the Annotation AST Node provided is likely to be an instance of the provided annotation type. * * @param type An actual annotation type, such as {@code lombok.Getter.class}. * @param node A Lombok AST node representing an annotation in source code. */ public static boolean annotationTypeMatches(Class type, JavacNode node) { if (node.getKind() != Kind.ANNOTATION) return false; return typeMatches(type, node, ((JCAnnotation)node.get()).annotationType); } /** * Checks if the given TypeReference node is likely to be a reference to the provided class. * * @param type An actual type. This method checks if {@code typeNode} is likely to be a reference to this type. * @param node A Lombok AST node. Any node in the appropriate compilation unit will do (used to get access to import statements). * @param typeNode A type reference to check. */ public static boolean typeMatches(Class type, JavacNode node, JCTree typeNode) { String typeName = typeNode.toString(); TypeResolver resolver = new TypeResolver(node.getImportList()); return resolver.typeMatches(node, type.getName(), typeName); } /** * Returns if a field is marked deprecated, either by {@code @Deprecated} or in javadoc * @param field the field to check * @return {@code true} if a field is marked deprecated, either by {@code @Deprecated} or in javadoc, otherwise {@code false} */ public static boolean isFieldDeprecated(JavacNode field) { if (!(field.get() instanceof JCVariableDecl)) return false; JCVariableDecl fieldNode = (JCVariableDecl) field.get(); if ((fieldNode.mods.flags & Flags.DEPRECATED) != 0) { return true; } for (JavacNode child : field.down()) { if (annotationTypeMatches(Deprecated.class, child)) { return true; } } return false; } /** * Returns if a node is marked deprecated (as picked up on by the parser). * @param node the node to check (type, method, or field decl). */ public static boolean nodeHasDeprecatedFlag(JCTree node) { if (node instanceof JCVariableDecl) return (((JCVariableDecl) node).mods.flags & Flags.DEPRECATED) != 0; if (node instanceof JCMethodDecl) return (((JCMethodDecl) node).mods.flags & Flags.DEPRECATED) != 0; if (node instanceof JCClassDecl) return (((JCClassDecl) node).mods.flags & Flags.DEPRECATED) != 0; return false; } /** * Creates an instance of {@code AnnotationValues} for the provided AST Node. * * @param type An annotation class type, such as {@code lombok.Getter.class}. * @param node A Lombok AST node representing an annotation in source code. */ public static AnnotationValues createAnnotation(Class type, final JavacNode node) { Map values = new HashMap(); JCAnnotation anno = (JCAnnotation) node.get(); List arguments = anno.getArguments(); for (JCExpression arg : arguments) { String mName; JCExpression rhs; java.util.List raws = new ArrayList(); java.util.List guesses = new ArrayList(); java.util.List expressions = new ArrayList(); final java.util.List positions = new ArrayList(); if (arg instanceof JCAssign) { JCAssign assign = (JCAssign) arg; mName = assign.lhs.toString(); rhs = assign.rhs; } else { rhs = arg; mName = "value"; } if (rhs instanceof JCNewArray) { List elems = ((JCNewArray)rhs).elems; for (JCExpression inner : elems) { raws.add(inner.toString()); expressions.add(inner); guesses.add(calculateGuess(inner)); positions.add(inner.pos()); } } else { raws.add(rhs.toString()); expressions.add(rhs); guesses.add(calculateGuess(rhs)); positions.add(rhs.pos()); } values.put(mName, new AnnotationValue(node, raws, expressions, guesses, true) { @Override public void setError(String message, int valueIdx) { if (valueIdx < 0) node.addError(message); else node.addError(message, positions.get(valueIdx)); } @Override public void setWarning(String message, int valueIdx) { if (valueIdx < 0) node.addWarning(message); else node.addWarning(message, positions.get(valueIdx)); } }); } for (Method m : type.getDeclaredMethods()) { if (!Modifier.isPublic(m.getModifiers())) continue; String name = m.getName(); if (!values.containsKey(name)) { values.put(name, new AnnotationValue(node, new ArrayList(), new ArrayList(), new ArrayList(), false) { @Override public void setError(String message, int valueIdx) { node.addError(message); } @Override public void setWarning(String message, int valueIdx) { node.addWarning(message); } }); } } return new AnnotationValues(type, values, node); } /** * Removes the annotation from javac's AST (it remains in lombok's AST), * then removes any import statement that imports this exact annotation (not star imports). * Only does this if the DeleteLombokAnnotations class is in the context. */ @SuppressWarnings("unchecked") public static void deleteAnnotationIfNeccessary(JavacNode annotation, Class annotationType) { deleteAnnotationIfNeccessary0(annotation, annotationType); } /** * Removes the annotation from javac's AST (it remains in lombok's AST), * then removes any import statement that imports this exact annotation (not star imports). * Only does this if the DeleteLombokAnnotations class is in the context. */ @SuppressWarnings("unchecked") public static void deleteAnnotationIfNeccessary(JavacNode annotation, Class annotationType1, Class annotationType2) { deleteAnnotationIfNeccessary0(annotation, annotationType1, annotationType2); } private static void deleteAnnotationIfNeccessary0(JavacNode annotation, Class... annotationTypes) { if (inNetbeansEditor(annotation)) return; if (!annotation.shouldDeleteLombokAnnotations()) return; JavacNode parentNode = annotation.directUp(); switch (parentNode.getKind()) { case FIELD: case ARGUMENT: case LOCAL: JCVariableDecl variable = (JCVariableDecl) parentNode.get(); variable.mods.annotations = filterList(variable.mods.annotations, annotation.get()); break; case METHOD: JCMethodDecl method = (JCMethodDecl) parentNode.get(); method.mods.annotations = filterList(method.mods.annotations, annotation.get()); break; case TYPE: try { JCClassDecl type = (JCClassDecl) parentNode.get(); type.mods.annotations = filterList(type.mods.annotations, annotation.get()); } catch (ClassCastException e) { //something rather odd has been annotated. Better to just break only delombok instead of everything. } break; default: //This really shouldn't happen, but if it does, better just break delombok instead of breaking everything. return; } parentNode.getAst().setChanged(); for (Class annotationType : annotationTypes) { deleteImportFromCompilationUnit(annotation, annotationType.getName()); } } public static void deleteImportFromCompilationUnit(JavacNode node, String name) { if (inNetbeansEditor(node)) return; if (!node.shouldDeleteLombokAnnotations()) return; ListBuffer newDefs = new ListBuffer(); JCCompilationUnit unit = (JCCompilationUnit) node.top().get(); for (JCTree def : unit.defs) { boolean delete = false; if (def instanceof JCImport) { JCImport imp0rt = (JCImport)def; delete = (!imp0rt.staticImport && imp0rt.qualid.toString().equals(name)); } if (!delete) newDefs.append(def); } unit.defs = newDefs.toList(); } private static List filterList(List annotations, JCTree jcTree) { ListBuffer newAnnotations = new ListBuffer(); for (JCAnnotation ann : annotations) { if (jcTree != ann) newAnnotations.append(ann); } return newAnnotations.toList(); } /** Serves as return value for the methods that check for the existence of fields and methods. */ public enum MemberExistsResult { NOT_EXISTS, EXISTS_BY_LOMBOK, EXISTS_BY_USER; } /** * Translates the given field into all possible getter names. * Convenient wrapper around {@link TransformationsUtil#toAllGetterNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static java.util.List toAllGetterNames(JavacNode field) { return HandlerUtil.toAllGetterNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); } /** * @return the likely getter name for the stated field. (e.g. private boolean foo; to isFoo). * * Convenient wrapper around {@link TransformationsUtil#toGetterName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toGetterName(JavacNode field) { return HandlerUtil.toGetterName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); } /** * Translates the given field into all possible setter names. * Convenient wrapper around {@link TransformationsUtil#toAllSetterNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static java.util.List toAllSetterNames(JavacNode field) { return HandlerUtil.toAllSetterNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); } /** * @return the likely setter name for the stated field. (e.g. private boolean foo; to setFoo). * * Convenient wrapper around {@link TransformationsUtil#toSetterName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toSetterName(JavacNode field) { return HandlerUtil.toSetterName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); } /** * Translates the given field into all possible wither names. * Convenient wrapper around {@link TransformationsUtil#toAllWitherNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static java.util.List toAllWitherNames(JavacNode field) { return HandlerUtil.toAllWitherNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); } /** * @return the likely wither name for the stated field. (e.g. private boolean foo; to withFoo). * * Convenient wrapper around {@link TransformationsUtil#toWitherName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toWitherName(JavacNode field) { return HandlerUtil.toWitherName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); } /** * When generating a setter, the setter either returns void (beanspec) or Self (fluent). * This method scans for the {@code Accessors} annotation to figure that out. */ public static boolean shouldReturnThis(JavacNode field) { if ((((JCVariableDecl) field.get()).mods.flags & Flags.STATIC) != 0) return false; AnnotationValues accessors = JavacHandlerUtil.getAccessorsForField(field); return HandlerUtil.shouldReturnThis0(accessors, field.getAst()); } public static JCExpression cloneSelfType(JavacNode childOfType) { JavacNode typeNode = childOfType; JavacTreeMaker maker = childOfType.getTreeMaker(); while (typeNode != null && typeNode.getKind() != Kind.TYPE) typeNode = typeNode.up(); if (typeNode != null && typeNode.get() instanceof JCClassDecl) { JCClassDecl type = (JCClassDecl) typeNode.get(); ListBuffer typeArgs = new ListBuffer(); if (!type.typarams.isEmpty()) { for (JCTypeParameter tp : type.typarams) { typeArgs.append(maker.Ident(tp.name)); } return maker.TypeApply(maker.Ident(type.name), typeArgs.toList()); } else { return maker.Ident(type.name); } } else { return null; } } public static boolean isBoolean(JavacNode field) { JCExpression varType = ((JCVariableDecl) field.get()).vartype; return isBoolean(varType); } public static boolean isBoolean(JCExpression varType) { return varType != null && varType.toString().equals("boolean"); } public static Name removePrefixFromField(JavacNode field) { java.util.List prefixes = null; for (JavacNode node : field.down()) { if (annotationTypeMatches(Accessors.class, node)) { AnnotationValues ann = createAnnotation(Accessors.class, node); if (ann.isExplicit("prefix")) prefixes = Arrays.asList(ann.getInstance().prefix()); break; } } if (prefixes == null) { JavacNode current = field.up(); outer: while (current != null) { for (JavacNode node : current.down()) { if (annotationTypeMatches(Accessors.class, node)) { AnnotationValues ann = createAnnotation(Accessors.class, node); if (ann.isExplicit("prefix")) prefixes = Arrays.asList(ann.getInstance().prefix()); break outer; } } current = current.up(); } } if (prefixes == null) prefixes = field.getAst().readConfiguration(ConfigurationKeys.ACCESSORS_PREFIX); if (!prefixes.isEmpty()) { CharSequence newName = removePrefix(field.getName(), prefixes); if (newName != null) return field.toName(newName.toString()); } return ((JCVariableDecl) field.get()).name; } public static AnnotationValues getAccessorsForField(JavacNode field) { for (JavacNode node : field.down()) { if (annotationTypeMatches(Accessors.class, node)) { return createAnnotation(Accessors.class, node); } } JavacNode current = field.up(); while (current != null) { for (JavacNode node : current.down()) { if (annotationTypeMatches(Accessors.class, node)) { return createAnnotation(Accessors.class, node); } } current = current.up(); } return AnnotationValues.of(Accessors.class, field); } /** * Checks if there is a field with the provided name. * * @param fieldName the field name to check for. * @param node Any node that represents the Type (JCClassDecl) to look in, or any child node thereof. */ public static MemberExistsResult fieldExists(String fieldName, JavacNode node) { node = upToTypeNode(node); if (node != null && node.get() instanceof JCClassDecl) { for (JCTree def : ((JCClassDecl)node.get()).defs) { if (def instanceof JCVariableDecl) { if (((JCVariableDecl)def).name.contentEquals(fieldName)) { return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } } return MemberExistsResult.NOT_EXISTS; } public static MemberExistsResult methodExists(String methodName, JavacNode node, int params) { return methodExists(methodName, node, true, params); } /** * Checks if there is a method with the provided name. In case of multiple methods (overloading), only * the first method decides if EXISTS_BY_USER or EXISTS_BY_LOMBOK is returned. * * @param methodName the method name to check for. * @param node Any node that represents the Type (JCClassDecl) to look in, or any child node thereof. * @param caseSensitive If the search should be case sensitive. * @param params The number of parameters the method should have; varargs count as 0-*. Set to -1 to find any method with the appropriate name regardless of parameter count. */ public static MemberExistsResult methodExists(String methodName, JavacNode node, boolean caseSensitive, int params) { node = upToTypeNode(node); if (node != null && node.get() instanceof JCClassDecl) { top: for (JCTree def : ((JCClassDecl)node.get()).defs) { if (def instanceof JCMethodDecl) { JCMethodDecl md = (JCMethodDecl) def; String name = md.name.toString(); boolean matches = caseSensitive ? name.equals(methodName) : name.equalsIgnoreCase(methodName); if (matches) { if (params > -1) { List ps = md.params; int minArgs = 0; int maxArgs = 0; if (ps != null && ps.length() > 0) { minArgs = ps.length(); if ((ps.last().mods.flags & Flags.VARARGS) != 0) { maxArgs = Integer.MAX_VALUE; minArgs--; } else { maxArgs = minArgs; } } if (params < minArgs || params > maxArgs) continue; } if (isTolerate(node, md)) continue top; return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } } return MemberExistsResult.NOT_EXISTS; } public static boolean isTolerate(JavacNode node, JCTree.JCMethodDecl md) { List annotations = md.getModifiers().getAnnotations(); if (annotations != null) for (JCTree.JCAnnotation anno : annotations) { if (typeMatches(Tolerate.class, node, anno.getAnnotationType())) return true; } return false; } /** * Checks if there is a (non-default) constructor. In case of multiple constructors (overloading), only * the first constructor decides if EXISTS_BY_USER or EXISTS_BY_LOMBOK is returned. * * @param node Any node that represents the Type (JCClassDecl) to look in, or any child node thereof. */ public static MemberExistsResult constructorExists(JavacNode node) { node = upToTypeNode(node); if (node != null && node.get() instanceof JCClassDecl) { for (JCTree def : ((JCClassDecl)node.get()).defs) { if (def instanceof JCMethodDecl) { JCMethodDecl md = (JCMethodDecl) def; if (md.name.contentEquals("")) { if ((md.mods.flags & Flags.GENERATEDCONSTR) != 0) continue; if (isTolerate(node, md)) continue; return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } } return MemberExistsResult.NOT_EXISTS; } public static boolean isConstructorCall(final JCStatement statement) { if (!(statement instanceof JCExpressionStatement)) return false; JCExpression expr = ((JCExpressionStatement) statement).expr; if (!(expr instanceof JCMethodInvocation)) return false; JCExpression invocation = ((JCMethodInvocation) expr).meth; String name; if (invocation instanceof JCFieldAccess) { name = ((JCFieldAccess) invocation).name.toString(); } else if (invocation instanceof JCIdent) { name = ((JCIdent) invocation).name.toString(); } else { name = ""; } return "super".equals(name) || "this".equals(name); } /** * Turns an {@code AccessLevel} instance into the flag bit used by javac. */ public static int toJavacModifier(AccessLevel accessLevel) { switch (accessLevel) { case MODULE: case PACKAGE: return 0; default: case PUBLIC: return Flags.PUBLIC; case NONE: case PRIVATE: return Flags.PRIVATE; case PROTECTED: return Flags.PROTECTED; } } private static class GetterMethod { private final Name name; private final JCExpression type; GetterMethod(Name name, JCExpression type) { this.name = name; this.type = type; } } private static GetterMethod findGetter(JavacNode field) { JCVariableDecl decl = (JCVariableDecl)field.get(); JavacNode typeNode = field.up(); for (String potentialGetterName : toAllGetterNames(field)) { for (JavacNode potentialGetter : typeNode.down()) { if (potentialGetter.getKind() != Kind.METHOD) continue; JCMethodDecl method = (JCMethodDecl) potentialGetter.get(); if (!method.name.toString().equalsIgnoreCase(potentialGetterName)) continue; /** static getX() methods don't count. */ if ((method.mods.flags & Flags.STATIC) != 0) continue; /** Nor do getters with a non-empty parameter list. */ if (method.params != null && method.params.size() > 0) continue; return new GetterMethod(method.name, method.restype); } } // Check if the field has a @Getter annotation. boolean hasGetterAnnotation = false; for (JavacNode child : field.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { AnnotationValues ann = createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } } // Check if the class has a @Getter annotation. if (!hasGetterAnnotation && new HandleGetter().fieldQualifiesForGetterGeneration(field)) { //Check if the class has @Getter or @Data annotation. JavacNode containingType = field.up(); if (containingType != null) for (JavacNode child : containingType.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Data.class, child)) hasGetterAnnotation = true; if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { AnnotationValues ann = createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } } } if (hasGetterAnnotation) { String getterName = toGetterName(field); if (getterName == null) return null; return new GetterMethod(field.toName(getterName), decl.vartype); } return null; } public enum FieldAccess { GETTER, PREFER_FIELD, ALWAYS_FIELD; } static boolean lookForGetter(JavacNode field, FieldAccess fieldAccess) { if (fieldAccess == FieldAccess.GETTER) return true; if (fieldAccess == FieldAccess.ALWAYS_FIELD) return false; // If @Getter(lazy = true) is used, then using it is mandatory. for (JavacNode child : field.down()) { if (child.getKind() != Kind.ANNOTATION) continue; if (annotationTypeMatches(Getter.class, child)) { AnnotationValues ann = createAnnotation(Getter.class, child); if (ann.getInstance().lazy()) return true; } } return false; } /** * Returns the type of the field, unless a getter exists for this field, in which case the return type of the getter is returned. * * @see #createFieldAccessor(TreeMaker, JavacNode, FieldAccess) */ static JCExpression getFieldType(JavacNode field, FieldAccess fieldAccess) { boolean lookForGetter = lookForGetter(field, fieldAccess); GetterMethod getter = lookForGetter ? findGetter(field) : null; if (getter == null) { return ((JCVariableDecl)field.get()).vartype; } return getter.type; } /** * Creates an expression that reads the field. Will either be {@code this.field} or {@code this.getField()} depending on whether or not there's a getter. */ static JCExpression createFieldAccessor(JavacTreeMaker maker, JavacNode field, FieldAccess fieldAccess) { return createFieldAccessor(maker, field, fieldAccess, null); } static JCExpression createFieldAccessor(JavacTreeMaker maker, JavacNode field, FieldAccess fieldAccess, JCExpression receiver) { boolean lookForGetter = lookForGetter(field, fieldAccess); GetterMethod getter = lookForGetter ? findGetter(field) : null; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); if (getter == null) { if (receiver == null) { if ((fieldDecl.mods.flags & Flags.STATIC) == 0) { receiver = maker.Ident(field.toName("this")); } else { JavacNode containerNode = field.up(); if (containerNode != null && containerNode.get() instanceof JCClassDecl) { JCClassDecl container = (JCClassDecl) field.up().get(); receiver = maker.Ident(container.name); } } } return receiver == null ? maker.Ident(fieldDecl.name) : maker.Select(receiver, fieldDecl.name); } if (receiver == null) receiver = maker.Ident(field.toName("this")); JCMethodInvocation call = maker.Apply(List.nil(), maker.Select(receiver, getter.name), List.nil()); return call; } public static Type getMirrorForFieldType(JavacNode fieldNode) { Element fieldElement = fieldNode.getElement(); if (fieldElement instanceof VarSymbol) return ((VarSymbol) fieldElement).type; return null; } /** * Adds the given new field declaration to the provided type AST Node. * The field carries the @{@link SuppressWarnings}("all") annotation. * Also takes care of updating the JavacAST. */ public static JavacNode injectFieldAndMarkGenerated(JavacNode typeNode, JCVariableDecl field) { return injectField(typeNode, field, true); } /** * Adds the given new field declaration to the provided type AST Node. * * Also takes care of updating the JavacAST. */ public static JavacNode injectField(JavacNode typeNode, JCVariableDecl field) { return injectField(typeNode, field, false); } private static JavacNode injectField(JavacNode typeNode, JCVariableDecl field, boolean addGenerated) { JCClassDecl type = (JCClassDecl) typeNode.get(); if (addGenerated) { addSuppressWarningsAll(field.mods, typeNode, field.pos, getGeneratedBy(field), typeNode.getContext()); addGenerated(field.mods, typeNode, field.pos, getGeneratedBy(field), typeNode.getContext()); } List insertAfter = null; List insertBefore = type.defs; while (true) { boolean skip = false; if (insertBefore.head instanceof JCVariableDecl) { JCVariableDecl f = (JCVariableDecl) insertBefore.head; if (isEnumConstant(f) || isGenerated(f)) skip = true; } else if (insertBefore.head instanceof JCMethodDecl) { if ((((JCMethodDecl) insertBefore.head).mods.flags & GENERATEDCONSTR) != 0) skip = true; } if (skip) { insertAfter = insertBefore; insertBefore = insertBefore.tail; continue; } break; } List fieldEntry = List.of(field); fieldEntry.tail = insertBefore; if (insertAfter == null) { type.defs = fieldEntry; } else { insertAfter.tail = fieldEntry; } return typeNode.add(field, Kind.FIELD); } public static boolean isEnumConstant(final JCVariableDecl field) { return (field.mods.flags & Flags.ENUM) != 0; } // jdk9 support, types have changed, names stay the same static class ClassSymbolMembersField { private static final Field membersField; private static final Method removeMethod; private static final Method enterMethod; static { Field f = null; Method r = null; Method e = null; try { f = ClassSymbol.class.getField("members_field"); r = f.getType().getMethod("remove", Symbol.class); e = f.getType().getMethod("enter", Symbol.class); } catch (Exception ex) {} membersField = f; removeMethod = r; enterMethod = e; } static void remove(ClassSymbol from, Symbol toRemove) { if (from == null) return; try { Scope scope = (Scope) membersField.get(from); if (scope == null) return; removeMethod.invoke(scope, toRemove); } catch (Exception e) {} } static void enter(ClassSymbol from, Symbol toEnter) { if (from == null) return; try { Scope scope = (Scope) membersField.get(from); if (scope == null) return; enterMethod.invoke(scope, toEnter); } catch (Exception e) {} } } public static void injectMethod(JavacNode typeNode, JCMethodDecl method) { injectMethod(typeNode, method, null, null); } /** * Adds the given new method declaration to the provided type AST Node. * Can also inject constructors. * * Also takes care of updating the JavacAST. */ public static void injectMethod(JavacNode typeNode, JCMethodDecl method, List paramTypes, Type returnType) { JCClassDecl type = (JCClassDecl) typeNode.get(); if (method.getName().contentEquals("")) { //Scan for default constructor, and remove it. int idx = 0; for (JCTree def : type.defs) { if (def instanceof JCMethodDecl) { if ((((JCMethodDecl) def).mods.flags & Flags.GENERATEDCONSTR) != 0) { JavacNode tossMe = typeNode.getNodeFor(def); if (tossMe != null) tossMe.up().removeChild(tossMe); type.defs = addAllButOne(type.defs, idx); ClassSymbolMembersField.remove(type.sym, ((JCMethodDecl)def).sym); break; } } idx++; } } addSuppressWarningsAll(method.mods, typeNode, method.pos, getGeneratedBy(method), typeNode.getContext()); addGenerated(method.mods, typeNode, method.pos, getGeneratedBy(method), typeNode.getContext()); type.defs = type.defs.append(method); fixMethodMirror(typeNode.getContext(), typeNode.getElement(), method.getModifiers().flags, method.getName(), paramTypes, returnType); typeNode.add(method, Kind.METHOD); } private static void fixMethodMirror(Context context, Element typeMirror, long access, Name methodName, List paramTypes, Type returnType) { if (typeMirror == null || paramTypes == null || returnType == null) return; ClassSymbol cs = (ClassSymbol) typeMirror; MethodSymbol methodSymbol = new MethodSymbol(access, methodName, new MethodType(paramTypes, returnType, List.nil(), Symtab.instance(context).methodClass), cs); ClassSymbolMembersField.enter(cs, methodSymbol); } /** * Adds an inner type (class, interface, enum) to the given type. Cannot inject top-level types. * * @param typeNode parent type to inject new type into * @param type New type (class, interface, etc) to inject. * @return */ public static JavacNode injectType(JavacNode typeNode, final JCClassDecl type) { JCClassDecl typeDecl = (JCClassDecl) typeNode.get(); addSuppressWarningsAll(type.mods, typeNode, type.pos, getGeneratedBy(type), typeNode.getContext()); addGenerated(type.mods, typeNode, type.pos, getGeneratedBy(type), typeNode.getContext()); typeDecl.defs = typeDecl.defs.append(type); return typeNode.add(type, Kind.TYPE); } public static long addFinalIfNeeded(long flags, Context context) { boolean addFinal = LombokOptionsFactory.getDelombokOptions(context).getFormatPreferences().generateFinalParams(); if (addFinal) flags |= Flags.FINAL; return flags; } public static JCExpression genTypeRef(JavacNode node, String complexName) { String[] parts = complexName.split("\\."); if (parts.length > 2 && parts[0].equals("java") && parts[1].equals("lang")) { String[] subParts = new String[parts.length - 2]; System.arraycopy(parts, 2, subParts, 0, subParts.length); return genJavaLangTypeRef(node, subParts); } return chainDots(node, parts); } public static JCExpression genJavaLangTypeRef(JavacNode node, String... simpleNames) { if (LombokOptionsFactory.getDelombokOptions(node.getContext()).getFormatPreferences().javaLangAsFqn()) { return chainDots(node, "java", "lang", simpleNames); } else { return chainDots(node, null, null, simpleNames); } } public static JCExpression genJavaLangTypeRef(JavacNode node, int pos, String... simpleNames) { if (LombokOptionsFactory.getDelombokOptions(node.getContext()).getFormatPreferences().javaLangAsFqn()) { return chainDots(node, pos, "java", "lang", simpleNames); } else { return chainDots(node, pos, null, null, simpleNames); } } public static void addSuppressWarningsAll(JCModifiers mods, JavacNode node, int pos, JCTree source, Context context) { if (!LombokOptionsFactory.getDelombokOptions(context).getFormatPreferences().generateSuppressWarnings()) return; addAnnotation(mods, node, pos, source, context, "java.lang.SuppressWarnings", node.getTreeMaker().Literal("all")); if (Boolean.TRUE.equals(node.getAst().readConfiguration(ConfigurationKeys.ADD_FINDBUGS_SUPPRESSWARNINGS_ANNOTATIONS))) { JavacTreeMaker maker = node.getTreeMaker(); JCExpression arg = maker.Assign(maker.Ident(node.toName("justification")), maker.Literal("generated code")); addAnnotation(mods, node, pos, source, context, "edu.umd.cs.findbugs.annotations.SuppressFBWarnings", arg); } } public static void addGenerated(JCModifiers mods, JavacNode node, int pos, JCTree source, Context context) { if (!LombokOptionsFactory.getDelombokOptions(context).getFormatPreferences().generateGenerated()) return; if (HandlerUtil.shouldAddGenerated(node)) { addAnnotation(mods, node, pos, source, context, "javax.annotation.Generated", node.getTreeMaker().Literal("lombok")); } if (Boolean.TRUE.equals(node.getAst().readConfiguration(ConfigurationKeys.ADD_LOMBOK_GENERATED_ANNOTATIONS))) { addAnnotation(mods, node, pos, source, context, "lombok.Generated", null); } } private static void addAnnotation(JCModifiers mods, JavacNode node, int pos, JCTree source, Context context, String annotationTypeFqn, JCExpression arg) { boolean isJavaLangBased; String simpleName; { int idx = annotationTypeFqn.lastIndexOf('.'); simpleName = idx == -1 ? annotationTypeFqn : annotationTypeFqn.substring(idx + 1); isJavaLangBased = idx == 9 && annotationTypeFqn.regionMatches(0, "java.lang.", 0, 10); } for (JCAnnotation ann : mods.annotations) { JCTree annType = ann.getAnnotationType(); if (annType instanceof JCIdent) { Name lastPart = ((JCIdent) annType).name; if (lastPart.contentEquals(simpleName)) return; } if (annType instanceof JCFieldAccess) { if (annType.toString().equals(annotationTypeFqn)) return; } } JavacTreeMaker maker = node.getTreeMaker(); JCExpression annType = isJavaLangBased ? genJavaLangTypeRef(node, simpleName) : chainDotsString(node, annotationTypeFqn); annType.pos = pos; if (arg != null) { arg.pos = pos; if (arg instanceof JCAssign) { ((JCAssign) arg).lhs.pos = pos; ((JCAssign) arg).rhs.pos = pos; } } List argList = arg != null ? List.of(arg) : List.nil(); JCAnnotation annotation = recursiveSetGeneratedBy(maker.Annotation(annType, argList), source, context); annotation.pos = pos; mods.annotations = mods.annotations.append(annotation); } private static List addAllButOne(List defs, int idx) { ListBuffer out = new ListBuffer(); int i = 0; for (JCTree def : defs) { if (i++ != idx) out.append(def); } return out.toList(); } /** * In javac, dotted access of any kind, from {@code java.lang.String} to {@code var.methodName} * is represented by a fold-left of {@code Select} nodes with the leftmost string represented by * a {@code Ident} node. This method generates such an expression. *

* The position of the generated node(s) will be unpositioned (-1). * * For example, maker.Select(maker.Select(maker.Ident(NAME[java]), NAME[lang]), NAME[String]). * * @see com.sun.tools.javac.tree.JCTree.JCIdent * @see com.sun.tools.javac.tree.JCTree.JCFieldAccess */ public static JCExpression chainDots(JavacNode node, String elem1, String elem2, String... elems) { return chainDots(node, -1, elem1, elem2, elems); } public static JCExpression chainDots(JavacNode node, String[] elems) { return chainDots(node, -1, null, null, elems); } public static JCExpression chainDots(JavacNode node, LombokImmutableList elems) { assert elems != null; JavacTreeMaker maker = node.getTreeMaker(); JCExpression e = null; for (String elem : elems) { if (e == null) e = maker.Ident(node.toName(elem)); else e = maker.Select(e, node.toName(elem)); } return e; } /** * In javac, dotted access of any kind, from {@code java.lang.String} to {@code var.methodName} * is represented by a fold-left of {@code Select} nodes with the leftmost string represented by * a {@code Ident} node. This method generates such an expression. *

* The position of the generated node(s) will be equal to the {@code pos} parameter. * * For example, maker.Select(maker.Select(maker.Ident(NAME[java]), NAME[lang]), NAME[String]). * * @see com.sun.tools.javac.tree.JCTree.JCIdent * @see com.sun.tools.javac.tree.JCTree.JCFieldAccess */ public static JCExpression chainDots(JavacNode node, int pos, String elem1, String elem2, String... elems) { assert elems != null; JavacTreeMaker maker = node.getTreeMaker(); if (pos != -1) maker = maker.at(pos); JCExpression e = null; if (elem1 != null) e = maker.Ident(node.toName(elem1)); if (elem2 != null) e = e == null ? maker.Ident(node.toName(elem2)) : maker.Select(e, node.toName(elem2)); for (int i = 0 ; i < elems.length ; i++) { e = e == null ? maker.Ident(node.toName(elems[i])) : maker.Select(e, node.toName(elems[i])); } assert e != null; return e; } /** * In javac, dotted access of any kind, from {@code java.lang.String} to {@code var.methodName} * is represented by a fold-left of {@code Select} nodes with the leftmost string represented by * a {@code Ident} node. This method generates such an expression. * * For example, maker.Select(maker.Select(maker.Ident(NAME[java]), NAME[lang]), NAME[String]). * * @see com.sun.tools.javac.tree.JCTree.JCIdent * @see com.sun.tools.javac.tree.JCTree.JCFieldAccess */ public static JCExpression chainDotsString(JavacNode node, String elems) { return chainDots(node, null, null, elems.split("\\.")); } /** * Searches the given field node for annotations and returns each one that matches the provided regular expression pattern. * * Only the simple name is checked - the package and any containing class are ignored. */ public static List findAnnotations(JavacNode fieldNode, Pattern namePattern) { ListBuffer result = new ListBuffer(); for (JavacNode child : fieldNode.down()) { if (child.getKind() == Kind.ANNOTATION) { JCAnnotation annotation = (JCAnnotation) child.get(); String name = annotation.annotationType.toString(); int idx = name.lastIndexOf("."); String suspect = idx == -1 ? name : name.substring(idx + 1); if (namePattern.matcher(suspect).matches()) { result.append(annotation); } } } return result.toList(); } /** * Generates a new statement that checks if the given variable is null, and if so, throws a specified exception with the * variable name as message. * * @param exName The name of the exception to throw; normally {@code java.lang.NullPointerException}. */ public static JCStatement generateNullCheck(JavacTreeMaker maker, JavacNode variable, JavacNode source) { NullCheckExceptionType exceptionType = source.getAst().readConfiguration(ConfigurationKeys.NON_NULL_EXCEPTION_TYPE); if (exceptionType == null) exceptionType = NullCheckExceptionType.NULL_POINTER_EXCEPTION; JCVariableDecl varDecl = (JCVariableDecl) variable.get(); if (isPrimitive(varDecl.vartype)) return null; Name fieldName = varDecl.name; JCExpression exType = genTypeRef(variable, exceptionType.getExceptionType()); JCExpression exception = maker.NewClass(null, List.nil(), exType, List.of(maker.Literal(exceptionType.toExceptionMessage(fieldName.toString()))), null); JCStatement throwStatement = maker.Throw(exception); JCBlock throwBlock = maker.Block(0, List.of(throwStatement)); return maker.If(maker.Binary(CTC_EQUAL, maker.Ident(fieldName), maker.Literal(CTC_BOT, null)), throwBlock, null); } /** * Given a list of field names and a node referring to a type, finds each name in the list that does not match a field within the type. */ public static List createListOfNonExistentFields(List list, JavacNode type, boolean excludeStandard, boolean excludeTransient) { boolean[] matched = new boolean[list.size()]; for (JavacNode child : type.down()) { if (list.isEmpty()) break; if (child.getKind() != Kind.FIELD) continue; JCVariableDecl field = (JCVariableDecl)child.get(); if (excludeStandard) { if ((field.mods.flags & Flags.STATIC) != 0) continue; if (field.name.toString().startsWith("$")) continue; } if (excludeTransient && (field.mods.flags & Flags.TRANSIENT) != 0) continue; int idx = list.indexOf(child.getName()); if (idx > -1) matched[idx] = true; } ListBuffer problematic = new ListBuffer(); for (int i = 0 ; i < list.size() ; i++) { if (!matched[i]) problematic.append(i); } return problematic.toList(); } static List unboxAndRemoveAnnotationParameter(JCAnnotation ast, String parameterName, String errorName, JavacNode annotationNode) { ListBuffer params = new ListBuffer(); ListBuffer result = new ListBuffer(); outer: for (JCExpression param : ast.args) { boolean allowRaw; String nameOfParam = "value"; JCExpression valueOfParam = null; if (param instanceof JCAssign) { JCAssign assign = (JCAssign) param; if (assign.lhs instanceof JCIdent) { JCIdent ident = (JCIdent) assign.lhs; nameOfParam = ident.name.toString(); } valueOfParam = assign.rhs; } /* strip trailing underscores */ { int lastIdx; for (lastIdx = nameOfParam.length() ; lastIdx > 0; lastIdx--) { if (nameOfParam.charAt(lastIdx - 1) != '_') break; } allowRaw = lastIdx < nameOfParam.length(); nameOfParam = nameOfParam.substring(0, lastIdx); } if (!parameterName.equals(nameOfParam)) { params.append(param); continue outer; } int endPos = Javac.getEndPosition(param.pos(), (JCCompilationUnit) annotationNode.top().get()); annotationNode.getAst().removeFromDeferredDiagnostics(param.pos, endPos); if (valueOfParam instanceof JCAnnotation) { String dummyAnnotationName = ((JCAnnotation) valueOfParam).annotationType.toString(); dummyAnnotationName = dummyAnnotationName.replace("_", "").replace("$", "").replace("x", "").replace("X", ""); if (dummyAnnotationName.length() > 0) { if (allowRaw) { result.append((JCAnnotation) valueOfParam); } else { addError(errorName, annotationNode); continue outer; } } else { for (JCExpression expr : ((JCAnnotation) valueOfParam).args) { if (expr instanceof JCAssign && ((JCAssign) expr).lhs instanceof JCIdent) { JCIdent id = (JCIdent) ((JCAssign) expr).lhs; if ("value".equals(id.name.toString())) { expr = ((JCAssign) expr).rhs; } else { addError(errorName, annotationNode); } } if (expr instanceof JCAnnotation) { result.append((JCAnnotation) expr); } else if (expr instanceof JCNewArray) { for (JCExpression expr2 : ((JCNewArray) expr).elems) { if (expr2 instanceof JCAnnotation) { result.append((JCAnnotation) expr2); } else { addError(errorName, annotationNode); continue outer; } } } else { addError(errorName, annotationNode); continue outer; } } } } else if (valueOfParam instanceof JCNewArray) { JCNewArray arr = (JCNewArray) valueOfParam; if (arr.elems.isEmpty()) { // Just remove it, this is always fine. } else if (allowRaw) { for (JCExpression jce : arr.elems) { if (jce instanceof JCAnnotation) result.append((JCAnnotation) jce); else addError(errorName, annotationNode); } } else { addError(errorName, annotationNode); } } else { addError(errorName, annotationNode); } } ast.args = params.toList(); return result.toList(); } private static void addError(String errorName, JavacNode node) { if (node.getLatestJavaSpecSupported() < 8) { node.addError("The correct format up to JDK7 is " + errorName + "=@__({@SomeAnnotation, @SomeOtherAnnotation}))"); } else { node.addError("The correct format for JDK8+ is " + errorName + "_={@SomeAnnotation, @SomeOtherAnnotation})"); } } public static List copyTypeParams(JavacNode source, List params) { if (params == null || params.isEmpty()) return params; ListBuffer out = new ListBuffer(); JavacTreeMaker maker = source.getTreeMaker(); Context context = source.getContext(); for (JCTypeParameter tp : params) { List bounds = tp.bounds; if (bounds != null && !bounds.isEmpty()) { ListBuffer boundsCopy = new ListBuffer(); for (JCExpression expr : tp.bounds) { boundsCopy.append(cloneType(maker, expr, source.get(), context)); } bounds = boundsCopy.toList(); } out.append(maker.TypeParameter(tp.name, bounds)); } return out.toList(); } public static JCExpression namePlusTypeParamsToTypeReference(JavacTreeMaker maker, Name typeName, List params) { ListBuffer typeArgs = new ListBuffer(); if (!params.isEmpty()) { for (JCTypeParameter param : params) { typeArgs.append(maker.Ident(param.name)); } return maker.TypeApply(maker.Ident(typeName), typeArgs.toList()); } return maker.Ident(typeName); } public static void sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(JavacNode typeNode, JavacNode errorNode) { List disallowed = List.nil(); for (JavacNode child : typeNode.down()) { for (Class annType : INVALID_ON_BUILDERS) { if (annotationTypeMatches(annType, child)) { disallowed = disallowed.append(annType.getSimpleName()); } } } int size = disallowed.size(); if (size == 0) return; if (size == 1) { errorNode.addError("@" + disallowed.head + " is not allowed on builder classes."); return; } StringBuilder out = new StringBuilder(); for (String a : disallowed) out.append("@").append(a).append(", "); out.setLength(out.length() - 2); errorNode.addError(out.append(" are not allowed on builder classes.").toString()); } static List copyAnnotations(List in) { ListBuffer out = new ListBuffer(); for (JCExpression expr : in) { if (!(expr instanceof JCAnnotation)) continue; out.append((JCAnnotation) expr.clone()); } return out.toList(); } static boolean isClass(JavacNode typeNode) { return isClassAndDoesNotHaveFlags(typeNode, Flags.INTERFACE | Flags.ENUM | Flags.ANNOTATION); } static boolean isClassOrEnum(JavacNode typeNode) { return isClassAndDoesNotHaveFlags(typeNode, Flags.INTERFACE | Flags.ANNOTATION); } public static boolean isClassAndDoesNotHaveFlags(JavacNode typeNode, int flags) { JCClassDecl typeDecl = null; if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl)typeNode.get(); else return false; long typeDeclflags = typeDecl == null ? 0 : typeDecl.mods.flags; return (typeDeclflags & flags) == 0; } public static JavacNode upToTypeNode(JavacNode node) { if (node == null) throw new NullPointerException("node"); while ((node != null) && !(node.get() instanceof JCClassDecl)) node = node.up(); return node; } /** * Creates a full clone of a given javac AST type node. Every part is cloned (every identifier, every select, every wildcard, every type apply). * * If there's any node in the tree that we don't know how to clone, that part isn't cloned. However, we wouldn't know what could possibly show up that we * can't currently clone; that's just a safeguard. * * This should be used if the type looks the same in the code, but resolves differently. For example, a static method that has some generics in it named after * the class's own parameter, but as its a static method, the static method's notion of {@code T} is different from the class notion of {@code T}. If you're duplicating * a type used in the class context, you need to use this method. */ public static JCExpression cloneType(JavacTreeMaker maker, JCExpression in, JCTree source, Context context) { JCExpression out = cloneType0(maker, in); if (out != null) recursiveSetGeneratedBy(out, source, context); return out; } private static JCExpression cloneType0(JavacTreeMaker maker, JCTree in) { if (in == null) return null; if (in instanceof JCPrimitiveTypeTree) return (JCExpression) in; if (in instanceof JCIdent) { return maker.Ident(((JCIdent) in).name); } if (in instanceof JCFieldAccess) { JCFieldAccess fa = (JCFieldAccess) in; return maker.Select(cloneType0(maker, fa.selected), fa.name); } if (in instanceof JCArrayTypeTree) { JCArrayTypeTree att = (JCArrayTypeTree) in; return maker.TypeArray(cloneType0(maker, att.elemtype)); } if (in instanceof JCTypeApply) { JCTypeApply ta = (JCTypeApply) in; ListBuffer lb = new ListBuffer(); for (JCExpression typeArg : ta.arguments) { lb.append(cloneType0(maker, typeArg)); } return maker.TypeApply(cloneType0(maker, ta.clazz), lb.toList()); } if (in instanceof JCWildcard) { JCWildcard w = (JCWildcard) in; JCExpression newInner = cloneType0(maker, w.inner); TypeBoundKind newKind; switch (w.getKind()) { case SUPER_WILDCARD: newKind = maker.TypeBoundKind(BoundKind.SUPER); break; case EXTENDS_WILDCARD: newKind = maker.TypeBoundKind(BoundKind.EXTENDS); break; default: case UNBOUNDED_WILDCARD: newKind = maker.TypeBoundKind(BoundKind.UNBOUND); break; } return maker.Wildcard(newKind, newInner); } // This is somewhat unsafe, but it's better than outright throwing an exception here. Returning null will just cause an exception down the pipeline. return (JCExpression) in; } private static final Pattern SECTION_FINDER = Pattern.compile("^\\s*\\**\\s*[-*][-*]+\\s*([GS]ETTER|WITHER)\\s*[-*][-*]+\\s*\\**\\s*$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); public static String stripLinesWithTagFromJavadoc(String javadoc, String regexpFragment) { Pattern p = Pattern.compile("^\\s*\\**\\s*" + regexpFragment + "\\s*\\**\\s*$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(javadoc); return m.replaceAll(""); } public static String stripSectionsFromJavadoc(String javadoc) { Matcher m = SECTION_FINDER.matcher(javadoc); if (!m.find()) return javadoc; return javadoc.substring(0, m.start()); } public static String[] splitJavadocOnSectionIfPresent(String javadoc, String sectionName) { Matcher m = SECTION_FINDER.matcher(javadoc); int getterSectionHeaderStart = -1; int getterSectionStart = -1; int getterSectionEnd = -1; while (m.find()) { if (m.group(1).equalsIgnoreCase(sectionName)) { getterSectionStart = m.end() + 1; getterSectionHeaderStart = m.start(); } else if (getterSectionStart != -1) { getterSectionEnd = m.start(); } } if (getterSectionStart != -1) { if (getterSectionEnd != -1) { return new String[] {javadoc.substring(getterSectionStart, getterSectionEnd), javadoc.substring(0, getterSectionHeaderStart) + javadoc.substring(getterSectionEnd)}; } else { return new String[] {javadoc.substring(getterSectionStart), javadoc.substring(0, getterSectionHeaderStart)}; } } return null; } public static enum CopyJavadoc { VERBATIM, GETTER { @Override public String[] split(String javadoc) { // step 1: Check if there is a 'GETTER' section. If yes, that becomes the new method's javadoc and we strip that from the original. String[] out = splitJavadocOnSectionIfPresent(javadoc, "GETTER"); if (out != null) return out; // failing that, create a copy, but strip @return from the original and @param from the copy, as well as other sections. String copy = javadoc; javadoc = stripLinesWithTagFromJavadoc(javadoc, "@returns?\\s+.*"); copy = stripLinesWithTagFromJavadoc(copy, "@param(?:eter)?\\s+.*"); copy = stripSectionsFromJavadoc(copy); return new String[] {copy, javadoc}; } }, SETTER { @Override public String[] split(String javadoc) { return splitForSetters(javadoc, "SETTER"); } }, WITHER { @Override public String[] split(String javadoc) { return splitForSetters(javadoc, "WITHER"); } }; private static String[] splitForSetters(String javadoc, String sectionName) { // step 1: Check if there is a 'SETTER' section. If yes, that becomes the new one and we strip that from the original. String[] out = splitJavadocOnSectionIfPresent(javadoc, sectionName); if (out != null) return out; // failing that, create a copy, but strip @param from the original and @return from the copy. String copy = javadoc; javadoc = stripLinesWithTagFromJavadoc(javadoc, "@param(?:eter)?\\s+.*"); copy = stripLinesWithTagFromJavadoc(copy, "@returns?\\s+.*"); copy = stripSectionsFromJavadoc(copy); return new String[] {copy, javadoc}; } /** Splits the javadoc into the section to be copied (ret[0]) and the section to replace the original with (ret[1]) */ public String[] split(String javadoc) { return new String[] {javadoc, javadoc}; } } /** * Copies javadoc on one node to the other. * * in 'GETTER' copyMode, first a 'GETTER' segment is searched for. If it exists, that will become the javadoc for the 'to' node, and this section is * stripped out of the 'from' node. If no 'GETTER' segment is found, then the entire javadoc is taken minus any {@code @param} lines and other sections. * any {@code @return} lines are stripped from 'from'. * * in 'SETTER' mode, stripping works similarly to 'GETTER' mode, except {@code param} are copied and stripped from the original and {@code @return} are skipped. */ public static void copyJavadoc(JavacNode from, JCTree to, CopyJavadoc copyMode) { if (copyMode == null) copyMode = CopyJavadoc.VERBATIM; try { JCCompilationUnit cu = ((JCCompilationUnit) from.top().get()); Object dc = Javac.getDocComments(cu); if (dc instanceof Map) { copyJavadoc_jdk6_7(from, to, copyMode, dc); } else if (Javac.instanceOfDocCommentTable(dc)) { CopyJavadoc_8.copyJavadoc(from, to, copyMode, dc); } } catch (Exception ignore) {} } private static final Pattern FIND_RETURN = Pattern.compile("^\\s*\\**\\s*@returns?\\s+.*$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); static String addReturnsThisIfNeeded(String in) { if (FIND_RETURN.matcher(in).find()) return in; return addJavadocLine(in, "@return this"); } static String addJavadocLine(String in, String line) { if (in.endsWith("\n")) return in + line + "\n"; return in + "\n" + line; } private static class CopyJavadoc_8 { static void copyJavadoc(JavacNode from, JCTree to, CopyJavadoc copyMode, Object dc) { DocCommentTable dct = (DocCommentTable) dc; Comment javadoc = dct.getComment(from.get()); if (javadoc != null) { String[] filtered = copyMode.split(javadoc.getText()); if (copyMode == CopyJavadoc.SETTER && shouldReturnThis(from)) { filtered[0] = addReturnsThisIfNeeded(filtered[0]); } dct.putComment(to, createJavadocComment(filtered[0], from)); dct.putComment(from.get(), createJavadocComment(filtered[1], from)); } } private static Comment createJavadocComment(final String text, final JavacNode field) { return new Comment() { @Override public String getText() { return text; } @Override public int getSourcePos(int index) { return -1; } @Override public CommentStyle getStyle() { return CommentStyle.JAVADOC; } @Override public boolean isDeprecated() { return text.contains("@deprecated") && field.getKind() == Kind.FIELD && isFieldDeprecated(field); } }; } } @SuppressWarnings({"unchecked", "all"}) private static void copyJavadoc_jdk6_7(JavacNode from, JCTree to, CopyJavadoc copyMode, Object dc) { Map docComments = (Map) dc; String javadoc = docComments.get(from.get()); if (javadoc != null) { String[] filtered = copyMode.split(javadoc); if (copyMode == CopyJavadoc.SETTER && shouldReturnThis(from)) { filtered[0] = addReturnsThisIfNeeded(filtered[0]); } docComments.put(to, filtered[0]); docComments.put(from.get(), filtered[1]); } } } lombok-1.16.18/src/core/lombok/javac/handlers/JavacResolver.java000066400000000000000000000056031312655740700244700ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import lombok.javac.JavacNode; import lombok.javac.JavacResolution; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; public enum JavacResolver { CLASS { @Override public Type resolveMember(JavacNode node, JCExpression expr) { Type type = expr.type; if (type == null) { try { new JavacResolution(node.getContext()).resolveClassMember(node); type = expr.type; } catch (Exception ignore) { } } return type; } }, METHOD { public Type resolveMember(JavacNode node, JCExpression expr) { Type type = expr.type; if (type == null) { try { JCExpression resolvedExpression = ((JCExpression) new JavacResolution(node.getContext()).resolveMethodMember(node).get(expr)); if (resolvedExpression != null) type = resolvedExpression.type; } catch (Exception ignore) { } } return type; } }, CLASS_AND_METHOD { @Override public Type resolveMember(JavacNode node, JCExpression expr) { Type type = METHOD.resolveMember(node, expr); if (type == null) { JavacNode classNode = node; while (classNode != null && noneOf(classNode.get(), JCBlock.class, JCMethodDecl.class, JCVariableDecl.class)) { classNode = classNode.up(); } if (classNode != null) { type = CLASS.resolveMember(classNode, expr); } } return type; } private boolean noneOf(Object o, Class... clazzes) { for (Class clazz : clazzes) { if (clazz.isInstance(o)) return false; } return true; } }; public abstract Type resolveMember(final JavacNode node, final JCExpression expr); } lombok-1.16.18/src/core/lombok/javac/handlers/JavacSingularsRecipes.java000066400000000000000000000314521312655740700261520ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import lombok.core.LombokImmutableList; import lombok.core.SpiLoadUtil; import lombok.core.TypeLibrary; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; public class JavacSingularsRecipes { private static final JavacSingularsRecipes INSTANCE = new JavacSingularsRecipes(); private final Map singularizers = new HashMap(); private final TypeLibrary singularizableTypes = new TypeLibrary(); private JavacSingularsRecipes() { try { loadAll(singularizableTypes, singularizers); singularizableTypes.lock(); } catch (IOException e) { System.err.println("Lombok's @Singularizable feature is broken due to misconfigured SPI files: " + e); } } private static void loadAll(TypeLibrary library, Map map) throws IOException { for (JavacSingularizer handler : SpiLoadUtil.findServices(JavacSingularizer.class, JavacSingularizer.class.getClassLoader())) { for (String type : handler.getSupportedTypes()) { JavacSingularizer existingSingularizer = map.get(type); if (existingSingularizer != null) { JavacSingularizer toKeep = existingSingularizer.getClass().getName().compareTo(handler.getClass().getName()) > 0 ? handler : existingSingularizer; System.err.println("Multiple singularizers found for type " + type + "; the alphabetically first class is used: " + toKeep.getClass().getName()); map.put(type, toKeep); } else { map.put(type, handler); library.addType(type); } } } } public static JavacSingularsRecipes get() { return INSTANCE; } public String toQualified(String typeReference) { return singularizableTypes.toQualified(typeReference); } public JavacSingularizer getSingularizer(String fqn) { return singularizers.get(fqn); } public static final class SingularData { private final JavacNode annotation; private final Name singularName; private final Name pluralName; private final List typeArgs; private final String targetFqn; private final JavacSingularizer singularizer; public SingularData(JavacNode annotation, Name singularName, Name pluralName, List typeArgs, String targetFqn, JavacSingularizer singularizer) { this.annotation = annotation; this.singularName = singularName; this.pluralName = pluralName; this.typeArgs = typeArgs; this.targetFqn = targetFqn; this.singularizer = singularizer; } public JavacNode getAnnotation() { return annotation; } public Name getSingularName() { return singularName; } public Name getPluralName() { return pluralName; } public List getTypeArgs() { return typeArgs; } public String getTargetFqn() { return targetFqn; } public JavacSingularizer getSingularizer() { return singularizer; } public String getTargetSimpleType() { int idx = targetFqn.lastIndexOf("."); return idx == -1 ? targetFqn : targetFqn.substring(idx + 1); } } public static abstract class JavacSingularizer { public abstract LombokImmutableList getSupportedTypes(); protected JCModifiers makeMods(JavacTreeMaker maker, JavacNode node, boolean deprecate) { if (deprecate) return maker.Modifiers(Flags.PUBLIC, List.of(maker.Annotation(genJavaLangTypeRef(node, "Deprecated"), List.nil()))); return maker.Modifiers(Flags.PUBLIC); } /** Checks if any of the to-be-generated nodes (fields, methods) already exist. If so, errors on these (singulars don't support manually writing some of it, and returns true). */ public boolean checkForAlreadyExistingNodesAndGenerateError(JavacNode builderType, SingularData data) { for (JavacNode child : builderType.down()) { switch (child.getKind()) { case FIELD: { JCVariableDecl field = (JCVariableDecl) child.get(); Name name = field.name; if (name == null) break; if (getGeneratedBy(field) != null) continue; for (Name fieldToBeGenerated : listFieldsToBeGenerated(data, builderType)) { if (!fieldToBeGenerated.equals(name)) continue; child.addError("Manually adding a field that @Singular @Builder would generate is not supported. If you want to manually manage the builder aspect for this field/parameter, don't use @Singular."); return true; } break; } case METHOD: { JCMethodDecl method = (JCMethodDecl) child.get(); Name name = method.name; if (name == null) break; if (getGeneratedBy(method) != null) continue; for (Name methodToBeGenerated : listMethodsToBeGenerated(data, builderType)) { if (!methodToBeGenerated.equals(name)) continue; child.addError("Manually adding a method that @Singular @Builder would generate is not supported. If you want to manually manage the builder aspect for this field/parameter, don't use @Singular."); return true; } break; }} } return false; } public java.util.List listFieldsToBeGenerated(SingularData data, JavacNode builderType) { return Collections.singletonList(data.pluralName); } public java.util.List listMethodsToBeGenerated(SingularData data, JavacNode builderType) { Name p = data.pluralName; Name s = data.singularName; if (p.equals(s)) return Collections.singletonList(p); return Arrays.asList(p, s); } public abstract java.util.List generateFields(SingularData data, JavacNode builderType, JCTree source); public abstract void generateMethods(SingularData data, boolean deprecate, JavacNode builderType, JCTree source, boolean fluent, boolean chain); public abstract void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer statements, Name targetVariableName); public boolean requiresCleaning() { try { return !getClass().getMethod("appendCleaningCode", SingularData.class, JavacNode.class, JCTree.class, ListBuffer.class).getDeclaringClass().equals(JavacSingularizer.class); } catch (NoSuchMethodException e) { return false; } } public void appendCleaningCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer statements) { } // -- Utility methods -- /** * Adds the requested number of type arguments to the provided type, copying each argument in {@code typeArgs}. If typeArgs is too long, the extra elements are ignored. * If {@code typeArgs} is null or too short, {@code java.lang.Object} will be substituted for each missing type argument. * * @param count The number of type arguments requested. * @param addExtends If {@code true}, all bounds are either '? extends X' or just '?'. If false, the reverse is applied, and '? extends Foo' is converted to Foo, '?' to Object, etc. * @param node Some node in the same AST. Just used to obtain makers and contexts and such. * @param type The type to add generics to. * @param typeArgs the list of type args to clone. * @param source The source annotation that is the root cause of this code generation. */ protected JCExpression addTypeArgs(int count, boolean addExtends, JavacNode node, JCExpression type, List typeArgs, JCTree source) { JavacTreeMaker maker = node.getTreeMaker(); List clonedAndFixedTypeArgs = createTypeArgs(count, addExtends, node, typeArgs, source); return maker.TypeApply(type, clonedAndFixedTypeArgs); } protected List createTypeArgs(int count, boolean addExtends, JavacNode node, List typeArgs, JCTree source) { JavacTreeMaker maker = node.getTreeMaker(); Context context = node.getContext(); if (count < 0) throw new IllegalArgumentException("count is negative"); if (count == 0) return List.nil(); ListBuffer arguments = new ListBuffer(); if (typeArgs != null) for (JCExpression orig : typeArgs) { if (!addExtends) { if (orig.getKind() == Kind.UNBOUNDED_WILDCARD || orig.getKind() == Kind.SUPER_WILDCARD) { arguments.append(genJavaLangTypeRef(node, "Object")); } else if (orig.getKind() == Kind.EXTENDS_WILDCARD) { JCExpression inner; try { inner = (JCExpression) ((JCWildcard) orig).inner; } catch (Exception e) { inner = genJavaLangTypeRef(node, "Object"); } arguments.append(cloneType(maker, inner, source, context)); } else { arguments.append(cloneType(maker, orig, source, context)); } } else { if (orig.getKind() == Kind.UNBOUNDED_WILDCARD || orig.getKind() == Kind.SUPER_WILDCARD) { arguments.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null)); } else if (orig.getKind() == Kind.EXTENDS_WILDCARD) { arguments.append(cloneType(maker, orig, source, context)); } else { arguments.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.EXTENDS), cloneType(maker, orig, source, context))); } } if (--count == 0) break; } while (count-- > 0) { if (addExtends) { arguments.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null)); } else { arguments.append(genJavaLangTypeRef(node, "Object")); } } return arguments.toList(); } /** Generates 'this.name.size()' as an expression; if nullGuard is true, it's this.name == null ? 0 : this.name.size(). */ protected JCExpression getSize(JavacTreeMaker maker, JavacNode builderType, Name name, boolean nullGuard, boolean parens) { Name thisName = builderType.toName("this"); JCExpression fn = maker.Select(maker.Select(maker.Ident(thisName), name), builderType.toName("size")); JCExpression sizeInvoke = maker.Apply(List.nil(), fn, List.nil()); if (nullGuard) { JCExpression isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(thisName), name), maker.Literal(CTC_BOT, 0)); JCExpression out = maker.Conditional(isNull, maker.Literal(CTC_INT, 0), sizeInvoke); if (parens) return maker.Parens(out); return out; } return sizeInvoke; } protected JCExpression cloneParamType(int index, JavacTreeMaker maker, List typeArgs, JavacNode builderType, JCTree source) { if (typeArgs == null || typeArgs.size() <= index) { return genJavaLangTypeRef(builderType, "Object"); } else { JCExpression originalType = typeArgs.get(index); if (originalType.getKind() == Kind.UNBOUNDED_WILDCARD || originalType.getKind() == Kind.SUPER_WILDCARD) { return genJavaLangTypeRef(builderType, "Object"); } else if (originalType.getKind() == Kind.EXTENDS_WILDCARD) { try { return cloneType(maker, (JCExpression) ((JCWildcard) originalType).inner, source, builderType.getContext()); } catch (Exception e) { return genJavaLangTypeRef(builderType, "Object"); } } else { return cloneType(maker, originalType, source, builderType.getContext()); } } } } } lombok-1.16.18/src/core/lombok/javac/handlers/package-info.java000066400000000000000000000027101312655740700242420ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Contains the classes that implement the transformations for all of lombok's various features on the javac v1.6 platform. * * NB: This package is not public API in the sense that contents of this package, * even public classes / methods / etc, may change in point releases. */ package lombok.javac.handlers; lombok-1.16.18/src/core/lombok/javac/handlers/singulars/000077500000000000000000000000001312655740700230625ustar00rootroot00000000000000lombok-1.16.18/src/core/lombok/javac/handlers/singulars/JavacGuavaMapSingularizer.java000066400000000000000000000043601312655740700307750ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers.singulars; import lombok.core.LombokImmutableList; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; import org.mangosdk.spi.ProviderFor; @ProviderFor(JavacSingularizer.class) public class JavacGuavaMapSingularizer extends JavacGuavaSingularizer { // TODO cgcc.ImmutableMultimap, cgcc.ImmutableListMultimap, cgcc.ImmutableSetMultimap // TODO cgcc.ImmutableClassToInstanceMap // TODO cgcc.ImmutableRangeMap private static final LombokImmutableList SUFFIXES = LombokImmutableList.of("key", "value"); private static final LombokImmutableList SUPPORTED_TYPES = LombokImmutableList.of( "com.google.common.collect.ImmutableMap", "com.google.common.collect.ImmutableBiMap", "com.google.common.collect.ImmutableSortedMap" ); @Override public LombokImmutableList getSupportedTypes() { return SUPPORTED_TYPES; } @Override protected LombokImmutableList getArgumentSuffixes() { return SUFFIXES; } @Override protected String getAddMethodName() { return "put"; } @Override protected String getAddAllTypeName() { return "java.util.Map"; } } lombok-1.16.18/src/core/lombok/javac/handlers/singulars/JavacGuavaSetListSingularizer.java000066400000000000000000000044301312655740700316450ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers.singulars; import org.mangosdk.spi.ProviderFor; import lombok.core.LombokImmutableList; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; @ProviderFor(JavacSingularizer.class) public class JavacGuavaSetListSingularizer extends JavacGuavaSingularizer { // TODO com.google.common.collect.ImmutableRangeSet // TODO com.google.common.collect.ImmutableMultiset and com.google.common.collect.ImmutableSortedMultiset private static final LombokImmutableList SUFFIXES = LombokImmutableList.of(""); private static final LombokImmutableList SUPPORTED_TYPES = LombokImmutableList.of( "com.google.common.collect.ImmutableCollection", "com.google.common.collect.ImmutableList", "com.google.common.collect.ImmutableSet", "com.google.common.collect.ImmutableSortedSet" ); @Override public LombokImmutableList getSupportedTypes() { return SUPPORTED_TYPES; } @Override protected LombokImmutableList getArgumentSuffixes() { return SUFFIXES; } @Override protected String getAddMethodName() { return "add"; } @Override protected String getAddAllTypeName() { return "java.lang.Iterable"; } } lombok-1.16.18/src/core/lombok/javac/handlers/singulars/JavacGuavaSingularizer.java000066400000000000000000000277421312655740700303500ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers.singulars; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.Collections; import lombok.core.GuavaTypeMap; import lombok.core.LombokImmutableList; import lombok.core.handlers.HandlerUtil; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacHandlerUtil; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; import lombok.javac.handlers.JavacSingularsRecipes.SingularData; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; abstract class JavacGuavaSingularizer extends JavacSingularizer { protected String getSimpleTargetTypeName(SingularData data) { return GuavaTypeMap.getGuavaTypeName(data.getTargetFqn()); } protected String getBuilderMethodName(SingularData data) { String simpleTypeName = getSimpleTargetTypeName(data); if ("ImmutableSortedSet".equals(simpleTypeName) || "ImmutableSortedMap".equals(simpleTypeName)) return "naturalOrder"; return "builder"; } @Override public java.util.List generateFields(SingularData data, JavacNode builderType, JCTree source) { JavacTreeMaker maker = builderType.getTreeMaker(); String simpleTypeName = getSimpleTargetTypeName(data); JCExpression type = JavacHandlerUtil.chainDots(builderType, "com", "google", "common", "collect", simpleTypeName, "Builder"); type = addTypeArgs(getTypeArgumentsCount(), false, builderType, type, data.getTypeArgs(), source); JCVariableDecl buildField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), data.getPluralName(), type, null); return Collections.singletonList(injectFieldAndMarkGenerated(builderType, buildField)); } @Override public void generateMethods(SingularData data, boolean deprecate, JavacNode builderType, JCTree source, boolean fluent, boolean chain) { JavacTreeMaker maker = builderType.getTreeMaker(); Symtab symbolTable = builderType.getSymbolTable(); JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID)); JCStatement returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null; generateSingularMethod(deprecate, maker, returnType, returnStatement, data, builderType, source, fluent); returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID)); returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null; generatePluralMethod(deprecate, maker, returnType, returnStatement, data, builderType, source, fluent); returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID)); returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null; generateClearMethod(deprecate, maker, returnType, returnStatement, data, builderType, source); } private void generateClearMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source) { JCModifiers mods = makeMods(maker, builderType, deprecate); List typeParams = List.nil(); List thrown = List.nil(); List params = List.nil(); JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()); JCStatement clearField = maker.Exec(maker.Assign(thisDotField, maker.Literal(CTC_BOT, null))); List statements = returnStatement != null ? List.of(clearField, returnStatement) : List.of(clearField); JCBlock body = maker.Block(0, statements); Name methodName = builderType.toName(HandlerUtil.buildAccessorName("clear", data.getPluralName().toString())); JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null); injectMethod(builderType, method); } void generateSingularMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) { List typeParams = List.nil(); List thrown = List.nil(); LombokImmutableList suffixes = getArgumentSuffixes(); Name[] names = new Name[suffixes.size()]; for (int i = 0; i < suffixes.size(); i++) { String s = suffixes.get(i); Name n = data.getSingularName(); names[i] = s.isEmpty() ? n : builderType.toName(s); } JCModifiers mods = makeMods(maker, builderType, deprecate); ListBuffer statements = new ListBuffer(); statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, source)); JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), getAddMethodName()); ListBuffer invokeAddExprBuilder = new ListBuffer(); for (int i = 0; i < suffixes.size(); i++) { invokeAddExprBuilder.append(maker.Ident(names[i])); } List invokeAddExpr = invokeAddExprBuilder.toList(); JCExpression invokeAdd = maker.Apply(List.nil(), thisDotFieldDotAdd, invokeAddExpr); statements.append(maker.Exec(invokeAdd)); if (returnStatement != null) statements.append(returnStatement); JCBlock body = maker.Block(0, statements.toList()); Name methodName = data.getSingularName(); long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(getAddMethodName(), methodName.toString())); ListBuffer params = new ListBuffer(); for (int i = 0; i < suffixes.size(); i++) { JCExpression pt = cloneParamType(i, maker, data.getTypeArgs(), builderType, source); JCVariableDecl p = maker.VarDef(maker.Modifiers(paramFlags), names[i], pt, null); params.append(p); } JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params.toList(), thrown, body, null); injectMethod(builderType, method); } protected void generatePluralMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) { List typeParams = List.nil(); List thrown = List.nil(); JCModifiers mods = makeMods(maker, builderType, deprecate); ListBuffer statements = new ListBuffer(); statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, source)); JCExpression thisDotFieldDotAddAll = chainDots(builderType, "this", data.getPluralName().toString(), getAddMethodName() + "All"); JCExpression invokeAddAll = maker.Apply(List.nil(), thisDotFieldDotAddAll, List.of(maker.Ident(data.getPluralName()))); statements.append(maker.Exec(invokeAddAll)); if (returnStatement != null) statements.append(returnStatement); JCBlock body = maker.Block(0, statements.toList()); Name methodName = data.getPluralName(); long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(getAddMethodName() + "All", methodName.toString())); JCExpression paramType; String aaTypeName = getAddAllTypeName(); if (aaTypeName.startsWith("java.lang.") && aaTypeName.indexOf('.', 11) == -1) { paramType = genJavaLangTypeRef(builderType, aaTypeName.substring(10)); } else { paramType = chainDotsString(builderType, aaTypeName); } paramType = addTypeArgs(getTypeArgumentsCount(), true, builderType, paramType, data.getTypeArgs(), source); JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null); JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, List.of(param), thrown, body, null); injectMethod(builderType, method); } @Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer statements, Name targetVariableName) { JavacTreeMaker maker = builderType.getTreeMaker(); List jceBlank = List.nil(); JCExpression varType = chainDotsString(builderType, data.getTargetFqn()); int agrumentsCount = getTypeArgumentsCount(); varType = addTypeArgs(agrumentsCount, false, builderType, varType, data.getTypeArgs(), source); JCExpression empty; { //ImmutableX.of() JCExpression emptyMethod = chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), "of"); List invokeTypeArgs = createTypeArgs(agrumentsCount, false, builderType, data.getTypeArgs(), source); empty = maker.Apply(invokeTypeArgs, emptyMethod, jceBlank); } JCExpression invokeBuild; { //this.pluralName.build(); invokeBuild = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName().toString(), "build"), jceBlank); } JCExpression isNull; { //this.pluralName == null isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()), maker.Literal(CTC_BOT, null)); } JCExpression init = maker.Conditional(isNull, empty, invokeBuild); // this.pluralName == null ? ImmutableX.of() : this.pluralName.build() JCStatement jcs = maker.VarDef(maker.Modifiers(0), data.getPluralName(), varType, init); statements.append(jcs); } protected JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source) { List jceBlank = List.nil(); JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()); JCExpression thisDotField2 = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()); JCExpression cond = maker.Binary(CTC_EQUAL, thisDotField, maker.Literal(CTC_BOT, null)); JCExpression create = maker.Apply(jceBlank, chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), getBuilderMethodName(data)), jceBlank); JCStatement thenPart = maker.Exec(maker.Assign(thisDotField2, create)); return maker.If(cond, thenPart, null); } protected abstract LombokImmutableList getArgumentSuffixes(); protected abstract String getAddMethodName(); protected abstract String getAddAllTypeName(); protected int getTypeArgumentsCount() { return getArgumentSuffixes().size(); } } lombok-1.16.18/src/core/lombok/javac/handlers/singulars/JavacGuavaTableSingularizer.java000066400000000000000000000040161312655740700313050ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers.singulars; import org.mangosdk.spi.ProviderFor; import lombok.core.LombokImmutableList; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; @ProviderFor(JavacSingularizer.class) public class JavacGuavaTableSingularizer extends JavacGuavaSingularizer { private static final LombokImmutableList SUFFIXES = LombokImmutableList.of("rowKey", "columnKey", "value"); private static final LombokImmutableList SUPPORTED_TYPES = LombokImmutableList.of("com.google.common.collect.ImmutableTable"); @Override public LombokImmutableList getSupportedTypes() { return SUPPORTED_TYPES; } @Override protected LombokImmutableList getArgumentSuffixes() { return SUFFIXES; } @Override protected String getAddMethodName() { return "put"; } @Override protected String getAddAllTypeName() { return "com.google.common.collect.Table"; } } lombok-1.16.18/src/core/lombok/javac/handlers/singulars/JavacJavaUtilListSetSingularizer.java000066400000000000000000000221701312655740700323220ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers.singulars; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.Collections; import lombok.core.handlers.HandlerUtil; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacHandlerUtil; import lombok.javac.handlers.JavacSingularsRecipes.SingularData; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; abstract class JavacJavaUtilListSetSingularizer extends JavacJavaUtilSingularizer { @Override public java.util.List listFieldsToBeGenerated(SingularData data, JavacNode builderType) { if (useGuavaInstead(builderType)) { return guavaListSetSingularizer.listFieldsToBeGenerated(data, builderType); } return super.listFieldsToBeGenerated(data, builderType); } @Override public java.util.List listMethodsToBeGenerated(SingularData data, JavacNode builderType) { if (useGuavaInstead(builderType)) { return guavaListSetSingularizer.listMethodsToBeGenerated(data, builderType); } return super.listMethodsToBeGenerated(data, builderType); } @Override public java.util.List generateFields(SingularData data, JavacNode builderType, JCTree source) { if (useGuavaInstead(builderType)) { return guavaListSetSingularizer.generateFields(data, builderType, source); } JavacTreeMaker maker = builderType.getTreeMaker(); JCExpression type = JavacHandlerUtil.chainDots(builderType, "java", "util", "ArrayList"); type = addTypeArgs(1, false, builderType, type, data.getTypeArgs(), source); JCVariableDecl buildField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), data.getPluralName(), type, null); return Collections.singletonList(injectFieldAndMarkGenerated(builderType, buildField)); } @Override public void generateMethods(SingularData data, boolean deprecate, JavacNode builderType, JCTree source, boolean fluent, boolean chain) { if (useGuavaInstead(builderType)) { guavaListSetSingularizer.generateMethods(data, deprecate, builderType, source, fluent, chain); return; } JavacTreeMaker maker = builderType.getTreeMaker(); Symtab symbolTable = builderType.getSymbolTable(); Name thisName = builderType.toName("this"); JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID)); JCStatement returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null; generateSingularMethod(deprecate, maker, returnType, returnStatement, data, builderType, source, fluent); returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID)); returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null; generatePluralMethod(deprecate, maker, returnType, returnStatement, data, builderType, source, fluent); returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID)); returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null; generateClearMethod(deprecate, maker, returnType, returnStatement, data, builderType, source); } private void generateClearMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source) { JCModifiers mods = makeMods(maker, builderType, deprecate); List typeParams = List.nil(); List thrown = List.nil(); List params = List.nil(); List jceBlank = List.nil(); JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()); JCExpression thisDotFieldDotClear = maker.Select(maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()), builderType.toName("clear")); JCStatement clearCall = maker.Exec(maker.Apply(jceBlank, thisDotFieldDotClear, jceBlank)); JCExpression cond = maker.Binary(CTC_NOT_EQUAL, thisDotField, maker.Literal(CTC_BOT, null)); JCStatement ifSetCallClear = maker.If(cond, clearCall, null); List statements = returnStatement != null ? List.of(ifSetCallClear, returnStatement) : List.of(ifSetCallClear); JCBlock body = maker.Block(0, statements); Name methodName = builderType.toName(HandlerUtil.buildAccessorName("clear", data.getPluralName().toString())); JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null); injectMethod(builderType, method); } void generateSingularMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) { List typeParams = List.nil(); List thrown = List.nil(); JCModifiers mods = makeMods(maker, builderType, deprecate); ListBuffer statements = new ListBuffer(); statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source)); JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "add"); JCExpression invokeAdd = maker.Apply(List.nil(), thisDotFieldDotAdd, List.of(maker.Ident(data.getSingularName()))); statements.append(maker.Exec(invokeAdd)); if (returnStatement != null) statements.append(returnStatement); JCBlock body = maker.Block(0, statements.toList()); Name name = data.getSingularName(); long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("add", name.toString())); JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source); JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null); JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null); injectMethod(builderType, method); } void generatePluralMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) { List typeParams = List.nil(); List thrown = List.nil(); JCModifiers mods = makeMods(maker, builderType, deprecate); ListBuffer statements = new ListBuffer(); statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source)); JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "addAll"); JCExpression invokeAdd = maker.Apply(List.nil(), thisDotFieldDotAdd, List.of(maker.Ident(data.getPluralName()))); statements.append(maker.Exec(invokeAdd)); if (returnStatement != null) statements.append(returnStatement); JCBlock body = maker.Block(0, statements.toList()); Name name = data.getPluralName(); long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("addAll", name.toString())); JCExpression paramType = chainDots(builderType, "java", "util", "Collection"); paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs(), source); JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null); JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null); injectMethod(builderType, method); } } lombok-1.16.18/src/core/lombok/javac/handlers/singulars/JavacJavaUtilListSingularizer.java000066400000000000000000000133371312655740700316530ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers.singulars; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import org.mangosdk.spi.ProviderFor; import lombok.core.LombokImmutableList; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; import lombok.javac.handlers.JavacSingularsRecipes.SingularData; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCase; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; @ProviderFor(JavacSingularizer.class) public class JavacJavaUtilListSingularizer extends JavacJavaUtilListSetSingularizer { @Override public LombokImmutableList getSupportedTypes() { return LombokImmutableList.of("java.util.List", "java.util.Collection", "java.lang.Iterable"); } @Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer statements, Name targetVariableName) { if (useGuavaInstead(builderType)) { guavaListSetSingularizer.appendBuildCode(data, builderType, source, statements, targetVariableName); return; } JavacTreeMaker maker = builderType.getTreeMaker(); List jceBlank = List.nil(); ListBuffer cases = new ListBuffer(); /* case 0: (empty); break; */ { JCStatement assignStat; { // pluralName = java.util.Collections.emptyList(); JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "emptyList"), jceBlank); assignStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke)); } JCStatement breakStat = maker.Break(null); JCCase emptyCase = maker.Case(maker.Literal(CTC_INT, 0), List.of(assignStat, breakStat)); cases.append(emptyCase); } /* case 1: (singletonList); break; */ { JCStatement assignStat; { // pluralName = java.util.Collections.singletonList(this.pluralName.get(0)); JCExpression zeroLiteral = maker.Literal(CTC_INT, 0); JCExpression arg = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName().toString(), "get"), List.of(zeroLiteral)); List args = List.of(arg); JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "singletonList"), args); assignStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke)); } JCStatement breakStat = maker.Break(null); JCCase singletonCase = maker.Case(maker.Literal(CTC_INT, 1), List.of(assignStat, breakStat)); cases.append(singletonCase); } /* default: Create with right size, then addAll */ { List defStats = createListCopy(maker, data, builderType, source); JCCase defaultCase = maker.Case(null, defStats); cases.append(defaultCase); } JCStatement switchStat = maker.Switch(getSize(maker, builderType, data.getPluralName(), true, false), cases.toList()); JCExpression localShadowerType = chainDotsString(builderType, data.getTargetFqn()); localShadowerType = addTypeArgs(1, false, builderType, localShadowerType, data.getTypeArgs(), source); JCStatement varDefStat = maker.VarDef(maker.Modifiers(0), data.getPluralName(), localShadowerType, null); statements.append(varDefStat); statements.append(switchStat); } private List createListCopy(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source) { List jceBlank = List.nil(); Name thisName = builderType.toName("this"); JCExpression argToUnmodifiable; { // new java.util.ArrayList(this.pluralName); List constructorArgs = List.nil(); JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName()); constructorArgs = List.of(thisDotPluralName); JCExpression targetTypeExpr = chainDots(builderType, "java", "util", "ArrayList"); targetTypeExpr = addTypeArgs(1, false, builderType, targetTypeExpr, data.getTypeArgs(), source); argToUnmodifiable = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null); } JCStatement unmodifiableStat; { // pluralname = Collections.unmodifiableInterfaceType(-newlist-); JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiableList"), List.of(argToUnmodifiable)); unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke)); } return List.of(unmodifiableStat); } } lombok-1.16.18/src/core/lombok/javac/handlers/singulars/JavacJavaUtilMapSingularizer.java000066400000000000000000000317771312655740700314650ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers.singulars; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.Arrays; import lombok.core.LombokImmutableList; import lombok.core.handlers.HandlerUtil; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacHandlerUtil; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; import lombok.javac.handlers.JavacSingularsRecipes.SingularData; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; @ProviderFor(JavacSingularizer.class) public class JavacJavaUtilMapSingularizer extends JavacJavaUtilSingularizer { @Override public LombokImmutableList getSupportedTypes() { return LombokImmutableList.of("java.util.Map", "java.util.SortedMap", "java.util.NavigableMap"); } @Override public java.util.List listFieldsToBeGenerated(SingularData data, JavacNode builderType) { if (useGuavaInstead(builderType)) { return guavaMapSingularizer.listFieldsToBeGenerated(data, builderType); } String p = data.getPluralName().toString(); return Arrays.asList(builderType.toName(p + "$key"), builderType.toName(p + "$value")); } @Override public java.util.List listMethodsToBeGenerated(SingularData data, JavacNode builderType) { if (useGuavaInstead(builderType)) { return guavaMapSingularizer.listMethodsToBeGenerated(data, builderType); } return super.listMethodsToBeGenerated(data, builderType); } @Override public java.util.List generateFields(SingularData data, JavacNode builderType, JCTree source) { if (useGuavaInstead(builderType)) { return guavaMapSingularizer.generateFields(data, builderType, source); } JavacTreeMaker maker = builderType.getTreeMaker(); JCVariableDecl buildKeyField; { JCExpression type = JavacHandlerUtil.chainDots(builderType, "java", "util", "ArrayList"); type = addTypeArgs(1, false, builderType, type, data.getTypeArgs(), source); buildKeyField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), builderType.toName(data.getPluralName() + "$key"), type, null); } JCVariableDecl buildValueField; { JCExpression type = JavacHandlerUtil.chainDots(builderType, "java", "util", "ArrayList"); List tArgs = data.getTypeArgs(); if (tArgs != null && tArgs.size() > 1) tArgs = tArgs.tail; else tArgs = List.nil(); type = addTypeArgs(1, false, builderType, type, tArgs, source); buildValueField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), builderType.toName(data.getPluralName() + "$value"), type, null); } JavacNode valueFieldNode = injectFieldAndMarkGenerated(builderType, buildValueField); JavacNode keyFieldNode = injectFieldAndMarkGenerated(builderType, buildKeyField); return Arrays.asList(keyFieldNode, valueFieldNode); } @Override public void generateMethods(SingularData data, boolean deprecate, JavacNode builderType, JCTree source, boolean fluent, boolean chain) { if (useGuavaInstead(builderType)) { guavaMapSingularizer.generateMethods(data, deprecate, builderType, source, fluent, chain); return; } JavacTreeMaker maker = builderType.getTreeMaker(); Symtab symbolTable = builderType.getSymbolTable(); JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID)); JCStatement returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null; generateSingularMethod(deprecate, maker, returnType, returnStatement, data, builderType, source, fluent); returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID)); returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null; generatePluralMethod(deprecate, maker, returnType, returnStatement, data, builderType, source, fluent); returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(symbolTable, CTC_VOID)); returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null; generateClearMethod(deprecate, maker, returnType, returnStatement, data, builderType, source); } private void generateClearMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source) { JCModifiers mods = makeMods(maker, builderType, deprecate); List typeParams = List.nil(); List thrown = List.nil(); List params = List.nil(); List jceBlank = List.nil(); JCExpression thisDotKeyField = chainDots(builderType, "this", data.getPluralName() + "$key"); JCExpression thisDotKeyFieldDotClear = chainDots(builderType, "this", data.getPluralName() + "$key", "clear"); JCExpression thisDotValueFieldDotClear = chainDots(builderType, "this", data.getPluralName() + "$value", "clear"); JCStatement clearKeyCall = maker.Exec(maker.Apply(jceBlank, thisDotKeyFieldDotClear, jceBlank)); JCStatement clearValueCall = maker.Exec(maker.Apply(jceBlank, thisDotValueFieldDotClear, jceBlank)); JCExpression cond = maker.Binary(CTC_NOT_EQUAL, thisDotKeyField, maker.Literal(CTC_BOT, null)); JCBlock clearCalls = maker.Block(0, List.of(clearKeyCall, clearValueCall)); JCStatement ifSetCallClear = maker.If(cond, clearCalls, null); List statements = returnStatement != null ? List.of(ifSetCallClear, returnStatement) : List.of(ifSetCallClear); JCBlock body = maker.Block(0, statements); Name methodName = builderType.toName(HandlerUtil.buildAccessorName("clear", data.getPluralName().toString())); JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null); injectMethod(builderType, method); } private void generateSingularMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) { List typeParams = List.nil(); List thrown = List.nil(); JCModifiers mods = makeMods(maker, builderType, deprecate); ListBuffer statements = new ListBuffer(); statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source)); Name keyName = builderType.toName(data.getSingularName().toString() + "Key"); Name valueName = builderType.toName(data.getSingularName().toString() + "Value"); /* this.pluralname$key.add(singularnameKey); */ { JCExpression thisDotKeyFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$key", "add"); JCExpression invokeAdd = maker.Apply(List.nil(), thisDotKeyFieldDotAdd, List.of(maker.Ident(keyName))); statements.append(maker.Exec(invokeAdd)); } /* this.pluralname$value.add(singularnameValue); */ { JCExpression thisDotValueFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$value", "add"); JCExpression invokeAdd = maker.Apply(List.nil(), thisDotValueFieldDotAdd, List.of(maker.Ident(valueName))); statements.append(maker.Exec(invokeAdd)); } if (returnStatement != null) statements.append(returnStatement); JCBlock body = maker.Block(0, statements.toList()); long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); Name name = data.getSingularName(); if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("put", name.toString())); JCExpression paramTypeKey = cloneParamType(0, maker, data.getTypeArgs(), builderType, source); JCExpression paramTypeValue = cloneParamType(1, maker, data.getTypeArgs(), builderType, source); JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, paramTypeKey, null); JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, paramTypeValue, null); JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(paramKey, paramValue), thrown, body, null); injectMethod(builderType, method); } private void generatePluralMethod(boolean deprecate, JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) { List typeParams = List.nil(); List jceBlank = List.nil(); JCModifiers mods = makeMods(maker, builderType, deprecate); ListBuffer statements = new ListBuffer(); statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source)); long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext()); long baseFlags = JavacHandlerUtil.addFinalIfNeeded(0, builderType.getContext()); Name entryName = builderType.toName("$lombokEntry"); JCExpression forEachType = chainDots(builderType, "java", "util", "Map", "Entry"); forEachType = addTypeArgs(2, true, builderType, forEachType, data.getTypeArgs(), source); JCExpression keyArg = maker.Apply(List.nil(), maker.Select(maker.Ident(entryName), builderType.toName("getKey")), List.nil()); JCExpression valueArg = maker.Apply(List.nil(), maker.Select(maker.Ident(entryName), builderType.toName("getValue")), List.nil()); JCExpression addKey = maker.Apply(List.nil(), chainDots(builderType, "this", data.getPluralName() + "$key", "add"), List.of(keyArg)); JCExpression addValue = maker.Apply(List.nil(), chainDots(builderType, "this", data.getPluralName() + "$value", "add"), List.of(valueArg)); JCBlock forEachBody = maker.Block(0, List.of(maker.Exec(addKey), maker.Exec(addValue))); JCExpression entrySetInvocation = maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("entrySet")), jceBlank); JCStatement forEach = maker.ForeachLoop(maker.VarDef(maker.Modifiers(baseFlags), entryName, forEachType, null), entrySetInvocation, forEachBody); statements.append(forEach); if (returnStatement != null) statements.append(returnStatement); JCBlock body = maker.Block(0, statements.toList()); Name name = data.getPluralName(); if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("putAll", name.toString())); JCExpression paramType = chainDots(builderType, "java", "util", "Map"); paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs(), source); JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null); JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), jceBlank, body, null); injectMethod(builderType, method); } @Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer statements, Name targetVariableName) { if (useGuavaInstead(builderType)) { guavaMapSingularizer.appendBuildCode(data, builderType, source, statements, targetVariableName); return; } JavacTreeMaker maker = builderType.getTreeMaker(); if (data.getTargetFqn().equals("java.util.Map")) { statements.appendList(createJavaUtilSetMapInitialCapacitySwitchStatements(maker, data, builderType, true, "emptyMap", "singletonMap", "LinkedHashMap", source)); } else { statements.appendList(createJavaUtilSimpleCreationAndFillStatements(maker, data, builderType, true, true, false, true, "TreeMap", source)); } } } lombok-1.16.18/src/core/lombok/javac/handlers/singulars/JavacJavaUtilSetSingularizer.java000066400000000000000000000051721312655740700314710ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers.singulars; import org.mangosdk.spi.ProviderFor; import lombok.core.LombokImmutableList; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; import lombok.javac.handlers.JavacSingularsRecipes.SingularData; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; @ProviderFor(JavacSingularizer.class) public class JavacJavaUtilSetSingularizer extends JavacJavaUtilListSetSingularizer { @Override public LombokImmutableList getSupportedTypes() { return LombokImmutableList.of("java.util.Set", "java.util.SortedSet", "java.util.NavigableSet"); } @Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer statements, Name targetVariableName) { if (useGuavaInstead(builderType)) { guavaListSetSingularizer.appendBuildCode(data, builderType, source, statements, targetVariableName); return; } JavacTreeMaker maker = builderType.getTreeMaker(); if (data.getTargetFqn().equals("java.util.Set")) { statements.appendList(createJavaUtilSetMapInitialCapacitySwitchStatements(maker, data, builderType, false, "emptySet", "singleton", "LinkedHashSet", source)); } else { statements.appendList(createJavaUtilSimpleCreationAndFillStatements(maker, data, builderType, false, true, false, true, "TreeSet", source)); } } } lombok-1.16.18/src/core/lombok/javac/handlers/singulars/JavacJavaUtilSingularizer.java000066400000000000000000000276411312655740700310220ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers.singulars; import static lombok.javac.Javac.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCase; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import lombok.ConfigurationKeys; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; import lombok.javac.handlers.JavacSingularsRecipes.SingularData; abstract class JavacJavaUtilSingularizer extends JavacSingularizer { protected final JavacSingularizer guavaListSetSingularizer = new JavacGuavaSetListSingularizer(); protected final JavacSingularizer guavaMapSingularizer = new JavacGuavaMapSingularizer(); protected boolean useGuavaInstead(JavacNode node) { return Boolean.TRUE.equals(node.getAst().readConfiguration(ConfigurationKeys.SINGULAR_USE_GUAVA)); } protected List createJavaUtilSetMapInitialCapacitySwitchStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, String emptyCollectionMethod, String singletonCollectionMethod, String targetType, JCTree source) { List jceBlank = List.nil(); ListBuffer cases = new ListBuffer(); if (emptyCollectionMethod != null) { // case 0: (empty); break; JCStatement assignStat; { // pluralName = java.util.Collections.emptyCollectionMethod(); JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", emptyCollectionMethod), jceBlank); assignStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke)); } JCStatement breakStat = maker.Break(null); JCCase emptyCase = maker.Case(maker.Literal(CTC_INT, 0), List.of(assignStat, breakStat)); cases.append(emptyCase); } if (singletonCollectionMethod != null) { // case 1: (singleton); break; JCStatement assignStat; { // !mapMode: pluralName = java.util.Collections.singletonCollectionMethod(this.pluralName.get(0)); // mapMode: pluralName = java.util.Collections.singletonCollectionMethod(this.pluralName$key.get(0), this.pluralName$value.get(0)); JCExpression zeroLiteral = maker.Literal(CTC_INT, 0); JCExpression arg = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + (mapMode ? "$key" : ""), "get"), List.of(zeroLiteral)); List args; if (mapMode) { JCExpression zeroLiteralClone = maker.Literal(CTC_INT, 0); JCExpression arg2 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + (mapMode ? "$value" : ""), "get"), List.of(zeroLiteralClone)); args = List.of(arg, arg2); } else { args = List.of(arg); } JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", singletonCollectionMethod), args); assignStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke)); } JCStatement breakStat = maker.Break(null); JCCase singletonCase = maker.Case(maker.Literal(CTC_INT, 1), List.of(assignStat, breakStat)); cases.append(singletonCase); } { // default: List statements = createJavaUtilSimpleCreationAndFillStatements(maker, data, builderType, mapMode, false, true, emptyCollectionMethod == null, targetType, source); JCCase defaultCase = maker.Case(null, statements); cases.append(defaultCase); } JCStatement switchStat = maker.Switch(getSize(maker, builderType, mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName(), true, false), cases.toList()); JCExpression localShadowerType = chainDotsString(builderType, data.getTargetFqn()); localShadowerType = addTypeArgs(mapMode ? 2 : 1, false, builderType, localShadowerType, data.getTypeArgs(), source); JCStatement varDefStat = maker.VarDef(maker.Modifiers(0), data.getPluralName(), localShadowerType, null); return List.of(varDefStat, switchStat); } protected JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, JCTree source) { List jceBlank = List.nil(); Name v1Name = mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName(); Name v2Name = mapMode ? builderType.toName(data.getPluralName() + "$value") : null; JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v1Name); JCExpression cond = maker.Binary(CTC_EQUAL, thisDotField, maker.Literal(CTC_BOT, null)); thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v1Name); JCExpression v1Type = chainDots(builderType, "java", "util", "ArrayList"); v1Type = addTypeArgs(1, false, builderType, v1Type, data.getTypeArgs(), source); JCExpression constructArrayList = maker.NewClass(null, jceBlank, v1Type, jceBlank, null); JCStatement initV1 = maker.Exec(maker.Assign(thisDotField, constructArrayList)); JCStatement thenPart; if (mapMode) { thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v2Name); JCExpression v2Type = chainDots(builderType, "java", "util", "ArrayList"); List tArgs = data.getTypeArgs(); if (tArgs != null && tArgs.tail != null) tArgs = tArgs.tail; else tArgs = List.nil(); v2Type = addTypeArgs(1, false, builderType, v2Type, tArgs, source); constructArrayList = maker.NewClass(null, jceBlank, v2Type, jceBlank, null); JCStatement initV2 = maker.Exec(maker.Assign(thisDotField, constructArrayList)); thenPart = maker.Block(0, List.of(initV1, initV2)); } else { thenPart = initV1; } return maker.If(cond, thenPart, null); } protected List createJavaUtilSimpleCreationAndFillStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, boolean defineVar, boolean addInitialCapacityArg, boolean nullGuard, String targetType, JCTree source) { List jceBlank = List.nil(); Name thisName = builderType.toName("this"); JCStatement createStat; { // pluralName = new java.util.TargetType(initialCap); List constructorArgs = List.nil(); if (addInitialCapacityArg) { Name varName = mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName(); // this.varName.size() < MAX_POWER_OF_2 ? 1 + this.varName.size() + (this.varName.size() - 3) / 3 : Integer.MAX_VALUE; // lessThanCutOff = this.varName.size() < MAX_POWER_OF_2 JCExpression lessThanCutoff = maker.Binary(CTC_LESS_THAN, getSize(maker, builderType, varName, nullGuard, true), maker.Literal(CTC_INT, 0x40000000)); JCExpression integerMaxValue = genJavaLangTypeRef(builderType, "Integer", "MAX_VALUE"); JCExpression sizeFormulaLeft = maker.Binary(CTC_PLUS, maker.Literal(CTC_INT, 1), getSize(maker, builderType, varName, nullGuard, true)); JCExpression sizeFormulaRightLeft = maker.Parens(maker.Binary(CTC_MINUS, getSize(maker, builderType, varName, nullGuard, true), maker.Literal(CTC_INT, 3))); JCExpression sizeFormulaRight = maker.Binary(CTC_DIV, sizeFormulaRightLeft, maker.Literal(CTC_INT, 3)); JCExpression sizeFormula = maker.Binary(CTC_PLUS, sizeFormulaLeft, sizeFormulaRight); constructorArgs = List.of(maker.Conditional(lessThanCutoff, sizeFormula, integerMaxValue)); } JCExpression targetTypeExpr = chainDots(builderType, "java", "util", targetType); targetTypeExpr = addTypeArgs(mapMode ? 2 : 1, false, builderType, targetTypeExpr, data.getTypeArgs(), source); JCExpression constructorCall = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null); if (defineVar) { JCExpression localShadowerType = chainDotsString(builderType, data.getTargetFqn()); localShadowerType = addTypeArgs(mapMode ? 2 : 1, false, builderType, localShadowerType, data.getTypeArgs(), source); createStat = maker.VarDef(maker.Modifiers(0), data.getPluralName(), localShadowerType, constructorCall); } else { createStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), constructorCall)); } } JCStatement fillStat; { if (mapMode) { // for (int $i = 0; $i < this.pluralname$key.size(); i++) pluralname.put(this.pluralname$key.get($i), this.pluralname$value.get($i)); Name ivar = builderType.toName("$i"); Name keyVarName = builderType.toName(data.getPluralName() + "$key"); JCExpression pluralnameDotPut = maker.Select(maker.Ident(data.getPluralName()), builderType.toName("put")); JCExpression arg1 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$key", "get"), List.of(maker.Ident(ivar))); JCExpression arg2 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$value", "get"), List.of(maker.Ident(ivar))); // [jdk9] We add an unneccessary (V) cast here. Not doing so gives an error in javac (build 9-ea+156-jigsaw-nightly-h6072-20170212): // error: method put in interface Map cannot be applied to given types; arg2 = maker.TypeCast(createTypeArgs(2, false, builderType, data.getTypeArgs(), source).get(1), arg2); JCStatement putStatement = maker.Exec(maker.Apply(jceBlank, pluralnameDotPut, List.of(arg1, arg2))); JCStatement forInit = maker.VarDef(maker.Modifiers(0), ivar, maker.TypeIdent(CTC_INT), maker.Literal(CTC_INT, 0)); JCExpression checkExpr = maker.Binary(CTC_LESS_THAN, maker.Ident(ivar), getSize(maker, builderType, keyVarName, nullGuard, true)); JCExpression incrementExpr = maker.Unary(CTC_POSTINC, maker.Ident(ivar)); fillStat = maker.ForLoop(List.of(forInit), checkExpr, List.of(maker.Exec(incrementExpr)), putStatement); } else { // pluralname.addAll(this.pluralname); JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName()); fillStat = maker.Exec(maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("addAll")), List.of(thisDotPluralName))); } if (nullGuard) { JCExpression thisDotField = maker.Select(maker.Ident(thisName), mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName()); JCExpression nullCheck = maker.Binary(CTC_NOT_EQUAL, thisDotField, maker.Literal(CTC_BOT, null)); fillStat = maker.If(nullCheck, fillStat, null); } } JCStatement unmodifiableStat; { // pluralname = Collections.unmodifiableInterfaceType(pluralname); JCExpression arg = maker.Ident(data.getPluralName()); JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiable" + data.getTargetSimpleType()), List.of(arg)); unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke)); } return List.of(createStat, fillStat, unmodifiableStat); } } lombok-1.16.18/src/core/lombok/javac/package-info.java000066400000000000000000000026521312655740700224470ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Includes the javac specific implementations of the lombok AST and annotation introspection support. * * NB: This package is not public API in the sense that contents of this package, * even public classes / methods / etc, may change in point releases. */ package lombok.javac; lombok-1.16.18/src/core/lombok/package-info.java000066400000000000000000000033441312655740700213620ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * This package contains all the annotations and support classes you need as a user of lombok. * All other packages are only relevant to those who are extending lombok for their own uses, except: * *

    *
  • {@code lombok.extern.*} – These packages contains lombok annotations that solve boilerplate issues for libraries not part of the JRE itself. *
  • {@code lombok.experimental} – This package contains lombok features that are new or likely to change before committing to long-term support. *
* * @see
Lombok features */ package lombok; lombok-1.16.18/src/core/lombok/val.java000066400000000000000000000034331312655740700176170ustar00rootroot00000000000000/* * Copyright (C) 2010-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; /** * Use {@code val} as the type of any local variable declaration (even in a for-each statement), and the type will be inferred from the initializing expression. * For example: {@code val x = 10.0;} will infer {@code double}, and {@code val y = new ArrayList();} will infer {@code ArrayList}. The local variable * will also be made final. *

* Note that this is an annotation type because {@code val x = 10;} will be desugared to {@code @val final int x = 10;} *

* Complete documentation is found at the project lombok features page for @val. */ public @interface val { } lombok-1.16.18/src/delombok/000077500000000000000000000000001312655740700155505ustar00rootroot00000000000000lombok-1.16.18/src/delombok/lombok/000077500000000000000000000000001312655740700170335ustar00rootroot00000000000000lombok-1.16.18/src/delombok/lombok/delombok/000077500000000000000000000000001312655740700206275ustar00rootroot00000000000000lombok-1.16.18/src/delombok/lombok/delombok/Delombok.java000066400000000000000000000517541312655740700232420ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import javax.tools.DiagnosticListener; import javax.tools.JavaFileObject; import lombok.Lombok; import lombok.javac.CommentCatcher; import lombok.javac.LombokOptions; import com.sun.tools.javac.comp.Todo; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; import com.zwitserloot.cmdreader.CmdReader; import com.zwitserloot.cmdreader.Description; import com.zwitserloot.cmdreader.Excludes; import com.zwitserloot.cmdreader.FullName; import com.zwitserloot.cmdreader.InvalidCommandLineException; import com.zwitserloot.cmdreader.Mandatory; import com.zwitserloot.cmdreader.Sequential; import com.zwitserloot.cmdreader.Shorthand; public class Delombok { private Charset charset = Charset.defaultCharset(); private Context context = new Context(); private Writer presetWriter; public void setWriter(Writer writer) { this.presetWriter = writer; } private PrintStream feedback = System.err; private boolean verbose; private boolean noCopy; private boolean force = false; private String classpath, sourcepath, bootclasspath; private LinkedHashMap fileToBase = new LinkedHashMap(); private List filesToParse = new ArrayList(); private Map formatPrefs = new HashMap(); /** If null, output to standard out. */ private File output = null; private static class CmdArgs { @Shorthand("v") @Description("Print the name of each file as it is being delombok-ed.") @Excludes("quiet") private boolean verbose; @Shorthand("f") @Description("Sets formatting rules. Use --format-help to list all available rules. Unset format rules are inferred by scanning the source for usages.") private List format = new ArrayList(); @FullName("format-help") private boolean formatHelp; @Shorthand("q") @Description("No warnings or errors will be emitted to standard error") @Excludes("verbose") private boolean quiet; @Shorthand("e") @Description("Sets the encoding of your source files. Defaults to the system default charset. Example: \"UTF-8\"") private String encoding; @Shorthand("p") @Description("Print delombok-ed code to standard output instead of saving it in target directory") private boolean print; @Shorthand("d") @Description("Directory to save delomboked files to") @Mandatory(onlyIfNot={"print", "help", "format-help"}) private String target; @Shorthand("c") @Description("Classpath (analogous to javac -cp option)") private String classpath; @Shorthand("s") @Description("Sourcepath (analogous to javac -sourcepath option)") private String sourcepath; @Description("override Bootclasspath (analogous to javac -bootclasspath option)") private String bootclasspath; @Description("Files to delombok. Provide either a file, or a directory. If you use a directory, all files in it (recursive) are delombok-ed") @Sequential private List input = new ArrayList(); @Description("Lombok will only delombok source files. Without this option, non-java, non-class files are copied to the target directory.") @Shorthand("n") private boolean nocopy; private boolean help; } private static String indentAndWordbreak(String in, int indent, int maxLen) { StringBuilder out = new StringBuilder(); StringBuilder line = new StringBuilder(); StringBuilder word = new StringBuilder(); int len = in.length(); for (int i = 0; i < (len + 1); i++) { char c = i == len ? ' ' : in.charAt(i); if (c == ' ') { if (line.length() + word.length() < maxLen) { line.append(word); } else { if (out.length() > 0) out.append("\n"); for (int j = 0; j < indent; j++) out.append(" "); out.append(line); line.setLength(0); line.append(word.toString().trim()); } word.setLength(0); } if (i < len) word.append(c); } if (line.length() > 0) { if (out.length() > 0) out.append("\n"); for (int j = 0; j < indent; j++) out.append(" "); out.append(line); } return out.toString(); } public static void main(String[] rawArgs) { CmdReader reader = CmdReader.of(CmdArgs.class); CmdArgs args; try { args = reader.make(rawArgs); } catch (InvalidCommandLineException e) { System.err.println("ERROR: " + e.getMessage()); System.err.println(reader.generateCommandLineHelp("delombok")); System.exit(1); return; } if (args.help || (args.input.isEmpty() && !args.formatHelp)) { if (!args.help) System.err.println("ERROR: no files or directories to delombok specified."); System.err.println(reader.generateCommandLineHelp("delombok")); System.exit(args.help ? 0 : 1); return; } Delombok delombok = new Delombok(); if (args.quiet) delombok.setFeedback(new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { //dummy - do nothing. } })); if (args.formatHelp) { System.out.println("Available format keys (to use, -f key:value -f key2:value2 -f ... ):"); for (Map.Entry e : FormatPreferences.getKeysAndDescriptions().entrySet()) { System.out.print(" "); System.out.print(e.getKey()); System.out.println(":"); System.out.println(indentAndWordbreak(e.getValue(), 4, 70)); } System.out.println("Example: -f indent:4 -f emptyLines:indent"); System.out.println("The '-f pretty' option is shorthand for '-f suppressWarnings:skip -f generated:skip -f danceAroundIdeChecks:skip -f generateDelombokComment:skip -f javaLangAsFQN:skip'"); System.exit(0); return; } try { delombok.setFormatPreferences(formatOptionsToMap(args.format)); } catch (InvalidFormatOptionException e) { System.out.println(e.getMessage() + " Try --format-help."); System.exit(1); return; } if (args.encoding != null) { try { delombok.setCharset(args.encoding); } catch (UnsupportedCharsetException e) { System.err.println("ERROR: Not a known charset: " + args.encoding); System.exit(1); return; } } if (args.verbose) delombok.setVerbose(true); if (args.nocopy) delombok.setNoCopy(true); if (args.print) { delombok.setOutputToStandardOut(); } else { delombok.setOutput(new File(args.target)); } if (args.classpath != null) delombok.setClasspath(args.classpath); if (args.sourcepath != null) delombok.setSourcepath(args.sourcepath); if (args.bootclasspath != null) delombok.setBootclasspath(args.bootclasspath); try { for (String in : args.input) { File f = new File(in).getAbsoluteFile(); if (f.isFile()) { delombok.addFile(f.getParentFile(), f.getName()); } else if (f.isDirectory()) { delombok.addDirectory(f); } else if (!f.exists()) { if (!args.quiet) System.err.println("WARNING: does not exist - skipping: " + f); } else { if (!args.quiet) System.err.println("WARNING: not a standard file or directory - skipping: " + f); } } delombok.delombok(); } catch (Exception e) { if (!args.quiet) { String msg = e.getMessage(); if (msg != null && msg.startsWith("DELOMBOK: ")) System.err.println(msg.substring("DELOMBOK: ".length())); else { e.printStackTrace(); } System.exit(1); return; } } } public static class InvalidFormatOptionException extends Exception { public InvalidFormatOptionException(String msg) { super(msg); } } public static Map formatOptionsToMap(List formatOptions) throws InvalidFormatOptionException { boolean prettyEnabled = false; Map formatPrefs = new HashMap(); for (String format : formatOptions) { int idx = format.indexOf(':'); if (idx == -1) { if (format.equalsIgnoreCase("pretty")) { prettyEnabled = true; continue; } else { throw new InvalidFormatOptionException("Format keys need to be 2 values separated with a colon."); } } String key = format.substring(0, idx); String value = format.substring(idx + 1); boolean valid = false; for (String k : FormatPreferences.getKeysAndDescriptions().keySet()) { if (k.equalsIgnoreCase(key)) { valid = true; break; } } if (!valid) throw new InvalidFormatOptionException("Unknown format key: '" + key + "'."); formatPrefs.put(key.toLowerCase(), value); } if (prettyEnabled) { if (!formatPrefs.containsKey("suppresswarnings")) formatPrefs.put("suppresswarnings", "skip"); if (!formatPrefs.containsKey("generated")) formatPrefs.put("generated", "skip"); if (!formatPrefs.containsKey("dancearoundidechecks")) formatPrefs.put("dancearoundidechecks", "skip"); if (!formatPrefs.containsKey("generatedelombokcomment")) formatPrefs.put("generatedelombokcomment", "skip"); if (!formatPrefs.containsKey("javalangasfqn")) formatPrefs.put("javalangasfqn", "skip"); } return formatPrefs; } public void setFormatPreferences(Map prefs) { this.formatPrefs = prefs; } public void setCharset(String charsetName) throws UnsupportedCharsetException { if (charsetName == null) { charset = Charset.defaultCharset(); return; } charset = Charset.forName(charsetName); } public void setDiagnosticsListener(DiagnosticListener diagnostics) { if (diagnostics != null) context.put(DiagnosticListener.class, diagnostics); } public void setForceProcess(boolean force) { this.force = force; } public void setFeedback(PrintStream feedback) { this.feedback = feedback; } public void setClasspath(String classpath) { this.classpath = classpath; } public void setSourcepath(String sourcepath) { this.sourcepath = sourcepath; } public void setBootclasspath(String bootclasspath) { this.bootclasspath = bootclasspath; } public void setVerbose(boolean verbose) { this.verbose = verbose; } public void setNoCopy(boolean noCopy) { this.noCopy = noCopy; } public void setOutput(File dir) { if (dir.isFile() || (!dir.isDirectory() && dir.getName().endsWith(".java"))) throw new IllegalArgumentException( "DELOMBOK: delombok will only write to a directory. " + "If you want to delombok a single file, use -p to output to standard output, then redirect this to a file:\n" + "delombok MyJavaFile.java -p >MyJavaFileDelombok.java"); output = dir; } public void setOutputToStandardOut() { this.output = null; } public void addDirectory(File base) throws IOException { addDirectory0(false, base, "", 0); } public void addDirectory1(boolean copy, File base, String name) throws IOException { File f = new File(base, name); if (f.isFile()) { String extension = getExtension(f); if (extension.equals("java")) addFile(base, name); else if (extension.equals("class")) skipClass(name); else copy(copy, base, name); } else if (!f.exists()) { feedback.printf("Skipping %s because it does not exist.\n", canonical(f)); } else if (!f.isDirectory()) { feedback.printf("Skipping %s because it is a special file type.\n", canonical(f)); } } private void addDirectory0(boolean inHiddenDir, File base, String suffix, int loop) throws IOException { File dir = suffix.isEmpty() ? base : new File(base, suffix); if (dir.isDirectory()) { boolean thisDirIsHidden = !inHiddenDir && new File(canonical(dir)).getName().startsWith("."); if (loop >= 100) { feedback.printf("Over 100 subdirectories? I'm guessing there's a loop in your directory structure. Skipping: %s\n", suffix); } else { File[] list = dir.listFiles(); if (list.length > 0) { if (thisDirIsHidden && !noCopy && output != null) { feedback.printf("Only processing java files (not copying non-java files) in %s because it's a hidden directory.\n", canonical(dir)); } for (File f : list) { addDirectory0(inHiddenDir || thisDirIsHidden, base, suffix + (suffix.isEmpty() ? "" : File.separator) + f.getName(), loop + 1); } } else { if (!thisDirIsHidden && !noCopy && !inHiddenDir && output != null && !suffix.isEmpty()) { File emptyDir = new File(output, suffix); emptyDir.mkdirs(); if (verbose) feedback.printf("Creating empty directory: %s\n", canonical(emptyDir)); } } } } else { addDirectory1(!inHiddenDir && !noCopy, base, suffix); } } private void skipClass(String fileName) { if (verbose) feedback.printf("Skipping class file: %s\n", fileName); } private void copy(boolean copy, File base, String fileName) throws IOException { if (output == null) { feedback.printf("Skipping resource file: %s\n", fileName); return; } if (!copy) { if (verbose) feedback.printf("Skipping resource file: %s\n", fileName); return; } if (verbose) feedback.printf("Copying resource file: %s\n", fileName); byte[] b = new byte[65536]; File inFile = new File(base, fileName); FileInputStream in = new FileInputStream(inFile); try { File outFile = new File(output, fileName); outFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(outFile); try { while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } } finally { out.close(); } } finally { in.close(); } } public void addFile(File base, String fileName) throws IOException { if (output != null && canonical(base).equals(canonical(output))) throw new IOException( "DELOMBOK: Output file and input file refer to the same filesystem location. Specify a separate path for output."); File f = new File(base, fileName); filesToParse.add(f); fileToBase.put(f, base); } private static com.sun.tools.javac.util.List toJavacList(List list) { com.sun.tools.javac.util.List out = com.sun.tools.javac.util.List.nil(); ListIterator li = list.listIterator(list.size()); while (li.hasPrevious()) out = out.prepend(li.previous()); return out; } public boolean delombok() throws IOException { LombokOptions options = LombokOptionsFactory.getDelombokOptions(context); options.deleteLombokAnnotations(); options.putJavacOption("ENCODING", charset.name()); if (classpath != null) options.putJavacOption("CLASSPATH", classpath); if (sourcepath != null) options.putJavacOption("SOURCEPATH", sourcepath); if (bootclasspath != null) options.putJavacOption("BOOTCLASSPATH", bootclasspath); options.setFormatPreferences(new FormatPreferences(formatPrefs)); options.put("compilePolicy", "check"); CommentCatcher catcher = CommentCatcher.create(context); JavaCompiler compiler = catcher.getCompiler(); List roots = new ArrayList(); Map baseMap = new IdentityHashMap(); compiler.initProcessAnnotations(Collections.singleton(new lombok.javac.apt.LombokProcessor())); for (File fileToParse : filesToParse) { @SuppressWarnings("deprecation") JCCompilationUnit unit = compiler.parse(fileToParse.getAbsolutePath()); baseMap.put(unit, fileToBase.get(fileToParse)); roots.add(unit); } if (compiler.errorCount() > 0) { // At least one parse error. No point continuing (a real javac run doesn't either). return false; } for (JCCompilationUnit unit : roots) { catcher.setComments(unit, new DocCommentIntegrator().integrate(catcher.getComments(unit), unit)); } com.sun.tools.javac.util.List trees = compiler.enterTrees(toJavacList(roots)); JavaCompiler delegate = compiler.processAnnotations(trees); Object care = callAttributeMethodOnJavaCompiler(delegate, delegate.todo); callFlowMethodOnJavaCompiler(delegate, care); FormatPreferences fps = new FormatPreferences(formatPrefs); for (JCCompilationUnit unit : roots) { DelombokResult result = new DelombokResult(catcher.getComments(unit), unit, force || options.isChanged(unit), fps); if (verbose) feedback.printf("File: %s [%s%s]\n", unit.sourcefile.getName(), result.isChanged() ? "delomboked" : "unchanged", force && !options.isChanged(unit) ? " (forced)" : ""); Writer rawWriter; if (presetWriter != null) rawWriter = createUnicodeEscapeWriter(presetWriter); else if (output == null) rawWriter = createStandardOutWriter(); else rawWriter = createFileWriter(output, baseMap.get(unit), unit.sourcefile.toUri()); BufferedWriter writer = new BufferedWriter(rawWriter); try { result.print(writer); } finally { if (output != null) { writer.close(); } else { writer.flush(); } } } delegate.close(); return true; } private static Method attributeMethod; /** Method is needed because the call signature has changed between javac6 and javac7; no matter what we compile against, using delombok in the other means VerifyErrors. */ private static Object callAttributeMethodOnJavaCompiler(JavaCompiler compiler, Todo arg) { if (attributeMethod == null) { try { attributeMethod = JavaCompiler.class.getDeclaredMethod("attribute", java.util.Queue.class); } catch (NoSuchMethodException e) { try { attributeMethod = JavaCompiler.class.getDeclaredMethod("attribute", com.sun.tools.javac.util.ListBuffer.class); } catch (NoSuchMethodException e2) { throw Lombok.sneakyThrow(e2); } } } try { return attributeMethod.invoke(compiler, arg); } catch (Exception e) { if (e instanceof InvocationTargetException) throw Lombok.sneakyThrow(e.getCause()); throw Lombok.sneakyThrow(e); } } private static Method flowMethod; /** Method is needed because the call signature has changed between javac6 and javac7; no matter what we compile against, using delombok in the other means VerifyErrors. */ private static void callFlowMethodOnJavaCompiler(JavaCompiler compiler, Object arg) { if (flowMethod == null) { try { flowMethod = JavaCompiler.class.getDeclaredMethod("flow", java.util.Queue.class); } catch (NoSuchMethodException e) { try { flowMethod = JavaCompiler.class.getDeclaredMethod("flow", com.sun.tools.javac.util.List.class); } catch (NoSuchMethodException e2) { throw Lombok.sneakyThrow(e2); } } } try { flowMethod.invoke(compiler, arg); } catch (Exception e) { if (e instanceof InvocationTargetException) throw Lombok.sneakyThrow(e.getCause()); throw Lombok.sneakyThrow(e); } } private static String canonical(File dir) { try { return dir.getCanonicalPath(); } catch (Exception e) { return dir.getAbsolutePath(); } } private static String getExtension(File dir) { String name = dir.getName(); int idx = name.lastIndexOf('.'); return idx == -1 ? "" : name.substring(idx+1); } private Writer createFileWriter(File outBase, File inBase, URI file) throws IOException { URI base = inBase.toURI(); URI relative = base.relativize(base.resolve(file)); File outFile; if (relative.isAbsolute()) { outFile = new File(outBase, new File(relative).getName()); } else { outFile = new File(outBase, relative.getPath()); } outFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(outFile); return createUnicodeEscapeWriter(out); } private Writer createStandardOutWriter() { return createUnicodeEscapeWriter(System.out); } private Writer createUnicodeEscapeWriter(Writer writer) { return new UnicodeEscapeWriter(writer, charset); } private Writer createUnicodeEscapeWriter(OutputStream out) { return new UnicodeEscapeWriter(new OutputStreamWriter(out, charset), charset); } } lombok-1.16.18/src/delombok/lombok/delombok/DelombokApp.java000066400000000000000000000212051312655740700236670ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import lombok.core.LombokApp; import org.mangosdk.spi.ProviderFor; @ProviderFor(LombokApp.class) public class DelombokApp extends LombokApp { @Override public int runApp(List args) throws Exception { try { Class.forName("com.sun.tools.javac.main.JavaCompiler"); runDirectly(args); return 0; } catch (ClassNotFoundException e) { Class delombokClass = loadDelombok(args); if (delombokClass == null) { return 1; } try { loadDelombok(args).getMethod("main", String[].class).invoke(null, new Object[] {args.toArray(new String[0])}); } catch (InvocationTargetException e1) { Throwable t = e1.getCause(); if (t instanceof Error) throw (Error)t; if (t instanceof Exception) throw (Exception)t; throw e1; } return 0; } } public static Class loadDelombok(List args) throws Exception { //tools.jar is probably not on the classpath. We're going to try and find it, and then load the rest via a ClassLoader that includes tools.jar. final File toolsJar = findToolsJar(); if (toolsJar == null) { String examplePath = "/path/to/tools.jar"; if (File.separator.equals("\\")) examplePath = "C:\\path\\to\\tools.jar"; StringBuilder sb = new StringBuilder(); for (String arg : args) { if (sb.length() > 0) sb.append(' '); if (arg.contains(" ")) { sb.append('"').append(arg).append('"'); } else { sb.append(arg); } } System.err.printf("Can't find tools.jar. Rerun delombok as: java -cp lombok.jar%1$s%2$s lombok.core.Main delombok %3$s\n", File.pathSeparator, examplePath, sb.toString()); return null; } // The jar file is used for the lifetime of the classLoader, therefore the lifetime of delombok. // Since we only read from it, not closing it should not be a problem. @SuppressWarnings({"resource", "all"}) final JarFile toolsJarFile = new JarFile(toolsJar); ClassLoader loader = new ClassLoader(DelombokApp.class.getClassLoader()) { private Class loadStreamAsClass(String name, boolean resolve, InputStream in) throws ClassNotFoundException { try { try { byte[] b = new byte[65536]; ByteArrayOutputStream out = new ByteArrayOutputStream(); while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } in.close(); byte[] data = out.toByteArray(); Class c = defineClass(name, data, 0, data.length); if (resolve) resolveClass(c); return c; } finally { in.close(); } } catch (Exception e2) { throw new ClassNotFoundException(name, e2); } } @Override protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { String rawName, altName; { String binName = name.replace(".", "/"); rawName = binName + ".class"; altName = binName + ".SCL.lombok"; } JarEntry entry = toolsJarFile.getJarEntry(rawName); if (entry == null) { if (name.startsWith("lombok.")) { InputStream res = getParent().getResourceAsStream(rawName); if (res == null) res = getParent().getResourceAsStream(altName); return loadStreamAsClass(name, resolve, res); } return super.loadClass(name, resolve); } try { return loadStreamAsClass(name, resolve, toolsJarFile.getInputStream(entry)); } catch (IOException e2) { throw new ClassNotFoundException(name, e2); } } @Override public URL getResource(String name) { JarEntry entry = toolsJarFile.getJarEntry(name); if (entry == null) return super.getResource(name); try { return new URL("jar:file:" + toolsJar.getAbsolutePath() + "!" + name); } catch (MalformedURLException ignore) { return null; } } @Override public Enumeration getResources(final String name) throws IOException { JarEntry entry = toolsJarFile.getJarEntry(name); final Enumeration parent = super.getResources(name); if (entry == null) return super.getResources(name); return new Enumeration() { private boolean first = false; @Override public boolean hasMoreElements() { return !first || parent.hasMoreElements(); } @Override public URL nextElement() { if (!first) { first = true; try { return new URL("jar:file:" + toolsJar.getAbsolutePath() + "!" + name); } catch (MalformedURLException ignore) { return parent.nextElement(); } } return parent.nextElement(); } }; } }; return loader.loadClass("lombok.delombok.Delombok"); } private void runDirectly(List args) { Delombok.main(args.toArray(new String[0])); } private static File findToolsJar() { try { File toolsJar = findToolsJarViaRT(); if (toolsJar != null) return toolsJar; } catch (Throwable ignore) { //fallthrough } try { File toolsJar = findToolsJarViaProperties(); if (toolsJar != null) return toolsJar; } catch (Throwable ignore) { //fallthrough } try { File toolsJar = findToolsJarViaEnvironment(); return toolsJar; } catch (Throwable ignore) { //fallthrough } return null; } private static File findToolsJarViaEnvironment() { for (Map.Entry s : System.getenv().entrySet()) { if ("JAVA_HOME".equalsIgnoreCase(s.getKey())) { return extensiveCheckToolsJar(new File(s.getValue())); } } return null; } private static File findToolsJarViaProperties() { File home = new File(System.getProperty("java.home", ".")); return extensiveCheckToolsJar(home); } private static File extensiveCheckToolsJar(File base) { File toolsJar = checkToolsJar(base); if (toolsJar != null) return toolsJar; toolsJar = checkToolsJar(new File(base, "lib")); if (toolsJar != null) return toolsJar; toolsJar = checkToolsJar(new File(base.getParentFile(), "lib")); if (toolsJar != null) return toolsJar; toolsJar = checkToolsJar(new File(new File(base, "jdk"), "lib")); if (toolsJar != null) return toolsJar; return null; } private static File findToolsJarViaRT() { String url = ClassLoader.getSystemClassLoader().getResource("java/lang/String.class").toString(); if (!url.startsWith("jar:file:")) return null; url = url.substring("jar:file:".length()); int idx = url.indexOf('!'); if (idx == -1) return null; url = url.substring(0, idx); File toolsJar = checkToolsJar(new File(url).getParentFile()); if (toolsJar != null) return toolsJar; toolsJar = checkToolsJar(new File(new File(url).getParentFile().getParentFile().getParentFile(), "lib")); if (toolsJar != null) return toolsJar; return null; } private static File checkToolsJar(File d) { if (d.getName().equals("tools.jar") && d.isFile() && d.canRead()) return d; d = new File(d, "tools.jar"); if (d.getName().equals("tools.jar") && d.isFile() && d.canRead()) return d; return null; } @Override public String getAppName() { return "delombok"; } @Override public List getAppAliases() { return Arrays.asList("unlombok"); } @Override public String getAppDescription() { return "Applies lombok transformations without compiling your\njava code (so, 'unpacks' lombok annotations and such)."; } } lombok-1.16.18/src/delombok/lombok/delombok/DelombokResult.java000066400000000000000000000060561312655740700244340ustar00rootroot00000000000000/* * Copyright (C) 2009-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok; import java.io.IOException; import java.io.Writer; import java.util.Date; import java.util.List; import javax.tools.JavaFileObject; import lombok.javac.CommentInfo; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; public class DelombokResult { private final List comments; private final JCCompilationUnit compilationUnit; private final boolean changed; private final FormatPreferences formatPreferences; public DelombokResult(List comments, JCCompilationUnit compilationUnit, boolean changed, FormatPreferences formatPreferences) { this.comments = comments; this.compilationUnit = compilationUnit; this.changed = changed; this.formatPreferences = formatPreferences; } public void print(Writer out) throws IOException { if (!changed) { CharSequence content = getContent(); if (content != null) { out.write(content.toString()); return; } } if (formatPreferences.generateDelombokComment()) { out.write("// Generated by delombok at "); out.write(String.valueOf(new Date())); out.write(System.getProperty("line.separator")); } com.sun.tools.javac.util.List comments_; if (comments instanceof com.sun.tools.javac.util.List) comments_ = (com.sun.tools.javac.util.List) comments; else comments_ = com.sun.tools.javac.util.List.from(comments.toArray(new CommentInfo[0])); FormatPreferences preferences = new FormatPreferenceScanner().scan(formatPreferences, getContent()); //compilationUnit.accept(new PrettyCommentsPrinter(out, compilationUnit, comments_, preferences)); compilationUnit.accept(new PrettyPrinter(out, compilationUnit, comments_, preferences)); } private CharSequence getContent() throws IOException { JavaFileObject sourceFile = compilationUnit.getSourceFile(); if (sourceFile == null) return null; return sourceFile.getCharContent(true); } public boolean isChanged() { return changed; } }lombok-1.16.18/src/delombok/lombok/delombok/DocCommentIntegrator.java000066400000000000000000000124571312655740700255720ustar00rootroot00000000000000/* * Copyright (C) 2009-2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import lombok.javac.CommentInfo; import lombok.javac.Javac; import lombok.javac.handlers.JavacHandlerUtil; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.tree.DocCommentTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; public class DocCommentIntegrator { /** * Returns the same comment list as when this integrator was created, minus all doc comments that have been successfully integrated into the compilation unit. */ public List integrate(List comments, JCCompilationUnit unit) { List out = new ArrayList(); CommentInfo lastExcisedComment = null; JCTree lastNode = null; for (CommentInfo cmt : comments) { if (!cmt.isJavadoc()) { out.add(cmt); continue; } JCTree node = findJavadocableNodeOnOrAfter(unit, cmt.endPos); if (node == null) { out.add(cmt); continue; } if (node == lastNode) { out.add(lastExcisedComment); } if (!attach(unit, node, cmt)) { out.add(cmt); } else { lastNode = node; lastExcisedComment = cmt; } } return out; } private static final Pattern CONTENT_STRIPPER = Pattern.compile("^(?:\\s*\\*)?[ \\t]*(.*?)$", Pattern.MULTILINE); @SuppressWarnings("unchecked") private boolean attach(JCCompilationUnit top, final JCTree node, CommentInfo cmt) { String docCommentContent = cmt.content; if (docCommentContent.startsWith("/**")) docCommentContent = docCommentContent.substring(3); if (docCommentContent.endsWith("*/")) docCommentContent = docCommentContent.substring(0, docCommentContent.length() -2); docCommentContent = CONTENT_STRIPPER.matcher(docCommentContent).replaceAll("$1"); docCommentContent = docCommentContent.trim(); if (Javac.getDocComments(top) == null) Javac.initDocComments(top); Object map_ = Javac.getDocComments(top); if (map_ instanceof Map) { ((Map) map_).put(node, docCommentContent); return true; } else if (Javac.instanceOfDocCommentTable(map_)) { CommentAttacher_8.attach(node, docCommentContent, map_); return true; } return false; } /* Container for code which will cause class loader exceptions on javac below 8. By being in a separate class, we avoid the problem. */ private static class CommentAttacher_8 { static void attach(final JCTree node, String docCommentContent, Object map_) { final String docCommentContent_ = docCommentContent; ((DocCommentTable) map_).putComment(node, new Comment() { @Override public String getText() { return docCommentContent_; } @Override public int getSourcePos(int index) { return -1; } @Override public CommentStyle getStyle() { return CommentStyle.JAVADOC; } @Override public boolean isDeprecated() { return JavacHandlerUtil.nodeHasDeprecatedFlag(node); } }); } } private JCTree findJavadocableNodeOnOrAfter(JCCompilationUnit unit, int endPos) { if (unit.pid != null && endPos <= unit.pid.pos) return null; Iterator it = unit.defs.iterator(); while (it.hasNext()) { JCTree node = it.next(); if (node.pos < endPos) { if (node instanceof JCClassDecl) { com.sun.tools.javac.util.List defs = ((JCClassDecl) node).defs; if (!defs.isEmpty()) while (!defs.tail.isEmpty()) defs = defs.tail; if (defs.head != null && defs.head.pos >= endPos) { // The associated node is IN this class declaration, so, replace the iterator. // There's no point looking beyond this member in the current iteration 'context' // so we don't need to save the old ref. Just start over inside this type declaration. it = ((JCClassDecl) node).defs.iterator(); } } continue; } if (node instanceof JCMethodDecl || node instanceof JCClassDecl || node instanceof JCVariableDecl) return node; return null; } return null; } } lombok-1.16.18/src/delombok/lombok/delombok/FormatPreferenceScanner.java000066400000000000000000000130441312655740700262350ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok; import java.io.CharArrayReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Scans a java source file to figure out certain format preferences. * Currently:

    *
  • Indent style (tab or 2-8 spaces are supported). Default: tab
  • *
  • Empty lines still carry the appropriate indent, vs. empty lines are empty. Default: empty
  • */ public class FormatPreferenceScanner { /** Checks validity of preferences, and returns with a non-null value if ALL format keys are available, thus negating the need for a scan. */ private FormatPreferences tryEasy(FormatPreferences preferences, boolean force) { int count = 0; for (Map.Entry e : preferences.rawMap.entrySet()) { if (!"scan".equalsIgnoreCase(e.getValue())) count++; } if (force || count >= FormatPreferences.KEYS.size()) return preferences; return null; } public FormatPreferences scan(FormatPreferences preferences, final CharSequence source) { FormatPreferences fps = tryEasy(preferences, source == null); if (fps != null) return fps; try { return scan_(preferences, new Reader() { int pos = 0; int max = source.length(); @Override public void close() throws IOException { } @Override public int read(char[] b, int p, int len) throws IOException { int read = 0; if (pos >= max) return -1; for (int i = p; i < p + len; i++) { b[i] = source.charAt(pos++); read++; if (pos == max) return read; } return len; } }); } catch (IOException e) { throw new RuntimeException(e); //Can't happen; CAR doesn't throw these. } } public FormatPreferences scan(FormatPreferences preferences, char[] source) { FormatPreferences fps = tryEasy(preferences, source == null); if (fps != null) return fps; try { return scan_(preferences, new CharArrayReader(source)); } catch (IOException e) { throw new RuntimeException(e); //Can't happen; CAR doesn't throw these. } } public FormatPreferences scan(FormatPreferences preferences, Reader in) throws IOException { FormatPreferences fps = tryEasy(preferences, in == null); if (fps != null) return fps; return scan_(preferences, in); } private static FormatPreferences scan_(FormatPreferences preferences, Reader in) throws IOException { int filledEmpties = 0; List indents = new ArrayList(); char[] buffer = new char[32700]; int pos = 1; int end = 0; StringBuilder indentSoFar = new StringBuilder(); boolean inIndent = true; boolean inComment = false; char lastChar = ' '; while (true) { if (pos >= end) { int r = in.read(buffer); if (r == -1) break; pos = 0; end = r; continue; } char c = buffer[pos++]; if (inComment) { if (lastChar == '*' && c == '/') inComment = false; lastChar = c; continue; } if (lastChar == '/' && c == '*') { inComment = true; lastChar = ' '; indentSoFar.setLength(0); inIndent = false; continue; } if (inIndent) { boolean w = Character.isWhitespace(c); if (c == '\n') { if (indentSoFar.length() > 0 && indentSoFar.charAt(indentSoFar.length() -1) == '\r') { indentSoFar.setLength(indentSoFar.length() - 1); } if (indentSoFar.length() > 0) { filledEmpties++; } else { } indents.add(indentSoFar.toString()); indentSoFar.setLength(0); lastChar = c; continue; } if (w) { indentSoFar.append(c); lastChar = c; continue; } if (indentSoFar.length() > 0) { indents.add(indentSoFar.toString()); indentSoFar.setLength(0); } lastChar = c; inIndent = false; continue; } lastChar = c; if (c == '\n') { inIndent = true; indentSoFar.setLength(0); } } String indent = null; int lowestSpaceCount = Integer.MAX_VALUE; for (String ind : indents) { if (ind.indexOf('\t') > -1) { indent = "\t"; break; } if (ind.length() < 2 || ind.length() > 8) continue; if (ind.length() < lowestSpaceCount) lowestSpaceCount = ind.length(); } if (lowestSpaceCount == Integer.MAX_VALUE) indent = "\t"; if (indent == null) { char[] id = new char[lowestSpaceCount]; Arrays.fill(id, ' '); indent = new String(id); } return new FormatPreferences(preferences.rawMap, indent, filledEmpties > 0); } } lombok-1.16.18/src/delombok/lombok/delombok/FormatPreferences.java000066400000000000000000000150361312655740700251110ustar00rootroot00000000000000/* * Copyright (C) 2013-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; public final class FormatPreferences { private final String indent; private final Boolean filledEmpties; private final boolean generateFinalParams; private final boolean generateConstructorProperties; private final boolean generateSuppressWarnings, danceAroundIdeChecks, generateDelombokComment, javaLangAsFqn; final Map rawMap; private final boolean generateGenerated; static final Map KEYS; static { Map keys = new LinkedHashMap(); keys.put("indent", "The indent to use. 'tab' can be used to represent 1 tab. A number means that many spaces. Default: 'tab'"); keys.put("emptyLines", "Either 'indent' or 'blank'. indent means: Indent an empty line to the right level. Default: 'blank'"); keys.put("finalParams", "Either 'generate' or 'skip'. generate means: All lombok-generated methods set all parameters to final. Default: 'generate'"); keys.put("constructorProperties", "Either 'generate' or 'skip'. generate means: All lombok-generated constructors with 1 or more arguments get an @ConstructorProperties annotation. Default: 'generate'"); keys.put("suppressWarnings", "Either 'generate' or 'skip'. generate means: All lombok-generated methods, types, and fields get a @SuppressWarnings annotation. Default: 'generate'"); keys.put("generated", "Either 'generate' or 'skip'. generate means: All lombok-generated methods, types, and fields get a @javax.annotation.Generated(\"lombok\") annotation. Default: 'generate'"); keys.put("danceAroundIdeChecks", "Either 'generate' or 'skip'. generate means: Lombok will intentionally obfuscate some generated code to avoid IDE warnings. Default: 'generate'"); keys.put("generateDelombokComment", "Either 'generate' or 'skip'. generate means: Any file modified by delombok will have a comment stating this at the top. Default: 'generate'"); keys.put("javaLangAsFQN", "Either 'generate' or 'skip'. generate means: Any generated reference to java.lang classes are prefixed with `java.lang.`. Default: 'generate'"); KEYS = Collections.unmodifiableMap(keys); } public FormatPreferences(Map preferences) { this(preferences, null, null); } public FormatPreferences(Map preferences, String indent, Boolean filledEmpties) { this.rawMap = preferences; if (preferences == null) preferences = Collections.emptyMap(); String indent_ = preferences.get("indent"); if (indent_ != null && !"scan".equalsIgnoreCase(indent_)) { try { int id = Integer.parseInt(indent_); if (id > 0 && id < 32) { char[] c = new char[id]; Arrays.fill(c, ' '); indent_ = new String(c); } } catch (NumberFormatException ignore) {} indent = indent_.replace("\\t", "\t").replace("tab", "\t"); } String empties_ = preferences.get("emptyLines".toLowerCase()); if ("indent".equalsIgnoreCase(empties_)) filledEmpties = true; else if ("blank".equalsIgnoreCase(empties_)) filledEmpties = false; else if (empties_ != null && !"scan".equalsIgnoreCase(empties_)) { throw new IllegalArgumentException("Legal values for 'emptyLines' are 'scan', 'indent', or 'blank'."); } this.indent = indent; this.filledEmpties = filledEmpties; this.generateFinalParams = unrollBoolean(preferences, "finalParams", "generate", "skip", true); this.generateConstructorProperties = unrollBoolean(preferences, "constructorProperties", "generate", "skip", true); this.generateSuppressWarnings = unrollBoolean(preferences, "suppressWarnings", "generate", "skip", true); this.generateGenerated = unrollBoolean(preferences, "generated", "generate", "skip", true); this.danceAroundIdeChecks = unrollBoolean(preferences, "danceAroundIdeChecks", "generate", "skip", true); this.generateDelombokComment = unrollBoolean(preferences, "generateDelombokComment", "generate", "skip", true); this.javaLangAsFqn = unrollBoolean(preferences, "javaLangAsFQN", "generate", "skip", true); } private static boolean unrollBoolean(Map preferences, String name, String trueStr, String falseStr, boolean defaultVal) { String v_ = preferences.get(name.toLowerCase()); if (v_ == null) return defaultVal; if (trueStr.equalsIgnoreCase(v_)) return true; if (falseStr.equalsIgnoreCase(v_)) return false; throw new IllegalArgumentException("Legal values for '" + name + "' are '" + trueStr + "', or '" + falseStr + "'."); } public static Map getKeysAndDescriptions() { return KEYS; } /** If true, empty lines should still be appropriately indented. If false, empty lines should be completely blank. */ public boolean fillEmpties() { return filledEmpties == null ? false : filledEmpties; } public String indent() { return indent == null ? "\t" : indent; } public boolean generateSuppressWarnings() { return generateSuppressWarnings; } public boolean generateGenerated() { return generateGenerated; } public boolean generateFinalParams() { return generateFinalParams; } public boolean danceAroundIdeChecks() { return danceAroundIdeChecks; } public boolean generateDelombokComment() { return generateDelombokComment; } public boolean javaLangAsFqn() { return javaLangAsFqn; } public boolean generateConstructorProperties() { return generateConstructorProperties; } @Override public String toString() { return rawMap.toString(); } } lombok-1.16.18/src/delombok/lombok/delombok/LombokOptionsFactory.java000066400000000000000000000044741312655740700256320ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok; import lombok.javac.Javac; import lombok.javac.Javac6BasedLombokOptions; import lombok.javac.Javac8BasedLombokOptions; import lombok.javac.LombokOptions; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Options; public class LombokOptionsFactory { enum LombokOptionCompilerVersion { JDK7_AND_LOWER { @Override LombokOptions createAndRegisterOptions(Context context) { return Javac6BasedLombokOptions.replaceWithDelombokOptions(context); } }, JDK8 { @Override LombokOptions createAndRegisterOptions(Context context) { return Javac8BasedLombokOptions.replaceWithDelombokOptions(context); } }; abstract LombokOptions createAndRegisterOptions(Context context); } public static LombokOptions getDelombokOptions(Context context) { Options rawOptions = Options.instance(context); if (rawOptions instanceof LombokOptions) return (LombokOptions) rawOptions; LombokOptions options; if (Javac.getJavaCompilerVersion() < 8) { options = LombokOptionCompilerVersion.JDK7_AND_LOWER.createAndRegisterOptions(context); } else { options = LombokOptionCompilerVersion.JDK8.createAndRegisterOptions(context); } return options; } } lombok-1.16.18/src/delombok/lombok/delombok/PrettyPrinter.java000066400000000000000000001177261312655740700243430ustar00rootroot00000000000000/* * Copyright (C) 2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok; import static com.sun.tools.javac.code.Flags.*; import static lombok.javac.Javac.*; import static lombok.javac.JavacTreeMaker.TreeTag.treeTag; import static lombok.javac.JavacTreeMaker.TypeTag.typeTag; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import com.sun.tools.javac.tree.DocCommentTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayAccess; import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; import com.sun.tools.javac.tree.JCTree.JCAssert; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCAssignOp; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCBreak; import com.sun.tools.javac.tree.JCTree.JCCase; import com.sun.tools.javac.tree.JCTree.JCCatch; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCConditional; import com.sun.tools.javac.tree.JCTree.JCContinue; import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop; import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop; import com.sun.tools.javac.tree.JCTree.JCErroneous; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCForLoop; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCIf; import com.sun.tools.javac.tree.JCTree.JCImport; import com.sun.tools.javac.tree.JCTree.JCInstanceOf; import com.sun.tools.javac.tree.JCTree.JCLabeledStatement; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCNewClass; import com.sun.tools.javac.tree.JCTree.JCParens; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCReturn; import com.sun.tools.javac.tree.JCTree.JCSkip; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCSwitch; import com.sun.tools.javac.tree.JCTree.JCSynchronized; import com.sun.tools.javac.tree.JCTree.JCThrow; import com.sun.tools.javac.tree.JCTree.JCTry; import com.sun.tools.javac.tree.JCTree.JCTypeApply; import com.sun.tools.javac.tree.JCTree.JCTypeCast; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCUnary; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWhileLoop; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.tree.JCTree.TypeBoundKind; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.Position; import lombok.javac.CommentInfo; import lombok.javac.CommentInfo.EndConnection; import lombok.javac.CommentInfo.StartConnection; import lombok.javac.JavacTreeMaker.TreeTag; import lombok.javac.JavacTreeMaker.TypeTag; public class PrettyPrinter extends JCTree.Visitor { private static final String LINE_SEP = System.getProperty("line.separator"); private static final Map OPERATORS; static { Map map = new HashMap(); map.put(treeTag("POS"), "+"); map.put(treeTag("NEG"), "-"); map.put(treeTag("NOT"), "!"); map.put(treeTag("COMPL"), "~"); map.put(treeTag("PREINC"), "++"); map.put(treeTag("PREDEC"), "--"); map.put(treeTag("POSTINC"), "++"); map.put(treeTag("POSTDEC"), "--"); map.put(treeTag("NULLCHK"), "<*nullchk*>"); map.put(treeTag("OR"), "||"); map.put(treeTag("AND"), "&&"); map.put(treeTag("EQ"), "=="); map.put(treeTag("NE"), "!="); map.put(treeTag("LT"), "<"); map.put(treeTag("GT"), ">"); map.put(treeTag("LE"), "<="); map.put(treeTag("GE"), ">="); map.put(treeTag("BITOR"), "|"); map.put(treeTag("BITXOR"), "^"); map.put(treeTag("BITAND"), "&"); map.put(treeTag("SL"), "<<"); map.put(treeTag("SR"), ">>"); map.put(treeTag("USR"), ">>>"); map.put(treeTag("PLUS"), "+"); map.put(treeTag("MINUS"), "-"); map.put(treeTag("MUL"), "*"); map.put(treeTag("DIV"), "/"); map.put(treeTag("MOD"), "%"); map.put(treeTag("BITOR_ASG"), "|="); map.put(treeTag("BITXOR_ASG"), "^="); map.put(treeTag("BITAND_ASG"), "&="); map.put(treeTag("SL_ASG"), "<<="); map.put(treeTag("SR_ASG"), ">>="); map.put(treeTag("USR_ASG"), ">>>="); map.put(treeTag("PLUS_ASG"), "+="); map.put(treeTag("MINUS_ASG"), "-="); map.put(treeTag("MUL_ASG"), "*="); map.put(treeTag("DIV_ASG"), "/="); map.put(treeTag("MOD_ASG"), "%="); OPERATORS = map; } private final Writer out; private final JCCompilationUnit compilationUnit; private List comments; private final FormatPreferences formatPreferences; private final Map docComments; private final DocCommentTable docTable; private int indent = 0; @SuppressWarnings({"unchecked", "rawtypes"}) public PrettyPrinter(Writer out, JCCompilationUnit cu, List comments, FormatPreferences preferences) { this.out = out; this.comments = comments; this.compilationUnit = cu; this.formatPreferences = preferences; /* load doc comments */ { Object dc = getDocComments(compilationUnit); if (dc instanceof Map) { this.docComments = (Map) dc; this.docTable = null; } else if (dc instanceof DocCommentTable) { this.docComments = null; this.docTable = (DocCommentTable) dc; } else { this.docComments = null; this.docTable = null; } } } private int endPos(JCTree tree) { return getEndPosition(tree, compilationUnit); } private static int lineEndPos(String s, int start) { int pos = s.indexOf('\n', start); if (pos < 0) pos = s.length(); return pos; } private boolean needsAlign, needsNewLine, onNewLine = true, needsSpace, aligned; public static final class UncheckedIOException extends RuntimeException { UncheckedIOException(IOException source) { super(toMsg(source)); setStackTrace(source.getStackTrace()); } private static String toMsg(Throwable t) { String msg = t.getMessage(); String n = t.getClass().getSimpleName(); if (msg == null || msg.isEmpty()) return n; return n + ": " + msg; } } private void align() { if (!onNewLine) return; try { for (int i = 0; i < indent; i++) out.write(formatPreferences.indent()); } catch (IOException e) { throw new UncheckedIOException(e); } onNewLine = false; aligned = true; needsAlign = false; } private void print(JCTree tree) { if (tree == null) { print("/*missing*/"); return; } consumeComments(tree); tree.accept(this); consumeTrailingComments(endPos(tree)); } private void print(List trees, String infix) { boolean first = true; JCTree prev = null; for (JCTree tree : trees) { if (suppress(tree)) continue; if (!first && infix != null && !infix.isEmpty()) { if ("\n".equals(infix)) println(prev); else print(infix); } first = false; print(tree); prev = tree; } } private boolean suppress(JCTree tree) { if (tree instanceof JCBlock) { JCBlock block = (JCBlock) tree; return (Position.NOPOS == block.pos) && block.stats.isEmpty(); } if (tree instanceof JCExpressionStatement) { JCExpression expr = ((JCExpressionStatement)tree).expr; if (expr instanceof JCMethodInvocation) { JCMethodInvocation inv = (JCMethodInvocation) expr; if (!inv.typeargs.isEmpty() || !inv.args.isEmpty()) return false; if (!(inv.meth instanceof JCIdent)) return false; return ((JCIdent) inv.meth).name.toString().equals("super"); } } return false; } private void print(CharSequence s) { boolean align = needsAlign; if (needsNewLine && !onNewLine) println(); if (align && !aligned) align(); try { if (needsSpace && !onNewLine && !aligned) out.write(' '); out.write(s.toString()); } catch (IOException e) { throw new UncheckedIOException(e); } needsSpace = false; onNewLine = false; aligned = false; } private void println() { try { out.write(LINE_SEP); } catch (IOException e) { throw new UncheckedIOException(e); } onNewLine = true; aligned = false; needsNewLine = false; } private void println(JCTree completed) { if (completed != null) { int endPos = endPos(completed); consumeTrailingComments(endPos); } try { out.write(LINE_SEP); } catch (IOException e) { throw new UncheckedIOException(e); } onNewLine = true; aligned = false; needsNewLine = false; } private void println(CharSequence s) { print(s); println(); } private void println(CharSequence s, JCTree completed) { print(s); println(completed); } private void aPrint(CharSequence s) { align(); print(s); } private void aPrintln(CharSequence s) { align(); print(s); println(); } private void aPrintln(CharSequence s, JCTree completed) { align(); print(s); println(completed); } private void consumeComments(int until) { CommentInfo head = comments.head; while (comments.nonEmpty() && head.pos < until) { printComment(head); comments = comments.tail; head = comments.head; } } private void consumeComments(JCTree tree) { consumeComments(tree.pos); } private void consumeTrailingComments(int from) { boolean prevNewLine = onNewLine; CommentInfo head = comments.head; boolean stop = false; while (comments.nonEmpty() && head.prevEndPos == from && !stop && !(head.start == StartConnection.ON_NEXT_LINE || head.start == StartConnection.START_OF_LINE)) { from = head.endPos; printComment(head); stop = (head.end == EndConnection.ON_NEXT_LINE); comments = comments.tail; head = comments.head; } if (!onNewLine && prevNewLine) { println(); } } private String getJavadocFor(JCTree node) { if (docComments != null) return docComments.get(node); if (docTable != null) return docTable.getCommentText(node); return null; } private int dims(JCExpression vartype) { if (vartype instanceof JCArrayTypeTree) { return 1 + dims(((JCArrayTypeTree) vartype).elemtype); } return 0; } private void printComment(CommentInfo comment) { switch (comment.start) { case DIRECT_AFTER_PREVIOUS: needsSpace = false; break; case AFTER_PREVIOUS: needsSpace = true; break; case START_OF_LINE: needsNewLine = true; needsAlign = false; break; case ON_NEXT_LINE: if (!onNewLine) { needsNewLine = true; needsAlign = true; } else if (!aligned) { needsAlign = true; } break; } if (onNewLine && !aligned && comment.start != StartConnection.START_OF_LINE) needsAlign = true; print(comment.content); switch (comment.end) { case ON_NEXT_LINE: if (!aligned) { needsNewLine = true; needsAlign = true; } break; case AFTER_COMMENT: needsSpace = true; break; case DIRECT_AFTER_COMMENT: // do nothing break; } } private void printDocComment(JCTree tree) { String dc = getJavadocFor(tree); if (dc == null) return; aPrintln("/**"); int pos = 0; int endpos = lineEndPos(dc, pos); boolean atStart = true; while (pos < dc.length()) { String line = dc.substring(pos, endpos); if (line.trim().isEmpty() && atStart) { atStart = false; continue; } atStart = false; aPrint(" *"); if (pos < dc.length() && dc.charAt(pos) > ' ') print(" "); println(dc.substring(pos, endpos)); pos = endpos + 1; endpos = lineEndPos(dc, pos); } aPrintln(" */"); } private Name __INIT__, __VALUE__; private Name name_init(Name someName) { if (__INIT__ == null) __INIT__ = someName.table.fromChars("".toCharArray(), 0, 6); return __INIT__; } private Name name_value(Name someName) { if (__VALUE__ == null) __VALUE__ = someName.table.fromChars("value".toCharArray(), 0, 5); return __VALUE__; } @Override public void visitTopLevel(JCCompilationUnit tree) { printDocComment(tree); if (tree.pid != null) { consumeComments(tree); aPrint("package "); print(tree.pid); println(";", tree.pid); } boolean first = true; for (JCTree child : tree.defs) { if (!(child instanceof JCImport)) continue; if (first) println(); first = false; print(child); } for (JCTree child : tree.defs) { if (child instanceof JCImport) continue; print(child); } consumeComments(Integer.MAX_VALUE); } @Override public void visitImport(JCImport tree) { aPrint("import "); if (tree.staticImport) print("static "); print(tree.qualid); println(";", tree); } private Name currentTypeName; @Override public void visitClassDef(JCClassDecl tree) { println(); printDocComment(tree); align(); print(tree.mods); boolean isInterface = (tree.mods.flags & INTERFACE) != 0; boolean isAnnotationInterface = isInterface && (tree.mods.flags & ANNOTATION) != 0; boolean isEnum = (tree.mods.flags & ENUM) != 0; if (isAnnotationInterface) print("@interface "); else if (isInterface) print("interface "); else if (isEnum) print("enum "); else print("class "); print(tree.name); Name prevTypeName = currentTypeName; currentTypeName = tree.name; if (tree.typarams.nonEmpty()) { print("<"); print(tree.typarams, ", "); print(">"); } JCTree extendsClause = getExtendsClause(tree); if (extendsClause != null) { print(" extends "); print(extendsClause); } if (tree.implementing.nonEmpty()) { print(isInterface ? " extends " : " implements "); print(tree.implementing, ", "); } println(" {"); indent++; printClassMembers(tree.defs, isEnum, isInterface); consumeComments(endPos(tree)); indent--; aPrintln("}", tree); currentTypeName = prevTypeName; } private void printClassMembers(List members, boolean isEnum, boolean isInterface) { Class prefType = null; int typeOfPrevEnumMember = isEnum ? 3 : 0; // 1 = normal, 2 = with body, 3 = no enum field yet. boolean prevWasEnumMember = isEnum; for (JCTree member : members) { if (typeOfPrevEnumMember == 3 && member instanceof JCMethodDecl && (((JCMethodDecl) member).mods.flags & GENERATEDCONSTR) != 0) continue; boolean isEnumVar = isEnum && member instanceof JCVariableDecl && (((JCVariableDecl) member).mods.flags & ENUM) != 0; if (!isEnumVar && prevWasEnumMember) { prevWasEnumMember = false; if (typeOfPrevEnumMember == 3) align(); println(";"); } if (isEnumVar) { if (prefType != null && prefType != JCVariableDecl.class) println(); switch (typeOfPrevEnumMember) { case 1: print(", "); break; case 2: println(","); align(); break; } print(member); JCTree init = ((JCVariableDecl) member).init; typeOfPrevEnumMember = init instanceof JCNewClass && ((JCNewClass) init).def != null ? 2 : 1; } else if (member instanceof JCVariableDecl) { if (prefType != null && prefType != JCVariableDecl.class) println(); if (isInterface) flagMod = -1L & ~(PUBLIC | STATIC | FINAL); print(member); } else if (member instanceof JCMethodDecl) { if ((((JCMethodDecl) member).mods.flags & GENERATEDCONSTR) != 0) continue; if (prefType != null) println(); if (isInterface) flagMod = -1L & ~(PUBLIC | ABSTRACT); print(member); } else if (member instanceof JCClassDecl) { if (prefType != null) println(); if (isInterface) flagMod = -1L & ~(PUBLIC | STATIC); print(member); } else { if (prefType != null) println(); print(member); } prefType = member.getClass(); } if (prevWasEnumMember) { prevWasEnumMember = false; if (typeOfPrevEnumMember == 3) align(); println(";"); } } @Override public void visitTypeParameter(JCTypeParameter tree) { List annotations = readObject(tree, "annotations", List.nil()); if (!annotations.isEmpty()) { print(annotations, " "); print(" "); } print(tree.name); if (tree.bounds.nonEmpty()) { print(" extends "); print(tree.bounds, " & "); } consumeComments(tree); } @Override public void visitVarDef(JCVariableDecl tree) { printDocComment(tree); align(); if ((tree.mods.flags & ENUM) != 0) { printEnumMember(tree); return; } printAnnotations(tree.mods.annotations, true); printModifierKeywords(tree.mods); printVarDef0(tree); println(";", tree); } private void printVarDefInline(JCVariableDecl tree) { printAnnotations(tree.mods.annotations, false); printModifierKeywords(tree.mods); printVarDef0(tree); } private void printVarDef0(JCVariableDecl tree) { boolean varargs = (tree.mods.flags & VARARGS) != 0; if (varargs && tree.vartype instanceof JCArrayTypeTree) { print(((JCArrayTypeTree) tree.vartype).elemtype); print("..."); } else { print(tree.vartype); } print(" "); print(tree.name); if (tree.init != null) { print(" = "); print(tree.init); } } private void printEnumMember(JCVariableDecl tree) { printAnnotations(tree.mods.annotations, true); print(tree.name); if (tree.init instanceof JCNewClass) { JCNewClass constructor = (JCNewClass) tree.init; if (constructor.args != null && constructor.args.nonEmpty()) { print("("); print(constructor.args, ", "); print(")"); } if (constructor.def != null && constructor.def.defs != null) { println(" {"); indent++; printClassMembers(constructor.def.defs, false, false); consumeComments(endPos(tree)); indent--; aPrint("}"); } } } // TODO: Test postfix syntax for methods (?), for decls. Multiline vardefs, possibly with comments. enums with bodies. constructor-local generics, method-local generics, also do/while, finally, try-with-resources, lambdas, annotations in java8 places... // TODO: Whatever is JCAnnotatedType? We handle it in the 7+ bucket in the old one... @Override public void visitTypeApply(JCTypeApply tree) { print(tree.clazz); print("<"); print(tree.arguments, ", "); print(">"); } @Override public void visitWildcard(JCWildcard tree) { switch (tree.getKind()) { default: case UNBOUNDED_WILDCARD: print("?"); return; case EXTENDS_WILDCARD: print("? extends "); print(tree.inner); return; case SUPER_WILDCARD: print("? super "); print(tree.inner); return; } } @Override public void visitLiteral(JCLiteral tree) { TypeTag typeTag = typeTag(tree); if (CTC_INT.equals(typeTag)) print("" + tree.value); else if (CTC_LONG.equals(typeTag)) print(tree.value + "L"); else if (CTC_FLOAT.equals(typeTag)) print(tree.value + "F"); else if (CTC_DOUBLE.equals(typeTag)) print("" + tree.value); else if (CTC_CHAR.equals(typeTag)) { print("\'" + quoteChar((char)((Number)tree.value).intValue()) + "\'"); } else if (CTC_BOOLEAN.equals(typeTag)) print(((Number)tree.value).intValue() == 1 ? "true" : "false"); else if (CTC_BOT.equals(typeTag)) print("null"); else print("\"" + quoteChars(tree.value.toString()) + "\""); } @Override public void visitMethodDef(JCMethodDecl tree) { boolean isConstructor = tree.name == name_init(tree.name); if (isConstructor && (tree.mods.flags & GENERATEDCONSTR) != 0) return; printDocComment(tree); align(); print(tree.mods); if (tree.typarams != null && tree.typarams.nonEmpty()) { print("<"); print(tree.typarams, ", "); print("> "); } if (isConstructor) { print(currentTypeName == null ? "" : currentTypeName); } else { print(tree.restype); print(" "); print(tree.name); } print("("); boolean first = true; for (JCVariableDecl param : tree.params) { if (!first) print(", "); first = false; printVarDefInline(param); } print(")"); if (tree.thrown.nonEmpty()) { print(" throws "); print(tree.thrown, ", "); } if (tree.defaultValue != null) { print(" default "); print(tree.defaultValue); } if (tree.body != null) { print(" "); print(tree.body); } else println(";", tree); } @Override public void visitSkip(JCSkip that) { if (onNewLine && !aligned) { align(); } println(";"); } @Override public void visitAnnotation(JCAnnotation tree) { print("@"); print(tree.annotationType); if (tree.args.isEmpty()) return; print("("); boolean done = false; if (tree.args.length() == 1 && tree.args.get(0) instanceof JCAssign) { JCAssign arg1 = (JCAssign) tree.args.get(0); JCIdent arg1Name = arg1.lhs instanceof JCIdent ? ((JCIdent) arg1.lhs) : null; if (arg1Name != null && arg1Name.name == name_value(arg1Name.name)) { print(arg1.rhs); done = true; } } if (!done) print(tree.args, ", "); print(")"); } @Override public void visitTypeArray(JCArrayTypeTree tree) { JCTree elem = tree.elemtype; while (elem instanceof JCWildcard) elem = ((JCWildcard) elem).inner; print(elem); print("[]"); } @Override public void visitNewArray(JCNewArray tree) { JCTree elem = tree.elemtype; int dims = 0; if (elem != null) { print("new "); while (elem instanceof JCArrayTypeTree) { dims++; elem = ((JCArrayTypeTree) elem).elemtype; } print(elem); for (JCExpression expr : tree.dims) { print("["); print(expr); print("]"); } } for (int i = 0; i < dims; i++) print("[]"); if (tree.elems != null) { if (elem != null) print("[] "); print("{"); print(tree.elems, ", "); print("}"); } } @Override public void visitNewClass(JCNewClass tree) { if (tree.encl != null) { print(tree.encl); print("."); } print("new "); if (!tree.typeargs.isEmpty()) { print("<"); print(tree.typeargs, ", "); print(">"); } print(tree.clazz); print("("); print(tree.args, ", "); print(")"); if (tree.def != null) { Name previousTypeName = currentTypeName; currentTypeName = null; println(" {"); indent++; print(tree.def.defs, ""); indent--; aPrint("}"); currentTypeName = previousTypeName; } } @Override public void visitIndexed(JCArrayAccess tree) { print(tree.indexed); print("["); print(tree.index); print("]"); } @Override public void visitTypeIdent(JCPrimitiveTypeTree tree) { TypeTag typeTag = typeTag(tree); if (CTC_BYTE.equals(typeTag)) print("byte"); else if (CTC_CHAR.equals(typeTag)) print("char"); else if (CTC_SHORT.equals(typeTag)) print("short"); else if (CTC_INT.equals(typeTag)) print("int"); else if (CTC_LONG.equals(typeTag)) print("long"); else if (CTC_FLOAT.equals(typeTag)) print("float"); else if (CTC_DOUBLE.equals(typeTag)) print("double"); else if (CTC_BOOLEAN.equals(typeTag)) print("boolean"); else if (CTC_VOID.equals(typeTag)) print("void"); else print("error"); } @Override public void visitLabelled(JCLabeledStatement tree) { aPrint(tree.label); print(":"); if (tree.body instanceof JCSkip || suppress(tree)) { println(" ;", tree); } else if (tree.body instanceof JCBlock) { print(" "); print(tree.body); } else { println(tree); print(tree.body); } } private long flagMod = -1L; private static final long DEFAULT = 1L<<43; @Override public void visitModifiers(JCModifiers tree) { printAnnotations(tree.annotations, true); printModifierKeywords(tree); } private void printAnnotations(List annotations, boolean newlines) { for (JCAnnotation ann : annotations) { print(ann); if (newlines) { println(); align(); } else print(" "); } } private void printModifierKeywords(JCModifiers tree) { long v = flagMod & tree.flags; flagMod = -1L; if ((v & SYNTHETIC) != 0) print("/* synthetic */ "); if ((v & PUBLIC) != 0) print("public "); if ((v & PRIVATE) != 0) print("private "); if ((v & PROTECTED) != 0) print("protected "); if ((v & STATIC) != 0) print("static "); if ((v & FINAL) != 0) print("final "); if ((v & SYNCHRONIZED) != 0) print("synchronized "); if ((v & VOLATILE) != 0) print("volatile "); if ((v & TRANSIENT) != 0) print("transient "); if ((v & NATIVE) != 0) print("native "); if ((v & ABSTRACT) != 0) print("abstract "); if ((v & STRICTFP) != 0) print("strictfp "); if ((v & DEFAULT) != 0 && (v & INTERFACE) == 0) print("default "); } @Override public void visitSelect(JCFieldAccess tree) { print(tree.selected); print("."); print(tree.name); } @Override public void visitIdent(JCIdent tree) { print(tree.name); } @Override public void visitApply(JCMethodInvocation tree) { if (tree.typeargs.nonEmpty()) { if (tree.meth instanceof JCFieldAccess) { JCFieldAccess fa = (JCFieldAccess) tree.meth; print(fa.selected); print(".<"); print(tree.typeargs, ", "); print(">"); print(fa.name); } else { print("<"); print(tree.typeargs, ", "); print(">"); print(tree.meth); } } else { print(tree.meth); } print("("); print(tree.args, ", "); print(")"); } @Override public void visitAssert(JCAssert tree) { aPrint("assert "); print(tree.cond); if (tree.detail != null) { print(" : "); print(tree.detail); } println(";", tree); } @Override public void visitAssign(JCAssign tree) { print(tree.lhs); print(" = "); print(tree.rhs); } @Override public void visitAssignop(JCAssignOp tree) { print(tree.lhs); String opname = operator(treeTag(tree)); print(" " + opname + " "); print(tree.rhs); } private static final int PREFIX = 14; @Override public void visitUnary(JCUnary tree) { String op = operator(treeTag(tree)); if (treeTag(tree).getOperatorPrecedenceLevel() == PREFIX) { print(op); print(tree.arg); } else { print(tree.arg); print(op); } } @Override public void visitBinary(JCBinary tree) { String op = operator(treeTag(tree)); print(tree.lhs); print(" "); print(op); print(" "); print(tree.rhs); } @Override public void visitTypeTest(JCInstanceOf tree) { print(tree.expr); print(" instanceof "); print(tree.clazz); } @Override public void visitTypeCast(JCTypeCast tree) { print("("); print(tree.clazz); print(") "); print(tree.expr); } @Override public void visitBlock(JCBlock tree) { if (tree.pos == Position.NOPOS && tree.stats.isEmpty()) return; if (onNewLine) align(); if ((tree.flags & STATIC) != 0) print("static "); println("{"); indent++; print(tree.stats, ""); consumeComments(endPos(tree)); indent--; aPrintln("}", tree); } @Override public void visitBreak(JCBreak tree) { aPrint("break"); if (tree.label != null) { print(" "); print(tree.label); } println(";", tree); } @Override public void visitContinue(JCContinue tree) { aPrint("continue"); if (tree.label != null) { print(" "); print(tree.label); } println(";", tree); } @Override public void visitConditional(JCConditional tree) { print(tree.cond); print(" ? "); print(tree.truepart); print(" : "); print(tree.falsepart); } @Override public void visitParens(JCParens tree) { print("("); print(tree.expr); print(")"); } @Override public void visitReturn(JCReturn tree) { aPrint("return"); if (tree.expr != null) { print(" "); print(tree.expr); } println(";", tree); } @Override public void visitThrow(JCThrow tree) { aPrint("throw "); print(tree.expr); println(";", tree); } @Override public void visitWhileLoop(JCWhileLoop tree) { aPrint("while "); if (tree.cond instanceof JCParens) { print(tree.cond); } else { print("("); print(tree.cond); print(")"); } print(" "); print(tree.body); // make sure to test while (true) ; and while(true){} and while(true) x = 5; } @Override public void visitForLoop(JCForLoop tree) { aPrint("for ("); if (tree.init.nonEmpty()) { // ForInit is either a StatementExpressionList or a LocalVariableDeclaration if (tree.init.head instanceof JCVariableDecl) { boolean first = true; int dims = 0; for (JCStatement i : tree.init) { JCVariableDecl vd = (JCVariableDecl) i; if (first) { printVarDefInline(vd); dims = dims(vd.vartype); } else { print(", "); print(vd.name); int dimDiff = dims(vd.vartype) - dims; for (int j = 0; j < dimDiff; j++) print("[]"); if (vd.init != null) { print(" = "); print(vd.init); } } first = false; } } else { boolean first = true; for (JCStatement exprStatement : tree.init) { if (!first) print(", "); first = false; print(((JCExpressionStatement) exprStatement).expr); } } } print("; "); if (tree.cond != null) print(tree.cond); print("; "); boolean first = true; for (JCExpressionStatement exprStatement : tree.step) { if (!first) print(", "); first = false; print(exprStatement.expr); } print(") "); print(tree.body); } @Override public void visitForeachLoop(JCEnhancedForLoop tree) { aPrint("for ("); printVarDefInline(tree.var); print(" : "); print(tree.expr); print(") "); print(tree.body); } @Override public void visitIf(JCIf tree) { aPrint("if "); if (tree.cond instanceof JCParens) { print(tree.cond); } else { print("("); print(tree.cond); print(")"); } print(" "); if (tree.thenpart instanceof JCBlock) { println("{"); indent++; print(((JCBlock) tree.thenpart).stats, ""); indent--; if (tree.elsepart == null) { aPrintln("}", tree); } else { aPrint("}"); } } else { print(tree.thenpart); } if (tree.elsepart != null) { aPrint(" else "); print(tree.elsepart); } } @Override public void visitExec(JCExpressionStatement tree) { align(); print(tree.expr); println(";", tree); } @Override public void visitDoLoop(JCDoWhileLoop tree) { aPrint("do "); if (tree.body instanceof JCBlock) { println("{"); indent++; print(((JCBlock) tree.body).stats, ""); indent--; aPrint("}"); } else print(tree.body); print(" while "); if (tree.cond instanceof JCParens) { print(tree.cond); } else { print("("); print(tree.cond); print(")"); } println(";", tree); } @Override public void visitSynchronized(JCSynchronized tree) { aPrint("synchronized "); if (tree.lock instanceof JCParens) { print(tree.lock); } else { print("("); print(tree.lock); print(")"); } print(" "); print(tree.body); } @Override public void visitCase(JCCase tree) { if (tree.pat == null) { aPrint("default"); } else { aPrint("case "); print(tree.pat); } println(": "); indent++; print(tree.stats, ""); indent--; } @Override public void visitCatch(JCCatch tree) { print(" catch ("); print(tree.param); print(") "); print(tree.body); } @Override public void visitSwitch(JCSwitch tree) { aPrint("switch "); if (tree.selector instanceof JCParens) { print(tree.selector); } else { print("("); print(tree.selector); print(")"); } println(" {"); print(tree.cases, "\n"); aPrintln("}", tree); } @Override public void visitTry(JCTry tree) { aPrint("try "); List resources = readObject(tree, "resources", List.nil()); int len = resources.length(); switch (len) { case 0: break; case 1: print("("); JCVariableDecl decl = (JCVariableDecl) resources.get(0); flagMod = -1L & ~FINAL; printVarDefInline(decl); print(") "); break; default: println("("); indent++; int c = 0; for (Object i : resources) { align(); flagMod = -1L & ~FINAL; printVarDefInline((JCVariableDecl) i); if (++c == len) { print(") "); } else { println(";", (JCTree) i); } } indent--; } println("{"); indent++; for (JCStatement stat : tree.body.stats) print(stat); indent--; aPrint("}"); for (JCCatch catchBlock : tree.catchers) { printCatch(catchBlock); } if (tree.finalizer != null) { println(" finally {"); indent++; for (JCStatement stat : tree.finalizer.stats) print(stat); indent--; aPrint("}"); } println(tree); } private void printCatch(JCCatch catchBlock) { print(" catch ("); printVarDefInline(catchBlock.param); // ExprType1 | ExprType2 handled via JCTypeUnion. println(") {"); indent++; for (JCStatement stat : catchBlock.body.stats) print(stat); indent--; aPrint("}"); } public void visitErroneous(JCErroneous tree) { print("(ERROR)"); } private static String operator(TreeTag tag) { String op = OPERATORS.get(tag); if (op == null) return "(?op?)"; return op; } private static String quoteChars(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) sb.append(quoteChar(s.charAt(i))); return sb.toString(); } private static String quoteChar(char ch) { switch (ch) { case '\b': return "\\b"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; case '\'': return "\\'"; case '\"': return "\\\""; case '\\': return "\\\\"; default: if (ch < 32) return String.format("\\%03o", (int) ch); return String.valueOf(ch); } } private static final Method getExtendsClause, getEndPosition, storeEnd; static { getExtendsClause = getMethod(JCClassDecl.class, "getExtendsClause", new Class[0]); getExtendsClause.setAccessible(true); if (getJavaCompilerVersion() < 8) { getEndPosition = getMethod(DiagnosticPosition.class, "getEndPosition", java.util.Map.class); storeEnd = getMethod(java.util.Map.class, "put", Object.class, Object.class); } else { getEndPosition = getMethod(DiagnosticPosition.class, "getEndPosition", "com.sun.tools.javac.tree.EndPosTable"); Method storeEndMethodTemp; Class endPosTable; try { endPosTable = Class.forName("com.sun.tools.javac.tree.EndPosTable"); } catch (ClassNotFoundException ex) { throw sneakyThrow(ex); } try { storeEndMethodTemp = endPosTable.getMethod("storeEnd", JCTree.class, int.class); } catch (NoSuchMethodException e) { try { endPosTable = Class.forName("com.sun.tools.javac.parser.JavacParser$AbstractEndPosTable"); storeEndMethodTemp = endPosTable.getDeclaredMethod("storeEnd", JCTree.class, int.class); } catch (NoSuchMethodException ex) { throw sneakyThrow(ex); } catch (ClassNotFoundException ex) { throw sneakyThrow(ex); } } storeEnd = storeEndMethodTemp; } getEndPosition.setAccessible(true); storeEnd.setAccessible(true); } private static Method getMethod(Class clazz, String name, Class... paramTypes) { try { return clazz.getMethod(name, paramTypes); } catch (NoSuchMethodException e) { throw sneakyThrow(e); } } private static Method getMethod(Class clazz, String name, String... paramTypes) { try { Class[] c = new Class[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) c[i] = Class.forName(paramTypes[i]); return clazz.getMethod(name, c); } catch (NoSuchMethodException e) { throw sneakyThrow(e); } catch (ClassNotFoundException e) { throw sneakyThrow(e); } } public static JCTree getExtendsClause(JCClassDecl decl) { try { return (JCTree) getExtendsClause.invoke(decl); } catch (IllegalAccessException e) { throw sneakyThrow(e); } catch (InvocationTargetException e) { throw sneakyThrow(e.getCause()); } } static RuntimeException sneakyThrow(Throwable t) { if (t == null) throw new NullPointerException("t"); PrettyPrinter.sneakyThrow0(t); return null; } @SuppressWarnings("unchecked") private static void sneakyThrow0(Throwable t) throws T { throw (T)t; } private static final Map, Map> reflectionCache = new HashMap, Map>(); @SuppressWarnings("unchecked") private T readObject(JCTree tree, String fieldName, T defaultValue) { Class tClass = tree.getClass(); Map c = reflectionCache.get(tClass); if (c == null) reflectionCache.put(tClass, c = new HashMap()); Field f = c.get(fieldName); if (f == null) { try { f = tClass.getDeclaredField(fieldName); } catch (Exception e) { return defaultValue; } f.setAccessible(true); c.put(fieldName, f); } try { return (T) f.get(tree); } catch (Exception e) { return defaultValue; } } public void visitTypeBoundKind(TypeBoundKind tree) { print(String.valueOf(tree.kind)); } @Override public void visitTree(JCTree tree) { String simpleName = tree.getClass().getSimpleName(); if ("JCTypeUnion".equals(simpleName)) { List types = readObject(tree, "alternatives", List.nil()); print(types, " | "); return; } else if ("JCTypeIntersection".equals(simpleName)) { print(readObject(tree, "bounds", List.nil()), " & "); return; } else if ("JCMemberReference".equals(simpleName)) { printMemberReference0(tree); return; } else if ("JCLambda".equals(simpleName)) { printLambda0(tree); return; } else if ("JCAnnotatedType".equals(simpleName)) { printAnnotatedType0(tree); return; } throw new AssertionError("Unhandled tree type: " + tree.getClass() + ": " + tree); } private void printMemberReference0(JCTree tree) { print(readObject(tree, "expr", (JCExpression) null)); print("::"); List typeArgs = readObject(tree, "typeargs", List.nil()); if (typeArgs != null && !typeArgs.isEmpty()) { print("<"); print(typeArgs, ", "); print(">"); } print(readObject(tree, "mode", new Object()).toString().equals("INVOKE") ? readObject(tree, "name", (Name) null) : "new"); } private void printLambda0(JCTree tree) { List params = readObject(tree, "params", List.nil()); boolean explicit = true; int paramLength = params.size(); try { explicit = readObject(tree, "paramKind", new Object()).toString().equals("EXPLICIT"); } catch (Exception e) {} boolean useParens = paramLength != 1 || explicit; if (useParens) print("("); if (explicit) { boolean first = true; for (JCVariableDecl vd : params) { if (!first) print(", "); first = false; printVarDefInline(vd); } } else { String sep = ""; for (JCVariableDecl param : params) { print(sep); print(param.name); sep = ", "; } } if (useParens) print(")"); print(" -> "); JCTree body = readObject(tree, "body", (JCTree) null); if (body instanceof JCBlock) { println("{"); indent++; print(((JCBlock) body).stats, ""); indent--; aPrint("}"); } else { print(body); } } private void printAnnotatedType0(JCTree tree) { JCTree underlyingType = readObject(tree, "underlyingType", (JCTree) null); if (underlyingType instanceof JCFieldAccess) { print(((JCFieldAccess) underlyingType).selected); print("."); print(readObject(tree, "annotations", List.nil()), " "); print(" "); print(((JCFieldAccess) underlyingType).name); } else { print(readObject(tree, "annotations", List.nil()), " "); print(" "); print(underlyingType); } } } lombok-1.16.18/src/delombok/lombok/delombok/UnicodeEscapeWriter.java000066400000000000000000000042421312655740700254000ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok; import java.io.IOException; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; public class UnicodeEscapeWriter extends Writer { private final Writer writer; private CharsetEncoder encoder; public UnicodeEscapeWriter(Writer writer, Charset charset) { this.writer = writer; encoder = charset.newEncoder(); } @Override public void close() throws IOException { writer.close(); } @Override public void flush() throws IOException { writer.flush(); } @Override public final void write(char[] cbuf, int off, int len) throws IOException { int start = off; int index = start; int end = off + len; while (index < end) { if (!encoder.canEncode(cbuf[index])) { writer.write(cbuf, start, index - start); writeUnicodeEscape(cbuf[index]); start = index + 1; } index++; } if (start < end) { writer.write(cbuf, start, end - start); } } protected void writeUnicodeEscape(char c) throws IOException { writer.write(String.format("\\u%04x", (int) c)); } }lombok-1.16.18/src/delombok/lombok/delombok/ant/000077500000000000000000000000001312655740700214115ustar00rootroot00000000000000lombok-1.16.18/src/delombok/lombok/delombok/ant/DelombokTask.java000066400000000000000000000140351312655740700246360ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok.ant; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import lombok.Lombok; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; @SuppressWarnings("unused") // we use reflection to transfer fields. class Tasks { public static class Format { private String value; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Format other = (Format) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } @Override public String toString() { return "FormatOption [value=" + value + "]"; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } public static class Delombok extends Task { private File fromDir, toDir; private Path classpath; private Path sourcepath; private boolean verbose; private String encoding; private Path path; private List formatOptions = new ArrayList(); public void setClasspath(Path classpath) { if (this.classpath == null) { this.classpath = classpath; } else { this.classpath.append(classpath); } } public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } public void setSourcepath(Path sourcepath) { if (this.sourcepath == null) { this.sourcepath = sourcepath; } else { this.sourcepath.append(sourcepath); } } public Path createSourcepath() { if (sourcepath == null) { sourcepath = new Path(getProject()); } return sourcepath.createPath(); } public void setSourcepathRef(Reference r) { createSourcepath().setRefid(r); } public void setFrom(File dir) { this.fromDir = dir; } public void setTo(File dir) { this.toDir = dir; } public void setVerbose(boolean verbose) { this.verbose = verbose; } public void setEncoding(String encoding) { this.encoding = encoding; } public void addFileset(FileSet set) { if (path == null) path = new Path(getProject()); path.add(set); } public Format createFormat() { return new Format(); } public void addFormat(Format format) { formatOptions.add(format); } private static ClassLoader shadowLoader; public static Class shadowLoadClass(String name) { try { if (shadowLoader == null) { try { Class.forName("lombok.core.LombokNode"); // If we get here, then lombok is already available. shadowLoader = Delombok.class.getClassLoader(); } catch (ClassNotFoundException e) { // If we get here, it isn't, and we should use the shadowloader. Class launcherMain = Class.forName("lombok.launch.Main"); Method m = launcherMain.getDeclaredMethod("createShadowClassLoader"); m.setAccessible(true); shadowLoader = (ClassLoader) m.invoke(null); } } return Class.forName(name, true, shadowLoader); } catch (Exception e) { throw Lombok.sneakyThrow(e); } } @Override public void execute() throws BuildException { Location loc = getLocation(); try { Object instance = shadowLoadClass("lombok.delombok.ant.DelombokTaskImpl").newInstance(); for(Field selfField : getClass().getDeclaredFields()) { if (selfField.isSynthetic() || Modifier.isStatic(selfField.getModifiers())) continue; Field otherField = instance.getClass().getDeclaredField(selfField.getName()); otherField.setAccessible(true); selfField.setAccessible(true); if (selfField.getName().equals("formatOptions")) { List rep = new ArrayList(); for (Format f : formatOptions) { if (f.getValue() == null) throw new BuildException("'value' property required for "); rep.add(f.getValue()); } otherField.set(instance, rep); } else { otherField.set(instance, selfField.get(this)); } } Method m = instance.getClass().getMethod("execute", Location.class); m.setAccessible(true); m.invoke(instance, loc); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (Exception e) { throw Lombok.sneakyThrow(e); } } } } lombok-1.16.18/src/delombok/lombok/delombok/ant/DelombokTaskImpl.java000066400000000000000000000070271312655740700254630ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.delombok.ant; import java.io.File; import java.io.IOException; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import lombok.delombok.Delombok; import lombok.delombok.Delombok.InvalidFormatOptionException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.resources.FileResource; public class DelombokTaskImpl { private File fromDir, toDir; private Path classpath; private Path sourcepath; private boolean verbose; private String encoding; private Path path; private List formatOptions = new ArrayList(); public void execute(Location location) throws BuildException { if (fromDir == null && path == null) throw new BuildException("Either 'from' attribute, or nested tags are required."); if (fromDir != null && path != null) throw new BuildException("You can't specify both 'from' attribute and nested filesets. You need one or the other."); if (toDir == null) throw new BuildException("The to attribute is required."); Delombok delombok = new Delombok(); if (verbose) delombok.setVerbose(true); try { if (encoding != null) delombok.setCharset(encoding); } catch (UnsupportedCharsetException e) { throw new BuildException("Unknown charset: " + encoding, location); } if (classpath != null) delombok.setClasspath(classpath.toString()); if (sourcepath != null) delombok.setSourcepath(sourcepath.toString()); try { delombok.setFormatPreferences(Delombok.formatOptionsToMap(formatOptions)); } catch (InvalidFormatOptionException e) { throw new BuildException(e.getMessage() + " Run java -jar lombok.jar --format-help for detailed format help."); } delombok.setOutput(toDir); try { if (fromDir != null) delombok.addDirectory(fromDir); else { Iterator it = path.iterator(); while (it.hasNext()) { FileResource fileResource = (FileResource) it.next(); File baseDir = fileResource.getBaseDir(); if (baseDir == null) { File file = fileResource.getFile(); delombok.addFile(file.getParentFile(), file.getName()); } else { delombok.addFile(baseDir, fileResource.getName()); } } } delombok.delombok(); } catch (IOException e) { throw new BuildException("I/O problem during delombok", e, location); } } } lombok-1.16.18/src/eclipseAgent/000077500000000000000000000000001312655740700163575ustar00rootroot00000000000000lombok-1.16.18/src/eclipseAgent/lombok/000077500000000000000000000000001312655740700176425ustar00rootroot00000000000000lombok-1.16.18/src/eclipseAgent/lombok/eclipse/000077500000000000000000000000001312655740700212665ustar00rootroot00000000000000lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/000077500000000000000000000000001312655740700223645ustar00rootroot00000000000000lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/EclipseLoaderPatcher.java000066400000000000000000000073161312655740700272600ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import lombok.patcher.ClassRootFinder; import lombok.patcher.Hook; import lombok.patcher.MethodTarget; import lombok.patcher.ScriptManager; import lombok.patcher.StackRequest; import lombok.patcher.scripts.ScriptBuilder; public class EclipseLoaderPatcher { private static final String TRANSPLANTS_CLASS_NAME = "lombok.eclipse.agent.EclipseLoaderPatcherTransplants"; public static void patchEquinoxLoaders(ScriptManager sm, Class launchingContext) { sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader", "loadClass", "java.lang.Class", "java.lang.String", "boolean")) .target(new MethodTarget("org.eclipse.osgi.framework.adapter.core.AbstractClassLoader", "loadClass", "java.lang.Class", "java.lang.String", "boolean")) .target(new MethodTarget("org.eclipse.osgi.internal.loader.ModuleClassLoader", "loadClass", "java.lang.Class", "java.lang.String", "boolean")) .decisionMethod(new Hook(TRANSPLANTS_CLASS_NAME, "overrideLoadDecide", "boolean", "java.lang.ClassLoader", "java.lang.String", "boolean")) .valueMethod(new Hook(TRANSPLANTS_CLASS_NAME, "overrideLoadResult", "java.lang.Class", "java.lang.ClassLoader", "java.lang.String", "boolean")) .transplant() .request(StackRequest.THIS, StackRequest.PARAM1, StackRequest.PARAM2).build()); sm.addScript(ScriptBuilder.addField().setPublic().setVolatile() .fieldType("Ljava/lang/ClassLoader;") .fieldName("lombok$shadowLoader") .targetClass("org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader") .targetClass("org.eclipse.osgi.framework.adapter.core.AbstractClassLoader") .targetClass("org.eclipse.osgi.internal.loader.ModuleClassLoader") .build()); sm.addScript(ScriptBuilder.addField().setPublic().setVolatile().setStatic() .fieldType("Ljava/lang/Class;") .fieldName("lombok$shadowLoaderClass") .targetClass("org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader") .targetClass("org.eclipse.osgi.framework.adapter.core.AbstractClassLoader") .targetClass("org.eclipse.osgi.internal.loader.ModuleClassLoader") .build()); sm.addScript(ScriptBuilder.addField().setPublic().setStatic().setFinal() .fieldType("Ljava/lang/String;") .fieldName("lombok$location") .targetClass("org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader") .targetClass("org.eclipse.osgi.framework.adapter.core.AbstractClassLoader") .targetClass("org.eclipse.osgi.internal.loader.ModuleClassLoader") .value(ClassRootFinder.findClassRootOfClass(launchingContext)) .build()); } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/EclipseLoaderPatcherTransplants.java000066400000000000000000000124041312655740700315040ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.jar.JarFile; import java.util.zip.ZipEntry; /** * Contains all the code to be transplanted into eclipse. * * Do not use: * * * Annotations * * Generics * * Varargs * * Auto (un)boxing * * class literals * * The above because this code is compiled with -source 1.4, and is transplanted. * * NB: The suppress warnings will be stripped out before compilation. */ @SuppressWarnings("all") public class EclipseLoaderPatcherTransplants { public static boolean overrideLoadDecide(ClassLoader original, String name, boolean resolve) { return name.startsWith("lombok."); } public static Class overrideLoadResult(ClassLoader original, String name, boolean resolve) throws ClassNotFoundException { try { Field shadowLoaderField = original.getClass().getField("lombok$shadowLoader"); ClassLoader shadowLoader = (ClassLoader) shadowLoaderField.get(original); if (shadowLoader == null) { synchronized ("lombok$shadowLoader$globalLock".intern()) { shadowLoader = (ClassLoader) shadowLoaderField.get(original); if (shadowLoader == null) { Class shadowClassLoaderClass = (Class) original.getClass().getField("lombok$shadowLoaderClass").get(null); Class classLoaderClass = Class.forName("java.lang.ClassLoader"); String jarLoc = (String) original.getClass().getField("lombok$location").get(null); if (shadowClassLoaderClass == null) { JarFile jf = new JarFile(jarLoc); InputStream in = null; try { ZipEntry entry = jf.getEntry("lombok/launch/ShadowClassLoader.class"); in = jf.getInputStream(entry); byte[] bytes = new byte[65536]; int len = 0; while (true) { int r = in.read(bytes, len, bytes.length - len); if (r == -1) break; len += r; if (len == bytes.length) throw new IllegalStateException("lombok.launch.ShadowClassLoader too large."); } in.close(); { Class[] paramTypes = new Class[4]; paramTypes[0] = "".getClass(); paramTypes[1] = new byte[0].getClass(); paramTypes[2] = Integer.TYPE; paramTypes[3] = paramTypes[2]; Method defineClassMethod = classLoaderClass.getDeclaredMethod("defineClass", paramTypes); defineClassMethod.setAccessible(true); shadowClassLoaderClass = (Class) defineClassMethod.invoke(original, new Object[] {"lombok.launch.ShadowClassLoader", bytes, new Integer(0), new Integer(len)}); original.getClass().getField("lombok$shadowLoaderClass").set(null, shadowClassLoaderClass); } } finally { if (in != null) in.close(); jf.close(); } } Class[] paramTypes = new Class[5]; paramTypes[0] = classLoaderClass; paramTypes[1] = "".getClass(); paramTypes[2] = paramTypes[1]; paramTypes[3] = Class.forName("java.util.List"); paramTypes[4] = paramTypes[3]; Constructor constructor = shadowClassLoaderClass.getDeclaredConstructor(paramTypes); constructor.setAccessible(true); shadowLoader = (ClassLoader) constructor.newInstance(new Object[] {original, "lombok", jarLoc, Arrays.asList(new Object[] {"lombok."}), Arrays.asList(new Object[] {"lombok.patcher.Symbols"})}); shadowLoaderField.set(original, shadowLoader); } } } if (resolve) { Class[] paramTypes = new Class[2]; paramTypes[0] = "".getClass(); paramTypes[1] = Boolean.TYPE; Method m = shadowLoader.getClass().getDeclaredMethod("loadClass", new Class[] {String.class, boolean.class}); m.setAccessible(true); return (Class) m.invoke(shadowLoader, new Object[] {name, Boolean.TRUE}); } else { return shadowLoader.loadClass(name); } } catch (Exception ex) { Throwable t = ex; if (t instanceof InvocationTargetException) t = t.getCause(); if (t instanceof RuntimeException) throw (RuntimeException) t; if (t instanceof Error) throw (Error) t; throw new RuntimeException(t); } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/EclipsePatcher.java000066400000000000000000001405321312655740700261270ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import static lombok.patcher.scripts.ScriptBuilder.*; import java.lang.instrument.Instrumentation; import java.net.URLClassLoader; import java.security.ProtectionDomain; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.core.AgentLauncher; import lombok.patcher.Filter; import lombok.patcher.Hook; import lombok.patcher.MethodTarget; import lombok.patcher.ScriptManager; import lombok.patcher.StackRequest; import lombok.patcher.TargetMatcher; import lombok.patcher.TransplantMapper; import lombok.patcher.scripts.ScriptBuilder; /** * This is a java-agent that patches some of eclipse's classes so AST Nodes are handed off to Lombok * for modification before Eclipse actually uses them to compile, render errors, show code outlines, * create auto-completion dialogs, and anything else eclipse does with java code. See the *Transformer * classes in this package for more information about which classes are transformed and how they are * transformed. */ public class EclipsePatcher implements AgentLauncher.AgentLaunchable { // At some point I'd like the agent to be capable of auto-detecting if its on eclipse or on ecj. This class is a sure sign we're not in ecj but in eclipse. -ReinierZ @SuppressWarnings("unused") private static final String ECLIPSE_SIGNATURE_CLASS = "org/eclipse/core/runtime/adaptor/EclipseStarter"; @Override public void runAgent(String agentArgs, Instrumentation instrumentation, boolean injected, Class launchingContext) throws Exception { String[] args = agentArgs == null ? new String[0] : agentArgs.split(":"); boolean forceEcj = false; boolean forceEclipse = false; for (String arg : args) { if (arg.trim().equalsIgnoreCase("ECJ")) forceEcj = true; if (arg.trim().equalsIgnoreCase("ECLIPSE")) forceEclipse = true; } if (forceEcj && forceEclipse) { forceEcj = false; forceEclipse = false; } boolean ecj; if (forceEcj) ecj = true; else if (forceEclipse) ecj = false; else ecj = injected; registerPatchScripts(instrumentation, injected, ecj, launchingContext); } private static void registerPatchScripts(Instrumentation instrumentation, boolean reloadExistingClasses, boolean ecjOnly, Class launchingContext) { ScriptManager sm = new ScriptManager(); sm.registerTransformer(instrumentation); sm.setFilter(new Filter() { @Override public boolean shouldTransform(ClassLoader loader, String className, Class classBeingDefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { if (!(loader instanceof URLClassLoader)) return true; ClassLoader parent = loader.getParent(); if (parent == null) return true; return !parent.getClass().getName().startsWith("org.eclipse.jdt.apt.core.internal.AnnotationProcessorFactoryLoader"); } }); final boolean forceBaseResourceNames = !"".equals(System.getProperty("shadow.override.lombok", "")); sm.setTransplantMapper(new TransplantMapper() { public String mapResourceName(int classFileFormatVersion, String resourceName) { if (classFileFormatVersion < 50 || forceBaseResourceNames) return resourceName; return "Class50/" + resourceName; } }); if (!ecjOnly) { EclipseLoaderPatcher.patchEquinoxLoaders(sm, launchingContext); patchCatchReparse(sm); patchIdentifierEndReparse(sm); patchRetrieveEllipsisStartPosition(sm); patchRetrieveRightBraceOrSemiColonPosition(sm); patchSetGeneratedFlag(sm); patchDomAstReparseIssues(sm); patchHideGeneratedNodes(sm); patchPostCompileHookEclipse(sm); patchFixSourceTypeConverter(sm); patchDisableLombokForCodeFormatterAndCleanup(sm); patchListRewriteHandleGeneratedMethods(sm); patchSyntaxAndOccurrencesHighlighting(sm); patchSortMembersOperation(sm); patchExtractInterface(sm); patchAboutDialog(sm); patchEclipseDebugPatches(sm); } else { patchPostCompileHookEcj(sm); } patchAvoidReparsingGeneratedCode(sm); patchLombokizeAST(sm); patchEcjTransformers(sm, ecjOnly); patchExtensionMethod(sm, ecjOnly); patchRenameField(sm); if (reloadExistingClasses) sm.reloadClasses(instrumentation); } private static void patchRenameField(ScriptManager sm) { /* RefactoringSearchEngine.search will not return results when renaming field and Data Annotation is present. Return a fake Element to make checks pass */ sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.rename.RenameFieldProcessor", "checkAccessorDeclarations", "org.eclipse.ltk.core.refactoring.RefactoringStatus", "org.eclipse.core.runtime.IProgressMonitor", "org.eclipse.jdt.core.IMethod")) .methodToWrap(new Hook("org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine", "search", "org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup[]", "org.eclipse.jdt.core.search.SearchPattern","org.eclipse.jdt.core.search.IJavaSearchScope","org.eclipse.core.runtime.IProgressMonitor","org.eclipse.ltk.core.refactoring.RefactoringStatus")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "createFakeSearchResult", "org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup[]", "org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup[]", "java.lang.Object")) .requestExtra(StackRequest.THIS) .transplant().build()); /* Filter search results which are Generated and based on Fields, e.g. Generated getters/setters */ sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.rename.RenameFieldProcessor", "addAccessorOccurrences", "void", "org.eclipse.core.runtime.IProgressMonitor", "org.eclipse.jdt.core.IMethod", "java.lang.String","java.lang.String","org.eclipse.ltk.core.refactoring.RefactoringStatus")) .methodToWrap(new Hook("org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup", "getSearchResults", "org.eclipse.jdt.core.search.SearchMatch[]")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "removeGenerated", "org.eclipse.jdt.core.search.SearchMatch[]", "org.eclipse.jdt.core.search.SearchMatch[]")) .transplant().build()); } private static void patchExtractInterface(ScriptManager sm) { /* Fix sourceEnding for generated nodes to avoid null pointer */ sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.compiler.SourceElementNotifier", "notifySourceElementRequestor", "void", "org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration", "org.eclipse.jdt.internal.compiler.ast.TypeDeclaration", "org.eclipse.jdt.internal.compiler.ast.ImportReference")) .methodToWrap(new Hook("org.eclipse.jdt.internal.compiler.util.HashtableOfObjectToInt", "get", "int", "java.lang.Object")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getSourceEndFixed", "int", "int", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .requestExtra(StackRequest.PARAM1) .transplant().build()); /* Make sure the generated source element is found instead of the annotation */ sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMethodDeclaration", "void", "org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite", "org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "org.eclipse.jdt.core.dom.AbstractTypeDeclaration", "org.eclipse.jdt.core.dom.MethodDeclaration" )) .methodToWrap(new Hook("org.eclipse.jface.text.IDocument", "get", "java.lang.String", "int", "int")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getRealMethodDeclarationSource", "java.lang.String", "java.lang.String", "java.lang.Object", "org.eclipse.jdt.core.dom.MethodDeclaration")) .requestExtra(StackRequest.THIS, StackRequest.PARAM4) .transplant().build()); /* get real generated node in stead of a random one generated by the annotation */ sm.addScript(ScriptBuilder.replaceMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMemberDeclarations")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMethodComments")) .methodToReplace(new Hook("org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil", "getMethodDeclarationNode", "org.eclipse.jdt.core.dom.MethodDeclaration", "org.eclipse.jdt.core.IMethod", "org.eclipse.jdt.core.dom.CompilationUnit")) .replacementMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getRealMethodDeclarationNode", "org.eclipse.jdt.core.dom.MethodDeclaration", "org.eclipse.jdt.core.IMethod", "org.eclipse.jdt.core.dom.CompilationUnit")) .transplant().build()); /* Do not add @Override's for generated methods */ sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ListRewrite", "insertFirst")) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "isListRewriteOnGeneratedNode", "boolean", "org.eclipse.jdt.core.dom.rewrite.ListRewrite")) .request(StackRequest.THIS) .transplant().build()); /* Do not add comments for generated methods */ sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMethodComment")) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "isGenerated", "boolean", "org.eclipse.jdt.core.dom.ASTNode")) .request(StackRequest.PARAM2) .transplant().build()); } private static void patchAboutDialog(ScriptManager sm) { /* * Add a line about lombok (+ version info) to eclipse's about dialog. * This is doable without patching, but we intentionally patch it so that presence of the lombok info * in the about dialog can be used to ascertain that patching in general is doing something. */ sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.core.internal.runtime.Product", "getProperty", "java.lang.String", "java.lang.String")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$LombokDeps", "addLombokNotesToEclipseAboutDialog", "java.lang.String", "java.lang.String", "java.lang.String")) .request(StackRequest.RETURN_VALUE, StackRequest.PARAM1) .transplant().build()); } private static void patchSyntaxAndOccurrencesHighlighting(ScriptManager sm) { /* * Skip generated nodes for "visual effects" (syntax highlighting && highlight occurrences) */ sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.jdt.internal.ui.search.OccurrencesFinder", "addUsage")) .target(new MethodTarget("org.eclipse.jdt.internal.ui.search.OccurrencesFinder", "addWrite")) .target(new MethodTarget("org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingReconciler$PositionCollector", "visit", "boolean", "org.eclipse.jdt.core.dom.SimpleName")) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "isGenerated", "boolean", "org.eclipse.jdt.core.dom.ASTNode")) .valueMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "returnFalse", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1) .build()); } private static void patchDisableLombokForCodeFormatterAndCleanup(ScriptManager sm) { sm.addScript(ScriptBuilder.setSymbolDuringMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.formatter.DefaultCodeFormatter", "formatCompilationUnit")) .callToWrap(new Hook("org.eclipse.jdt.internal.core.util.CodeSnippetParsingUtil", "parseCompilationUnit", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration", "char[]", "java.util.Map", "boolean")) .symbol("lombok.disable") .build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.ControlStatementsFix$ControlStatementFinder", "visit", "boolean", "org.eclipse.jdt.core.dom.DoStatement")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.ControlStatementsFix$ControlStatementFinder", "visit", "boolean", "org.eclipse.jdt.core.dom.EnhancedForStatement")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.ControlStatementsFix$ControlStatementFinder", "visit", "boolean", "org.eclipse.jdt.core.dom.ForStatement")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.ControlStatementsFix$ControlStatementFinder", "visit", "boolean", "org.eclipse.jdt.core.dom.IfStatement")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.ControlStatementsFix$ControlStatementFinder", "visit", "boolean", "org.eclipse.jdt.core.dom.WhileStatement")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.CodeStyleFix$ThisQualifierVisitor", "visit", "boolean", "org.eclipse.jdt.core.dom.MethodInvocation")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.CodeStyleFix$ThisQualifierVisitor", "visit", "boolean", "org.eclipse.jdt.core.dom.FieldAccess")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.CodeStyleFix$CodeStyleVisitor", "visit", "boolean", "org.eclipse.jdt.core.dom.MethodInvocation")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.CodeStyleFix$CodeStyleVisitor", "visit", "boolean", "org.eclipse.jdt.core.dom.TypeDeclaration")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.CodeStyleFix$CodeStyleVisitor", "visit", "boolean", "org.eclipse.jdt.core.dom.QualifiedName")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.CodeStyleFix$CodeStyleVisitor", "visit", "boolean", "org.eclipse.jdt.core.dom.SimpleName")) // if a generated node has children we can just ignore them as well; .decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "isGenerated", "boolean", "org.eclipse.jdt.core.dom.ASTNode")) .request(StackRequest.PARAM1) .valueMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "returnFalse", "boolean", "java.lang.Object")) .build()); } private static void patchListRewriteHandleGeneratedMethods(ScriptManager sm) { sm.addScript(ScriptBuilder.replaceMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.dom.rewrite.ASTRewriteAnalyzer$ListRewriter", "rewriteList")) .methodToReplace(new Hook("org.eclipse.jdt.internal.core.dom.rewrite.RewriteEvent", "getChildren", "org.eclipse.jdt.internal.core.dom.rewrite.RewriteEvent[]")) .replacementMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "listRewriteHandleGeneratedMethods", "org.eclipse.jdt.internal.core.dom.rewrite.RewriteEvent[]", "org.eclipse.jdt.internal.core.dom.rewrite.RewriteEvent")) .build()); } private static void patchSortMembersOperation(ScriptManager sm) { /* Fixes "sort members" action with @Data @Log * I would have liked to patch sortMembers, but kept getting a VerifyError: Illegal type in constant pool * So now I just patch all calling methods */ sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.SortElementsOperation$2", "visit", "boolean", "org.eclipse.jdt.core.dom.CompilationUnit")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.CompilationUnit", "types", "java.util.List")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "removeGeneratedNodes", "java.util.List", "java.util.List")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.SortElementsOperation$2", "visit", "boolean", "org.eclipse.jdt.core.dom.AnnotationTypeDeclaration")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.AnnotationTypeDeclaration", "bodyDeclarations", "java.util.List")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "removeGeneratedNodes", "java.util.List", "java.util.List")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.SortElementsOperation$2", "visit", "boolean", "org.eclipse.jdt.core.dom.AnonymousClassDeclaration")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.AnonymousClassDeclaration", "bodyDeclarations", "java.util.List")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "removeGeneratedNodes", "java.util.List", "java.util.List")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.SortElementsOperation$2", "visit", "boolean", "org.eclipse.jdt.core.dom.TypeDeclaration")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.TypeDeclaration", "bodyDeclarations", "java.util.List")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "removeGeneratedNodes", "java.util.List", "java.util.List")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.SortElementsOperation$2", "visit", "boolean", "org.eclipse.jdt.core.dom.EnumDeclaration")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.EnumDeclaration", "bodyDeclarations", "java.util.List")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "removeGeneratedNodes", "java.util.List", "java.util.List")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.SortElementsOperation$2", "visit", "boolean", "org.eclipse.jdt.core.dom.EnumDeclaration")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.EnumDeclaration", "enumConstants", "java.util.List")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "removeGeneratedNodes", "java.util.List", "java.util.List")) .transplant().build()); } private static void patchDomAstReparseIssues(ScriptManager sm) { sm.addScript(ScriptBuilder.replaceMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.dom.rewrite.ASTRewriteAnalyzer", "visit")) .methodToReplace(new Hook("org.eclipse.jdt.internal.core.dom.rewrite.TokenScanner", "getTokenEndOffset", "int", "int", "int")) .replacementMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getTokenEndOffsetFixed", "int", "org.eclipse.jdt.internal.core.dom.rewrite.TokenScanner", "int", "int", "java.lang.Object")) .requestExtra(StackRequest.PARAM1) .transplant() .build()); } private static void patchPostCompileHookEclipse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder", "writeClassFileContents")) .target(new MethodTarget("org.eclipse.jdt.internal.core.builder.AbstractImageBuilder", "writeClassFileContents")) .methodToWrap(new Hook("org.eclipse.jdt.internal.compiler.ClassFile", "getBytes", "byte[]")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$LombokDeps", "runPostCompiler", "byte[]", "byte[]", "java.lang.String")) .requestExtra(StackRequest.PARAM3) .build()); } private static void patchPostCompileHookEcj(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.compiler.tool.EclipseCompilerImpl", "outputClassFiles")) .methodToWrap(new Hook("javax.tools.JavaFileObject", "openOutputStream", "java.io.OutputStream")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$LombokDeps", "runPostCompiler", "java.io.OutputStream", "java.io.OutputStream")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.compiler.util.Util", "writeToDisk")) .methodToWrap(new Hook("java.io.BufferedOutputStream", "", "void", "java.io.OutputStream", "int")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$LombokDeps", "runPostCompiler", "java.io.BufferedOutputStream", "java.io.BufferedOutputStream", "java.lang.String", "java.lang.String")) .requestExtra(StackRequest.PARAM2, StackRequest.PARAM3) .transplant().build()); } private static void patchHideGeneratedNodes(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder", "findByNode")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder", "findByBinding")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "removeGeneratedSimpleNames", "org.eclipse.jdt.core.dom.SimpleName[]", "org.eclipse.jdt.core.dom.SimpleName[]")) .request(StackRequest.RETURN_VALUE).build()); patchRefactorScripts(sm); patchFormatters(sm); } private static void patchFormatters(ScriptManager sm) { sm.addScript(ScriptBuilder.setSymbolDuringMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy", "format", "void")) .callToWrap(new Hook("org.eclipse.jdt.internal.corext.util.CodeFormatterUtil", "reformat", "org.eclipse.text.edits.TextEdit", "int", "java.lang.String", "int", "int", "int", "java.lang.String", "java.util.Map")) .symbol("lombok.disable").build()); sm.addScript(ScriptBuilder.setSymbolDuringMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.corext.fix.CodeFormatFix", "createCleanUp", "org.eclipse.jdt.ui.cleanup.ICleanUpFix", "org.eclipse.jdt.core.ICompilationUnit", "org.eclipse.jface.text.IRegion[]", "boolean", "boolean", "boolean", "boolean")) .callToWrap(new Hook("org.eclipse.jdt.internal.corext.util.CodeFormatterUtil", "reformat", "org.eclipse.text.edits.TextEdit", "int", "java.lang.String", "int", "java.lang.String", "java.util.Map")) .symbol("lombok.disable").build()); } private static void patchRefactorScripts(ScriptManager sm) { sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "replace")) .target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "remove")) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "skipRewritingGeneratedNodes", "boolean", "org.eclipse.jdt.core.dom.ASTNode")) .transplant().request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor", "addConstructorRenames")) .methodToWrap(new Hook("org.eclipse.jdt.core.IType", "getMethods", "org.eclipse.jdt.core.IMethod[]")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "removeGeneratedMethods", "org.eclipse.jdt.core.IMethod[]", "org.eclipse.jdt.core.IMethod[]")) .transplant().build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceAnalyzer", "visit", "boolean", "org.eclipse.jdt.core.dom.SimpleName")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.rename.RenameAnalyzeUtil$ProblemNodeFinder$NameNodeVisitor", "visit", "boolean", "org.eclipse.jdt.core.dom.SimpleName")) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "isGenerated", "boolean", "org.eclipse.jdt.core.dom.ASTNode")) .valueMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "returnTrue", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1) .transplant().build()); } private static void patchCatchReparse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveStartingCatchPosition")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "fixRetrieveStartingCatchPosition", "int", "int", "int")) .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM1).build()); } private static void patchIdentifierEndReparse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveIdentifierEndPosition")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "fixRetrieveIdentifierEndPosition", "int", "int", "int")) .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM2).build()); } private static void patchRetrieveEllipsisStartPosition(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveEllipsisStartPosition")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "fixRetrieveEllipsisStartPosition", "int", "int", "int")) .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM2).build()); } private static void patchRetrieveRightBraceOrSemiColonPosition(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convert", "org.eclipse.jdt.core.dom.ASTNode", "boolean", "org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.ASTConverter", "retrieveRightBraceOrSemiColonPosition", "int", "int", "int")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "fixRetrieveRightBraceOrSemiColonPosition", "int", "int", "org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration")) .requestExtra(StackRequest.PARAM2) .transplant() .build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convert", "org.eclipse.jdt.core.dom.ASTNode", "boolean", "org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.ASTConverter", "retrieveRightBrace", "int", "int", "int")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "fixRetrieveRightBraceOrSemiColonPosition", "int", "int", "org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration")) .requestExtra(StackRequest.PARAM2) .transplant() .build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convert", "org.eclipse.jdt.core.dom.ASTNode", "org.eclipse.jdt.internal.compiler.ast.FieldDeclaration")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.ASTConverter", "retrieveRightBrace", "int", "int", "int")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "fixRetrieveRightBraceOrSemiColonPosition", "int", "int", "org.eclipse.jdt.internal.compiler.ast.FieldDeclaration")) .requestExtra(StackRequest.PARAM1) .transplant() .build()); // sm.addScript(ScriptBuilder.wrapReturnValue() // .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveRightBraceOrSemiColonPosition")) // .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveRightBrace")) // .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "fixRetrieveRightBraceOrSemiColonPosition", "int", "int", "int")) // .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM2).build()); } private static void patchSetGeneratedFlag(ScriptManager sm) { sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.internal.compiler.ast.ASTNode") .fieldName("$generatedBy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic().setTransient().build()); sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.core.dom.ASTNode") .fieldName("$isGenerated").fieldType("Z") .setPublic().setTransient().build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new TargetMatcher() { @Override public boolean matches(String classSpec, String methodName, String descriptor) { if (!"convert".equals(methodName)) return false; List fullDesc = MethodTarget.decomposeFullDesc(descriptor); if ("V".equals(fullDesc.get(0))) return false; if (fullDesc.size() < 2) return false; if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; return true; } @Override public Collection getAffectedClasses() { return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); } }).request(StackRequest.PARAM1, StackRequest.RETURN_VALUE) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "setIsGeneratedFlag", "void", "org.eclipse.jdt.core.dom.ASTNode", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .transplant().build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convert", "org.eclipse.jdt.core.dom.ASTNode", "boolean", "org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration")) .request(StackRequest.PARAM2, StackRequest.RETURN_VALUE) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "setIsGeneratedFlag", "void", "org.eclipse.jdt.core.dom.ASTNode", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .transplant().build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convertToFieldDeclaration", "org.eclipse.jdt.core.dom.FieldDeclaration", "org.eclipse.jdt.internal.compiler.ast.FieldDeclaration")) /* Targets beneath are only patched because the resulting dom nodes should be marked if generated. * However I couldn't find a usecase where these were actually used */ .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convertToType", "org.eclipse.jdt.core.dom.Type", "org.eclipse.jdt.internal.compiler.ast.NameReference")) .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convertType", "org.eclipse.jdt.core.dom.Type", "org.eclipse.jdt.internal.compiler.ast.TypeReference")) .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convertToVariableDeclarationExpression", "org.eclipse.jdt.core.dom.VariableDeclarationExpression", "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration")) .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convertToSingleVariableDeclaration", "org.eclipse.jdt.core.dom.SingleVariableDeclaration", "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration")) .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convertToVariableDeclarationFragment", "org.eclipse.jdt.core.dom.VariableDeclarationFragment", "org.eclipse.jdt.internal.compiler.ast.FieldDeclaration")) .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convertToVariableDeclarationFragment", "org.eclipse.jdt.core.dom.VariableDeclarationFragment", "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration")) .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convertToVariableDeclarationStatement", "org.eclipse.jdt.core.dom.VariableDeclarationStatement", "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration")) /* Targets above are only patched because the resulting dom nodes should be marked if generated. */ .request(StackRequest.PARAM1, StackRequest.RETURN_VALUE) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "setIsGeneratedFlag", "void", "org.eclipse.jdt.core.dom.ASTNode", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .transplant().build()); /* Set generated flag for SimpleNames */ sm.addScript(ScriptBuilder.wrapMethodCall() .target(new TargetMatcher() { @Override public boolean matches(String classSpec, String methodName, String descriptor) { if (!methodName.startsWith("convert")) return false; List fullDesc = MethodTarget.decomposeFullDesc(descriptor); if (fullDesc.size() < 2) return false; if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; return true; } @Override public Collection getAffectedClasses() { return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); } }).methodToWrap(new Hook("org.eclipse.jdt.core.dom.SimpleName", "", "void", "org.eclipse.jdt.core.dom.AST")) .requestExtra(StackRequest.PARAM1) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "setIsGeneratedFlagForName", "void", "org.eclipse.jdt.core.dom.Name", "java.lang.Object")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "convert", "org.eclipse.jdt.core.dom.ASTNode", "boolean", "org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.SimpleName", "", "void", "org.eclipse.jdt.core.dom.AST")) .requestExtra(StackRequest.PARAM2) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "setIsGeneratedFlagForName", "void", "org.eclipse.jdt.core.dom.Name", "java.lang.Object")) .transplant().build()); /* Set generated flag for QualifiedNames */ sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "setQualifiedNameNameAndSourceRanges", "org.eclipse.jdt.core.dom.QualifiedName", "char[][]", "long[]", "int", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.SimpleName", "", "void", "org.eclipse.jdt.core.dom.AST")) .requestExtra(StackRequest.PARAM4) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "setIsGeneratedFlagForName", "void", "org.eclipse.jdt.core.dom.Name", "java.lang.Object")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "setQualifiedNameNameAndSourceRanges", "org.eclipse.jdt.core.dom.QualifiedName", "char[][]", "long[]", "int", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.QualifiedName", "", "void", "org.eclipse.jdt.core.dom.AST")) .requestExtra(StackRequest.PARAM4) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "setIsGeneratedFlagForName", "void", "org.eclipse.jdt.core.dom.Name", "java.lang.Object")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "setQualifiedNameNameAndSourceRanges", "org.eclipse.jdt.core.dom.QualifiedName", "char[][]", "long[]", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.SimpleName", "", "void", "org.eclipse.jdt.core.dom.AST")) .requestExtra(StackRequest.PARAM3) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "setIsGeneratedFlagForName", "void", "org.eclipse.jdt.core.dom.Name", "java.lang.Object")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "setQualifiedNameNameAndSourceRanges", "org.eclipse.jdt.core.dom.QualifiedName", "char[][]", "long[]", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .methodToWrap(new Hook("org.eclipse.jdt.core.dom.QualifiedName", "", "void", "org.eclipse.jdt.core.dom.AST")) .requestExtra(StackRequest.PARAM3) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "setIsGeneratedFlagForName", "void", "org.eclipse.jdt.core.dom.Name", "java.lang.Object")) .transplant().build()); } private static void patchAvoidReparsingGeneratedCode(ScriptManager sm) { final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.MethodDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .transplant() .request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration", "boolean")) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .transplant() .request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.Initializer", "org.eclipse.jdt.internal.compiler.ast.TypeDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .transplant() .request(StackRequest.PARAM1).build()); } private static void patchLombokizeAST(ScriptManager sm) { sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration") .fieldName("$lombokAST").fieldType("Ljava/lang/Object;") .setPublic().setTransient().build()); final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; final String CUD_SIG = "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration"; sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "getMethodBodies", "void", CUD_SIG)) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$Transform", "transform", "void", PARSER_SIG, CUD_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "endParse", CUD_SIG, "int")) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$Transform", "transform_swapped", "void", CUD_SIG, PARSER_SIG)) .request(StackRequest.THIS, StackRequest.RETURN_VALUE).build()); } private static void patchEcjTransformers(ScriptManager sm, boolean ecj) { addPatchesForDelegate(sm, ecj); addPatchesForVal(sm); if (!ecj) addPatchesForValEclipse(sm); } private static void addPatchesForDelegate(ScriptManager sm, boolean ecj) { final String CLASSSCOPE_SIG = "org.eclipse.jdt.internal.compiler.lookup.ClassScope"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(CLASSSCOPE_SIG, "buildFieldsAndMethods", "void")) .request(StackRequest.THIS) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$Delegate", "handleDelegateForType", "boolean", "java.lang.Object")) .build()); } private static void addPatchesForValEclipse(ScriptManager sm) { final String LOCALDECLARATION_SIG = "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration"; final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; final String VARIABLEDECLARATIONSTATEMENT_SIG = "org.eclipse.jdt.core.dom.VariableDeclarationStatement"; final String SINGLEVARIABLEDECLARATION_SIG = "org.eclipse.jdt.core.dom.SingleVariableDeclaration"; final String ASTCONVERTER_SIG = "org.eclipse.jdt.core.dom.ASTConverter"; sm.addScript(ScriptBuilder.addField() .fieldName("$initCopy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic() .setTransient() .targetClass("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration") .build()); sm.addScript(ScriptBuilder.addField() .fieldName("$iterableCopy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic() .setTransient() .targetClass("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration") .build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "consumeExitVariableWithInitialization", "void")) .request(StackRequest.THIS) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$ValPortal", "copyInitializationOfLocalDeclaration", "void", "java.lang.Object")) .build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "consumeEnhancedForStatementHeader", "void")) .request(StackRequest.THIS) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$ValPortal", "copyInitializationOfForEachIterable", "void", "java.lang.Object")) .build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(ASTCONVERTER_SIG, "setModifiers", "void", VARIABLEDECLARATIONSTATEMENT_SIG, LOCALDECLARATION_SIG)) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$ValPortal", "addFinalAndValAnnotationToVariableDeclarationStatement", "void", "java.lang.Object", "java.lang.Object", "java.lang.Object")) .request(StackRequest.THIS, StackRequest.PARAM1, StackRequest.PARAM2).build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(ASTCONVERTER_SIG, "setModifiers", "void", SINGLEVARIABLEDECLARATION_SIG, LOCALDECLARATION_SIG)) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$ValPortal", "addFinalAndValAnnotationToSingleVariableDeclaration", "void", "java.lang.Object", "java.lang.Object", "java.lang.Object")) .request(StackRequest.THIS, StackRequest.PARAM1, StackRequest.PARAM2).build()); } private static void addPatchesForVal(ScriptManager sm) { final String LOCALDECLARATION_SIG = "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration"; final String FOREACHSTATEMENT_SIG = "org.eclipse.jdt.internal.compiler.ast.ForeachStatement"; final String EXPRESSION_SIG = "org.eclipse.jdt.internal.compiler.ast.Expression"; final String BLOCKSCOPE_SIG = "org.eclipse.jdt.internal.compiler.lookup.BlockScope"; final String TYPEBINDING_SIG = "org.eclipse.jdt.internal.compiler.lookup.TypeBinding"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(LOCALDECLARATION_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$Val", "handleValForLocalDeclaration", "boolean", LOCALDECLARATION_SIG, BLOCKSCOPE_SIG)) .build()); sm.addScript(ScriptBuilder.replaceMethodCall() .target(new MethodTarget(LOCALDECLARATION_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .methodToReplace(new Hook(EXPRESSION_SIG, "resolveType", TYPEBINDING_SIG, BLOCKSCOPE_SIG)) .requestExtra(StackRequest.THIS) .replacementMethod(new Hook("lombok.launch.PatchFixesHider$Val", "skipResolveInitializerIfAlreadyCalled2", TYPEBINDING_SIG, EXPRESSION_SIG, BLOCKSCOPE_SIG, LOCALDECLARATION_SIG)) .build()); sm.addScript(ScriptBuilder.replaceMethodCall() .target(new MethodTarget(FOREACHSTATEMENT_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .methodToReplace(new Hook(EXPRESSION_SIG, "resolveType", TYPEBINDING_SIG, BLOCKSCOPE_SIG)) .replacementMethod(new Hook("lombok.launch.PatchFixesHider$Val", "skipResolveInitializerIfAlreadyCalled", TYPEBINDING_SIG, EXPRESSION_SIG, BLOCKSCOPE_SIG)) .build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(FOREACHSTATEMENT_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1) .decisionMethod(new Hook("lombok.launch.PatchFixesHider$Val", "handleValForForEach", "boolean", FOREACHSTATEMENT_SIG, BLOCKSCOPE_SIG)) .build()); } private static void patchFixSourceTypeConverter(ScriptManager sm) { final String SOURCE_TYPE_CONVERTER_SIG = "org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter"; final String I_ANNOTATABLE_SIG = "org.eclipse.jdt.core.IAnnotatable"; final String ANNOTATION_SIG = "org.eclipse.jdt.internal.compiler.ast.Annotation"; sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(SOURCE_TYPE_CONVERTER_SIG, "convertAnnotations", ANNOTATION_SIG + "[]", I_ANNOTATABLE_SIG)) .wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "convertAnnotations", ANNOTATION_SIG + "[]", ANNOTATION_SIG + "[]", I_ANNOTATABLE_SIG)) .request(StackRequest.PARAM1, StackRequest.RETURN_VALUE).build()); } private static void patchEclipseDebugPatches(ScriptManager sm) { final String ASTNODE_SIG = "org.eclipse.jdt.core.dom.ASTNode"; final String PATCH_DEBUG = "lombok.eclipse.agent.PatchDiagnostics"; sm.addScript(exitEarly() .target(new MethodTarget(ASTNODE_SIG, "setSourceRange", "void", "int", "int")) .request(StackRequest.THIS) .request(StackRequest.PARAM1) .request(StackRequest.PARAM2) .decisionMethod(new Hook(PATCH_DEBUG, "setSourceRangeCheck", "boolean", "java.lang.Object", "int", "int")) .build()); } private static void patchExtensionMethod(ScriptManager sm, boolean ecj) { final String PATCH_EXTENSIONMETHOD = "lombok.launch.PatchFixesHider$ExtensionMethod"; final String PATCH_EXTENSIONMETHOD_COMPLETIONPROPOSAL_PORTAL = "lombok.eclipse.agent.PatchExtensionMethodCompletionProposalPortal"; final String MESSAGE_SEND_SIG = "org.eclipse.jdt.internal.compiler.ast.MessageSend"; final String TYPE_BINDING_SIG = "org.eclipse.jdt.internal.compiler.lookup.TypeBinding"; final String SCOPE_SIG = "org.eclipse.jdt.internal.compiler.lookup.Scope"; final String BLOCK_SCOPE_SIG = "org.eclipse.jdt.internal.compiler.lookup.BlockScope"; final String TYPE_BINDINGS_SIG = "org.eclipse.jdt.internal.compiler.lookup.TypeBinding[]"; final String PROBLEM_REPORTER_SIG = "org.eclipse.jdt.internal.compiler.problem.ProblemReporter"; final String METHOD_BINDING_SIG = "org.eclipse.jdt.internal.compiler.lookup.MethodBinding"; final String COMPLETION_PROPOSAL_COLLECTOR_SIG = "org.eclipse.jdt.ui.text.java.CompletionProposalCollector"; final String I_JAVA_COMPLETION_PROPOSAL_SIG = "org.eclipse.jdt.ui.text.java.IJavaCompletionProposal[]"; sm.addScript(wrapReturnValue() .target(new MethodTarget(MESSAGE_SEND_SIG, "resolveType", TYPE_BINDING_SIG, BLOCK_SCOPE_SIG)) .request(StackRequest.RETURN_VALUE) .request(StackRequest.THIS) .request(StackRequest.PARAM1) .wrapMethod(new Hook(PATCH_EXTENSIONMETHOD, "resolveType", TYPE_BINDING_SIG, TYPE_BINDING_SIG, MESSAGE_SEND_SIG, BLOCK_SCOPE_SIG)) .build()); sm.addScript(replaceMethodCall() .target(new MethodTarget(MESSAGE_SEND_SIG, "resolveType", TYPE_BINDING_SIG, BLOCK_SCOPE_SIG)) .methodToReplace(new Hook(PROBLEM_REPORTER_SIG, "errorNoMethodFor", "void", MESSAGE_SEND_SIG, TYPE_BINDING_SIG, TYPE_BINDINGS_SIG)) .replacementMethod(new Hook(PATCH_EXTENSIONMETHOD, "errorNoMethodFor", "void", PROBLEM_REPORTER_SIG, MESSAGE_SEND_SIG, TYPE_BINDING_SIG, TYPE_BINDINGS_SIG)) .build()); sm.addScript(replaceMethodCall() .target(new MethodTarget(MESSAGE_SEND_SIG, "resolveType", TYPE_BINDING_SIG, BLOCK_SCOPE_SIG)) .methodToReplace(new Hook(PROBLEM_REPORTER_SIG, "invalidMethod", "void", MESSAGE_SEND_SIG, METHOD_BINDING_SIG)) .replacementMethod(new Hook(PATCH_EXTENSIONMETHOD, "invalidMethod", "void", PROBLEM_REPORTER_SIG, MESSAGE_SEND_SIG, METHOD_BINDING_SIG)) .build()); // Since eclipse mars; they added a param. sm.addScript(replaceMethodCall() .target(new MethodTarget(MESSAGE_SEND_SIG, "resolveType", TYPE_BINDING_SIG, BLOCK_SCOPE_SIG)) .methodToReplace(new Hook(PROBLEM_REPORTER_SIG, "invalidMethod", "void", MESSAGE_SEND_SIG, METHOD_BINDING_SIG, SCOPE_SIG)) .replacementMethod(new Hook(PATCH_EXTENSIONMETHOD, "invalidMethod", "void", PROBLEM_REPORTER_SIG, MESSAGE_SEND_SIG, METHOD_BINDING_SIG, SCOPE_SIG)) .build()); if (!ecj) { sm.addScript(wrapReturnValue() .target(new MethodTarget(COMPLETION_PROPOSAL_COLLECTOR_SIG, "getJavaCompletionProposals", I_JAVA_COMPLETION_PROPOSAL_SIG)) .request(StackRequest.RETURN_VALUE) .request(StackRequest.THIS) .wrapMethod(new Hook(PATCH_EXTENSIONMETHOD_COMPLETIONPROPOSAL_PORTAL, "getJavaCompletionProposals", I_JAVA_COMPLETION_PROPOSAL_SIG, "java.lang.Object[]", "java.lang.Object")) .build()); } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/ExtensionMethodCompletionProposal.java000066400000000000000000000107551312655740700321260ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccStatic; import java.util.Arrays; import org.eclipse.jdt.core.CompletionProposal; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.codeassist.CompletionEngine; import org.eclipse.jdt.internal.codeassist.InternalCompletionProposal; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnMemberAccess; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnQualifiedNameReference; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnSingleNameReference; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; public class ExtensionMethodCompletionProposal extends InternalCompletionProposal { public ExtensionMethodCompletionProposal(final int replacementOffset) { super(CompletionProposal.METHOD_REF, replacementOffset - 1); } public void setMethodBinding(final MethodBinding method, final ASTNode node) { MethodBinding original = method.original(); TypeBinding[] parameters = Arrays.copyOf(method.parameters, method.parameters.length); method.parameters = Arrays.copyOfRange(method.parameters, 1, method.parameters.length); TypeBinding[] originalParameters = null; if (original != method) { originalParameters = Arrays.copyOf(method.original().parameters, method.original().parameters.length); method.original().parameters = Arrays.copyOfRange(method.original().parameters, 1, method.original().parameters.length); } int length = method.parameters == null ? 0 : method.parameters.length; char[][] parameterPackageNames = new char[length][]; char[][] parameterTypeNames = new char[length][]; for (int i = 0; i < length; i++) { TypeBinding type = method.original().parameters[i]; parameterPackageNames[i] = type.qualifiedPackageName(); parameterTypeNames[i] = type.qualifiedSourceName(); } char[] completion = CharOperation.concat(method.selector, new char[] { '(', ')' }); setDeclarationSignature(CompletionEngine.getSignature(method.declaringClass)); setSignature(CompletionEngine.getSignature(method)); if (original != method) { setOriginalSignature(CompletionEngine.getSignature(original)); } setDeclarationPackageName(method.declaringClass.qualifiedPackageName()); setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); setParameterPackageNames(parameterPackageNames); setParameterTypeNames(parameterTypeNames); setPackageName(method.returnType.qualifiedPackageName()); setTypeName(method.returnType.qualifiedSourceName()); setName(method.selector); setCompletion(completion); setFlags(method.modifiers & (~AccStatic)); int index = node.sourceEnd + 1; if (node instanceof CompletionOnQualifiedNameReference) { index -= ((CompletionOnQualifiedNameReference) node).completionIdentifier.length; } if (node instanceof CompletionOnMemberAccess) { index -= ((CompletionOnMemberAccess) node).token.length; } if (node instanceof CompletionOnSingleNameReference) { index -= ((CompletionOnSingleNameReference) node).token.length; } setReplaceRange(index, index); setTokenRange(index, index); setRelevance(100); method.parameters = parameters; if (original != method) { method.original().parameters = originalParameters; } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchDelegate.java000066400000000000000000001107301312655740700257230ustar00rootroot00000000000000/* * Copyright (C) 2010-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import static lombok.eclipse.Eclipse.*; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import static lombok.eclipse.EclipseAugments.Annotation_applied; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import lombok.core.AST.Kind; import lombok.eclipse.EclipseAST; import lombok.eclipse.EclipseNode; import lombok.eclipse.TransformEclipseAST; import lombok.eclipse.handlers.SetGeneratedByVisitor; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding; import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.eclipse.jdt.internal.compiler.lookup.BaseTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.Binding; import org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; public class PatchDelegate { private static class ClassScopeEntry { ClassScopeEntry(ClassScope scope) { this.scope = scope; } final ClassScope scope; String corruptedPath; } private static ThreadLocal> visited = new ThreadLocal>() { protected List initialValue() { return new ArrayList(); } }; private static String nameOfScope(ClassScope scope) { TypeDeclaration decl = scope.referenceContext; if (decl == null) return "(unknown)"; if (decl.name == null || decl.name.length == 0) return "(unknown)"; return new String(decl.name); } private static boolean hasDelegateMarkedFieldsOrMethods(TypeDeclaration decl) { if (decl.fields != null) for (FieldDeclaration field : decl.fields) { if (field.annotations == null) continue; for (Annotation ann : field.annotations) { if (isDelegate(ann, decl)) return true; } } if (decl.methods != null) for (AbstractMethodDeclaration method : decl.methods) { if (method.annotations == null) continue; for (Annotation ann : method.annotations) { if (isDelegate(ann, decl)) return true; } } return false; } public static boolean handleDelegateForType(ClassScope scope) { if (TransformEclipseAST.disableLombok) return false; if (!hasDelegateMarkedFieldsOrMethods(scope.referenceContext)) return false; List stack = visited.get(); StringBuilder corrupted = null; for (ClassScopeEntry entry : stack) { if (corrupted != null) { corrupted.append(" -> ").append(nameOfScope(entry.scope)); } else if (entry.scope == scope) { corrupted = new StringBuilder().append(nameOfScope(scope)); } } if (corrupted != null) { boolean found = false; String path = corrupted.toString(); for (ClassScopeEntry entry : stack) { if (!found && entry.scope == scope) found = true; if (found) entry.corruptedPath = path; } } else { ClassScopeEntry entry = new ClassScopeEntry(scope); stack.add(entry); try { TypeDeclaration decl = scope.referenceContext; if (decl != null) { CompilationUnitDeclaration cud = scope.compilationUnitScope().referenceContext; EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true); List methodsToDelegate = new ArrayList(); fillMethodBindingsForFields(cud, scope, methodsToDelegate); if (entry.corruptedPath != null) { eclipseAst.get(scope.referenceContext).addError("No @Delegate methods created because there's a loop: " + entry.corruptedPath); } else { generateDelegateMethods(eclipseAst.get(decl), methodsToDelegate, DelegateReceiver.FIELD); } methodsToDelegate.clear(); fillMethodBindingsForMethods(cud, scope, methodsToDelegate); if (entry.corruptedPath != null) { eclipseAst.get(scope.referenceContext).addError("No @Delegate methods created because there's a loop: " + entry.corruptedPath); } else { generateDelegateMethods(eclipseAst.get(decl), methodsToDelegate, DelegateReceiver.METHOD); } } } finally { stack.remove(stack.size() - 1); } } return false; } /** * Returns a string containing the signature of a method that appears (erased) at least twice in the list. * If no duplicates are present, {@code null} is returned. */ private static String containsDuplicates(List tuples) { Set sigs = new HashSet(); for (BindingTuple tuple : tuples) { if (!sigs.add(printSig(tuple.parameterized))) return printSig(tuple.parameterized); } return null; } public static void markHandled(Annotation annotation) { Annotation_applied.set(annotation, true); } private static void fillMethodBindingsForFields(CompilationUnitDeclaration cud, ClassScope scope, List methodsToDelegate) { TypeDeclaration decl = scope.referenceContext; if (decl == null) return; if (decl.fields != null) for (FieldDeclaration field : decl.fields) { if (field.annotations == null) continue; for (Annotation ann : field.annotations) { if (!isDelegate(ann, decl)) continue; if (Annotation_applied.getAndSet(ann, true)) continue; if ((field.modifiers & ClassFileConstants.AccStatic) != 0) { EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true); eclipseAst.get(ann).addError(LEGALITY_OF_DELEGATE); break; } List rawTypes = rawTypes(ann, "types"); List excludedRawTypes = rawTypes(ann, "excludes"); List methodsToExclude = new ArrayList(); List methodsToDelegateForThisAnn = new ArrayList(); try { for (ClassLiteralAccess cla : excludedRawTypes) { addAllMethodBindings(methodsToExclude, cla.type.resolveType(decl.initializerScope), new HashSet(), field.name, ann); } Set banList = new HashSet(); for (BindingTuple excluded : methodsToExclude) banList.add(printSig(excluded.parameterized)); if (rawTypes.isEmpty()) { addAllMethodBindings(methodsToDelegateForThisAnn, field.type.resolveType(decl.initializerScope), banList, field.name, ann); } else { for (ClassLiteralAccess cla : rawTypes) { addAllMethodBindings(methodsToDelegateForThisAnn, cla.type.resolveType(decl.initializerScope), banList, field.name, ann); } } } catch (DelegateRecursion e) { EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true); eclipseAst.get(ann).addError(String.format(RECURSION_NOT_ALLOWED, new String(e.member), new String(e.type))); break; } // Not doing this right now because of problems - see commented-out-method for info. // removeExistingMethods(methodsToDelegate, decl, scope); String dupe = containsDuplicates(methodsToDelegateForThisAnn); if (dupe != null) { EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true); eclipseAst.get(ann).addError("The method '" + dupe + "' is being delegated by more than one specified type."); } else { methodsToDelegate.addAll(methodsToDelegateForThisAnn); } } } } private static final String LEGALITY_OF_DELEGATE = "@Delegate is legal only on instance fields or no-argument instance methods."; private static final String RECURSION_NOT_ALLOWED = "@Delegate does not support recursion (delegating to a type that itself has @Delegate members). Member \"%s\" is @Delegate in type \"%s\""; private static void fillMethodBindingsForMethods(CompilationUnitDeclaration cud, ClassScope scope, List methodsToDelegate) { TypeDeclaration decl = scope.referenceContext; if (decl == null) return; if (decl.methods != null) for (AbstractMethodDeclaration methodDecl : decl.methods) { if (methodDecl.annotations == null) continue; for (Annotation ann : methodDecl.annotations) { if (!isDelegate(ann, decl)) continue; if (Annotation_applied.getAndSet(ann, true)) continue; if (!(methodDecl instanceof MethodDeclaration)) { EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true); eclipseAst.get(ann).addError(LEGALITY_OF_DELEGATE); break; } if (methodDecl.arguments != null) { EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true); eclipseAst.get(ann).addError(LEGALITY_OF_DELEGATE); break; } if ((methodDecl.modifiers & ClassFileConstants.AccStatic) != 0) { EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true); eclipseAst.get(ann).addError(LEGALITY_OF_DELEGATE); break; } MethodDeclaration method = (MethodDeclaration) methodDecl; List rawTypes = rawTypes(ann, "types"); List excludedRawTypes = rawTypes(ann, "excludes"); List methodsToExclude = new ArrayList(); List methodsToDelegateForThisAnn = new ArrayList(); try { for (ClassLiteralAccess cla : excludedRawTypes) { addAllMethodBindings(methodsToExclude, cla.type.resolveType(decl.initializerScope), new HashSet(), method.selector, ann); } Set banList = new HashSet(); for (BindingTuple excluded : methodsToExclude) banList.add(printSig(excluded.parameterized)); if (rawTypes.isEmpty()) { if (method.returnType == null) continue; addAllMethodBindings(methodsToDelegateForThisAnn, method.returnType.resolveType(decl.initializerScope), banList, method.selector, ann); } else { for (ClassLiteralAccess cla : rawTypes) { addAllMethodBindings(methodsToDelegateForThisAnn, cla.type.resolveType(decl.initializerScope), banList, method.selector, ann); } } } catch (DelegateRecursion e) { EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true); eclipseAst.get(ann).addError(String.format(RECURSION_NOT_ALLOWED, new String(e.member), new String(e.type))); break; } // Not doing this right now because of problems - see commented-out-method for info. // removeExistingMethods(methodsToDelegate, decl, scope); String dupe = containsDuplicates(methodsToDelegateForThisAnn); if (dupe != null) { EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true); eclipseAst.get(ann).addError("The method '" + dupe + "' is being delegated by more than one specified type."); } else { methodsToDelegate.addAll(methodsToDelegateForThisAnn); } } } } private static boolean isDelegate(Annotation ann, TypeDeclaration decl) { if (ann.type == null) return false; TypeBinding tb = ann.type.resolveType(decl.initializerScope); if (tb == null) return false; if (!charArrayEquals("lombok", tb.qualifiedPackageName()) && !charArrayEquals("lombok.experimental", tb.qualifiedPackageName())) return false; if (!charArrayEquals("Delegate", tb.qualifiedSourceName())) return false; return true; } private static List rawTypes(Annotation ann, String name) { List rawTypes = new ArrayList(); for (MemberValuePair pair : ann.memberValuePairs()) { if (charArrayEquals(name, pair.name)) { if (pair.value instanceof ArrayInitializer) { for (Expression expr : ((ArrayInitializer)pair.value).expressions) { if (expr instanceof ClassLiteralAccess) rawTypes.add((ClassLiteralAccess) expr); } } if (pair.value instanceof ClassLiteralAccess) { rawTypes.add((ClassLiteralAccess) pair.value); } } } return rawTypes; } /* * We may someday finish this method. Steps to be completed: * * (A) Turn any Parameterized anythings into non-parameterized versions. Resolving parameterized stuff will definitely not work safely. * (B) scope.problemReporter() will need to return a noop reporter as various errors are marked off. * (C) Find a way to do _something_ for references to typevars (i.e. 'T') which are declared on the method itself. * (D) getTypeBinding isn't public, so call it via reflection. */ // private static TypeBinding safeResolveAndErase(TypeReference ref, Scope scope) { // if (ref.resolvedType != null) { // return ref.resolvedType.isValidBinding() ? ref.resolvedType : null; // } // // try { // TypeBinding bind = ref.getTypeBinding(scope); // if (!bind.isValidBinding()) return null; // } catch (AbortCompilation e) { // return null; // } // return bind.erasure(); // } /* * Not using this because calling clone.resolveType() taints a bunch of caches and reports erroneous errors. */ // private static void removeExistingMethods(List list, TypeDeclaration decl, ClassScope scope) { // for (AbstractMethodDeclaration methodDecl : decl.methods) { // if (!(methodDecl instanceof MethodDeclaration)) continue; // MethodDeclaration md = (MethodDeclaration) methodDecl; // char[] name = md.selector; // TypeBinding[] args = md.arguments == null ? new TypeBinding[0] : new TypeBinding[md.arguments.length]; // for (int i = 0; i < args.length; i++) { // TypeReference clone = Eclipse.copyType(md.arguments[i].type, md.arguments[i]); // args[i] = clone.resolveType(scope).erasure(); // This is the problematic line // } // Iterator it = list.iterator(); // methods: // while (it.hasNext()) { // MethodBinding mb = it.next().parameterized; // if (!Arrays.equals(mb.selector, name)) continue; // int paramLen = mb.parameters == null ? 0 : mb.parameters.length; // if (paramLen != args.length) continue; // if (md.typeParameters == null || md.typeParameters.length == 0) { // for (int i = 0; i < paramLen; i++) { // if (!mb.parameters[i].erasure().isEquivalentTo(args[i])) continue methods; // } // } else { // for (int i = 0; i < paramLen; i++) { // if (!mb.parameters[i].erasure().isEquivalentTo(args[i])) ; // } // //BUG #???: We erase the method's parameter types using the class scope, but we should be using the method scope. // // In practice this is no problem UNLESS the method has type parameters, such as T[] toArray(T[] in). // // In this case the class scope cannot resolve the T[] parameter and erase it to Object[], which is a big problem because // // it would mean manually writing X[] toArray(X[] in) does NOT stop lombok from ALSO trying to make the delegated toArray method, // // thus causing an error (2 methods with post-erasure duplicate signatures). Our 'fix' for this is to treat any method with type parameters // // as if each parameter's type matches anything else; so, if the name matches and the parameter count, we DONT generate it, even if its just // // an overloaded method. // // // // The reason we do this now is because making that MethodScope properly is effectively impossible at this step, so we need to do the resolving // // ourselves, which involves chasing down array bindings (T[]), following the path down type variables, i.e. , and then // // resolving the final result of this exercise against the class scope. // // // When this crappy incomplete workaround of ours occurs, we end up in this else block, which does nothing and thus we fall through and remove // // the method. // } // it.remove(); // Method already exists in this class - don't create a delegating implementation. // } // } // } private static void generateDelegateMethods(EclipseNode typeNode, List methods, DelegateReceiver delegateReceiver) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) typeNode.top().get(); for (BindingTuple pair : methods) { EclipseNode annNode = typeNode.getAst().get(pair.responsible); MethodDeclaration method = createDelegateMethod(pair.fieldName, typeNode, pair, top.compilationResult, annNode, delegateReceiver); if (method != null) { SetGeneratedByVisitor visitor = new SetGeneratedByVisitor(annNode.get()); method.traverse(visitor, ((TypeDeclaration)typeNode.get()).scope); injectMethod(typeNode, method); } } } public static void checkConflictOfTypeVarNames(BindingTuple binding, EclipseNode typeNode) throws CantMakeDelegates { TypeVariableBinding[] typeVars = binding.parameterized.typeVariables(); if (typeVars == null || typeVars.length == 0) return; Set usedInOurType = new HashSet(); EclipseNode enclosingType = typeNode; while (enclosingType != null) { if (enclosingType.getKind() == Kind.TYPE) { TypeParameter[] typeParameters = ((TypeDeclaration)enclosingType.get()).typeParameters; if (typeParameters != null) { for (TypeParameter param : typeParameters) { if (param.name != null) usedInOurType.add(new String(param.name)); } } } enclosingType = enclosingType.up(); } Set usedInMethodSig = new HashSet(); for (TypeVariableBinding var : typeVars) { char[] sourceName = var.sourceName(); if (sourceName != null) usedInMethodSig.add(new String(sourceName)); } usedInMethodSig.retainAll(usedInOurType); if (usedInMethodSig.isEmpty()) return; // We might be delegating a List, and we are making method toArray(). A conflict is possible. // But only if the toArray method also uses type vars from its class, otherwise we're only shadowing, // which is okay as we'll add a @SuppressWarnings. TypeVarFinder finder = new TypeVarFinder(); finder.visitRaw(binding.base); Set names = new HashSet(finder.getTypeVariables()); names.removeAll(usedInMethodSig); if (!names.isEmpty()) { // We have a confirmed conflict. We could dig deeper as this may still be a false alarm, but its already an exceedingly rare case. CantMakeDelegates cmd = new CantMakeDelegates(); cmd.conflicted = usedInMethodSig; throw cmd; } } public static class CantMakeDelegates extends Exception { public Set conflicted; } public static class TypeVarFinder extends EclipseTypeBindingScanner { private Set typeVars = new HashSet(); public Set getTypeVariables() { return typeVars; } @Override public void visitTypeVariable(TypeVariableBinding binding) { if (binding.sourceName != null) typeVars.add(new String(binding.sourceName)); super.visitTypeVariable(binding); } } public abstract static class EclipseTypeBindingScanner { public void visitRaw(Binding binding) { if (binding == null) return; if (binding instanceof MethodBinding) visitMethod((MethodBinding) binding); if (binding instanceof BaseTypeBinding) visitBase((BaseTypeBinding) binding); if (binding instanceof ArrayBinding) visitArray((ArrayBinding) binding); if (binding instanceof UnresolvedReferenceBinding) visitUnresolved((UnresolvedReferenceBinding) binding); if (binding instanceof WildcardBinding) visitWildcard((WildcardBinding) binding); if (binding instanceof TypeVariableBinding) visitTypeVariable((TypeVariableBinding) binding); if (binding instanceof ParameterizedTypeBinding) visitParameterized((ParameterizedTypeBinding) binding); if (binding instanceof ReferenceBinding) visitReference((ReferenceBinding) binding); } public void visitReference(ReferenceBinding binding) { } public void visitParameterized(ParameterizedTypeBinding binding) { visitRaw(binding.genericType()); TypeVariableBinding[] typeVars = binding.typeVariables(); if (typeVars != null) for (TypeVariableBinding child : typeVars) { visitRaw(child); } } public void visitTypeVariable(TypeVariableBinding binding) { visitRaw(binding.superclass); ReferenceBinding[] supers = binding.superInterfaces(); if (supers != null) for (ReferenceBinding child : supers) { visitRaw(child); } } public void visitWildcard(WildcardBinding binding) { visitRaw(binding.bound); } public void visitUnresolved(UnresolvedReferenceBinding binding) { } public void visitArray(ArrayBinding binding) { visitRaw(binding.leafComponentType()); } public void visitBase(BaseTypeBinding binding) { } public void visitMethod(MethodBinding binding) { if (binding.parameters != null) for (TypeBinding child : binding.parameters) { visitRaw(child); } visitRaw(binding.returnType); if (binding.thrownExceptions != null) for (TypeBinding child : binding.thrownExceptions) { visitRaw(child); } TypeVariableBinding[] typeVars = binding.typeVariables(); if (typeVars != null) for (TypeVariableBinding child : typeVars) { visitRaw(child.superclass); ReferenceBinding[] supers = child.superInterfaces(); if (supers != null) for (ReferenceBinding child2 : supers) { visitRaw(child2); } } } } private static MethodDeclaration createDelegateMethod(char[] name, EclipseNode typeNode, BindingTuple pair, CompilationResult compilationResult, EclipseNode annNode, DelegateReceiver delegateReceiver) { /* public ReturnType methodName(ParamType1 name1, ParamType2 name2, ...) throws T1, T2, ... { * (return) delegate.methodName(name1, name2); * } */ boolean isVarargs = (pair.base.modifiers & ClassFileConstants.AccVarargs) != 0; try { checkConflictOfTypeVarNames(pair, typeNode); } catch (CantMakeDelegates e) { annNode.addError("There's a conflict in the names of type parameters. Fix it by renaming the following type parameters of your class: " + e.conflicted); return null; } ASTNode source = annNode.get(); int pS = source.sourceStart, pE = source.sourceEnd; MethodBinding binding = pair.parameterized; MethodDeclaration method = new MethodDeclaration(compilationResult); setGeneratedBy(method, source); method.sourceStart = pS; method.sourceEnd = pE; method.modifiers = ClassFileConstants.AccPublic; method.returnType = makeType(binding.returnType, source, false); boolean isDeprecated = binding.isDeprecated(); method.selector = binding.selector; if (binding.thrownExceptions != null && binding.thrownExceptions.length > 0) { method.thrownExceptions = new TypeReference[binding.thrownExceptions.length]; for (int i = 0; i < method.thrownExceptions.length; i++) { method.thrownExceptions[i] = makeType(binding.thrownExceptions[i], source, false); } } MessageSend call = new MessageSend(); call.sourceStart = pS; call.sourceEnd = pE; call.nameSourcePosition = pos(source); setGeneratedBy(call, source); call.receiver = delegateReceiver.get(source, name); call.selector = binding.selector; if (binding.typeVariables != null && binding.typeVariables.length > 0) { method.typeParameters = new TypeParameter[binding.typeVariables.length]; call.typeArguments = new TypeReference[binding.typeVariables.length]; for (int i = 0; i < method.typeParameters.length; i++) { method.typeParameters[i] = new TypeParameter(); method.typeParameters[i].sourceStart = pS; method.typeParameters[i].sourceEnd = pE; setGeneratedBy(method.typeParameters[i], source); method.typeParameters[i].name = binding.typeVariables[i].sourceName; call.typeArguments[i] = new SingleTypeReference(binding.typeVariables[i].sourceName, pos(source)); setGeneratedBy(call.typeArguments[i], source); ReferenceBinding super1 = binding.typeVariables[i].superclass; ReferenceBinding[] super2 = binding.typeVariables[i].superInterfaces; if (super2 == null) super2 = new ReferenceBinding[0]; if (super1 != null || super2.length > 0) { int offset = super1 == null ? 0 : 1; method.typeParameters[i].bounds = new TypeReference[super2.length + offset - 1]; if (super1 != null) method.typeParameters[i].type = makeType(super1, source, false); else method.typeParameters[i].type = makeType(super2[0], source, false); int ctr = 0; for (int j = (super1 == null) ? 1 : 0; j < super2.length; j++) { method.typeParameters[i].bounds[ctr] = makeType(super2[j], source, false); method.typeParameters[i].bounds[ctr++].bits |= ASTNode.IsSuperType; } } } } if (isDeprecated) { method.annotations = new Annotation[] { generateDeprecatedAnnotation(source) }; } method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; if (binding.parameters != null && binding.parameters.length > 0) { method.arguments = new Argument[binding.parameters.length]; call.arguments = new Expression[method.arguments.length]; for (int i = 0; i < method.arguments.length; i++) { AbstractMethodDeclaration sourceElem; try { sourceElem = pair.base.sourceMethod(); } catch (Exception e) { sourceElem = null; } char[] argName; if (sourceElem == null) argName = ("arg" + i).toCharArray(); else { argName = sourceElem.arguments[i].name; } method.arguments[i] = new Argument( argName, pos(source), makeType(binding.parameters[i], source, false), ClassFileConstants.AccFinal); setGeneratedBy(method.arguments[i], source); call.arguments[i] = new SingleNameReference(argName, pos(source)); setGeneratedBy(call.arguments[i], source); } if (isVarargs) { method.arguments[method.arguments.length - 1].type.bits |= ASTNode.IsVarArgs; } } Statement body; if (method.returnType instanceof SingleTypeReference && ((SingleTypeReference)method.returnType).token == TypeConstants.VOID) { body = call; } else { body = new ReturnStatement(call, source.sourceStart, source.sourceEnd); setGeneratedBy(body, source); } method.statements = new Statement[] {body}; return method; } private static final class Reflection { public static final Method classScopeBuildFieldsAndMethodsMethod; static { Method m = null; try { m = ClassScope.class.getDeclaredMethod("buildFieldsAndMethods"); m.setAccessible(true); } catch (Throwable t) { // That's problematic, but as long as no local classes are used we don't actually need it. // Better fail on local classes than crash altogether. } classScopeBuildFieldsAndMethodsMethod = m; } } private static void addAllMethodBindings(List list, TypeBinding binding, Set banList, char[] fieldName, ASTNode responsible) throws DelegateRecursion { banList.addAll(METHODS_IN_OBJECT); addAllMethodBindings0(list, binding, banList, fieldName, responsible); } private static class DelegateRecursion extends Throwable { final char[] type, member; public DelegateRecursion(char[] type, char[] member) { this.type = type; this.member = member; } } private static void addAllMethodBindings0(List list, TypeBinding binding, Set banList, char[] fieldName, ASTNode responsible) throws DelegateRecursion { if (binding instanceof SourceTypeBinding) { ClassScope scope = ((SourceTypeBinding) binding).scope; if (scope != null) scope.environment().globalOptions.storeAnnotations = true; } if (binding == null) return; TypeBinding inner; if (binding instanceof ParameterizedTypeBinding) { inner = ((ParameterizedTypeBinding) binding).genericType(); } else { inner = binding; } if (inner instanceof SourceTypeBinding) { ClassScope cs = ((SourceTypeBinding)inner).scope; if (cs != null) { try { Reflection.classScopeBuildFieldsAndMethodsMethod.invoke(cs); } catch (Exception e) { // See 'Reflection' class for why we ignore this exception. } } } if (!(binding instanceof ReferenceBinding)) { return; } ReferenceBinding rb = (ReferenceBinding) binding; MethodBinding[] availableMethods = rb.availableMethods(); FieldBinding[] availableFields = rb.availableFields(); failIfContainsAnnotation(binding, availableMethods); failIfContainsAnnotation(binding, availableFields); MethodBinding[] parameterizedSigs = availableMethods; MethodBinding[] baseSigs = parameterizedSigs; if (binding instanceof ParameterizedTypeBinding) { baseSigs = ((ParameterizedTypeBinding)binding).genericType().availableMethods(); if (baseSigs.length != parameterizedSigs.length) { // The last known state of eclipse source says this can't happen, so we rely on it, // but if this invariant is broken, better to go with 'arg0' naming instead of crashing. baseSigs = parameterizedSigs; } } for (int i = 0; i < parameterizedSigs.length; i++) { MethodBinding mb = parameterizedSigs[i]; String sig = printSig(mb); if (mb.isStatic()) continue; if (mb.isBridge()) continue; if (mb.isConstructor()) continue; if (mb.isDefaultAbstract()) continue; if (!mb.isPublic()) continue; if (mb.isSynthetic()) continue; if (!banList.add(sig)) continue; // If add returns false, it was already in there. BindingTuple pair = new BindingTuple(mb, baseSigs[i], fieldName, responsible); list.add(pair); } addAllMethodBindings0(list, rb.superclass(), banList, fieldName, responsible); ReferenceBinding[] interfaces = rb.superInterfaces(); if (interfaces != null) { for (ReferenceBinding iface : interfaces) addAllMethodBindings0(list, iface, banList, fieldName, responsible); } } private static final char[] STRING_LOMBOK = new char[] {'l', 'o', 'm', 'b', 'o', 'k'}; private static final char[] STRING_EXPERIMENTAL = new char[] {'e', 'x', 'p', 'e', 'r', 'i', 'm', 'e', 'n', 't', 'a', 'l'}; private static final char[] STRING_DELEGATE = new char[] {'D', 'e', 'l', 'e', 'g', 'a', 't', 'e'}; private static void failIfContainsAnnotation(TypeBinding parent, Binding[] bindings) throws DelegateRecursion { if (bindings == null) return; for (Binding b : bindings) { AnnotationBinding[] anns = null; if (b instanceof MethodBinding) anns = ((MethodBinding) b).getAnnotations(); if (b instanceof FieldBinding) anns = ((FieldBinding) b).getAnnotations(); // anns = b.getAnnotations() would make a heck of a lot more sense, but that is a late addition to ecj, so would cause NoSuchMethodErrors! Don't use that! if (anns == null) continue; for (AnnotationBinding ann : anns) { char[][] name = null; try { name = ann.getAnnotationType().compoundName; } catch (Exception ignore) {} if (name == null || name.length < 2 || name.length > 3) continue; if (!Arrays.equals(STRING_LOMBOK, name[0])) continue; if (!Arrays.equals(STRING_DELEGATE, name[name.length - 1])) continue; if (name.length == 3 && !Arrays.equals(STRING_EXPERIMENTAL, name[1])) continue; throw new DelegateRecursion(parent.readableName(), b.readableName()); } } } private static final class BindingTuple { BindingTuple(MethodBinding parameterized, MethodBinding base, char[] fieldName, ASTNode responsible) { this.parameterized = parameterized; this.base = base; this.fieldName = fieldName; this.responsible = responsible; } final MethodBinding parameterized, base; final char[] fieldName; final ASTNode responsible; @Override public String toString() { return String.format("{param: %s, base: %s, fieldName: %s}", parameterized == null ? "(null)" : printSig(parameterized), base == null ? "(null)" : printSig(base), new String(fieldName)); } } private static final List METHODS_IN_OBJECT = Collections.unmodifiableList(Arrays.asList( "hashCode()", "canEqual(java.lang.Object)", //Not in j.l.Object, but it goes with hashCode and equals so if we ignore those two, we should ignore this one. "equals(java.lang.Object)", "wait()", "wait(long)", "wait(long, int)", "notify()", "notifyAll()", "toString()", "getClass()", "clone()", "finalize()")); private static String printSig(MethodBinding binding) { StringBuilder signature = new StringBuilder(); signature.append(binding.selector); signature.append("("); boolean first = true; if (binding.parameters != null) for (TypeBinding param : binding.parameters) { if (!first) signature.append(", "); first = false; signature.append(typeBindingToSignature(param)); } signature.append(")"); return signature.toString(); } private static String typeBindingToSignature(TypeBinding binding) { binding = binding.erasure(); if (binding != null && binding.isBaseType()) { return new String (binding.sourceName()); } else if (binding instanceof ReferenceBinding) { String pkg = binding.qualifiedPackageName() == null ? "" : new String(binding.qualifiedPackageName()); String qsn = binding.qualifiedSourceName() == null ? "" : new String(binding.qualifiedSourceName()); return pkg.isEmpty() ? qsn : (pkg + "." + qsn); } else if (binding instanceof ArrayBinding) { StringBuilder out = new StringBuilder(); out.append(typeBindingToSignature(binding.leafComponentType())); for (int i = 0; i < binding.dimensions(); i++) out.append("[]"); return out.toString(); } return ""; } private static boolean charArrayEquals(String s, char[] c) { if (s == null) return c == null; if (c == null) return false; if (s.length() != c.length) return false; for (int i = 0; i < s.length(); i++) if (s.charAt(i) != c[i]) return false; return true; } private enum DelegateReceiver { METHOD { public Expression get(final ASTNode source, char[] name) { MessageSend call = new MessageSend(); call.sourceStart = source.sourceStart; call.sourceEnd = source.sourceEnd; call.nameSourcePosition = pos(source); setGeneratedBy(call, source); call.selector = name; call.receiver = new ThisReference(source.sourceStart, source.sourceEnd); setGeneratedBy(call.receiver, source); return call; } }, FIELD { public Expression get(final ASTNode source, char[] name) { FieldReference fieldRef = new FieldReference(name, pos(source)); setGeneratedBy(fieldRef, source); fieldRef.receiver = new ThisReference(source.sourceStart, source.sourceEnd); setGeneratedBy(fieldRef.receiver, source); return fieldRef; } }; public abstract Expression get(final ASTNode source, char[] name); } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchDelegatePortal.java000066400000000000000000000053141312655740700271060ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import lombok.Lombok; public class PatchDelegatePortal { static final String CLASS_SCOPE = "org.eclipse.jdt.internal.compiler.lookup.ClassScope"; public static boolean handleDelegateForType(Object classScope) { try { return (Boolean) Reflection.handleDelegateForType.invoke(null, classScope); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. return false; } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(Reflection.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. return false; } } private static final class Reflection { public static final Method handleDelegateForType; public static final Throwable problem; static { Method m = null; Throwable problem_ = null; try { m = PatchDelegate.class.getMethod("handleDelegateForType", Class.forName(CLASS_SCOPE)); } catch (Throwable t) { // That's problematic, but as long as no local classes are used we don't actually need it. // Better fail on local classes than crash altogether. problem_ = t; } handleDelegateForType = m; problem = problem_; } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchDiagnostics.java000066400000000000000000000043731312655740700264650ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; public class PatchDiagnostics { /** * * org.eclipse.jdt.core.dom.ASTNode#setSourceRange starts off doing some sanity checks on the input arguments, and, if these fail the sanity check, * a {@code IllegalArgumentException} is thrown. However, these IAEs do not have any message and are thus pretty much useless. We do the exact same * checks, and throw the exact same exception (thus, effectively, we don't change how eclipse operates), but, we do provide a useful message. */ public static boolean setSourceRangeCheck(Object astNode, int startPosition, int length) { if (startPosition >= 0 && length < 0) { throw new IllegalArgumentException("startPos = " + startPosition + " and length is " + length + ".\n" + "This breaks the rule that lengths are not allowed to be negative. Affected Node:\n" + astNode); } if (startPosition < 0 && length != 0) { throw new IllegalArgumentException("startPos = " + startPosition + " and length is " + length + ".\n" + "This breaks the rule that length must be 0 if startPosition is negative. Affected Node:\n" + astNode); } return false; } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchExtensionMethod.java000066400000000000000000000352371312655740700273360ustar00rootroot00000000000000/* * Copyright (C) 2012-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import static lombok.eclipse.handlers.EclipseHandlerUtil.createAnnotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.AnnotationValues.AnnotationValueDecodeFail; import lombok.core.FieldAugment; import lombok.eclipse.EclipseAST; import lombok.eclipse.EclipseNode; import lombok.eclipse.TransformEclipseAST; import lombok.eclipse.handlers.EclipseHandlerUtil; import lombok.experimental.ExtensionMethod; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.NameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SuperReference; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.lookup.Binding; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.ProblemMethodBinding; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.Scope; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; public class PatchExtensionMethod { static class Extension { List extensionMethods; boolean suppressBaseMethods; } private static class PostponedNoMethodError implements PostponedError { private final ProblemReporter problemReporter; private final WeakReference messageSendRef; private final TypeBinding recType; private final TypeBinding[] params; PostponedNoMethodError(ProblemReporter problemReporter, MessageSend messageSend, TypeBinding recType, TypeBinding[] params) { this.problemReporter = problemReporter; this.messageSendRef = new WeakReference(messageSend); this.recType = recType; this.params = params; } public void fire() { MessageSend messageSend = messageSendRef.get(); if (messageSend != null) problemReporter.errorNoMethodFor(messageSend, recType, params); } } private static class PostponedInvalidMethodError implements PostponedError { private final ProblemReporter problemReporter; private final WeakReference messageSendRef; private final MethodBinding method; private final Scope scope; private static final Method shortMethod = getMethod("invalidMethod", MessageSend.class, MethodBinding.class); private static final Method longMethod = getMethod("invalidMethod", MessageSend.class, MethodBinding.class, Scope.class); private static Method getMethod(String name, Class... types) { try { Method m = ProblemReporter.class.getMethod(name, types); m.setAccessible(true); return m; } catch (Exception e) { return null; } } PostponedInvalidMethodError(ProblemReporter problemReporter, MessageSend messageSend, MethodBinding method, Scope scope) { this.problemReporter = problemReporter; this.messageSendRef = new WeakReference(messageSend); this.method = method; this.scope = scope; } static void invoke(ProblemReporter problemReporter, MessageSend messageSend, MethodBinding method, Scope scope) { if (messageSend != null) { try { if (shortMethod != null) shortMethod.invoke(problemReporter, messageSend, method); else if (longMethod != null) longMethod.invoke(problemReporter, messageSend, method, scope); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof Error) throw (Error) t; if (t instanceof RuntimeException) throw (RuntimeException) t; throw new RuntimeException(t); } } } public void fire() { MessageSend messageSend = messageSendRef.get(); invoke(problemReporter, messageSend, method, scope); } } private static interface PostponedError { public void fire(); } public static EclipseNode getTypeNode(TypeDeclaration decl) { CompilationUnitDeclaration cud = decl.scope.compilationUnitScope().referenceContext; EclipseAST astNode = TransformEclipseAST.getAST(cud, false); EclipseNode node = astNode.get(decl); if (node == null) { astNode = TransformEclipseAST.getAST(cud, true); node = astNode.get(decl); } return node; } public static Annotation getAnnotation(Class expectedType, EclipseNode node) { TypeDeclaration decl = (TypeDeclaration) node.get(); if (decl.annotations != null) for (Annotation ann : decl.annotations) { if (EclipseHandlerUtil.typeMatches(expectedType, node, ann.type)) return ann; } return null; } static EclipseNode upToType(EclipseNode typeNode) { EclipseNode node = typeNode; do { node = node.up(); } while ((node != null) && (node.getKind() != Kind.TYPE)); return node; } static List getApplicableExtensionMethods(EclipseNode typeNode, Annotation ann, TypeBinding receiverType) { List extensions = new ArrayList(); if ((typeNode != null) && (ann != null) && (receiverType != null)) { BlockScope blockScope = ((TypeDeclaration) typeNode.get()).initializerScope; EclipseNode annotationNode = typeNode.getNodeFor(ann); AnnotationValues annotation = createAnnotation(ExtensionMethod.class, annotationNode); boolean suppressBaseMethods = false; try { suppressBaseMethods = annotation.getInstance().suppressBaseMethods(); } catch (AnnotationValueDecodeFail fail) { fail.owner.setError(fail.getMessage(), fail.idx); } for (Object extensionMethodProvider : annotation.getActualExpressions("value")) { if (extensionMethodProvider instanceof ClassLiteralAccess) { TypeBinding binding = ((ClassLiteralAccess) extensionMethodProvider).type.resolveType(blockScope); if (binding == null) continue; if (!binding.isClass() && !binding.isEnum()) continue; Extension e = new Extension(); e.extensionMethods = getApplicableExtensionMethodsDefinedInProvider(typeNode, (ReferenceBinding) binding, receiverType); e.suppressBaseMethods = suppressBaseMethods; extensions.add(e); } } } return extensions; } private static List getApplicableExtensionMethodsDefinedInProvider(EclipseNode typeNode, ReferenceBinding extensionMethodProviderBinding, TypeBinding receiverType) { List extensionMethods = new ArrayList(); CompilationUnitScope cuScope = ((CompilationUnitDeclaration) typeNode.top().get()).scope; for (MethodBinding method : extensionMethodProviderBinding.methods()) { if (!method.isStatic()) continue; if (!method.isPublic()) continue; if (method.parameters == null || method.parameters.length == 0) continue; TypeBinding firstArgType = method.parameters[0]; if (receiverType.isProvablyDistinct(firstArgType) && !receiverType.isCompatibleWith(firstArgType.erasure())) continue; TypeBinding[] argumentTypes = Arrays.copyOfRange(method.parameters, 1, method.parameters.length); if ((receiverType instanceof ReferenceBinding) && ((ReferenceBinding) receiverType).getExactMethod(method.selector, argumentTypes, cuScope) != null) continue; extensionMethods.add(method); } return extensionMethods; } private static final FieldAugment MessageSend_postponedErrors = FieldAugment.augment(MessageSend.class, PostponedError.class, "lombok$postponedErrors"); public static void errorNoMethodFor(ProblemReporter problemReporter, MessageSend messageSend, TypeBinding recType, TypeBinding[] params) { MessageSend_postponedErrors.set(messageSend, new PostponedNoMethodError(problemReporter, messageSend, recType, params)); } public static void invalidMethod(ProblemReporter problemReporter, MessageSend messageSend, MethodBinding method) { MessageSend_postponedErrors.set(messageSend, new PostponedInvalidMethodError(problemReporter, messageSend, method, null)); } public static void invalidMethod(ProblemReporter problemReporter, MessageSend messageSend, MethodBinding method, Scope scope) { MessageSend_postponedErrors.set(messageSend, new PostponedInvalidMethodError(problemReporter, messageSend, method, scope)); } public static TypeBinding resolveType(TypeBinding resolvedType, MessageSend methodCall, BlockScope scope) { List extensions = new ArrayList(); TypeDeclaration decl = scope.classScope().referenceContext; EclipseNode owningType = null; for (EclipseNode typeNode = getTypeNode(decl); typeNode != null; typeNode = upToType(typeNode)) { Annotation ann = getAnnotation(ExtensionMethod.class, typeNode); if (ann != null) { extensions.addAll(0, getApplicableExtensionMethods(typeNode, ann, methodCall.receiver.resolvedType)); if (owningType == null) owningType = typeNode; } } boolean skip = false; if (methodCall.receiver instanceof ThisReference && (((ThisReference)methodCall.receiver).bits & ASTNode.IsImplicitThis) != 0) skip = true; if (methodCall.receiver instanceof SuperReference) skip = true; if (methodCall.receiver instanceof NameReference) { Binding binding = ((NameReference)methodCall.receiver).binding; if (binding instanceof TypeBinding) skip = true; } if (!skip) for (Extension extension : extensions) { if (!extension.suppressBaseMethods && !(methodCall.binding instanceof ProblemMethodBinding)) continue; for (MethodBinding extensionMethod : extension.extensionMethods) { if (!Arrays.equals(methodCall.selector, extensionMethod.selector)) continue; MessageSend_postponedErrors.clear(methodCall); if (methodCall.receiver instanceof ThisReference) { methodCall.receiver.bits &= ~ASTNode.IsImplicitThis; } List arguments = new ArrayList(); arguments.add(methodCall.receiver); if (methodCall.arguments != null) arguments.addAll(Arrays.asList(methodCall.arguments)); List argumentTypes = new ArrayList(); for (Expression argument : arguments) { if (argument.resolvedType != null) argumentTypes.add(argument.resolvedType); // TODO: Instead of just skipping nulls entirely, there is probably a 'unresolved type' placeholder. THAT is what we ought to be adding here! } Expression[] originalArgs = methodCall.arguments; methodCall.arguments = arguments.toArray(new Expression[0]); MethodBinding fixedBinding = scope.getMethod(extensionMethod.declaringClass, methodCall.selector, argumentTypes.toArray(new TypeBinding[0]), methodCall); if (fixedBinding instanceof ProblemMethodBinding) { methodCall.arguments = originalArgs; if (fixedBinding.declaringClass != null) { PostponedInvalidMethodError.invoke(scope.problemReporter(), methodCall, fixedBinding, scope); } } else { for (int i = 0, iend = arguments.size(); i < iend; i++) { Expression arg = arguments.get(i); if (fixedBinding.parameters[i].isArrayType() != arg.resolvedType.isArrayType()) break; if (arg instanceof MessageSend) { ((MessageSend) arg).valueCast = arg.resolvedType; } if (!fixedBinding.parameters[i].isBaseType() && arg.resolvedType.isBaseType()) { int id = arg.resolvedType.id; arg.implicitConversion = TypeIds.BOXING | (id + (id << 4)); // magic see TypeIds } else if (fixedBinding.parameters[i].isBaseType() && !arg.resolvedType.isBaseType()) { int id = fixedBinding.parameters[i].id; arg.implicitConversion = TypeIds.UNBOXING | (id + (id << 4)); // magic see TypeIds } } methodCall.receiver = createNameRef(extensionMethod.declaringClass, methodCall); methodCall.actualReceiverType = extensionMethod.declaringClass; methodCall.binding = fixedBinding; methodCall.resolvedType = methodCall.binding.returnType; } return methodCall.resolvedType; } } PostponedError error = MessageSend_postponedErrors.get(methodCall); if (error != null) error.fire(); MessageSend_postponedErrors.clear(methodCall); return resolvedType; } private static NameReference createNameRef(TypeBinding typeBinding, ASTNode source) { long p = ((long) source.sourceStart << 32) | source.sourceEnd; char[] pkg = typeBinding.qualifiedPackageName(); char[] basename = typeBinding.qualifiedSourceName(); StringBuilder sb = new StringBuilder(); if (pkg != null) sb.append(pkg); if (sb.length() > 0) sb.append("."); sb.append(basename); String tName = sb.toString(); if (tName.indexOf('.') == -1) { return new SingleNameReference(basename, p); } else { char[][] sources; String[] in = tName.split("\\."); sources = new char[in.length][]; for (int i = 0; i < in.length; i++) sources[i] = in[i].toCharArray(); long[] poss = new long[in.length]; Arrays.fill(poss, p); return new QualifiedNameReference(sources, poss, source.sourceStart, source.sourceEnd); } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchExtensionMethodCompletionProposal.java000066400000000000000000000265001312655740700331010ustar00rootroot00000000000000/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import static lombok.eclipse.agent.PatchExtensionMethod.*; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.eclipse.EclipseNode; import lombok.eclipse.agent.PatchExtensionMethod.Extension; import lombok.experimental.ExtensionMethod; import org.eclipse.jdt.core.CompletionProposal; import org.eclipse.jdt.internal.codeassist.InternalCompletionContext; import org.eclipse.jdt.internal.codeassist.InternalCompletionProposal; import org.eclipse.jdt.internal.codeassist.InternalExtendedCompletionContext; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnMemberAccess; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnQualifiedNameReference; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnSingleNameReference; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.NameReference; import org.eclipse.jdt.internal.compiler.ast.SuperReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.lookup.Binding; import org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.Scope; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.lookup.VariableBinding; import org.eclipse.jdt.internal.core.SearchableEnvironment; import org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal; import org.eclipse.jdt.ui.text.java.CompletionProposalCollector; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; public class PatchExtensionMethodCompletionProposal { public static IJavaCompletionProposal[] getJavaCompletionProposals(IJavaCompletionProposal[] javaCompletionProposals, CompletionProposalCollector completionProposalCollector) { List proposals = new ArrayList(Arrays.asList(javaCompletionProposals)); if (canExtendCodeAssist(proposals)) { IJavaCompletionProposal firstProposal = proposals.get(0); int replacementOffset = getReplacementOffset(firstProposal); for (Extension extension : getExtensionMethods(completionProposalCollector)) { for (MethodBinding method : extension.extensionMethods) { ExtensionMethodCompletionProposal newProposal = new ExtensionMethodCompletionProposal(replacementOffset); copyNameLookupAndCompletionEngine(completionProposalCollector, firstProposal, newProposal); ASTNode node = getAssistNode(completionProposalCollector); newProposal.setMethodBinding(method, node); createAndAddJavaCompletionProposal(completionProposalCollector, newProposal, proposals); } } } return proposals.toArray(new IJavaCompletionProposal[proposals.size()]); } private static List getExtensionMethods(CompletionProposalCollector completionProposalCollector) { List extensions = new ArrayList(); ClassScope classScope = getClassScope(completionProposalCollector); if (classScope != null) { TypeDeclaration decl = classScope.referenceContext; TypeBinding firstParameterType = getFirstParameterType(decl, completionProposalCollector); for (EclipseNode typeNode = getTypeNode(decl); typeNode != null; typeNode = upToType(typeNode)) { Annotation ann = getAnnotation(ExtensionMethod.class, typeNode); extensions.addAll(0, getApplicableExtensionMethods(typeNode, ann, firstParameterType)); } } return extensions; } static TypeBinding getFirstParameterType(TypeDeclaration decl, CompletionProposalCollector completionProposalCollector) { TypeBinding firstParameterType = null; ASTNode node = getAssistNode(completionProposalCollector); if (node == null) return null; if (!(node instanceof CompletionOnQualifiedNameReference) && !(node instanceof CompletionOnSingleNameReference) && !(node instanceof CompletionOnMemberAccess)) return null; // Never offer on 'super.'. if (node instanceof FieldReference && ((FieldReference)node).receiver instanceof SuperReference) return null; if (node instanceof NameReference) { Binding binding = ((NameReference) node).binding; // Unremark next block to allow a 'blank' autocomplete to list any extensions that apply to the current scope, but make sure we're not in a static context first, which this doesn't do. // Lacking good use cases, and having this particular concept be a little tricky on javac, means for now we don't support extension methods like this. this.X() will be fine, though. /* if ((node instanceof SingleNameReference) && (((SingleNameReference) node).token.length == 0)) { firstParameterType = decl.binding; } else */if (binding instanceof VariableBinding) { firstParameterType = ((VariableBinding) binding).type; } } else if (node instanceof FieldReference) { firstParameterType = ((FieldReference) node).actualReceiverType; } return firstParameterType; } private static ASTNode getAssistNode(CompletionProposalCollector completionProposalCollector) { try { InternalCompletionContext context = (InternalCompletionContext) Reflection.contextField.get(completionProposalCollector); InternalExtendedCompletionContext extendedContext = (InternalExtendedCompletionContext) Reflection.extendedContextField.get(context); if (extendedContext == null) return null; return (ASTNode) Reflection.assistNodeField.get(extendedContext); } catch (Exception ignore) { return null; } } private static ClassScope getClassScope(CompletionProposalCollector completionProposalCollector) { ClassScope scope = null; try { InternalCompletionContext context = (InternalCompletionContext) Reflection.contextField.get(completionProposalCollector); InternalExtendedCompletionContext extendedContext = (InternalExtendedCompletionContext) Reflection.extendedContextField.get(context); if (extendedContext != null) { Scope assistScope = ((Scope) Reflection.assistScopeField.get(extendedContext)); if (assistScope != null) { scope = assistScope.classScope(); } } } catch (IllegalAccessException ignore) { // ignore } return scope; } private static void copyNameLookupAndCompletionEngine(CompletionProposalCollector completionProposalCollector, IJavaCompletionProposal proposal, InternalCompletionProposal newProposal) { try { InternalCompletionContext context = (InternalCompletionContext) Reflection.contextField.get(completionProposalCollector); InternalExtendedCompletionContext extendedContext = (InternalExtendedCompletionContext) Reflection.extendedContextField.get(context); LookupEnvironment lookupEnvironment = (LookupEnvironment) Reflection.lookupEnvironmentField.get(extendedContext); Reflection.nameLookupField.set(newProposal, ((SearchableEnvironment) lookupEnvironment.nameEnvironment).nameLookup); Reflection.completionEngineField.set(newProposal, lookupEnvironment.typeRequestor); } catch (IllegalAccessException ignore) { // ignore } } private static void createAndAddJavaCompletionProposal(CompletionProposalCollector completionProposalCollector, CompletionProposal newProposal, List proposals) { try { proposals.add((IJavaCompletionProposal) Reflection.createJavaCompletionProposalMethod.invoke(completionProposalCollector, newProposal)); } catch (Exception ignore) { // ignore } } private static boolean canExtendCodeAssist(List proposals) { return !proposals.isEmpty() && Reflection.isComplete(); } private static int getReplacementOffset(Object proposal) { try { return Reflection.replacementOffsetField.getInt(proposal); } catch (Exception ignore) { return 0; } } static class Reflection { public static final Field replacementOffsetField; public static final Field contextField; public static final Field extendedContextField; public static final Field assistNodeField; public static final Field assistScopeField; public static final Field lookupEnvironmentField; public static final Field completionEngineField; public static final Field nameLookupField; public static final Method createJavaCompletionProposalMethod; static { replacementOffsetField = accessField(AbstractJavaCompletionProposal.class, "fReplacementOffset"); contextField = accessField(CompletionProposalCollector.class, "fContext"); extendedContextField = accessField(InternalCompletionContext.class, "extendedContext"); assistNodeField = accessField(InternalExtendedCompletionContext.class, "assistNode"); assistScopeField = accessField(InternalExtendedCompletionContext.class, "assistScope"); lookupEnvironmentField = accessField(InternalExtendedCompletionContext.class, "lookupEnvironment"); completionEngineField = accessField(InternalCompletionProposal.class, "completionEngine"); nameLookupField = accessField(InternalCompletionProposal.class, "nameLookup"); createJavaCompletionProposalMethod = accessMethod(CompletionProposalCollector.class, "createJavaCompletionProposal", CompletionProposal.class); } static boolean isComplete() { Object[] requiredFieldsAndMethods = { replacementOffsetField, contextField, extendedContextField, assistNodeField, assistScopeField, lookupEnvironmentField, completionEngineField, nameLookupField, createJavaCompletionProposalMethod }; for (Object o : requiredFieldsAndMethods) if (o == null) return false; return true; } private static Field accessField(Class clazz, String fieldName) { try { return makeAccessible(clazz.getDeclaredField(fieldName)); } catch (Exception e) { return null; } } private static Method accessMethod(Class clazz, String methodName, Class parameter) { try { return makeAccessible(clazz.getDeclaredMethod(methodName, parameter)); } catch (Exception e) { return null; } } private static T makeAccessible(T object) { object.setAccessible(true); return object; } } } PatchExtensionMethodCompletionProposalPortal.java000066400000000000000000000064371312655740700342130ustar00rootroot00000000000000lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/* * Copyright (C) 2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import lombok.Lombok; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; public class PatchExtensionMethodCompletionProposalPortal { private static final String COMPLETION_PROPOSAL_COLLECTOR = "org.eclipse.jdt.ui.text.java.CompletionProposalCollector"; private static final String I_JAVA_COMPLETION_PROPOSAL_ARRAY = "[Lorg.eclipse.jdt.ui.text.java.IJavaCompletionProposal;"; public static IJavaCompletionProposal[] getJavaCompletionProposals(Object[] javaCompletionProposals, Object completionProposalCollector) { try { return (IJavaCompletionProposal[]) ReflectionForUi.getJavaCompletionProposals.invoke(null, javaCompletionProposals, completionProposalCollector); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. return (IJavaCompletionProposal[]) javaCompletionProposals; } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(ReflectionForUi.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. return (IJavaCompletionProposal[]) javaCompletionProposals; } } private static final class ReflectionForUi { public static final Method getJavaCompletionProposals; public static final Throwable problem; static { Method p = null; Throwable problem_ = null; try { p = PatchExtensionMethodCompletionProposal.class.getMethod("getJavaCompletionProposals", Class.forName(I_JAVA_COMPLETION_PROPOSAL_ARRAY), Class.forName(COMPLETION_PROPOSAL_COLLECTOR)); } catch (Throwable t) { // That's problematic, but as long as no local classes are used we don't actually need it. // Better fail on local classes than crash altogether. problem_ = t; } getJavaCompletionProposals = p; problem = problem_; } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchExtensionMethodPortal.java000066400000000000000000000104571312655740700305150ustar00rootroot00000000000000package lombok.eclipse.agent; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import lombok.Lombok; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; public class PatchExtensionMethodPortal { private static final String TYPE_BINDING = "org.eclipse.jdt.internal.compiler.lookup.TypeBinding"; private static final String TYPE_BINDING_ARRAY = "[Lorg.eclipse.jdt.internal.compiler.lookup.TypeBinding;"; private static final String MESSAGE_SEND = "org.eclipse.jdt.internal.compiler.ast.MessageSend"; private static final String BLOCK_SCOPE = "org.eclipse.jdt.internal.compiler.lookup.BlockScope"; private static final String METHOD_BINDING = "org.eclipse.jdt.internal.compiler.lookup.MethodBinding"; private static final String PROBLEM_REPORTER = "org.eclipse.jdt.internal.compiler.problem.ProblemReporter"; public static TypeBinding resolveType(Object resolvedType, Object methodCall, Object scope) { try { return (TypeBinding) Reflection.resolveType.invoke(null, resolvedType, methodCall, scope); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. return (TypeBinding) resolvedType; } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(Reflection.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. return (TypeBinding)resolvedType; } } public static void errorNoMethodFor(Object problemReporter, Object messageSend, Object recType, Object params) { try { Reflection.errorNoMethodFor.invoke(null, problemReporter, messageSend, recType, params); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(Reflection.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } } public static void invalidMethod(Object problemReporter, Object messageSend, Object method) { try { Reflection.invalidMethod.invoke(null, problemReporter, messageSend, method); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(Reflection.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } } private static final class Reflection { public static final Method resolveType, errorNoMethodFor, invalidMethod; public static final Throwable problem; static { Method m = null, n = null, o = null; Throwable problem_ = null; try { m = PatchExtensionMethod.class.getMethod("resolveType", Class.forName(TYPE_BINDING), Class.forName(MESSAGE_SEND), Class.forName(BLOCK_SCOPE)); n = PatchExtensionMethod.class.getMethod("errorNoMethodFor", Class.forName(PROBLEM_REPORTER), Class.forName(MESSAGE_SEND), Class.forName(TYPE_BINDING), Class.forName(TYPE_BINDING_ARRAY)); o = PatchExtensionMethod.class.getMethod("invalidMethod", Class.forName(PROBLEM_REPORTER), Class.forName(MESSAGE_SEND), Class.forName(METHOD_BINDING)); } catch (Throwable t) { // That's problematic, but as long as no local classes are used we don't actually need it. // Better fail on local classes than crash altogether. problem_ = t; } resolveType = m; errorNoMethodFor = n; invalidMethod = o; problem = problem_; } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchFixesShadowLoaded.java000066400000000000000000000044711312655740700275520ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import lombok.core.DiagnosticsReceiver; import lombok.core.PostCompiler; import lombok.core.Version; public class PatchFixesShadowLoaded { public static String addLombokNotesToEclipseAboutDialog(String origReturnValue, String key) { if ("aboutText".equals(key)) { return origReturnValue + "\n\nLombok " + Version.getFullVersion() + " is installed. https://projectlombok.org/"; } return origReturnValue; } public static byte[] runPostCompiler(byte[] bytes, String fileName) { byte[] transformed = PostCompiler.applyTransformations(bytes, fileName, DiagnosticsReceiver.CONSOLE); return transformed == null ? bytes : transformed; } public static OutputStream runPostCompiler(OutputStream out) throws IOException { return PostCompiler.wrapOutputStream(out, "TEST", DiagnosticsReceiver.CONSOLE); } public static BufferedOutputStream runPostCompiler(BufferedOutputStream out, String path, String name) throws IOException { String fileName = path + "/" + name; return new BufferedOutputStream(PostCompiler.wrapOutputStream(out, fileName, DiagnosticsReceiver.CONSOLE)); } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchVal.java000066400000000000000000000265741312655740700247470ustar00rootroot00000000000000/* * Copyright (C) 2010-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.ForeachStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.eclipse.jdt.internal.compiler.lookup.Binding; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import java.lang.reflect.Field; import static lombok.eclipse.Eclipse.poss; import static lombok.eclipse.handlers.EclipseHandlerUtil.makeType; public class PatchVal { // This is half of the work for 'val' support - the other half is in PatchValEclipse. This half is enough for ecj. // Creates a copy of the 'initialization' field on a LocalDeclaration if the type of the LocalDeclaration is 'val', because the completion parser will null this out, // which in turn stops us from inferring the intended type for 'val x = 5;'. We look at the copy. // Also patches local declaration to not call .resolveType() on the initializer expression if we've already done so (calling it twice causes weird errors), // and patches .resolve() on LocalDeclaration itself to just-in-time replace the 'val' vartype with the right one. public static TypeBinding skipResolveInitializerIfAlreadyCalled(Expression expr, BlockScope scope) { if (expr.resolvedType != null) return expr.resolvedType; try { return expr.resolveType(scope); } catch (NullPointerException e) { return null; } catch (ArrayIndexOutOfBoundsException e) { // This will occur internally due to for example 'val x = mth("X");', where mth takes 2 arguments. return null; } } public static TypeBinding skipResolveInitializerIfAlreadyCalled2(Expression expr, BlockScope scope, LocalDeclaration decl) { if (decl != null && LocalDeclaration.class.equals(decl.getClass()) && expr.resolvedType != null) return expr.resolvedType; try { return expr.resolveType(scope); } catch (NullPointerException e) { return null; } catch (ArrayIndexOutOfBoundsException e) { // This will occur internally due to for example 'val x = mth("X");', where mth takes 2 arguments. return null; } } public static boolean matches(String key, char[] array) { if (array == null || key.length() != array.length) return false; for (int i = 0; i < array.length; i++) { if (key.charAt(i) != array[i]) return false; } return true; } public static boolean couldBe(String key, TypeReference ref) { String[] keyParts = key.split("\\."); if (ref instanceof SingleTypeReference) { char[] token = ((SingleTypeReference)ref).token; return matches(keyParts[keyParts.length - 1], token); } if (ref instanceof QualifiedTypeReference) { char[][] tokens = ((QualifiedTypeReference)ref).tokens; if (keyParts.length != tokens.length) return false; for(int i = 0; i < tokens.length; ++i) { String part = keyParts[i]; char[] token = tokens[i]; if (!matches(part, token)) return false; } return true; } return false; } private static boolean is(TypeReference ref, BlockScope scope, String key) { if (!couldBe(key, ref)) return false; TypeBinding resolvedType = ref.resolvedType; if (resolvedType == null) resolvedType = ref.resolveType(scope, false); if (resolvedType == null) return false; char[] pkg = resolvedType.qualifiedPackageName(); char[] nm = resolvedType.qualifiedSourceName(); int pkgFullLength = pkg.length > 0 ? pkg.length + 1: 0; char[] fullName = new char[pkgFullLength + nm.length]; if(pkg.length > 0) { System.arraycopy(pkg, 0, fullName, 0, pkg.length); fullName[pkg.length] = '.'; } System.arraycopy(nm, 0, fullName, pkgFullLength, nm.length); return matches(key, fullName); } public static final class Reflection { private static final Field initCopyField, iterableCopyField; static { Field a = null, b = null; try { a = LocalDeclaration.class.getDeclaredField("$initCopy"); b = LocalDeclaration.class.getDeclaredField("$iterableCopy"); } catch (Throwable t) { //ignore - no $initCopy exists when running in ecj. } initCopyField = a; iterableCopyField = b; } } public static boolean handleValForLocalDeclaration(LocalDeclaration local, BlockScope scope) { if (local == null || !LocalDeclaration.class.equals(local.getClass())) return false; boolean decomponent = false; boolean val = isVal(local, scope); boolean var = isVar(local, scope); if (!(val || var)) return false; StackTraceElement[] st = new Throwable().getStackTrace(); for (int i = 0; i < st.length - 2 && i < 10; i++) { if (st[i].getClassName().equals("lombok.launch.PatchFixesHider$Val")) { boolean valInForStatement = val && st[i + 1].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration") && st[i + 2].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.ForStatement"); if (valInForStatement) return false; break; } } Expression init = local.initialization; if (init == null && Reflection.initCopyField != null) { try { init = (Expression) Reflection.initCopyField.get(local); } catch (Exception e) { // init remains null. } } if (init == null && Reflection.iterableCopyField != null) { try { init = (Expression) Reflection.iterableCopyField.get(local); decomponent = true; } catch (Exception e) { // init remains null. } } TypeReference replacement = null; if (init != null) { if (init.getClass().getName().equals("org.eclipse.jdt.internal.compiler.ast.LambdaExpression")) { return false; } TypeBinding resolved = null; try { resolved = decomponent ? getForEachComponentType(init, scope) : resolveForExpression(init, scope); } catch (NullPointerException e) { // This definitely occurs if as part of resolving the initializer expression, a // lambda expression in it must also be resolved (such as when lambdas are part of // a ternary expression). This can't result in a viable 'val' matching, so, we // just go with 'Object' and let the IDE print the appropriate errors. resolved = null; } if (resolved != null) { try { replacement = makeType(resolved, local.type, false); } catch (Exception e) { // Some type thing failed. It might be an IntersectionType } } } if(val) local.modifiers |= ClassFileConstants.AccFinal; local.annotations = addValAnnotation(local.annotations, local.type, scope); local.type = replacement != null ? replacement : new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(local.type, 3)); return false; } private static boolean isVar(LocalDeclaration local, BlockScope scope) { return is(local.type, scope, "lombok.experimental.var"); } private static boolean isVal(LocalDeclaration local, BlockScope scope) { return is(local.type, scope, "lombok.val"); } public static boolean handleValForForEach(ForeachStatement forEach, BlockScope scope) { if (forEach.elementVariable == null) return false; boolean val = isVal(forEach.elementVariable, scope); boolean var = isVar(forEach.elementVariable, scope); if (!(val || var)) return false; TypeBinding component = getForEachComponentType(forEach.collection, scope); if (component == null) return false; TypeReference replacement = makeType(component, forEach.elementVariable.type, false); if (val) forEach.elementVariable.modifiers |= ClassFileConstants.AccFinal; forEach.elementVariable.annotations = addValAnnotation(forEach.elementVariable.annotations, forEach.elementVariable.type, scope); forEach.elementVariable.type = replacement != null ? replacement : new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(forEach.elementVariable.type, 3)); return false; } private static Annotation[] addValAnnotation(Annotation[] originals, TypeReference originalRef, BlockScope scope) { Annotation[] newAnn; if (originals != null) { newAnn = new Annotation[1 + originals.length]; System.arraycopy(originals, 0, newAnn, 0, originals.length); } else { newAnn = new Annotation[1]; } newAnn[newAnn.length - 1] = new org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation(originalRef, originalRef.sourceStart); return newAnn; } private static TypeBinding getForEachComponentType(Expression collection, BlockScope scope) { if (collection != null) { TypeBinding resolved = collection.resolvedType; if (resolved == null) resolved = resolveForExpression(collection, scope); if (resolved == null) return null; if (resolved.isArrayType()) { resolved = ((ArrayBinding) resolved).elementsType(); return resolved; } else if (resolved instanceof ReferenceBinding) { ReferenceBinding iterableType = ((ReferenceBinding)resolved).findSuperTypeOriginatingFrom(TypeIds.T_JavaLangIterable, false); TypeBinding[] arguments = null; if (iterableType != null) switch (iterableType.kind()) { case Binding.GENERIC_TYPE : // for (T t : Iterable) - in case used inside Iterable itself arguments = iterableType.typeVariables(); break; case Binding.PARAMETERIZED_TYPE : // for(E e : Iterable) arguments = ((ParameterizedTypeBinding)iterableType).arguments; break; case Binding.RAW_TYPE : // for(Object e : Iterable) return null; } if (arguments != null && arguments.length == 1) { return arguments[0]; } } } return null; } private static TypeBinding resolveForExpression(Expression collection, BlockScope scope) { try { return collection.resolveType(scope); } catch (ArrayIndexOutOfBoundsException e) { // Known cause of issues; for example: val e = mth("X"), where mth takes 2 arguments. return null; } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchValEclipse.java000066400000000000000000000262211312655740700262410ustar00rootroot00000000000000/* * Copyright (C) 2010-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * Thanks to Stephen Haberman for a patch to solve some NPEs in Eclipse. */ package lombok.eclipse.agent; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import lombok.Lombok; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.IExtendedModifier; import org.eclipse.jdt.core.dom.MarkerAnnotation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationStatement; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ForeachStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.parser.Parser; public class PatchValEclipse { public static void copyInitializationOfForEachIterable(Parser parser) { ASTNode[] astStack; int astPtr; try { astStack = (ASTNode[]) Reflection.astStackField.get(parser); astPtr = (Integer) Reflection.astPtrField.get(parser); } catch (Exception e) { // Most likely we're in ecj or some other plugin usage of the eclipse compiler. No need for this. return; } ForeachStatement foreachDecl = (ForeachStatement) astStack[astPtr]; ASTNode init = foreachDecl.collection; if (init == null) return; boolean val = couldBeVal(foreachDecl.elementVariable.type); boolean var = couldBeVar(foreachDecl.elementVariable.type); if (foreachDecl.elementVariable == null || !(val || var)) return; try { if (Reflection.iterableCopyField != null) Reflection.iterableCopyField.set(foreachDecl.elementVariable, init); } catch (Exception e) { // In ecj mode this field isn't there and we don't need the copy anyway, so, we ignore the exception. } } public static void copyInitializationOfLocalDeclaration(Parser parser) { ASTNode[] astStack; int astPtr; try { astStack = (ASTNode[]) Reflection.astStackField.get(parser); astPtr = (Integer)Reflection.astPtrField.get(parser); } catch (Exception e) { // Most likely we're in ecj or some other plugin usage of the eclipse compiler. No need for this. return; } AbstractVariableDeclaration variableDecl = (AbstractVariableDeclaration) astStack[astPtr]; if (!(variableDecl instanceof LocalDeclaration)) return; ASTNode init = variableDecl.initialization; if (init == null) return; boolean val = couldBeVal(variableDecl.type); boolean var = couldBeVar(variableDecl.type); if (!(val || var)) return; try { if (Reflection.initCopyField != null) Reflection.initCopyField.set(variableDecl, init); } catch (Exception e) { // In ecj mode this field isn't there and we don't need the copy anyway, so, we ignore the exception. } } private static boolean couldBeVar(TypeReference type) { return PatchVal.couldBe("lombok.experimental.var", type); } public static void addFinalAndValAnnotationToSingleVariableDeclaration(Object converter, SingleVariableDeclaration out, LocalDeclaration in) { @SuppressWarnings("unchecked") List modifiers = out.modifiers(); addFinalAndValAnnotationToModifierList(converter, modifiers, out.getAST(), in); } public static void addFinalAndValAnnotationToVariableDeclarationStatement(Object converter, VariableDeclarationStatement out, LocalDeclaration in) { @SuppressWarnings("unchecked") List modifiers = out.modifiers(); addFinalAndValAnnotationToModifierList(converter, modifiers, out.getAST(), in); } public static void addFinalAndValAnnotationToModifierList(Object converter, List modifiers, AST ast, LocalDeclaration in) { // First check that 'in' has the final flag on, and a @val / @lombok.val annotation. if ((in.modifiers & ClassFileConstants.AccFinal) == 0) return; if (in.annotations == null) return; boolean found = false; Annotation valAnnotation = null; for (Annotation ann : in.annotations) { if (couldBeVal(ann.type)) { found = true; valAnnotation = ann; break; } } if (!found) return; // Now check that 'out' is missing either of these. if (modifiers == null) return; // This is null only if the project is 1.4 or less. Lombok doesn't work in that. boolean finalIsPresent = false; boolean valIsPresent = false; for (Object present : modifiers) { if (present instanceof Modifier) { ModifierKeyword keyword = ((Modifier)present).getKeyword(); if (keyword == null) continue; if (keyword.toFlagValue() == Modifier.FINAL) finalIsPresent = true; } if (present instanceof org.eclipse.jdt.core.dom.Annotation) { Name typeName = ((org.eclipse.jdt.core.dom.Annotation) present).getTypeName(); if (typeName != null) { String fullyQualifiedName = typeName.getFullyQualifiedName(); if ("val".equals(fullyQualifiedName) || "lombok.val".equals(fullyQualifiedName)) { valIsPresent = true; } } } } if (!finalIsPresent) { modifiers.add( createModifier(ast, ModifierKeyword.FINAL_KEYWORD, valAnnotation.sourceStart, valAnnotation.sourceEnd)); } if (!valIsPresent) { MarkerAnnotation newAnnotation = createValAnnotation(ast, valAnnotation, valAnnotation.sourceStart, valAnnotation.sourceEnd); try { Reflection.astConverterRecordNodes.invoke(converter, newAnnotation, valAnnotation); Reflection.astConverterRecordNodes.invoke(converter, newAnnotation.getTypeName(), valAnnotation.type); } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } modifiers.add(newAnnotation); } } private static boolean couldBeVal(TypeReference type) { return PatchVal.couldBe("lombok.val", type); } public static Modifier createModifier(AST ast, ModifierKeyword keyword, int start, int end) { Modifier modifier = null; try { modifier = Reflection.modifierConstructor.newInstance(ast); } catch (InstantiationException e) { throw Lombok.sneakyThrow(e); } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e); } if (modifier != null) { modifier.setKeyword(keyword); modifier.setSourceRange(start, end - start + 1); } return modifier; } public static MarkerAnnotation createValAnnotation(AST ast, Annotation original, int start, int end) { MarkerAnnotation out = null; try { out = Reflection.markerAnnotationConstructor.newInstance(ast); } catch (InstantiationException e) { throw Lombok.sneakyThrow(e); } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e); } if (out != null) { SimpleName valName = ast.newSimpleName("val"); valName.setSourceRange(start, end - start + 1); if (original.type instanceof SingleTypeReference) { out.setTypeName(valName); setIndex(valName, 1); } else { SimpleName lombokName = ast.newSimpleName("lombok"); lombokName.setSourceRange(start, end - start + 1); setIndex(lombokName, 1); setIndex(valName, 2); QualifiedName fullName = ast.newQualifiedName(lombokName, valName); setIndex(fullName, 1); fullName.setSourceRange(start, end - start + 1); out.setTypeName(fullName); } out.setSourceRange(start, end - start + 1); } return out; } private static final Field FIELD_NAME_INDEX; static { Field f = null; try { f = Name.class.getDeclaredField("index"); f.setAccessible(true); } catch (Throwable t) { // Leave it null, in which case we don't set index. That'll result in error log messages but its better than crashing here. } FIELD_NAME_INDEX = f; } private static void setIndex(Name name, int index) { try { if (FIELD_NAME_INDEX != null) FIELD_NAME_INDEX.set(name, index); } catch (Exception e) { // Don't do anything - safest fallback behaviour. } } public static final class Reflection { private static final Field initCopyField, iterableCopyField; private static final Field astStackField, astPtrField; private static final Constructor modifierConstructor; private static final Constructor markerAnnotationConstructor; private static final Method astConverterRecordNodes; static { Field a = null, b = null, c = null, d = null; Constructor f = null; Constructor g = null; Method h = null; try { a = LocalDeclaration.class.getDeclaredField("$initCopy"); b = LocalDeclaration.class.getDeclaredField("$iterableCopy"); } catch (Throwable t) { //ignore - no $initCopy exists when running in ecj. } try { c = Parser.class.getDeclaredField("astStack"); c.setAccessible(true); d = Parser.class.getDeclaredField("astPtr"); d.setAccessible(true); f = Modifier.class.getDeclaredConstructor(AST.class); f.setAccessible(true); g = MarkerAnnotation.class.getDeclaredConstructor(AST.class); g.setAccessible(true); Class z = Class.forName("org.eclipse.jdt.core.dom.ASTConverter"); h = z.getDeclaredMethod("recordNodes", org.eclipse.jdt.core.dom.ASTNode.class, org.eclipse.jdt.internal.compiler.ast.ASTNode.class); h.setAccessible(true); } catch (Throwable t) { // Most likely we're in ecj or some other plugin usage of the eclipse compiler. No need for this. } initCopyField = a; iterableCopyField = b; astStackField = c; astPtrField = d; modifierConstructor = f; markerAnnotationConstructor = g; astConverterRecordNodes = h; } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/PatchValEclipsePortal.java000066400000000000000000000146631312655740700274320ustar00rootroot00000000000000/* * Copyright (C) 2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import lombok.Lombok; public class PatchValEclipsePortal { static final String LOCALDECLARATION_SIG = "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration"; static final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; static final String VARIABLEDECLARATIONSTATEMENT_SIG = "org.eclipse.jdt.core.dom.VariableDeclarationStatement"; static final String SINGLEVARIABLEDECLARATION_SIG = "org.eclipse.jdt.core.dom.SingleVariableDeclaration"; static final String ASTCONVERTER_SIG = "org.eclipse.jdt.core.dom.ASTConverter"; public static void copyInitializationOfForEachIterable(Object parser) { try { Reflection.copyInitializationOfForEachIterable.invoke(null, parser); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(Reflection.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } } public static void copyInitializationOfLocalDeclaration(Object parser) { try { Reflection.copyInitializationOfLocalDeclaration.invoke(null, parser); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(Reflection.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } } public static void addFinalAndValAnnotationToVariableDeclarationStatement(Object converter, Object out, Object in) { try { Reflection.addFinalAndValAnnotationToVariableDeclarationStatement.invoke(null, converter, out, in); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(Reflection.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } } public static void addFinalAndValAnnotationToSingleVariableDeclaration(Object converter, Object out, Object in) { try { Reflection.addFinalAndValAnnotationToSingleVariableDeclaration.invoke(null, converter, out, in); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(Reflection.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } } private static final class Reflection { public static final Method copyInitializationOfForEachIterable; public static final Method copyInitializationOfLocalDeclaration; public static final Method addFinalAndValAnnotationToVariableDeclarationStatement; public static final Method addFinalAndValAnnotationToSingleVariableDeclaration; public static final Throwable problem; static { Method m = null, n = null, o = null, p = null; Throwable problem_ = null; try { m = PatchValEclipse.class.getMethod("copyInitializationOfForEachIterable", Class.forName(PARSER_SIG)); n = PatchValEclipse.class.getMethod("copyInitializationOfLocalDeclaration", Class.forName(PARSER_SIG)); o = PatchValEclipse.class.getMethod("addFinalAndValAnnotationToVariableDeclarationStatement", Object.class, Class.forName(VARIABLEDECLARATIONSTATEMENT_SIG), Class.forName(LOCALDECLARATION_SIG)); p = PatchValEclipse.class.getMethod("addFinalAndValAnnotationToSingleVariableDeclaration", Object.class, Class.forName(SINGLEVARIABLEDECLARATION_SIG), Class.forName(LOCALDECLARATION_SIG)); } catch (Throwable t) { // That's problematic, but as long as no local classes are used we don't actually need it. // Better fail on local classes than crash altogether. problem_ = t; } copyInitializationOfForEachIterable = m; copyInitializationOfLocalDeclaration = n; addFinalAndValAnnotationToVariableDeclarationStatement = o; addFinalAndValAnnotationToSingleVariableDeclaration = p; problem = problem_; } } } lombok-1.16.18/src/eclipseAgent/lombok/eclipse/agent/package-info.java000066400000000000000000000023511312655740700255540ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Contains the mechanism that instruments eclipse by being loaded as a javaagent. */ package lombok.eclipse.agent; lombok-1.16.18/src/eclipseAgent/lombok/launch/000077500000000000000000000000001312655740700211145ustar00rootroot00000000000000lombok-1.16.18/src/eclipseAgent/lombok/launch/PatchFixesHider.java000066400000000000000000000715041312655740700250000ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.launch; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Stack; import lombok.eclipse.EclipseAugments; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IAnnotatable; import org.eclipse.jdt.core.IAnnotation; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.search.SearchMatch; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.ForeachStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.Scope; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.parser.Parser; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.eclipse.jdt.internal.core.SourceField; import org.eclipse.jdt.internal.core.dom.rewrite.NodeRewriteEvent; import org.eclipse.jdt.internal.core.dom.rewrite.RewriteEvent; import org.eclipse.jdt.internal.core.dom.rewrite.TokenScanner; import org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup; import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; /** These contain a mix of the following: *
      *
    • 'dependency free' method wrappers that cross the shadowloader barrier. *
    • methods that directly patch, but, these should ALWAYS be transplanted. *
    * * This class lives on the outside of the shadowloader barrier, and as a consequence, cannot access any other lombok code except other * code in the {@code lombok.launch} package!. *

    * This class is package private with lots of public inner static classes. This hides all of them from IDE autocomplete dialogs and such but at the JVM * level the inner static class are just plain public, which is important, because calls to the contents of these inner static classes are injected into * various eclipse classes verbatim, and if they weren't public, the verifier wouldn't accept it. */ final class PatchFixesHider { /** These utility methods are only used 'internally', but because of transplant methods, the class (and its methods) still have to be public! */ public static final class Util { private static ClassLoader shadowLoader; public static Class shadowLoadClass(String name) { try { if (shadowLoader == null) { try { Class.forName("lombok.core.LombokNode"); // If we get here, then lombok is already available. shadowLoader = Util.class.getClassLoader(); } catch (ClassNotFoundException e) { // If we get here, it isn't, and we should use the shadowloader. shadowLoader = Main.createShadowClassLoader(); } } return Class.forName(name, true, shadowLoader); } catch (ClassNotFoundException e) { throw sneakyThrow(e); } } public static Method findMethod(Class type, String name, Class... parameterTypes) { try { return type.getDeclaredMethod(name, parameterTypes); } catch (NoSuchMethodException e) { throw sneakyThrow(e); } } public static Object invokeMethod(Method method, Object... args) { try { return method.invoke(null, args); } catch (IllegalAccessException e) { throw sneakyThrow(e); } catch (InvocationTargetException e) { throw sneakyThrow(e.getCause()); } } private static RuntimeException sneakyThrow(Throwable t) { if (t == null) throw new NullPointerException("t"); Util.sneakyThrow0(t); return null; } @SuppressWarnings("unchecked") private static void sneakyThrow0(Throwable t) throws T { throw (T)t; } } /** Contains patch fixes that are dependent on lombok internals. */ public static final class LombokDeps { public static final Method ADD_LOMBOK_NOTES; public static final Method POST_COMPILER_BYTES_STRING; public static final Method POST_COMPILER_OUTPUTSTREAM; public static final Method POST_COMPILER_BUFFEREDOUTPUTSTREAM_STRING_STRING; static { Class shadowed = Util.shadowLoadClass("lombok.eclipse.agent.PatchFixesShadowLoaded"); ADD_LOMBOK_NOTES = Util.findMethod(shadowed, "addLombokNotesToEclipseAboutDialog", String.class, String.class); POST_COMPILER_BYTES_STRING = Util.findMethod(shadowed, "runPostCompiler", byte[].class, String.class); POST_COMPILER_OUTPUTSTREAM = Util.findMethod(shadowed, "runPostCompiler", OutputStream.class); POST_COMPILER_BUFFEREDOUTPUTSTREAM_STRING_STRING = Util.findMethod(shadowed, "runPostCompiler", BufferedOutputStream.class, String.class, String.class); } public static String addLombokNotesToEclipseAboutDialog(String origReturnValue, String key) { return (String) Util.invokeMethod(LombokDeps.ADD_LOMBOK_NOTES, origReturnValue, key); } public static byte[] runPostCompiler(byte[] bytes, String fileName) { return (byte[]) Util.invokeMethod(LombokDeps.POST_COMPILER_BYTES_STRING, bytes, fileName); } public static OutputStream runPostCompiler(OutputStream out) throws IOException { return (OutputStream) Util.invokeMethod(LombokDeps.POST_COMPILER_OUTPUTSTREAM, out); } public static BufferedOutputStream runPostCompiler(BufferedOutputStream out, String path, String name) throws IOException { return (BufferedOutputStream) Util.invokeMethod(LombokDeps.POST_COMPILER_BUFFEREDOUTPUTSTREAM_STRING_STRING, out, path, name); } } public static final class Transform { private static final Method TRANSFORM; private static final Method TRANSFORM_SWAPPED; static { Class shadowed = Util.shadowLoadClass("lombok.eclipse.TransformEclipseAST"); TRANSFORM = Util.findMethod(shadowed, "transform", Parser.class, CompilationUnitDeclaration.class); TRANSFORM_SWAPPED = Util.findMethod(shadowed, "transform_swapped", CompilationUnitDeclaration.class, Parser.class); } public static void transform(Parser parser, CompilationUnitDeclaration ast) throws IOException { Util.invokeMethod(TRANSFORM, parser, ast); } public static void transform_swapped(CompilationUnitDeclaration ast, Parser parser) throws IOException { Util.invokeMethod(TRANSFORM_SWAPPED, ast, parser); } } /** Contains patch code to support {@code @Delegate} */ public static final class Delegate { private static final Method HANDLE_DELEGATE_FOR_TYPE; static { Class shadowed = Util.shadowLoadClass("lombok.eclipse.agent.PatchDelegatePortal"); HANDLE_DELEGATE_FOR_TYPE = Util.findMethod(shadowed, "handleDelegateForType", Object.class); } public static boolean handleDelegateForType(Object classScope) { return (Boolean) Util.invokeMethod(HANDLE_DELEGATE_FOR_TYPE, classScope); } } /** Contains patch code to support {@code val} (eclipse specific) */ public static final class ValPortal { private static final Method COPY_INITIALIZATION_OF_FOR_EACH_ITERABLE; private static final Method COPY_INITIALIZATION_OF_LOCAL_DECLARATION; private static final Method ADD_FINAL_AND_VAL_ANNOTATION_TO_VARIABLE_DECLARATION_STATEMENT; private static final Method ADD_FINAL_AND_VAL_ANNOTATION_TO_SINGLE_VARIABLE_DECLARATION; static { Class shadowed = Util.shadowLoadClass("lombok.eclipse.agent.PatchValEclipsePortal"); COPY_INITIALIZATION_OF_FOR_EACH_ITERABLE = Util.findMethod(shadowed, "copyInitializationOfForEachIterable", Object.class); COPY_INITIALIZATION_OF_LOCAL_DECLARATION = Util.findMethod(shadowed, "copyInitializationOfLocalDeclaration", Object.class); ADD_FINAL_AND_VAL_ANNOTATION_TO_VARIABLE_DECLARATION_STATEMENT = Util.findMethod(shadowed, "addFinalAndValAnnotationToVariableDeclarationStatement", Object.class, Object.class, Object.class); ADD_FINAL_AND_VAL_ANNOTATION_TO_SINGLE_VARIABLE_DECLARATION = Util.findMethod(shadowed, "addFinalAndValAnnotationToSingleVariableDeclaration", Object.class, Object.class, Object.class); } public static void copyInitializationOfForEachIterable(Object parser) { Util.invokeMethod(COPY_INITIALIZATION_OF_FOR_EACH_ITERABLE, parser); } public static void copyInitializationOfLocalDeclaration(Object parser) { Util.invokeMethod(COPY_INITIALIZATION_OF_LOCAL_DECLARATION, parser); } public static void addFinalAndValAnnotationToVariableDeclarationStatement(Object converter, Object out, Object in) { Util.invokeMethod(ADD_FINAL_AND_VAL_ANNOTATION_TO_VARIABLE_DECLARATION_STATEMENT, converter, out, in); } public static void addFinalAndValAnnotationToSingleVariableDeclaration(Object converter, Object out, Object in) { Util.invokeMethod(ADD_FINAL_AND_VAL_ANNOTATION_TO_SINGLE_VARIABLE_DECLARATION, converter, out, in); } } /** Contains patch code to support {@code val} (eclipse and ecj) */ public static final class Val { private static final Method SKIP_RESOLVE_INITIALIZER_IF_ALREADY_CALLED; private static final Method SKIP_RESOLVE_INITIALIZER_IF_ALREADY_CALLED2; private static final Method HANDLE_VAL_FOR_LOCAL_DECLARATION; private static final Method HANDLE_VAL_FOR_FOR_EACH; static { Class shadowed = Util.shadowLoadClass("lombok.eclipse.agent.PatchVal"); SKIP_RESOLVE_INITIALIZER_IF_ALREADY_CALLED = Util.findMethod(shadowed, "skipResolveInitializerIfAlreadyCalled", Expression.class, BlockScope.class); SKIP_RESOLVE_INITIALIZER_IF_ALREADY_CALLED2 = Util.findMethod(shadowed, "skipResolveInitializerIfAlreadyCalled2", Expression.class, BlockScope.class, LocalDeclaration.class); HANDLE_VAL_FOR_LOCAL_DECLARATION = Util.findMethod(shadowed, "handleValForLocalDeclaration", LocalDeclaration.class, BlockScope.class); HANDLE_VAL_FOR_FOR_EACH = Util.findMethod(shadowed, "handleValForForEach", ForeachStatement.class, BlockScope.class); } public static TypeBinding skipResolveInitializerIfAlreadyCalled(Expression expr, BlockScope scope) { return (TypeBinding) Util.invokeMethod(SKIP_RESOLVE_INITIALIZER_IF_ALREADY_CALLED, expr, scope); } public static TypeBinding skipResolveInitializerIfAlreadyCalled2(Expression expr, BlockScope scope, LocalDeclaration decl) { return (TypeBinding) Util.invokeMethod(SKIP_RESOLVE_INITIALIZER_IF_ALREADY_CALLED2, expr, scope, decl); } public static boolean handleValForLocalDeclaration(LocalDeclaration local, BlockScope scope) { return (Boolean) Util.invokeMethod(HANDLE_VAL_FOR_LOCAL_DECLARATION, local, scope); } public static boolean handleValForForEach(ForeachStatement forEach, BlockScope scope) { return (Boolean) Util.invokeMethod(HANDLE_VAL_FOR_FOR_EACH, forEach, scope); } } /** Contains patch code to support {@code @ExtensionMethod} */ public static final class ExtensionMethod { private static final Method RESOLVE_TYPE; private static final Method ERROR_NO_METHOD_FOR; private static final Method INVALID_METHOD, INVALID_METHOD2; static { Class shadowed = Util.shadowLoadClass("lombok.eclipse.agent.PatchExtensionMethod"); RESOLVE_TYPE = Util.findMethod(shadowed, "resolveType", TypeBinding.class, MessageSend.class, BlockScope.class); ERROR_NO_METHOD_FOR = Util.findMethod(shadowed, "errorNoMethodFor", ProblemReporter.class, MessageSend.class, TypeBinding.class, TypeBinding[].class); INVALID_METHOD = Util.findMethod(shadowed, "invalidMethod", ProblemReporter.class, MessageSend.class, MethodBinding.class); INVALID_METHOD2 = Util.findMethod(shadowed, "invalidMethod", ProblemReporter.class, MessageSend.class, MethodBinding.class, Scope.class); } public static TypeBinding resolveType(TypeBinding resolvedType, MessageSend methodCall, BlockScope scope) { return (TypeBinding) Util.invokeMethod(RESOLVE_TYPE, resolvedType, methodCall, scope); } public static void errorNoMethodFor(ProblemReporter problemReporter, MessageSend messageSend, TypeBinding recType, TypeBinding[] params) { Util.invokeMethod(ERROR_NO_METHOD_FOR, problemReporter, messageSend, recType, params); } public static void invalidMethod(ProblemReporter problemReporter, MessageSend messageSend, MethodBinding method) { Util.invokeMethod(INVALID_METHOD, problemReporter, messageSend, method); } public static void invalidMethod(ProblemReporter problemReporter, MessageSend messageSend, MethodBinding method, Scope scope) { Util.invokeMethod(INVALID_METHOD2, problemReporter, messageSend, method, scope); } } /** * Contains a mix of methods: ecj only, ecj+eclipse, and eclipse only. As a consequence, _EVERY_ method from here used for ecj MUST be * transplanted, as ecj itself cannot load this class (signatures refer to things that don't exist in ecj-only mode). *

    * Because of usage of transplant(), a bunch of these contain direct code and don't try to cross the shadowloader barrier. */ public static final class PatchFixes { public static boolean isGenerated(org.eclipse.jdt.core.dom.ASTNode node) { boolean result = false; try { result = ((Boolean)node.getClass().getField("$isGenerated").get(node)).booleanValue(); if (!result && node.getParent() != null && node.getParent() instanceof org.eclipse.jdt.core.dom.QualifiedName) { result = isGenerated(node.getParent()); } } catch (Exception e) { // better to assume it isn't generated } return result; } public static boolean isListRewriteOnGeneratedNode(org.eclipse.jdt.core.dom.rewrite.ListRewrite rewrite) { return isGenerated(rewrite.getParent()); } public static boolean returnFalse(java.lang.Object object) { return false; } public static boolean returnTrue(java.lang.Object object) { return true; } @java.lang.SuppressWarnings({"unchecked", "rawtypes"}) public static java.util.List removeGeneratedNodes(java.util.List list) { try { java.util.List realNodes = new java.util.ArrayList(list.size()); for (java.lang.Object node : list) { if(!isGenerated(((org.eclipse.jdt.core.dom.ASTNode)node))) { realNodes.add(node); } } return realNodes; } catch (Exception e) { } return list; } public static java.lang.String getRealMethodDeclarationSource(java.lang.String original, Object processor, org.eclipse.jdt.core.dom.MethodDeclaration declaration) throws Exception { if (!isGenerated(declaration)) return original; List annotations = new ArrayList(); for (Object modifier : declaration.modifiers()) { if (modifier instanceof org.eclipse.jdt.core.dom.Annotation) { org.eclipse.jdt.core.dom.Annotation annotation = (org.eclipse.jdt.core.dom.Annotation)modifier; String qualifiedAnnotationName = annotation.resolveTypeBinding().getQualifiedName(); if (!"java.lang.Override".equals(qualifiedAnnotationName) && !"java.lang.SuppressWarnings".equals(qualifiedAnnotationName)) annotations.add(annotation); } } StringBuilder signature = new StringBuilder(); addAnnotations(annotations, signature); if ((Boolean)processor.getClass().getDeclaredField("fPublic").get(processor)) signature.append("public "); if ((Boolean)processor.getClass().getDeclaredField("fAbstract").get(processor)) signature.append("abstract "); signature .append(declaration.getReturnType2().toString()) .append(" ").append(declaration.getName().getFullyQualifiedName()) .append("("); boolean first = true; for (Object parameter : declaration.parameters()) { if (!first) signature.append(", "); first = false; // We should also add the annotations of the parameters signature.append(parameter); } signature.append(");"); return signature.toString(); } // part of getRealMethodDeclarationSource(...) public static void addAnnotations(List annotations, StringBuilder signature) { /* * We SHOULD be able to handle the following cases: * @Override * @Override() * @SuppressWarnings("all") * @SuppressWarnings({"all", "unused"}) * @SuppressWarnings(value = "all") * @SuppressWarnings(value = {"all", "unused"}) * @EqualsAndHashCode(callSuper=true, of="id") * * Currently, we only seem to correctly support: * @Override * @Override() N.B. We lose the parentheses here, since there are no values. No big deal. * @SuppressWarnings("all") */ for (org.eclipse.jdt.core.dom.Annotation annotation : annotations) { List values = new ArrayList(); if (annotation.isSingleMemberAnnotation()) { org.eclipse.jdt.core.dom.SingleMemberAnnotation smAnn = (org.eclipse.jdt.core.dom.SingleMemberAnnotation) annotation; values.add(smAnn.getValue().toString()); } else if (annotation.isNormalAnnotation()) { org.eclipse.jdt.core.dom.NormalAnnotation normalAnn = (org.eclipse.jdt.core.dom.NormalAnnotation) annotation; for (Object value : normalAnn.values()) values.add(value.toString()); } signature.append("@").append(annotation.resolveTypeBinding().getQualifiedName()); if (!values.isEmpty()) { signature.append("("); boolean first = true; for (String string : values) { if (!first) signature.append(", "); first = false; signature.append('"').append(string).append('"'); } signature.append(")"); } signature.append(" "); } } public static org.eclipse.jdt.core.dom.MethodDeclaration getRealMethodDeclarationNode(org.eclipse.jdt.core.IMethod sourceMethod, org.eclipse.jdt.core.dom.CompilationUnit cuUnit) throws JavaModelException { MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, cuUnit); if (isGenerated(methodDeclarationNode)) { IType declaringType = sourceMethod.getDeclaringType(); Stack typeStack = new Stack(); while (declaringType != null) { typeStack.push(declaringType); declaringType = declaringType.getDeclaringType(); } IType rootType = typeStack.pop(); org.eclipse.jdt.core.dom.AbstractTypeDeclaration typeDeclaration = findTypeDeclaration(rootType, cuUnit.types()); while (!typeStack.isEmpty() && typeDeclaration != null) { typeDeclaration = findTypeDeclaration(typeStack.pop(), typeDeclaration.bodyDeclarations()); } if (typeStack.isEmpty() && typeDeclaration != null) { String methodName = sourceMethod.getElementName(); for (Object declaration : typeDeclaration.bodyDeclarations()) { if (declaration instanceof org.eclipse.jdt.core.dom.MethodDeclaration) { org.eclipse.jdt.core.dom.MethodDeclaration methodDeclaration = (org.eclipse.jdt.core.dom.MethodDeclaration) declaration; if (methodDeclaration.getName().toString().equals(methodName)) { return methodDeclaration; } } } } } return methodDeclarationNode; } // part of getRealMethodDeclarationNode public static org.eclipse.jdt.core.dom.AbstractTypeDeclaration findTypeDeclaration(IType searchType, List nodes) { for (Object object : nodes) { if (object instanceof org.eclipse.jdt.core.dom.AbstractTypeDeclaration) { org.eclipse.jdt.core.dom.AbstractTypeDeclaration typeDeclaration = (org.eclipse.jdt.core.dom.AbstractTypeDeclaration) object; if (typeDeclaration.getName().toString().equals(searchType.getElementName())) return typeDeclaration; } } return null; } public static int getSourceEndFixed(int sourceEnd, org.eclipse.jdt.internal.compiler.ast.ASTNode node) throws Exception { if (sourceEnd == -1) { org.eclipse.jdt.internal.compiler.ast.ASTNode object = (org.eclipse.jdt.internal.compiler.ast.ASTNode)node.getClass().getField("$generatedBy").get(node); if (object != null) { return object.sourceEnd; } } return sourceEnd; } public static int fixRetrieveStartingCatchPosition(int original, int start) { return original == -1 ? start : original; } public static int fixRetrieveIdentifierEndPosition(int original, int end) { return original == -1 ? end : original; } public static int fixRetrieveEllipsisStartPosition(int original, int end) { return original == -1 ? end : original; } public static int fixRetrieveRightBraceOrSemiColonPosition(int original, int end) { // if (original == -1) { // Thread.dumpStack(); // } return original == -1 ? end : original; } public static int fixRetrieveRightBraceOrSemiColonPosition(int retVal, AbstractMethodDeclaration amd) { if (retVal != -1 || amd == null) return retVal; boolean isGenerated = EclipseAugments.ASTNode_generatedBy.get(amd) != null; if (isGenerated) return amd.declarationSourceEnd; return -1; } public static int fixRetrieveRightBraceOrSemiColonPosition(int retVal, FieldDeclaration fd) { if (retVal != -1 || fd == null) return retVal; boolean isGenerated = EclipseAugments.ASTNode_generatedBy.get(fd) != null; if (isGenerated) return fd.declarationSourceEnd; return -1; } public static final int ALREADY_PROCESSED_FLAG = 0x800000; //Bit 24 public static boolean checkBit24(Object node) throws Exception { int bits = (Integer)(node.getClass().getField("bits").get(node)); return (bits & ALREADY_PROCESSED_FLAG) != 0; } public static boolean skipRewritingGeneratedNodes(org.eclipse.jdt.core.dom.ASTNode node) throws Exception { return ((Boolean) node.getClass().getField("$isGenerated").get(node)).booleanValue(); } public static void setIsGeneratedFlag(org.eclipse.jdt.core.dom.ASTNode domNode, org.eclipse.jdt.internal.compiler.ast.ASTNode internalNode) throws Exception { if (internalNode == null || domNode == null) return; boolean isGenerated = EclipseAugments.ASTNode_generatedBy.get(internalNode) != null; if (isGenerated) domNode.getClass().getField("$isGenerated").set(domNode, true); } public static void setIsGeneratedFlagForName(org.eclipse.jdt.core.dom.Name name, Object internalNode) throws Exception { if (internalNode instanceof org.eclipse.jdt.internal.compiler.ast.ASTNode) { boolean isGenerated = EclipseAugments.ASTNode_generatedBy.get((org.eclipse.jdt.internal.compiler.ast.ASTNode) internalNode) != null; if (isGenerated) name.getClass().getField("$isGenerated").set(name, true); } } public static RewriteEvent[] listRewriteHandleGeneratedMethods(RewriteEvent parent) { RewriteEvent[] children = parent.getChildren(); List newChildren = new ArrayList(); List modifiedChildren = new ArrayList(); for (int i = 0; i < children.length; i++) { RewriteEvent child = children[i]; boolean isGenerated = isGenerated((org.eclipse.jdt.core.dom.ASTNode) child.getOriginalValue()); if (isGenerated) { boolean isReplacedOrRemoved = child.getChangeKind() == RewriteEvent.REPLACED || child.getChangeKind() == RewriteEvent.REMOVED; boolean convertingFromMethod = child.getOriginalValue() instanceof org.eclipse.jdt.core.dom.MethodDeclaration; if (isReplacedOrRemoved && convertingFromMethod && child.getNewValue() != null) { modifiedChildren.add(new NodeRewriteEvent(null, child.getNewValue())); } } else { newChildren.add(child); } } // Since Eclipse doesn't honor the "insert at specified location" for already existing members, // we'll just add them last newChildren.addAll(modifiedChildren); return newChildren.toArray(new RewriteEvent[newChildren.size()]); } public static int getTokenEndOffsetFixed(TokenScanner scanner, int token, int startOffset, Object domNode) throws CoreException { boolean isGenerated = false; try { isGenerated = (Boolean) domNode.getClass().getField("$isGenerated").get(domNode); } catch (Exception e) { // If this fails, better to break some refactor scripts than to crash eclipse. } if (isGenerated) return -1; return scanner.getTokenEndOffset(token, startOffset); } public static IMethod[] removeGeneratedMethods(IMethod[] methods) throws Exception { List result = new ArrayList(); for (IMethod m : methods) { if (m.getNameRange().getLength() > 0 && !m.getNameRange().equals(m.getSourceRange())) result.add(m); } return result.size() == methods.length ? methods : result.toArray(new IMethod[result.size()]); } public static SearchMatch[] removeGenerated(SearchMatch[] returnValue) { List result = new ArrayList(); for (int j = 0; j < returnValue.length; j++) { SearchMatch searchResult = returnValue[j]; if (searchResult.getElement() instanceof IField) { IField field = (IField) searchResult.getElement(); // can not check for value=lombok because annotation is // not fully resolved IAnnotation annotation = field.getAnnotation("Generated"); if (annotation != null) { // Method generated at field location, skip continue; } } result.add(searchResult); } return result.toArray(new SearchMatch[result.size()]); } public static SearchResultGroup[] createFakeSearchResult(SearchResultGroup[] returnValue, Object/* * org.eclipse.jdt.internal.corext.refactoring.rename. * RenameFieldProcessor */ processor) throws Exception { if (returnValue == null || returnValue.length == 0) { // if no matches were found, check if Data annotation is present on the class Field declaredField = processor.getClass().getDeclaredField("fField"); if (declaredField != null) { declaredField.setAccessible(true); SourceField fField = (SourceField) declaredField.get(processor); IAnnotation dataAnnotation = fField.getDeclaringType().getAnnotation("Data"); if (dataAnnotation != null) { // add fake item, to make refactoring checks pass return new SearchResultGroup[] {new SearchResultGroup(null, new SearchMatch[1])}; } } } return returnValue; } public static SimpleName[] removeGeneratedSimpleNames(SimpleName[] in) throws Exception { Field f = SimpleName.class.getField("$isGenerated"); int count = 0; for (int i = 0; i < in.length; i++) { if (in[i] == null || !((Boolean)f.get(in[i])).booleanValue()) count++; } if (count == in.length) return in; SimpleName[] newSimpleNames = new SimpleName[count]; count = 0; for (int i = 0; i < in.length; i++) { if (in[i] == null || !((Boolean)f.get(in[i])).booleanValue()) newSimpleNames[count++] = in[i]; } return newSimpleNames; } public static Annotation[] convertAnnotations(Annotation[] out, IAnnotatable annotatable) { IAnnotation[] in; try { in = annotatable.getAnnotations(); } catch (Exception e) { return out; } if (out == null) return null; int toWrite = 0; for (int idx = 0; idx < out.length; idx++) { String oName = new String(out[idx].type.getLastToken()); boolean found = false; for (IAnnotation i : in) { String name = i.getElementName(); int li = name.lastIndexOf('.'); if (li > -1) name = name.substring(li + 1); if (name.equals(oName)) { found = true; break; } } if (!found) out[idx] = null; else toWrite++; } Annotation[] replace = out; if (toWrite < out.length) { replace = new Annotation[toWrite]; int idx = 0; for (int i = 0; i < out.length; i++) { if (out[i] == null) continue; replace[idx++] = out[i]; } } return replace; } } } lombok-1.16.18/src/installer/000077500000000000000000000000001312655740700157515ustar00rootroot00000000000000lombok-1.16.18/src/installer/lombok/000077500000000000000000000000001312655740700172345ustar00rootroot00000000000000lombok-1.16.18/src/installer/lombok/installer/000077500000000000000000000000001312655740700212315ustar00rootroot00000000000000lombok-1.16.18/src/installer/lombok/installer/AppleNativeLook.java000066400000000000000000000035521312655740700251360ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; import java.awt.Image; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; /** * Mac OS X specific code to gussy up the GUI a little bit, mostly with a nice dock icon. Well, nicer than * the standard icon, at any rate. */ class AppleNativeLook { public static void go() throws Exception { Class appClass = Class.forName("com.apple.eawt.Application"); Object app = appClass.getMethod("getApplication").invoke(null); appClass.getMethod("removeAboutMenuItem").invoke(app); appClass.getMethod("removePreferencesMenuItem").invoke(app); BufferedImage image = ImageIO.read(AppleNativeLook.class.getResource("lombokIcon.png")); appClass.getMethod("setDockIconImage", Image.class).invoke(app, image); } } lombok-1.16.18/src/installer/lombok/installer/CorruptedIdeLocationException.java000066400000000000000000000035671312655740700300500ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * Represents an installation location problem. * You should throw it upon creation of a {@code IdeLocation} class * if the provided location looks like your kind of IDE but there's something wrong with it. */ public class CorruptedIdeLocationException extends Exception { private final String ideType; public CorruptedIdeLocationException(String message, String ideType, Throwable cause) { super(message, cause); this.ideType = ideType; } public String getIdeType() { return ideType; } void showDialog(JFrame appWindow) { JOptionPane.showMessageDialog(appWindow, getMessage(), "Cannot configure " + ideType + " installation", JOptionPane.WARNING_MESSAGE); } } lombok-1.16.18/src/installer/lombok/installer/IdeLocation.java000066400000000000000000000057421312655740700242760ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; import java.io.File; import java.io.IOException; import java.net.URL; import lombok.patcher.ClassRootFinder; /** * Represents a location that contains an IDE. */ public abstract class IdeLocation { /** Toggling the 'selected' checkbox in the GUI is tracked via this boolean */ boolean selected = true; public abstract String install() throws InstallException; public abstract void uninstall() throws UninstallException; public abstract String getName(); public abstract boolean hasLombok(); public abstract URL getIdeIcon(); /** * Returns a File object pointing to our own jar file. Will obviously fail if the installer was started via * a jar that wasn't accessed via the file-system, or if its started via e.g. unpacking the jar. */ public static File findOurJar() { return new File(ClassRootFinder.findClassRootOfClass(OsUtils.class)); } @Override public String toString() { return getName(); } /** * Returns a full path to the provided file. * Returns the canonical path, unless that is not available, in which case it returns the absolute path. */ public static String canonical(File p) { try { return p.getCanonicalPath(); } catch (IOException e) { String x = p.getAbsolutePath(); return x == null ? p.getPath() : x; } } private static final String LEGAL_PATH_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_/"; private static final String LEGAL_PATH_CHARS_WINDOWS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_/:\\ "; public static String escapePath(String path) { StringBuilder out = new StringBuilder(); String legalChars = OsUtils.getOS() == OsUtils.OS.UNIX ? LEGAL_PATH_CHARS : LEGAL_PATH_CHARS_WINDOWS; for (char c : path.toCharArray()) { if (legalChars.indexOf(c) == -1) out.append('\\'); out.append(c); } return out.toString(); } } lombok-1.16.18/src/installer/lombok/installer/IdeLocationProvider.java000066400000000000000000000044151312655740700260050ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; import java.util.List; import java.util.regex.Pattern; public interface IdeLocationProvider { /** * @throws CorruptedIdeLocationException * Only throw this exception if the location seems like a proper installation except there's something wrong with it. * Do not throw it (just return {@code null}) if there's nothing there or it looks absolutely nothing like your IDE. */ IdeLocation create(String path) throws CorruptedIdeLocationException; /** * Return the usual name of the IDE executable or other obvious marker of an IDE installation on the current platform. */ Pattern getLocationSelectors(); /** * Look for installations of your IDE in the usual places. * * @param locations Add to this list any valid locations that you found. * @param problems * Add to this list any locations that look like installations, * but have problems that prevent you from installing/uninstalling from them. DONT add to this list * any common locations that have no installation at all - only add near misses. */ void findIdes(List locations, List problems); } lombok-1.16.18/src/installer/lombok/installer/InstallException.java000066400000000000000000000030621312655740700253620ustar00rootroot00000000000000/* * Copyright (C) 2009-2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; /** * Thrown when installation of lombok into an IDE fails. */ public class InstallException extends Exception { private boolean warning; public InstallException(String message, Throwable cause) { super(message, cause); } public InstallException(boolean warning, String message, Throwable cause) { super(message, cause); this.warning = warning; } public boolean isWarning() { return warning; } } lombok-1.16.18/src/installer/lombok/installer/Installer.java000066400000000000000000000242111312655740700240310ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; import java.awt.HeadlessException; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import javax.swing.SwingUtilities; import javax.swing.UIManager; import lombok.Lombok; import lombok.core.LombokApp; import lombok.core.SpiLoadUtil; import lombok.core.Version; import lombok.installer.OsUtils.OS; import lombok.patcher.ClassRootFinder; import org.mangosdk.spi.ProviderFor; import com.zwitserloot.cmdreader.CmdReader; import com.zwitserloot.cmdreader.Description; import com.zwitserloot.cmdreader.InvalidCommandLineException; import com.zwitserloot.cmdreader.Sequential; import com.zwitserloot.cmdreader.Shorthand; /** * The lombok installer proper. * Uses swing to show a simple GUI that can add and remove the java agent to Eclipse installations. * Also offers info on what this installer does in case people want to instrument their Eclipse manually, * and looks in some common places on Mac OS X, Linux and Windows. */ public class Installer { static final URI ABOUT_LOMBOK_URL = URI.create("https://projectlombok.org"); static final List locationProviders; static { List list = new ArrayList(); try { for (IdeLocationProvider provider : SpiLoadUtil.findServices(IdeLocationProvider.class)) { list.add(provider); } } catch (IOException e) { throw Lombok.sneakyThrow(e); } locationProviders = Collections.unmodifiableList(list); } static List getIdeExecutableNames() { List list = new ArrayList(); for (IdeLocationProvider provider : locationProviders) { Pattern p = provider.getLocationSelectors(); if (p != null) list.add(p); } return list; } static IdeLocation tryAllProviders(String location) throws CorruptedIdeLocationException { for (IdeLocationProvider provider : locationProviders) { IdeLocation loc = provider.create(location); if (loc != null) return loc; } return null; } static void autoDiscover(List locations, List problems) { for (IdeLocationProvider provider : locationProviders) { provider.findIdes(locations, problems); } } public static boolean isSelf(String jar) { String self = ClassRootFinder.findClassRootOfClass(Installer.class); if (self == null) return false; File a = new File(jar).getAbsoluteFile(); File b = new File(self).getAbsoluteFile(); try { a = a.getCanonicalFile(); } catch (IOException ignore) {} try { b = b.getCanonicalFile(); } catch (IOException ignore) {} return a.equals(b); } @ProviderFor(LombokApp.class) public static class GraphicalInstallerApp extends LombokApp { @Override public String getAppName() { return "installer"; } @Override public String getAppDescription() { return "Runs the graphical installer tool (default)."; } @Override public List getAppAliases() { return Arrays.asList(""); } @Override public int runApp(List args) throws Exception { return guiInstaller(); } } @ProviderFor(LombokApp.class) public static class CommandLineInstallerApp extends LombokApp { @Override public String getAppName() { return "install"; } @Override public String getAppDescription() { return "Runs the 'handsfree' command line scriptable installer."; } @Override public int runApp(List args) throws Exception { return cliInstaller(false, args); } } @ProviderFor(LombokApp.class) public static class CommandLineUninstallerApp extends LombokApp { @Override public String getAppName() { return "uninstall"; } @Override public String getAppDescription() { return "Runs the 'handsfree' command line scriptable uninstaller."; } @Override public int runApp(List args) throws Exception { return cliInstaller(true, args); } } private static int guiInstaller() { if (OsUtils.getOS() == OS.MAC_OS_X) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Lombok Installer"); System.setProperty("com.apple.macos.use-file-dialog-packages", "true"); } try { SwingUtilities.invokeLater(new Runnable() { public void run() { try { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ignore) {} new InstallerGUI().show(); } catch (HeadlessException e) { printHeadlessInfo(); } } }); synchronized (InstallerGUI.exitMarker) { while (!Thread.interrupted() && InstallerGUI.exitMarker.get() == null) { try { InstallerGUI.exitMarker.wait(); } catch (InterruptedException e) { return 1; } } Integer errCode = InstallerGUI.exitMarker.get(); return errCode == null ? 1 : errCode; } } catch (HeadlessException e) { printHeadlessInfo(); return 1; } } private static class CmdArgs { @Description("Specify paths to a location to install/uninstall. Use 'auto' to apply to all automatically discoverable installations.") @Sequential List path = new ArrayList(); @Shorthand({"h", "?"}) @Description("Shows this help text") boolean help; } public static int cliInstaller(boolean uninstall, List rawArgs) { CmdReader reader = CmdReader.of(CmdArgs.class); CmdArgs args; try { args = reader.make(rawArgs.toArray(new String[0])); } catch (InvalidCommandLineException e) { System.err.println(e.getMessage()); System.err.println("--------------------------"); System.err.println(generateCliHelp(uninstall, reader)); return 1; } if (args.help) { System.out.println(generateCliHelp(uninstall, reader)); return 0; } if (args.path.isEmpty()) { System.err.println("ERROR: Nothing to do!"); System.err.println("--------------------------"); System.err.println(generateCliHelp(uninstall, reader)); return 1; } final List locations = new ArrayList(); final List problems = new ArrayList(); if (args.path.contains("auto")) autoDiscover(locations, problems); for (String rawPath : args.path) { if (!rawPath.equals("auto")) { try { IdeLocation loc = tryAllProviders(rawPath); if (loc != null) locations.add(loc); else problems.add(new CorruptedIdeLocationException("Can't find any IDE at: " + rawPath, null, null)); } catch (CorruptedIdeLocationException e) { problems.add(e); } } } int validLocations = locations.size(); for (IdeLocation loc : locations) { try { if (uninstall) { loc.uninstall(); } else { loc.install(); } System.out.printf("Lombok %s %s: %s\n", uninstall ? "uninstalled" : "installed", uninstall ? "from" : "to", loc.getName()); } catch (InstallException e) { if (e.isWarning()) { System.err.printf("Warning while installing at %s:\n", loc.getName()); } else { System.err.printf("Installation at %s failed:\n", loc.getName()); validLocations--; } System.err.println(e.getMessage()); } catch (UninstallException e) { if (e.isWarning()) { System.err.printf("Warning while uninstalling at %s:\n", loc.getName()); } else { System.err.printf("Uninstall at %s failed:\n", loc.getName()); validLocations--; } System.err.println(e.getMessage()); } } for (CorruptedIdeLocationException problem : problems) { System.err.println("WARNING: " + problem.getMessage()); } if (validLocations == 0) { System.err.println("WARNING: Zero valid locations found; so nothing was done!"); } return 0; } private static String generateCliHelp(boolean uninstall, CmdReader reader) { return reader.generateCommandLineHelp("java -jar lombok.jar " + (uninstall ? "uninstall" : "install")); } /** * If run in headless mode, the installer can't show its fancy GUI. There's little point in running * the installer without a GUI environment, as Eclipse doesn't run in headless mode either, so * we'll make do with showing some basic info on Lombok as well as instructions for using lombok with javac. */ private static void printHeadlessInfo() { System.out.printf("About lombok v%s\n" + "Lombok makes java better by providing very spicy additions to the Java programming language," + "such as using @Getter to automatically generate a getter method for any field.\n\n" + "Browse to %s for more information. To install lombok on Eclipse, re-run this jar file on a " + "graphical computer system - this message is being shown because your terminal is not graphics capable.\n" + "Alternatively, use the command line installer (java -jar lombok.jar install --help).\n" + "If you are just using 'javac' or a tool that calls on javac, no installation is neccessary; just " + "make sure lombok.jar is in the classpath when you compile. Example:\n\n" + " java -cp lombok.jar MyCode.java\n", Version.getVersion(), ABOUT_LOMBOK_URL); } } lombok-1.16.18/src/installer/lombok/installer/InstallerGUI.java000066400000000000000000000765111312655740700244100ustar00rootroot00000000000000/* * Copyright (C) 2009-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.font.TextAttribute; import java.io.File; import java.io.FilenameFilter; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.Scrollable; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.filechooser.FileFilter; import javax.swing.text.html.HTMLDocument; import lombok.core.Version; import lombok.installer.OsUtils.OS; /** * The lombok GUI installer. * Uses swing to show a simple GUI that can add and remove the java agent to IDE installations. * Also offers info on what this installer does in case people want to instrument their IDE manually. */ public class InstallerGUI { private static final int INSTALLER_WINDOW_WIDTH = 662; static final AtomicReference exitMarker = new AtomicReference(); private JFrame appWindow; private JComponent loadingExpl; private Component javacArea; private Component ideArea; private Component uninstallArea; private Component howIWorkArea; private Component successArea; private Box uninstallBox; private JHyperLink uninstallButton; private JLabel uninstallPlaceholder; private JButton installButton; private List toUninstall; private final Set installSpecificMessages = new LinkedHashSet(); /** * Creates a new installer that starts out invisible. * Call the {@link #show()} method on a freshly created installer to render it. */ public InstallerGUI() { appWindow = new JFrame(String.format("Project Lombok v%s - Installer", Version.getVersion())); appWindow.setLocationByPlatform(true); appWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); appWindow.setResizable(false); appWindow.setIconImage(Toolkit.getDefaultToolkit().getImage(Installer.class.getResource("lombokIcon.png"))); try { javacArea = buildJavacArea(); ideArea = buildIdeArea(); uninstallArea = buildUninstallArea(); uninstallArea.setVisible(false); howIWorkArea = buildHowIWorkArea(); howIWorkArea.setVisible(false); successArea = buildSuccessArea(); successArea.setVisible(false); buildChrome(appWindow.getContentPane()); appWindow.pack(); } catch (Throwable t) { handleException(t); } } private void handleException(final Throwable t) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(appWindow, "There was a problem during the installation process:\n" + t, "Uh Oh!", JOptionPane.ERROR_MESSAGE); t.printStackTrace(); System.exit(1); } }); } private Component buildHowIWorkArea() { JPanel container = new JPanel(); container.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; container.add(new JLabel(HOW_I_WORK_TITLE), constraints); constraints.gridy = 1; constraints.insets = new Insets(8, 0, 0, 16); container.add(new JLabel(String.format(HOW_I_WORK_EXPLANATION, File.separator)), constraints); Box buttonBar = Box.createHorizontalBox(); JButton backButton = new JButton("Okay - Good to know!"); buttonBar.add(Box.createHorizontalGlue()); buttonBar.add(backButton); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { howIWorkArea.setVisible(false); javacArea.setVisible(true); ideArea.setVisible(true); successArea.setVisible(false); appWindow.pack(); } }); constraints.gridy = 2; container.add(buttonBar, constraints); container.setPreferredSize(new Dimension(INSTALLER_WINDOW_WIDTH, 415)); container.setMinimumSize(new Dimension(INSTALLER_WINDOW_WIDTH, 415)); return container; } private void showSuccess(String installSpecific) { successExplanation.setText(SUCCESS_EXPLANATION.replace("%%%", installSpecific)); howIWorkArea.setVisible(false); javacArea.setVisible(false); ideArea.setVisible(false); successArea.setVisible(true); appWindow.pack(); } private JLabel successExplanation; private Component buildSuccessArea() { JPanel container = new JPanel(); container.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; JLabel title; container.add(title = new JLabel(SUCCESS_TITLE), constraints); title.setPreferredSize(new Dimension(INSTALLER_WINDOW_WIDTH - 82, 20)); title.setMinimumSize(new Dimension(INSTALLER_WINDOW_WIDTH - 82, 20)); constraints.gridy = 1; constraints.insets = new Insets(8, 0, 0, 16); container.add(successExplanation = new JLabel(SUCCESS_EXPLANATION), constraints); successExplanation.setPreferredSize(new Dimension(INSTALLER_WINDOW_WIDTH - 82, 175)); successExplanation.setMinimumSize(new Dimension(INSTALLER_WINDOW_WIDTH - 82, 175)); constraints.gridy++; constraints.fill = GridBagConstraints.BOTH; JTextPane notes = new JTextPane(); notes.setContentType("text/html"); notes.setText(readChangeLog()); notes.setEditable(false); notes.setOpaque(false); notes.setBorder(null); notes.setSelectionStart(0); notes.setSelectionEnd(0); Font font = UIManager.getFont("Label.font"); String bodyRule = "body { font-family: " + font.getFamily() + "; font-size: " + font.getSize() + "pt; }"; ((HTMLDocument) notes.getDocument()).getStyleSheet().addRule(bodyRule); JScrollPane scroller = new JScrollPane(notes); container.add(scroller, constraints); scroller.setPreferredSize(new Dimension(INSTALLER_WINDOW_WIDTH - 82, 200)); scroller.setMinimumSize(new Dimension(INSTALLER_WINDOW_WIDTH - 82, 200)); container.setPreferredSize(new Dimension(INSTALLER_WINDOW_WIDTH, 415)); container.setMinimumSize(new Dimension(INSTALLER_WINDOW_WIDTH, 415)); return container; } private String readChangeLog() { InputStream in = Installer.class.getResourceAsStream("/latestchanges.html"); try { char[] buff = new char[8192]; StringBuilder contents = new StringBuilder(); InputStreamReader reader = new InputStreamReader(in, "UTF-8"); while (true) { int read = reader.read(buff); if (read == -1) break; contents.append(buff, 0, read); } return "" + contents + ""; } catch (Exception e) { return "No Changelog available"; } finally { try { in.close(); } catch (Exception ignore){ /**/} } } private Component buildUninstallArea() { JPanel container = new JPanel(); container.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; container.add(new JLabel(UNINSTALL_TITLE), constraints); constraints.gridy = 1; constraints.insets = new Insets(8, 0, 0, 16); container.add(new JLabel(UNINSTALL_EXPLANATION), constraints); uninstallBox = Box.createVerticalBox(); constraints.gridy = 2; constraints.fill = GridBagConstraints.HORIZONTAL; container.add(uninstallBox, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridy = 3; container.add(new JLabel("Are you sure?"), constraints); Box buttonBar = Box.createHorizontalBox(); JButton noButton = new JButton("No - Don't uninstall"); buttonBar.add(noButton); buttonBar.add(Box.createHorizontalGlue()); JButton yesButton = new JButton("Yes - uninstall Lombok"); buttonBar.add(yesButton); noButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { uninstallArea.setVisible(false); javacArea.setVisible(true); ideArea.setVisible(true); appWindow.pack(); } }); yesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doUninstall(); } }); constraints.gridy = 4; container.add(buttonBar, constraints); container.setPreferredSize(new Dimension(INSTALLER_WINDOW_WIDTH, 415)); container.setMinimumSize(new Dimension(INSTALLER_WINDOW_WIDTH, 415)); return container; } private Component buildJavacArea() { JPanel container = new JPanel(); container.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(8, 0, 0, 16); container.add(new JLabel(JAVAC_TITLE), constraints); constraints.gridy = 1; constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; container.add(new JLabel(JAVAC_EXPLANATION), constraints); JLabel example = new JLabel(JAVAC_EXAMPLE); constraints.gridy = 2; container.add(example, constraints); container.setPreferredSize(new Dimension(INSTALLER_WINDOW_WIDTH, 105)); container.setMinimumSize(new Dimension(INSTALLER_WINDOW_WIDTH, 105)); return container; } private Component buildIdeArea() { JPanel container = new JPanel(); container.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(8, 0, 0, 16); container.add(new JLabel(IDE_TITLE), constraints); constraints.gridy = 1; container.add(new JLabel(IDE_EXPLANATION), constraints); constraints.gridy = 2; loadingExpl = Box.createHorizontalBox(); loadingExpl.add(new JLabel(new ImageIcon(Installer.class.getResource("loading.gif")))); loadingExpl.add(new JLabel(IDE_LOADING_EXPLANATION)); container.add(loadingExpl, constraints); constraints.weightx = 1.0; constraints.gridy = 3; constraints.fill = GridBagConstraints.HORIZONTAL; idesList = new IdesList(); JScrollPane idesListScroll = new JScrollPane(idesList); idesListScroll.setBackground(Color.WHITE); idesListScroll.getViewport().setBackground(Color.WHITE); container.add(idesListScroll, constraints); Thread findIdesThread = new Thread() { @Override public void run() { try { final List locations = new ArrayList(); final List problems = new ArrayList(); Installer.autoDiscover(locations, problems); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (IdeLocation location : locations) { try { idesList.addLocation(location); } catch (Throwable t) { handleException(t); } } for (CorruptedIdeLocationException problem : problems) { problem.showDialog(appWindow); } loadingExpl.setVisible(false); if (locations.size() + problems.size() == 0) { JOptionPane.showMessageDialog(appWindow, "I can't find any IDEs on your computer.\n" + "If you have IDEs installed on this computer, please use the " + "'Specify Location...' button to manually point out the \n" + "location of your IDE installation to me. Thanks!", "Can't find IDE", JOptionPane.INFORMATION_MESSAGE); } } }); } catch (Throwable t) { handleException(t); } } }; findIdesThread.start(); Box buttonBar = Box.createHorizontalBox(); JButton specifyIdeLocationButton = new JButton("Specify location..."); buttonBar.add(specifyIdeLocationButton); specifyIdeLocationButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { final List exeNames = Installer.getIdeExecutableNames(); String file = null; if (OsUtils.getOS() == OS.MAC_OS_X) { FileDialog chooser = new FileDialog(appWindow); chooser.setMode(FileDialog.LOAD); chooser.setFilenameFilter(new FilenameFilter() { @Override public boolean accept(File dir, String fileName) { for (Pattern exeName : exeNames) if (exeName.matcher(fileName).matches()) return true; return false; } }); chooser.setVisible(true); if (chooser.getDirectory() != null && chooser.getFile() != null) { file = new File(chooser.getDirectory(), chooser.getFile()).getAbsolutePath(); } } else { JFileChooser chooser = new JFileChooser(); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { if (f.isDirectory()) return true; for (Pattern exeName : exeNames) if (exeName.matcher(f.getName()).matches()) return true; return false; } @Override public String getDescription() { return "IDE Installation"; } }); switch (chooser.showDialog(appWindow, "Select")) { case JFileChooser.APPROVE_OPTION: file = chooser.getSelectedFile().getAbsolutePath(); } } if (file != null) { try { IdeLocation loc = Installer.tryAllProviders(file); if (loc != null) idesList.addLocation(loc); else JOptionPane.showMessageDialog(appWindow, "I can't find any IDE that lombok supports at location: " + file, "No IDE found", JOptionPane.WARNING_MESSAGE); } catch (CorruptedIdeLocationException e) { e.showDialog(appWindow); } catch (Throwable t) { handleException(t); } } } }); buttonBar.add(Box.createHorizontalGlue()); installButton = new JButton("Install / Update"); buttonBar.add(installButton); installButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List locationsToInstall = new ArrayList(idesList.getSelectedIdes()); if (locationsToInstall.isEmpty()) { JOptionPane.showMessageDialog(appWindow, "You haven't selected any IDE installations!.", "No Selection", JOptionPane.WARNING_MESSAGE); return; } install(locationsToInstall); } }); constraints.gridy = 4; constraints.weightx = 0; container.add(buttonBar, constraints); constraints.gridy = 5; constraints.fill = GridBagConstraints.NONE; JHyperLink showMe = new JHyperLink("Show me what this installer will do to my IDE installation."); container.add(showMe, constraints); showMe.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showWhatIDo(); } }); constraints.gridy = 6; uninstallButton = new JHyperLink("Uninstall lombok from selected IDE installations."); uninstallPlaceholder = new JLabel(" "); uninstallButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List locationsToUninstall = new ArrayList(); for (IdeLocation location : idesList.getSelectedIdes()) { if (location.hasLombok()) locationsToUninstall.add(location); } if (locationsToUninstall.isEmpty()) { JOptionPane.showMessageDialog(appWindow, "You haven't selected any IDE installations that have been lombok-enabled.", "No Selection", JOptionPane.WARNING_MESSAGE); return; } uninstall(locationsToUninstall); } }); container.add(uninstallButton, constraints); uninstallPlaceholder.setVisible(false); container.add(uninstallPlaceholder, constraints); container.setPreferredSize(new Dimension(INSTALLER_WINDOW_WIDTH, 296)); container.setMinimumSize(new Dimension(INSTALLER_WINDOW_WIDTH, 296)); return container; } private void showWhatIDo() { javacArea.setVisible(false); ideArea.setVisible(false); howIWorkArea.setVisible(true); successArea.setVisible(false); appWindow.pack(); } private void uninstall(List locations) { javacArea.setVisible(false); ideArea.setVisible(false); uninstallBox.removeAll(); uninstallBox.add(Box.createRigidArea(new Dimension(1, 16))); for (IdeLocation location : locations) { JLabel label = new JLabel(location.getName()); label.setFont(label.getFont().deriveFont(Font.BOLD)); uninstallBox.add(label); } uninstallBox.add(Box.createRigidArea(new Dimension(1, 16))); toUninstall = locations; uninstallArea.setVisible(true); appWindow.pack(); } private void install(final List toInstall) { JPanel spinner = new JPanel(); spinner.setOpaque(true); spinner.setLayout(new FlowLayout()); spinner.add(new JLabel(new ImageIcon(Installer.class.getResource("loading.gif")))); final Container appWindowContent = appWindow.getContentPane(); appWindow.setContentPane(spinner); final AtomicInteger successes = new AtomicInteger(); final AtomicBoolean failure = new AtomicBoolean(); new Thread() { @Override public void run() { for (IdeLocation loc : toInstall) { try { installSpecificMessages.add(loc.install()); successes.incrementAndGet(); } catch (final InstallException e) { if (e.isWarning()) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(appWindow, e.getMessage(), "Install Problem", JOptionPane.WARNING_MESSAGE); } }); } catch (Exception e2) { e2.printStackTrace(); //Shouldn't happen. throw new RuntimeException(e2); } } else { failure.set(true); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(appWindow, e.getMessage(), "Install Problem", JOptionPane.ERROR_MESSAGE); } }); } catch (Exception e2) { e2.printStackTrace(); //Shouldn't happen. throw new RuntimeException(e2); } } } } if (successes.get() > 0) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { appWindow.setContentPane(appWindowContent); appWindow.pack(); StringBuilder installSpecific = new StringBuilder(); for (String installSpecificMessage : installSpecificMessages) { installSpecific.append("
    ").append(installSpecificMessage); } showSuccess(installSpecific.toString()); } }); } catch (Exception e) { // Shouldn't happen. throw new RuntimeException(e); } } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { synchronized (exitMarker) { exitMarker.set(failure.get() ? 1 : 0); exitMarker.notifyAll(); } } }); } } }.start(); } private void doUninstall() { JPanel spinner = new JPanel(); spinner.setOpaque(true); spinner.setLayout(new FlowLayout()); spinner.add(new JLabel(new ImageIcon(Installer.class.getResource("/lombok/installer/loading.gif")))); final Container originalContentPane = appWindow.getContentPane(); appWindow.setContentPane(spinner); final AtomicInteger successes = new AtomicInteger(); new Thread(new Runnable() { @Override public void run() { for (IdeLocation loc : toUninstall) { try { loc.uninstall(); successes.incrementAndGet(); } catch (final UninstallException e) { if (e.isWarning()) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(appWindow, e.getMessage(), "Uninstall Problem", JOptionPane.WARNING_MESSAGE); } }); } catch (Exception e2) { e2.printStackTrace(); //Shouldn't happen. throw new RuntimeException(e2); } } else { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(appWindow, e.getMessage(), "Uninstall Problem", JOptionPane.ERROR_MESSAGE); } }); } catch (Exception e2) { e2.printStackTrace(); //Shouldn't happen. throw new RuntimeException(e2); } } } } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (successes.get() > 0) { JOptionPane.showMessageDialog(appWindow, "Lombok has been removed from the selected IDE installations.", "Uninstall successful", JOptionPane.INFORMATION_MESSAGE); appWindow.setVisible(false); System.exit(0); return; } appWindow.setContentPane(originalContentPane); } }); } }).start(); } private IdesList idesList = new IdesList(); void selectedLomboksChanged(List selectedIdes) { boolean uninstallAvailable = false; boolean installAvailable = false; for (IdeLocation loc : selectedIdes) { if (loc.hasLombok()) uninstallAvailable = true; installAvailable = true; } uninstallButton.setVisible(uninstallAvailable); uninstallPlaceholder.setVisible(!uninstallAvailable); installButton.setEnabled(installAvailable); } private class IdesList extends JPanel implements Scrollable { private static final long serialVersionUID = 1L; List locations = new ArrayList(); IdesList() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBackground(Color.WHITE); } List getSelectedIdes() { List list = new ArrayList(); for (IdeLocation loc : locations) if (loc.selected) list.add(loc); return list; } void fireSelectionChange() { selectedLomboksChanged(getSelectedIdes()); } void addLocation(final IdeLocation location) { if (locations.contains(location)) return; Box box = Box.createHorizontalBox(); box.setBackground(Color.WHITE); final JCheckBox checkbox = new JCheckBox(location.getName()); checkbox.setBackground(Color.WHITE); box.add(new JLabel(new ImageIcon(location.getIdeIcon()))); box.add(checkbox); checkbox.setSelected(true); checkbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { location.selected = checkbox.isSelected(); fireSelectionChange(); } }); if (location.hasLombok()) { box.add(new JLabel(new ImageIcon(Installer.class.getResource("lombokIcon.png")))); } box.add(Box.createHorizontalGlue()); locations.add(location); add(box); getParent().doLayout(); fireSelectionChange(); } @Override public Dimension getPreferredScrollableViewportSize() { return new Dimension(1, 100); } @Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return 12; } @Override public boolean getScrollableTracksViewportHeight() { return false; } @Override public boolean getScrollableTracksViewportWidth() { return true; } @Override public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 1; } } private void buildChrome(Container appWindowContainer) { JLabel leftGraphic = new JLabel(new ImageIcon(Installer.class.getResource("lombok.png"))); GridBagConstraints constraints = new GridBagConstraints(); appWindowContainer.setLayout(new GridBagLayout()); constraints.gridheight = 3; constraints.gridwidth = 1; constraints.gridx = 0; constraints.gridy = 0; constraints.insets = new Insets(8, 8, 8, 8); appWindowContainer.add(leftGraphic, constraints); constraints.insets = new Insets(0, 0, 0, 0); constraints.gridx++; constraints.gridy++; constraints.gridheight = 1; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.ipadx = 16; constraints.ipady = 14; appWindowContainer.add(javacArea, constraints); constraints.gridy++; appWindowContainer.add(ideArea, constraints); appWindowContainer.add(uninstallArea, constraints); appWindowContainer.add(howIWorkArea, constraints); appWindowContainer.add(successArea, constraints); constraints.gridy++; constraints.gridwidth = 2; constraints.gridx = 0; constraints.weightx = 0; constraints.weighty = 0; constraints.ipadx = 0; constraints.ipady = 0; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.anchor = GridBagConstraints.SOUTHWEST; constraints.insets = new Insets(0, 16, 8, 8); appWindow.add(buildButtonBar(), constraints); } private Box buildButtonBar() { Box buttonBar = Box.createHorizontalBox(); JHyperLink aboutLink = new JHyperLink(Installer.ABOUT_LOMBOK_URL.toString()); aboutLink.addActionListener(openBrowser(aboutLink, Installer.ABOUT_LOMBOK_URL)); buttonBar.add(aboutLink); buttonBar.add(Box.createRigidArea(new Dimension(16, 1))); JLabel versionLabel = new JLabel(); versionLabel.setText("v" + Version.getVersion()); buttonBar.add(versionLabel); buttonBar.add(Box.createRigidArea(new Dimension(16, 1))); JHyperLink changelogLink = new JHyperLink("View full changelog"); changelogLink.addActionListener(openBrowser(changelogLink, Installer.ABOUT_LOMBOK_URL.resolve("/changelog.html"))); buttonBar.add(changelogLink); buttonBar.add(Box.createHorizontalGlue()); JButton quitButton = new JButton("Quit Installer"); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { appWindow.setVisible(false); System.exit(0); } }); buttonBar.add(quitButton); return buttonBar; } private ActionListener openBrowser(final JHyperLink hyperlink, final URI location) { return new ActionListener() { @Override public void actionPerformed(ActionEvent event) { hyperlink.setForeground(new Color(85, 145, 90)); try { //java.awt.Desktop doesn't exist in 1.5. Object desktop = Class.forName("java.awt.Desktop").getMethod("getDesktop").invoke(null); Class.forName("java.awt.Desktop").getMethod("browse", URI.class).invoke(desktop, location); } catch (Exception e) { Runtime rt = Runtime.getRuntime(); try { switch (OsUtils.getOS()) { case WINDOWS: String[] cmd = new String[4]; cmd[0] = "cmd.exe"; cmd[1] = "/C"; cmd[2] = "start"; cmd[3] = location.toString(); rt.exec(cmd); break; case MAC_OS_X: rt.exec("open " + location.toString()); break; default: case UNIX: rt.exec("firefox " + location.toString()); break; } } catch (Exception e2) { JOptionPane.showMessageDialog(appWindow, "Well, this is embarrassing. I don't know how to open a webbrowser.\n" + "I guess you'll have to open it. Browse to:\n" + location + " for more information about Lombok.", "I'm embarrassed", JOptionPane.INFORMATION_MESSAGE); } } } }; } /** * Makes the installer window visible. */ public void show() { appWindow.setVisible(true); if (OsUtils.getOS() == OS.MAC_OS_X) { try { AppleNativeLook.go(); } catch (Throwable ignore) { //We're just prettying up the app. If it fails, meh. } } } private static final String IDE_TITLE = "IDEs "; private static final String IDE_EXPLANATION = "Lombok can update your Eclipse or eclipse-based IDE to fully support all Lombok features.
    " + "Select IDE installations below and hit 'Install/Update'."; private static final String IDE_LOADING_EXPLANATION = "Scanning your drives for IDE installations..."; private static final String JAVAC_TITLE = "Javac       (and tools that invoke javac such as ant and maven)"; private static final String JAVAC_EXPLANATION = "Lombok works 'out of the box' with javac.
    Just make sure the lombok.jar is in your classpath when you compile."; private static final String JAVAC_EXAMPLE = "Example: javac -cp lombok.jar MyCode.java"; private static final String UNINSTALL_TITLE = "Uninstall "; private static final String UNINSTALL_EXPLANATION = "Uninstall Lombok from the following IDE Installations?"; private static final String HOW_I_WORK_TITLE = "What this installer does "; private static final String HOW_I_WORK_EXPLANATION = "

    Eclipse

      " + "
    1. First, I copy myself (lombok.jar) to your Eclipse install directory.
    2. " + "
    3. Then, I edit the eclipse.ini file to add the following entry:
      " + "
      -javaagent:lombok.jar
    " + "On Mac OS X, eclipse.ini is hidden in
    " + "Eclipse.app/Contents/MacOS so that's where I place the jar files."; private static final String SUCCESS_TITLE = "Install successful "; private static final String SUCCESS_EXPLANATION = "Lombok has been installed on the selected IDE installations.
    " + "Don't forget to:
    • add lombok.jar to your projects,
    • exit and start your IDE,
    • rebuild all projects!
    %%%"; private static class JHyperLink extends JButton { private static final long serialVersionUID = 1L; public JHyperLink(String text) { super(); setFont(getFont().deriveFont(Collections.singletonMap(TextAttribute.UNDERLINE, 1))); setText(text); setBorder(null); setContentAreaFilled(false); setForeground(Color.BLUE); setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); setMargin(new Insets(0, 0, 0, 0)); } } } lombok-1.16.18/src/installer/lombok/installer/OsUtils.java000066400000000000000000000102451312655740700235000ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import lombok.core.Version; /** * Implement and provide this class to add auto-finding a certain brand of IDEs to the lombok installer. */ public final class OsUtils { private static final AtomicBoolean windowsDriveInfoLibLoaded = new AtomicBoolean(false); private OsUtils() { // Prevent instantiation } private static void loadWindowsDriveInfoLib() throws IOException { if (!windowsDriveInfoLibLoaded.compareAndSet(false, true)) return; final String prefix = "lombok-" + Version.getVersion() + "-"; File temp = File.createTempFile("lombok", ".mark"); File dll1 = new File(temp.getParentFile(), prefix + "WindowsDriveInfo-i386.dll"); File dll2 = new File(temp.getParentFile(), prefix + "WindowsDriveInfo-x86_64.dll"); temp.delete(); dll1.deleteOnExit(); dll2.deleteOnExit(); try { if (unpackDLL("WindowsDriveInfo-i386.dll", dll1)) { System.load(dll1.getAbsolutePath()); return; } } catch (Throwable ignore) {} try { if (unpackDLL("WindowsDriveInfo-x86_64.dll", dll2)) { System.load(dll2.getAbsolutePath()); } } catch (Throwable ignore) {} } private static boolean unpackDLL(String dllName, File target) throws IOException { InputStream in = OsUtils.class.getResourceAsStream(dllName); try { try { FileOutputStream out = new FileOutputStream(target); try { byte[] b = new byte[32000]; while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } } finally { out.close(); } } catch (IOException e) { //Fall through - if there is a file named lombok-WindowsDriveInfo-arch.dll, we'll try it. return target.exists() && target.canRead(); } } finally { in.close(); } return true; } /** * Returns all drive letters on windows that represent fixed disks. * * Floppy drives, optical drives, USB sticks, and network drives should all be excluded. * * @return A List of drive letters, such as ["C", "D", "X"]. */ public static List getDrivesOnWindows() throws Throwable { loadWindowsDriveInfoLib(); List drives = new ArrayList(); WindowsDriveInfo info = new WindowsDriveInfo(); for (String drive : info.getLogicalDrives()) { if (info.isFixedDisk(drive)) drives.add(drive); } return drives; } public static enum OS { MAC_OS_X("\n"), WINDOWS("\r\n"), UNIX("\n"); private final String lineEnding; OS(String lineEnding) { this.lineEnding = lineEnding; } public String getLineEnding() { return lineEnding; } } public static OS getOS() { String prop = System.getProperty("os.name", "").toLowerCase(); if (prop.matches("^.*\\bmac\\b.*$")) return OS.MAC_OS_X; if (prop.matches("^.*\\bdarwin\\b.*$")) return OS.MAC_OS_X; if (prop.matches("^.*\\bwin(dows|32|64)?\\b.*$")) return OS.WINDOWS; return OS.UNIX; } } lombok-1.16.18/src/installer/lombok/installer/UninstallException.java000066400000000000000000000030721312655740700257260ustar00rootroot00000000000000/* * Copyright (C) 2009-2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; /** * Thrown when uninstallation of lombok into an IDE fails. */ public class UninstallException extends Exception { private boolean warning; public UninstallException(String message, Throwable cause) { super(message, cause); } public UninstallException(boolean warning, String message, Throwable cause) { super(message, cause); this.warning = warning; } public boolean isWarning() { return warning; } } lombok-1.16.18/src/installer/lombok/installer/WindowsDriveInfo.java000066400000000000000000000114531312655740700253400ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer; import java.util.ArrayList; import java.util.List; /** * This class uses native calls on windows to figure out all drives, * and, for each drive, if its a harddisk or something else. * * The output is essentially equivalent to running windows executable: *
    fsutil fsinfo drives
    * and *
    fsutil fsinfo drivetype C:
    * * except that (A) fsutil requires privileges, (B) someone might have moved * it out of the path or some such, and (C) its output is internationalized, * so unless you want to include a table of how to say "Fixed Disk" in 300 * languages, this really is a superior solution. *

    * To compile it, you'll need windows, as well as MinGW: * http://sourceforge.net/projects/mingw/files/ *

    * Fetch gcc 4.0.4+, you don't need anything extra. Toss /c/mingw/bin in * your git bash prompt's path (/etc/profile) and then run: * * $ gcc -c \ -I "/c/Program Files/Java/jdk1.6.0_14/include" \ -I "/c/Program Files/Java/jdk1.6.0_14/include/win32" \ -D__int64="long long" lombok_installer_WindowsDriveInfo.c * * $ dllwrap.exe --add-stdcall-alias \ -o WindowsDriveInfo-i386.dll \ lombok_installer_WindowsDriveInfo.o * * You may get a warning along the lines of "Creating an export definition". * This is expected behaviour. * *

    * Now download MinGW-w64 to build the 64-bit version of the dll (you thought you were done, weren't you?) * from: http://sourceforge.net/projects/mingw-w64/files/ * (under toolchains targetting Win64 / Release for GCC 4.4.0 (or later) / the version for your OS.) * * Then, do this all over again, but this time with the x86_64-w64-mingw32-gcc and * x86_64-w64-mingw32-dllwrap versions that are part of the MinGW-w64 distribution. * Name the dll 'WindowsDriveInfo-x86_64.dll'. * * Both the 32-bit and 64-bit DLLs that this produces have been checked into the git repository * under src/lombok/installer so you won't need to build them again unless you make some changes to * the code in the winsrc directory. */ public class WindowsDriveInfo { /** * Return a list of all available drive letters, such as ["A", "C", "D"]. */ public List getLogicalDrives() { int flags = getLogicalDrives0(); List letters = new ArrayList(); for (int i = 0; i < 26; i++) { if ((flags & (1 << i)) != 0) letters.add(Character.toString((char)('A' + i))); } return letters; } /** * Calls kernel32's GetLogicalDrives, which returns an int containing * flags; bit 0 corresponds to drive A, bit 25 to drive Z. on = disk exists. */ private native int getLogicalDrives0(); /** * Feed it a drive letter (such as 'A') to see if it is a fixed disk. */ public boolean isFixedDisk(String letter) { if (letter.length() != 1) throw new IllegalArgumentException("Supply 1 letter, not: " + letter); char drive = Character.toUpperCase(letter.charAt(0)); if (drive < 'A' || drive > 'Z') throw new IllegalArgumentException( "A drive is indicated by a letter, so A-Z inclusive. Not " + drive); return getDriveType(drive + ":\\") == 3L; } /** * Mirror of kernel32's GetDriveTypeA. You must pass in 'A:\\' - * so including both a colon and a backslash! * * 0 = error * 1 = doesn't exist * 2 = removable drive * 3 = fixed disk * 4 = remote (network) disk * 5 = cd-rom * 6 = ram disk */ private native int getDriveType(String name); public static void main(String[] args) { System.loadLibrary("WindowsDriveInfo"); WindowsDriveInfo info = new WindowsDriveInfo(); for (String letter : info.getLogicalDrives()) { System.out.printf("Drive %s: - %s\n", letter, info.isFixedDisk(letter) ? "Fixed Disk" : "Not Fixed Disk"); } } } lombok-1.16.18/src/installer/lombok/installer/eclipse/000077500000000000000000000000001312655740700226555ustar00rootroot00000000000000lombok-1.16.18/src/installer/lombok/installer/eclipse/EclipseLocationProvider.java000066400000000000000000000032441312655740700303130ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer.eclipse; import java.util.Collections; import lombok.installer.IdeLocationProvider; import org.mangosdk.spi.ProviderFor; @ProviderFor(IdeLocationProvider.class) public class EclipseLocationProvider extends EclipseProductLocationProvider { private static final EclipseProductDescriptor ECLIPSE = new StandardProductDescriptor( "Eclipse", "eclipse", "eclipse", EclipseLocationProvider.class.getResource("eclipse.png"), Collections.emptySet() ); public EclipseLocationProvider() { super(ECLIPSE); } } lombok-1.16.18/src/installer/lombok/installer/eclipse/EclipseProductDescriptor.java000066400000000000000000000031741312655740700305110ustar00rootroot00000000000000/* * Copyright (C) 2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer.eclipse; import java.net.URL; import java.util.List; import java.util.regex.Pattern; public interface EclipseProductDescriptor { String getProductName(); String getWindowsExecutableName(); String getUnixAppName(); String getMacAppName(); String getDirectoryName(); List getExecutableNames(); List getSourceDirsOnWindows(); List getSourceDirsOnMac(); List getSourceDirsOnUnix(); String getIniFileName(); Pattern getLocationSelectors(); URL getIdeIcon(); }lombok-1.16.18/src/installer/lombok/installer/eclipse/EclipseProductLocation.java000066400000000000000000000333011312655740700301360ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer.eclipse; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import lombok.installer.CorruptedIdeLocationException; import lombok.installer.OsUtils; import lombok.installer.IdeLocation; import lombok.installer.InstallException; import lombok.installer.Installer; import lombok.installer.UninstallException; /** * Represents an Eclipse installation. * An instance can figure out if an Eclipse installation has been lombok-ified, and can * install and uninstall lombok from the Eclipse installation. */ public final class EclipseProductLocation extends IdeLocation { private static final String OS_NEWLINE = OsUtils.getOS().getLineEnding(); private final EclipseProductDescriptor descriptor; private final String name; private final File eclipseIniPath; private final String pathToLombokJarPrefix; private final boolean hasLombok; EclipseProductLocation(EclipseProductDescriptor descriptor, String nameOfLocation, File pathToEclipseIni) throws CorruptedIdeLocationException { this.descriptor = descriptor; this.name = nameOfLocation; this.eclipseIniPath = pathToEclipseIni; File p1 = pathToEclipseIni.getParentFile(); File p2 = p1 == null ? null : p1.getParentFile(); File p3 = p2 == null ? null : p2.getParentFile(); if (p1 != null && p1.getName().equals("Eclipse") && p2 != null && p2.getName().equals("Contents") && p3 != null && p3.getName().endsWith(".app")) { this.pathToLombokJarPrefix = "../Eclipse/"; } else { this.pathToLombokJarPrefix = ""; } try { this.hasLombok = checkForLombok(eclipseIniPath); } catch (IOException e) { throw new CorruptedIdeLocationException( "I can't read the configuration file of the " + descriptor.getProductName() + " installed at " + name + "\n" + "You may need to run this installer with root privileges if you want to modify that " + descriptor.getProductName() + ".", descriptor.getProductName(), e); } } @Override public int hashCode() { return eclipseIniPath.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof EclipseProductLocation)) return false; return ((EclipseProductLocation)o).eclipseIniPath.equals(eclipseIniPath); } /** * Returns the name of this location; generally the path to the eclipse executable. */ @Override public String getName() { return name; } /** * @return true if the Eclipse installation has been instrumented with lombok. */ @Override public boolean hasLombok() { return hasLombok; } private static final Pattern JAVA_AGENT_LINE_MATCHER = Pattern.compile( "^\\-javaagent\\:.*lombok.*\\.jar$", Pattern.CASE_INSENSITIVE); private static final Pattern BOOTCLASSPATH_LINE_MATCHER = Pattern.compile( "^\\-Xbootclasspath\\/a\\:(.*lombok.*\\.jar.*)$", Pattern.CASE_INSENSITIVE); private static boolean checkForLombok(File iniFile) throws IOException { if (!iniFile.exists()) return false; FileInputStream fis = new FileInputStream(iniFile); try { BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { if (JAVA_AGENT_LINE_MATCHER.matcher(line.trim()).matches()) { br.close(); return true; } } br.close(); return false; } finally { fis.close(); } } /** Returns directories that may contain lombok.jar files that need to be deleted. */ private List getUninstallDirs() { List result = new ArrayList(); File x = new File(name); if (!x.isDirectory()) x = x.getParentFile(); if (x.isDirectory()) result.add(x); result.add(eclipseIniPath.getParentFile()); return result; } /** * Uninstalls lombok from this location. * It's a no-op if lombok wasn't there in the first place, * and it will remove a half-succeeded lombok installation as well. * * @throws UninstallException * If there's an obvious I/O problem that is preventing * installation. bugs in the uninstall code will probably throw * other exceptions; this is intentional. */ @Override public void uninstall() throws UninstallException { final List lombokJarsForWhichCantDeleteSelf = new ArrayList(); StringBuilder newContents = new StringBuilder(); if (eclipseIniPath.exists()) { try { FileInputStream fis = new FileInputStream(eclipseIniPath); try { BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { if (JAVA_AGENT_LINE_MATCHER.matcher(line).matches()) continue; Matcher m = BOOTCLASSPATH_LINE_MATCHER.matcher(line); if (m.matches()) { StringBuilder elemBuilder = new StringBuilder(); elemBuilder.append("-Xbootclasspath/a:"); boolean first = true; for (String elem : m.group(1).split(Pattern.quote(File.pathSeparator))) { if (elem.toLowerCase().endsWith("lombok.jar")) continue; /* legacy code -see previous comment that starts with 'legacy' */ { if (elem.toLowerCase().endsWith("lombok.eclipse.agent.jar")) continue; } if (first) first = false; else elemBuilder.append(File.pathSeparator); elemBuilder.append(elem); } if (!first) newContents.append(elemBuilder.toString()).append(OS_NEWLINE); continue; } newContents.append(line).append(OS_NEWLINE); } br.close(); } finally { fis.close(); } FileOutputStream fos = new FileOutputStream(eclipseIniPath); try { fos.write(newContents.toString().getBytes()); } finally { fos.close(); } } catch (IOException e) { throw new UninstallException("Cannot uninstall lombok from " + name + generateWriteErrorMessage(), e); } } for (File dir : getUninstallDirs()) { File lombokJar = new File(dir, "lombok.jar"); if (lombokJar.exists()) { if (!lombokJar.delete()) { if (OsUtils.getOS() == OsUtils.OS.WINDOWS && Installer.isSelf(lombokJar.getAbsolutePath())) { lombokJarsForWhichCantDeleteSelf.add(lombokJar); } else { throw new UninstallException( "Can't delete " + lombokJar.getAbsolutePath() + generateWriteErrorMessage(), null); } } } /* legacy code - lombok at one point used to have a separate jar for the eclipse agent. * Leave this code in to delete it for those upgrading from an old version. */ { File agentJar = new File(dir, "lombok.eclipse.agent.jar"); if (agentJar.exists()) { agentJar.delete(); } } } if (!lombokJarsForWhichCantDeleteSelf.isEmpty()) { throw new UninstallException(true, String.format( "lombok.jar cannot delete itself on windows.\nHowever, lombok has been uncoupled from your %s.\n" + "You can safely delete this jar file. You can find it at:\n%s", descriptor.getProductName(), lombokJarsForWhichCantDeleteSelf.get(0).getAbsolutePath()), null); } } private static String generateWriteErrorMessage() { String osSpecificError; switch (OsUtils.getOS()) { default: case MAC_OS_X: case UNIX: osSpecificError = ":\nStart terminal, go to the directory with lombok.jar, and run: sudo java -jar lombok.jar"; break; case WINDOWS: osSpecificError = ":\nStart a new cmd (dos box) with admin privileges, go to the directory with lombok.jar, and run: java -jar lombok.jar"; break; } return ", probably because this installer does not have the access rights.\n" + "Try re-running the installer with administrative privileges" + osSpecificError; } /** * Install lombok into the Eclipse at this location. * If lombok is already there, it is overwritten neatly (upgrade mode). * * @throws InstallException * If there's an obvious I/O problem that is preventing * installation. bugs in the install code will probably throw * other exceptions; this is intentional. */ @Override public String install() throws InstallException { // For whatever reason, relative paths in your eclipse.ini file don't work on linux, but only for -javaagent. // If someone knows how to fix this, please do so, as this current hack solution (putting the absolute path // to the jar files in your eclipse.ini) means you can't move your eclipse around on linux without lombok // breaking it. NB: rerunning lombok.jar installer and hitting 'update' will fix it if you do that. boolean fullPathRequired = OsUtils.getOS() == OsUtils.OS.UNIX || System.getProperty("lombok.installer.fullpath") != null; boolean installSucceeded = false; StringBuilder newContents = new StringBuilder(); File lombokJar = new File(eclipseIniPath.getParentFile(), "lombok.jar"); /* No need to copy lombok.jar to itself, obviously. On windows this would generate an error so we check for this. */ if (!Installer.isSelf(lombokJar.getAbsolutePath())) { File ourJar = findOurJar(); byte[] b = new byte[524288]; boolean readSucceeded = true; try { FileOutputStream out = new FileOutputStream(lombokJar); try { readSucceeded = false; InputStream in = new FileInputStream(ourJar); try { while (true) { int r = in.read(b); if (r == -1) break; if (r > 0) readSucceeded = true; out.write(b, 0, r); } } finally { in.close(); } } finally { out.close(); } } catch (IOException e) { try { lombokJar.delete(); } catch (Throwable ignore) { /* Nothing we can do about that. */ } if (!readSucceeded) throw new InstallException( "I can't read my own jar file. I think you've found a bug in this installer!\nI suggest you restart it " + "and use the 'what do I do' link, to manually install lombok. Also, tell us about this at:\n" + "http://groups.google.com/group/project-lombok - Thanks!", e); throw new InstallException("I can't write to your " + descriptor.getProductName() + " directory at " + name + generateWriteErrorMessage(), e); } } /* legacy - delete lombok.eclipse.agent.jar if its there, which lombok no longer uses. */ { new File(lombokJar.getParentFile(), "lombok.eclipse.agent.jar").delete(); } try { FileInputStream fis = new FileInputStream(eclipseIniPath); try { BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { if (JAVA_AGENT_LINE_MATCHER.matcher(line).matches()) continue; Matcher m = BOOTCLASSPATH_LINE_MATCHER.matcher(line); if (m.matches()) { StringBuilder elemBuilder = new StringBuilder(); elemBuilder.append("-Xbootclasspath/a:"); boolean first = true; for (String elem : m.group(1).split(Pattern.quote(File.pathSeparator))) { if (elem.toLowerCase().endsWith("lombok.jar")) continue; /* legacy code -see previous comment that starts with 'legacy' */ { if (elem.toLowerCase().endsWith("lombok.eclipse.agent.jar")) continue; } if (first) first = false; else elemBuilder.append(File.pathSeparator); elemBuilder.append(elem); } if (!first) newContents.append(elemBuilder.toString()).append(OS_NEWLINE); continue; } newContents.append(line).append(OS_NEWLINE); } br.close(); } finally { fis.close(); } String pathPrefix; if (fullPathRequired) { pathPrefix = lombokJar.getParentFile().getCanonicalPath() + File.separator; } else { pathPrefix = pathToLombokJarPrefix; } newContents.append(String.format( "-javaagent:%s", escapePath(pathPrefix + "lombok.jar"))).append(OS_NEWLINE); FileOutputStream fos = new FileOutputStream(eclipseIniPath); try { fos.write(newContents.toString().getBytes()); } finally { fos.close(); } installSucceeded = true; } catch (IOException e) { throw new InstallException("Cannot install lombok at " + name + generateWriteErrorMessage(), e); } finally { if (!installSucceeded) try { lombokJar.delete(); } catch (Throwable ignore) {} } if (!installSucceeded) { throw new InstallException("I can't find the " + descriptor.getIniFileName() + " file. Is this a real " + descriptor.getProductName() + " installation?", null); } return "If you start " + descriptor.getProductName() + " with a custom -vm parameter, you'll need to add:
    " + "-vmargs -javaagent:lombok.jar
    as parameter as well."; } @Override public URL getIdeIcon() { return descriptor.getIdeIcon(); } } lombok-1.16.18/src/installer/lombok/installer/eclipse/EclipseProductLocationProvider.java000066400000000000000000000300141312655740700316470ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer.eclipse; import static java.util.Arrays.asList; import static lombok.installer.IdeLocation.canonical; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import lombok.installer.CorruptedIdeLocationException; import lombok.installer.OsUtils; import lombok.installer.IdeLocation; import lombok.installer.IdeLocationProvider; public class EclipseProductLocationProvider implements IdeLocationProvider { private final EclipseProductDescriptor descriptor; EclipseProductLocationProvider(EclipseProductDescriptor descriptor) { this.descriptor = descriptor; } @Override public final IdeLocation create(String path) throws CorruptedIdeLocationException { return create0(path); } /** * Create a new EclipseLocation by pointing at either the directory contains the Eclipse executable, or the executable itself, * or an eclipse.ini file. * * @throws NotAnIdeLocationException * If this isn't an Eclipse executable or a directory with an * Eclipse executable. */ private IdeLocation create0(String path) throws CorruptedIdeLocationException { if (path == null) throw new NullPointerException("path"); String iniName = descriptor.getIniFileName(); File p = new File(path); if (!p.exists()) return null; if (p.isDirectory()) { for (String possibleExeName : descriptor.getExecutableNames()) { File f = new File(p, possibleExeName); if (f.exists()) return findEclipseIniFromExe(f, 0); } File f = new File(p, iniName); if (f.exists()) return makeLocation(canonical(p), f); } if (p.isFile()) { if (p.getName().equalsIgnoreCase(iniName)) { return makeLocation(canonical(p.getParentFile()), p); } } if (descriptor.getExecutableNames().contains(p.getName().toLowerCase())) { return findEclipseIniFromExe(p, 0); } return null; } private IdeLocation findEclipseIniFromExe(File exePath, int loopCounter) throws CorruptedIdeLocationException { String iniName = descriptor.getIniFileName(); /* Try looking for eclipse.ini as sibling to the executable */ { File ini = new File(exePath.getParentFile(), iniName); if (ini.isFile()) return makeLocation(canonical(exePath), ini); } String macAppName = descriptor.getMacAppName(); /* Try looking for Eclipse.app/Contents/MacOS/eclipse.ini as sibling to executable; this works on Mac OS X. */ { File ini = new File(exePath.getParentFile(), macAppName + "/Contents/MacOS/" + iniName); if (ini.isFile()) return makeLocation(canonical(exePath), ini); } /* Starting with Eclipse Mars (with the oomph installer), the structure has changed, and it's now at Eclipse.app/Contents/Eclipse/eclipse.ini*/ { File ini = new File(exePath.getParentFile(), macAppName + "/Contents/Eclipse/" + iniName); if (ini.isFile()) return makeLocation(canonical(exePath), ini); } /* If executable is a soft link, follow it and retry. */ { if (loopCounter < 50) { try { String oPath = exePath.getAbsolutePath(); String nPath = exePath.getCanonicalPath(); if (!oPath.equals(nPath)) try { IdeLocation loc = findEclipseIniFromExe(new File(nPath), loopCounter + 1); if (loc != null) return loc; } catch (CorruptedIdeLocationException ignore) { // Unlinking didn't help find an eclipse, so continue. } } catch (IOException ignore) { /* okay, that didn't work, assume it isn't a soft link then. */ } } } /* If executable is a linux LSB-style path, then look in the usual places that package managers like apt-get use.*/ { String path = exePath.getAbsolutePath(); try { path = exePath.getCanonicalPath(); } catch (IOException ignore) { /* We'll stick with getAbsolutePath()'s result then. */ } String unixAppName = descriptor.getUnixAppName(); if (path.equals("/usr/bin/" + unixAppName) || path.equals("/bin/" + unixAppName) || path.equals("/usr/local/bin/" + unixAppName)) { File ini = new File("/usr/lib/" + unixAppName + "/" + iniName); if (ini.isFile()) return makeLocation(path, ini); ini = new File("/usr/local/lib/" + unixAppName + "/" + iniName); if (ini.isFile()) return makeLocation(path, ini); ini = new File("/usr/local/etc/" + unixAppName + "/" + iniName); if (ini.isFile()) return makeLocation(path, ini); ini = new File("/etc/" + iniName); if (ini.isFile()) return makeLocation(path, ini); } } /* If we get this far, we lose. */ return null; } private IdeLocation makeLocation(String name, File ini) throws CorruptedIdeLocationException { return new EclipseProductLocation(descriptor, name, ini); } @Override public Pattern getLocationSelectors() { return descriptor.getLocationSelectors(); } /** * Calls the OS-dependent 'find Eclipse' routine. If the local OS doesn't have a routine written for it, * null is returned. * * @param locations * List of valid eclipse locations - provide an empty list; this * method will fill it. * @param problems * List of eclipse locations that seem to contain half-baked * eclipses that can't be installed. Provide an empty list; this * method will fill it. */ @Override public void findIdes(List locations, List problems) { switch (OsUtils.getOS()) { case WINDOWS: new WindowsFinder().findEclipse(locations, problems); break; case MAC_OS_X: new MacFinder().findEclipse(locations, problems); break; default: case UNIX: new UnixFinder().findEclipse(locations, problems); break; } } private List transformToFiles(List fileNames) { List files = new ArrayList(); for (String fileName : fileNames) { files.add(new File(fileName)); } return files; } private List getFlatSourceLocationsOnUnix() { List dirs = new ArrayList(); dirs.add(new File("/usr/bin/")); dirs.add(new File("/usr/local/bin/")); dirs.add(new File(System.getProperty("user.home", "."), "bin/")); return dirs; } private List getNestedSourceLocationOnUnix() { List dirs = new ArrayList(); dirs.add(new File("/usr/local/share")); dirs.add(new File("/usr/local")); dirs.add(new File("/usr/share")); return dirs; } private class UnixFinder extends DirectoryFinder { UnixFinder() { super(getNestedSourceLocationOnUnix(), getFlatSourceLocationsOnUnix()); } @Override protected String findEclipseOnPlatform(File dir) { File possible = new File(dir, descriptor.getUnixAppName()); return (possible.exists()) ? possible.getAbsolutePath() : null; } } /** * Returns a list of paths of Eclipse installations. * * The search process works by scanning for each 'source dir' for either an eclipse installation or a folder containing the text returned * by getDirName(). If such a folder is found, this process is applied recursively. On windows, this process is run on each drive letter * which represents a physical hard disk. If the native windows API call to determine these drive letters fails, only 'C:' is checked. */ private List getSourceDirsOnWindowsWithDriveLetters() { List driveLetters = asList("C"); try { driveLetters = OsUtils.getDrivesOnWindows(); } catch (Throwable ignore) { ignore.printStackTrace(); } List sourceDirs = new ArrayList(); for (String letter : driveLetters) { for (String possibleSource : descriptor.getSourceDirsOnWindows()) { if (!isDriveSpecificOnWindows(possibleSource)) { sourceDirs.add(letter + ":" + possibleSource); } } } for (String possibleSource : descriptor.getSourceDirsOnWindows()) { if (isDriveSpecificOnWindows(possibleSource)) sourceDirs.add(possibleSource); } return sourceDirs; } private boolean isDriveSpecificOnWindows(String path) { return path.length() > 1 && path.charAt(1) == ':'; } private class WindowsFinder extends DirectoryFinder { WindowsFinder() { super(transformToFiles(getSourceDirsOnWindowsWithDriveLetters()), Collections.emptyList()); } /** Checks if the provided directory contains 'eclipse.exe', and if so, returns the directory, otherwise null. */ @Override protected String findEclipseOnPlatform(File dir) { File possible = new File(dir, descriptor.getWindowsExecutableName()); return (possible.isFile()) ? dir.getAbsolutePath() : null; } } private class MacFinder extends DirectoryFinder { MacFinder() { super(transformToFiles(descriptor.getSourceDirsOnMac()), Collections.emptyList()); } protected String findEclipseOnPlatform(File dir) { if (dir.getName().toLowerCase().equals(descriptor.getMacAppName().toLowerCase())) return dir.getParent(); if (dir.getName().toLowerCase().contains(descriptor.getDirectoryName())) { if (new File(dir, descriptor.getMacAppName()).exists()) return dir.toString(); } return null; } } private abstract class DirectoryFinder { private final List flatSourceDirs; private final List nestedSourceDirs; DirectoryFinder(List nestedSourceDirs, List flatSourceDirs) { this.nestedSourceDirs = nestedSourceDirs; this.flatSourceDirs = flatSourceDirs; } void findEclipse(List locations, List problems) { for (File dir : nestedSourceDirs) recurseDirectory(locations, problems, dir); for (File dir : flatSourceDirs) findEclipse(locations, problems, dir); } abstract String findEclipseOnPlatform(File dir); void recurseDirectory(List locations, List problems, File dir) { recurseDirectory0(locations, problems, dir, 0, false); } private void recurseDirectory0(List locations, List problems, File f, int loopCounter, boolean nameFound) { //Various try/catch/ignore statements are in this for loop. Weird conditions on the disk can cause exceptions, //such as an unformatted drive causing a NullPointerException on listFiles. Best action is almost invariably to just //continue onwards. File[] listFiles = f.listFiles(); if (listFiles == null) return; for (File dir : listFiles) { if (!dir.isDirectory()) continue; try { if (nameFound || dir.getName().toLowerCase().contains(descriptor.getDirectoryName())) { findEclipse(locations, problems, dir); if (loopCounter < 50) recurseDirectory0(locations, problems, dir, loopCounter + 1, true); } } catch (Exception ignore) {} } } private void findEclipse(List locations, List problems, File dir) { String eclipseLocation = findEclipseOnPlatform(dir); if (eclipseLocation != null) { try { IdeLocation newLocation = create(eclipseLocation); if (newLocation != null) locations.add(newLocation); } catch (CorruptedIdeLocationException e) { problems.add(e); } } } } } lombok-1.16.18/src/installer/lombok/installer/eclipse/JbdsLocationProvider.java000066400000000000000000000032441312655740700276110ustar00rootroot00000000000000/* * Copyright (C) 2013-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer.eclipse; import java.util.Collections; import lombok.installer.IdeLocationProvider; import org.mangosdk.spi.ProviderFor; @ProviderFor(IdeLocationProvider.class) public class JbdsLocationProvider extends EclipseProductLocationProvider { private static final EclipseProductDescriptor JBDS = new StandardProductDescriptor( "JBoss Developer Studio", "jbdevstudio", "studio", JbdsLocationProvider.class.getResource("jbds.png"), Collections.emptySet() ); public JbdsLocationProvider() { super(JBDS); } } lombok-1.16.18/src/installer/lombok/installer/eclipse/MyEclipseLocationProvider.java000066400000000000000000000032631312655740700306220ustar00rootroot00000000000000/* * Copyright (C) 2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer.eclipse; import java.util.Collections; import lombok.installer.IdeLocationProvider; import org.mangosdk.spi.ProviderFor; @ProviderFor(IdeLocationProvider.class) public class MyEclipseLocationProvider extends EclipseProductLocationProvider { private static final EclipseProductDescriptor MY_ECLIPSE = new StandardProductDescriptor( "MyEclipse", "myeclipse", "myeclipse", MyEclipseLocationProvider.class.getResource("myeclipse.png"), Collections.emptySet() ); public MyEclipseLocationProvider() { super(MY_ECLIPSE); } } lombok-1.16.18/src/installer/lombok/installer/eclipse/RhdsLocationProvider.java000066400000000000000000000032531312655740700276270ustar00rootroot00000000000000/* * Copyright (C) 2013-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer.eclipse; import java.util.Collections; import lombok.installer.IdeLocationProvider; import org.mangosdk.spi.ProviderFor; @ProviderFor(IdeLocationProvider.class) public class RhdsLocationProvider extends EclipseProductLocationProvider { private static final EclipseProductDescriptor RHDS = new StandardProductDescriptor( "Red Hat JBoss Developer Studio", "devstudio", "studio", RhdsLocationProvider.class.getResource("rhds.png"), Collections.emptySet() ); public RhdsLocationProvider() { super(RHDS); } } lombok-1.16.18/src/installer/lombok/installer/eclipse/STS.png000066400000000000000000000034171312655740700240410ustar00rootroot00000000000000‰PNG  IHDRàw=øtEXtSoftwareAdobe ImageReadyqÉe<±IDATxÚtV l×½ïÍ›ÏÎ~½ïbll ¡±@ìʸÂh$§(‚¦Ê¯-ªPUH©T)•Ú&Uµ*µ¢@+ª~)­ ”’8´ ‚qj\ÇÁš5ÇØ»özmïÏû›_ïì¬q5Oš™·;ï{ß¹çÞ;Ä0ŒZHÂGF¶XÈ…g' A—DŽ=~üÊkî³2ºïMCåÒD:ùm­ÿÀo C$„÷Àÿn†·)¼Tó—ªk0Ÿ*]±LnÍETÕâsÃW›Ï¥¡¥º¥{¿p¦µ¦øìDüòÏ%>¸³Òµc‹¦gõn¨@ ÿAŠ7‡9K Àw_= §G.Ïøÿž¸yæâÍþw^úÇïë¾’ ¿Uç«<ÄÕŠf;L)™<Š¥ÎörT^o€éܤóÿACù%¶4C `*9 «*BÏï=}øÄÕsˆ„ )[7ížl¯mê<о Vûøê‘É£—æ3Wˆp3òÇ9®ø[› ¡Éì 0Î6~e ×4@§Óó°XÌC¥Ó÷µ_½uòðØØ0€ilPé Á¡OíûY󊂯 LÎwŸ¥N7P"‚À¡¨ÎÂhôy­bâˆ<+òÕ{4-c@™)¦jš2ƒ$&<5xêH4~ÀÄWè^zv~¢‚NÏqŸÝŠ:ö•ñø±uÄ Àq6\¡!^Ämˆ%_ïÅüO?ã”ÖíRÕ`¬‚Ò¢®¤ã‹ÉÏw_8]¸®küuÛX$N!#D½ÏåŠHÛrÏ0JJe˜MŸUK¡¡žG3ùðYŠA7ÅÈ Šê{yàŸ?¾Ñ‡!©@Pj° §èõ©Ü 0zU[,¾¯pD(½!Xe*¨ L#]s õpgöàÚÅû†éÐÝ÷žþë»o639q—nm/"0p÷ZË|^tˆüzMäm¦Zð`eprOf`“¹A0iÊÞƒxúü‹Œ³š ?=…ΖN´.hªå›¹W”áíÛƒIæ_X¸¥–dÙS-TSF奄 W¢(Ñ*¨æßÞ‚Bx‚ž xí¨”æP-¤²)“Ð2;¸ ›„_÷|:[(z9®ù‹ûCº¢%Êþ[Da5(ÙÒõ•8ØÄÕ+ŽËy% wÐûn)^z!W ì‡N/Ú çóŽáÈç=r}x•wO¿@ÅŠ1Y¦É0ue¤€'.ÐLcjKs‚ÀJ‰:B¸’´Ú€™TD¤ƒ“–<,{fÚq¸¡ç݋ƛ£C/Q¹v÷šœkzÞ¢–ÍQ åš-)‹ç|ÝÖ¸ 1à±$ÔU­òp™X'áxÐ’³äÂhÿ”Ð5viû€k[^ÕÓe½%õQ׌¤ ×À&Ôf%¡z–>¾á3} ˆp}ú´T5à 4 Ü(k‘”%Ëxšužý×ÝXø¯ßÙyQW)›—üDzï:æD Ürë% ú+´1°²c÷'¹Þ7~+k¬L6sÁ”…y-…cX¯r0×"Éxlk/ò¬—.IÖ¢ª DÀ!ݹí{ŠžšW‹ðB×þ­ñWc¢,BG} &xúCIdíÌC6ŸO7×Ö…•tn9Ö‹ hoî„®õ›˜ÈN§ ®^ÈöW™¥šŠ>&Dð:¶œÅæ³ÛT—ÄW—\3ÓV÷ÛÝ()†]mñXƒ¿jí‘}ßîY·¶ Û\ ©É‚×_ ]÷uÜú‡´¨r{©¢~d0òqŸ-8°0ðþüô“/¾ql[×7=röUÃHí”ø:©èùP+¦I³ëã>[þ'ÀgäkRú]IEND®B`‚lombok-1.16.18/src/installer/lombok/installer/eclipse/STSLocationProvider.java000066400000000000000000000032031312655740700273730ustar00rootroot00000000000000/* * Copyright (C) 2009-2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer.eclipse; import java.util.Collections; import lombok.installer.IdeLocationProvider; import org.mangosdk.spi.ProviderFor; @ProviderFor(IdeLocationProvider.class) public class STSLocationProvider extends EclipseProductLocationProvider { private static final EclipseProductDescriptor STS = new StandardProductDescriptor("STS", "STS", "sts", STSLocationProvider.class.getResource("STS.png"), Collections.singleton("springsource") ); public STSLocationProvider() { super(STS); } } lombok-1.16.18/src/installer/lombok/installer/eclipse/StandardProductDescriptor.java000066400000000000000000000124231312655740700306620ustar00rootroot00000000000000/* * Copyright (C) 2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.installer.eclipse; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import lombok.installer.OsUtils; public class StandardProductDescriptor implements EclipseProductDescriptor { private static final String USER_HOME = System.getProperty("user.home", "."); private static final String[] WINDOWS_ROOTS = {"\\", "\\Program Files", "\\Program Files (x86)", USER_HOME}; private static final String[] MAC_ROOTS = {"/Applications", USER_HOME}; private static final String[] UNIX_ROOTS = {USER_HOME}; private final String productName; private final String windowsName; private final String unixName; private final String macAppName; private final List executableNames; private final List sourceDirsOnWindows; private final List sourceDirsOnMac; private final List sourceDirsOnUnix; private final String iniFileName; private final Pattern locationSelectors; private final String directoryName; private final URL ideIcon; public StandardProductDescriptor(String productName, String baseName, String directoryName, URL ideIcon, Collection alternativeDirectoryNames) { this.productName = productName; this.windowsName = baseName + ".exe"; this.unixName = baseName; this.macAppName = baseName + ".app"; this.executableNames = executableNames(baseName); this.sourceDirsOnWindows = generateAlternatives(WINDOWS_ROOTS, "\\", alternativeDirectoryNames); this.sourceDirsOnMac = generateAlternatives(MAC_ROOTS, "/", alternativeDirectoryNames); this.sourceDirsOnUnix = generateAlternatives(UNIX_ROOTS, "/", alternativeDirectoryNames); this.iniFileName = baseName + ".ini"; this.locationSelectors = getLocationSelectors(baseName); this.directoryName = directoryName.toLowerCase(); this.ideIcon = ideIcon; } @Override public String getProductName() { return productName; } @Override public String getWindowsExecutableName() { return windowsName; } @Override public String getUnixAppName() { return unixName; } @Override public String getMacAppName() { return macAppName; } @Override public String getDirectoryName() { return directoryName; } @Override public List getExecutableNames() { return executableNames; } @Override public List getSourceDirsOnWindows() { return sourceDirsOnWindows; } @Override public List getSourceDirsOnMac() { return sourceDirsOnMac; } @Override public List getSourceDirsOnUnix() { return sourceDirsOnUnix; } @Override public String getIniFileName() { return iniFileName; } @Override public Pattern getLocationSelectors() { return locationSelectors; } @Override public URL getIdeIcon() { return ideIcon; } private static Pattern getLocationSelectors(String baseName) { return Pattern.compile(String.format(platformPattern(), baseName.toLowerCase()), Pattern.CASE_INSENSITIVE); } private static String platformPattern() { switch (OsUtils.getOS()) { case MAC_OS_X: return "^(%s|% executableNames(String baseName) { String base = baseName.toLowerCase(); return Collections.unmodifiableList(Arrays.asList(base, base + ".app", base + ".exe", base + "c.exe")); } private static List generateAlternatives(String[] roots, String pathSeparator, Collection alternatives) { List result = new ArrayList(); for (String root : roots) { result.add(concat(root, pathSeparator, "")); for (String alternative : alternatives) { result.add(concat(root, pathSeparator, alternative)); } } return Collections.unmodifiableList(result); } private static String concat(String base, String pathSeparator, String alternative) { if (alternative.isEmpty()) { return base; } if (base.endsWith(pathSeparator)) { return base + alternative.replaceAll("[\\/]", "\\" + pathSeparator); } return base + pathSeparator + alternative.replaceAll("[\\/]", "\\" + pathSeparator); } } lombok-1.16.18/src/installer/lombok/installer/eclipse/eclipse.png000066400000000000000000000024601312655740700250110ustar00rootroot00000000000000‰PNG  IHDRàw=øtEXtSoftwareAdobe ImageReadyqÉe<ÒIDATxÚ´V=oU½ïÍì쮽‰gcC>¢ „hR"h±€"ŽJƒq$šP A~„HET) "‰1$AŽp¼ëxwfÞ7ç¾7»Ž"ÚØ¾ö›Ù™sï=ïÜó,Bt?¿ò+_þœVH$2I­^›ô $©ta…xãúÀ¼~mä_81»m½SÆ’ô?îŸRÛ Æ˜sJ™ µª©WTÕ9ïI‘ìäJ7‚¶Tr¥šÛûéš–ý«FÑÍшt­H8KÞ;ÒHbŒ] Þ-YëÞvÁ_ïââ½H!q0Qà^û ùÄÁ³Ã }ÓëRoA »rÊ‚#km qCZ2Ú¬æíB¾4á›J|³q Øùcúlˆ4ÅëÀ(“èTRÞÆô±ù Ã! Àsð€Ë"]À5Ô5‰BH¼;®Ò%Àh%Ølö%¨¬Ì1ÚW»‚޲iŒ?ùôPl¼ûÆâ:n®›V|³á.UÎÉyNR‚š%{ { \ö-{ýßΑ¢ˆjü%ÉOë©çè(Í$Qƒ‚T3É<l€Öìšðà×Ù¼²þûÝÖ·‡÷Í[ƒî[P„€rDŽy  ªñ쎂l!(*+ÃçY!žAó9èÔÙ"!ÏÏûUêTíÃgO/ÌÒ\.h O¦3yØs2´8±ijãsnâMnê´ß…g˜2É>]÷Ëþ^ñÑ‘Có4‚Uls’‰‰;õÝx‹‘ .ùR’k’nTРg=žØVâ*ûásí;÷âc‹´±5¢!ÜͬqÈÆæAïrVçàX9ÇéàÃçÓ#Ó4Gr°P‚p+¯<õÈö|âüÅ+´Nf[Ø´9±hc\ªÞ5•û)第U |œNàœ­¼t< |„ZÈ šþîɃýË÷çŽ Æeïï[›4ØÚŽªaÝsµJéü^št Ô¼Š_Ý{dfÇàîcÙBÏ•ö—îßsæ™Ã~tq_{¦Ýš÷Á‰Z)U×F·‹Üv‹ü/PwÃõ>:9…woþßâ~ÿÛòŸ-v´C#w5XIEND®B`‚lombok-1.16.18/src/installer/lombok/installer/eclipse/jbds.png000066400000000000000000000066161312655740700243160ustar00rootroot00000000000000‰PNG  IHDRàw=øgAMA¯È7Šé$iCCPICC Profile8…UßoÛT>‰oR¤? XG‡ŠÅ¯US[¹­ÆI“¥íJ¥éØ*$ä:7‰©Û鶪O{7ü@ÙH§kk?ì<Ê»øÎí¾kktüqóÝ‹mÇ6°nÆ¶ÂøØ¯±-ümR;`zŠ–¡Êðv x#=\Ó% ëoàYÐÚRÚ±£¥êùÐ#&Á?È>ÌÒ¹áЪþ¢þ©n¨_¨Ôß;j„;¦$}*}+ý(}'}/ýLŠtYº"ý$]•¾‘.9»ï½Ÿ%Ø{¯_aÝŠ]hÕkŸ5'SNÊ{äå”ü¼ü²<°¹_“§ä½ðì öÍ ý½t ³jMµ{-ñ4%ׯTÅ„«tYÛŸ“¦R6ÈÆØô#§v\œå–Šx:žŠ'H‰ï‹OÄÇâ3·ž¼ø^ø&°¦õþ“0::àm,L%È3â:qVEô t›ÐÍ]~ߢI«vÖ6ÊWÙ¯ª¯) |ʸ2]ÕG‡Í4Ïå(6w¸½Â‹£$¾ƒ"ŽèAÞû¾EvÝ mî[D‡ÿÂ;ëVh[¨}íõ¿Ú†ðN|æ3¢‹õº½âç£Hä‘S:°ßûéKâÝt·Ñx€÷UÏ'D;7ÿ®7;_"ÿÑeó?Yqxl+ pHYs  šœdiTXtXML:com.adobe.xmp Adobe ImageReady åzIDATH eV lç}ÿÎìí½|¯mlccð(vR„–:)qAÂ@HKI”„Rµj¥MÒÖ!D%U’hÒ´Á† „BŒDŠp^0IØÆ^/>ðµë½wÖsôÛ-A•:Òhþùgæ}×ûÞ7LQüïÑÀ×¢(Rlï­5kjîœ=»Îf²Ô-ß¹#7"Ü­>ÂÈðð¬pé ‹[³s³Oÿ¼µõRìý“ \ÃÉ“2a>e׌z)öðí5uÎ[=|CÎêÊ­[QTU•ÍŠ„´4Œ;‡à™œ„³ý O4#@ßX ´ååÏݳ£µÕƒy€ù_#±ZÅ7cëÆ²²}»uFe/ÙºöäðÔä¬ Êt*¢QdQTÂ~¿25:"yæÌlÓºµòz÷gt¾»aËq¼¦¢Ä1¿µw¾±¤¤I†w©‡ñãóçÅô<€ääó‚À¡MMCtÆC%A41} _5·ˆ¡@7™Ìpöôü奎ŽçD¢°––nýúõRkã÷&%§îW¢‚h_´Ó30×-(îiÈ”€$ؾWy6 )"@6Ò ÏÈÂsÿRNü¡Q²ZùÌÂùûö8¯ÄêàX]]EQ}}ûõ“'1?-I©Þ€žnFäK8%Ï4Ôéé0•‚3šêí†po!ŽƒzE5¤Ì9ð{ýè¼Ô¦´7·0Õ…*þª(WyZcxÆ{ 0†æâEѾç7|dØy'RZ¸éI¨Õj˜¬DàãÓàssÀ ”þ^0{˜Bï;o"’˜Šy,g3ýR¼\~Ù¢?t%ÿî¦M5zA¨æ :¥þÂyÞ˜’ÅçƒÜÛ[ñBp2å<ýÊÕÛÐ,_Pw'·ïA¶Ú ¸\©N³Q]?†Õ/4r“SòÝ+íÇ7lXÅ[SR6k¢Qtì|NR~¹‹Ï^TŠ™#aðŽA¤¨¸ªBNK‡º¨’Å ÁïEÔlEâ¡WÀÛív\ìrtéYÐRä7ßOîüúUZqq=7ß3sØuå2–È¢Lïó€»ÛCZ.XÈ ~a9ü×ð\üšÚ'ÀB·¤þ~”>ûž„gÈ…`× h2s‘Nކœ¬¯ï.K0™ùàäÔ£!ÚP€l‰PË2™â D"™ŠfFhÛ9+¥+<ãÃØ¡&èJ3É‘dd­Z ß…Ëýûs¸«Bù¶íL“W[ÁüUÀÝÝK§ÏPô´—SQ)ƒºÓA]Y Û†ÍÐ>õÌÛw"åµýà2³¡Ë™‹Ñ×›(e*¨Šsгí9x¿î@´¯®µ Ðé´ÈxþYð÷ƒ°fe‚Òk͑۲úûÏZtkéÖ­J~Õw™›º×KŒÜ…¹|8“ÓŸ‡~Ù2/´CjgPAMüŒrx‘Á»`ĬÔÍOƒu]m_(¡”4¦Ë°;U_=z¶ßq )ss¥Ëo6aøÖmHf3î~z×Öm$¯ ‰ñ0ôÈÚþ ôònˆ´È㟜 Ñ€ò¥#ˆ†Ãïîù‘r)§¤sŠŠ>ãÖa®¶ö§I‰6öÍ;GYðf'’S¨õ¥‘qØÊÃh±`êÐX¿³ÖòÐeÛ¡6ãòÁRÌ0T­†d2¡ï½ãp^¿‰ÎîÖwç“}¾ßª~¯(—4²Ô¦3‰”£5Fow"{åʘŒCeL€ ‚È‹©Sƒûó6HB\zTA”h<ÖÑþ#GáJ&&ŠaðÌ87¿­qpðR\ì¶1¶bíÁƒ¿Ûk¯¾ª$RRæ--Aaý`Î/@ßÞ_A£Ñ‚'MbÄ.Ùé±v9TI);u‚M¯Æ„©YYqº=,D}Uºdqů/_¾Ê•tuq¿ëì¼wb÷îÙ…¯z<¯¶FJ̙Ò—±Ô¥åð‘¨ùì‚(ù lˆŠ«—Øâž†ÀÇ&ÜÊ@8")›*­¨ø…}Žö>”ëXéTv3ÖT°qã®Ô ʱ]ÇßæÍ¤õùuO@ñû0s§çbOÖ¦gÐ}ìƒøÈŒð*1˜›Ïg-)CRfæûO>¼%>pbÀ±º‹Í8ºÇOÛç^6Ð:™Œ&Иђ¼Ûk«Xröˆ4Í’KaVˆ*ƒ7nHŠÉÂI’Ä"<{FÆK›ßxãO1:âN;2ãFâ;dèÅG­vÝ; L»«µ$ÃLŠõ$âYXY<ê ǹO¡Öj¤æ“%±ÍÛݽ‡þFþoèÇNükŽ…ðà·ÅAËš_Ôxýud¸.<>0/—O¡Ú´~Ø<šwQ¯¶j œþ˜Èý¶Ð%F¸x6b{ÿßõ«gsÒèIEND®B`‚lombok-1.16.18/src/installer/lombok/installer/eclipse/myeclipse.png000066400000000000000000000020611312655740700253540ustar00rootroot00000000000000‰PNG  IHDRàw=øøIDATxÚ¥–wLSQÆŠ¢`\qÁQðµ…**T£Å0ʬÈPˆÆm‰qDM\Ñ?4FE#1Æ•8âŒÁˆŠÑµDT4¸2dz…ÏsoimáQ›œÐÛ{ÞýósÏC&"?Ê•Q¹eu6·ë¶Ì]ˆ¶ö×$YmšUIÆþª´iúÞà;:y«ÌMˆåÊh¸;™ÜÉÜÛ1€xÆb & t TãÒ]Ì?,ÕøÏ€.ªh ™EX ?œ™oèdô I„Ï(†‡§Bžfúg@g¥ `Üwôdx¨þì‘lþÀ¬;ÉC2pÈM¢ÔÞÿz©ãmR€eã¼×3(®c; wpz³T©K)ÆN!¿X.×=ßkS"/uéj9nº É zSþ´?>q®­k(?’Ì¿9+^d9xDt 9],¸ ñ—_«k±÷ài”<(ƒÕjÅ›_0uéfxPtÌßG›Ž-¹ÇQÛ`†µ±/*ßbéÚœ0Í‘ÕÐ1É&YOu¼èMú±Hò‹ï£¦¶ùE÷ð¸¼MMMxûþ3òò‹ñäY%*^½CDÆ2Þ÷gòn š|/–àà™+(}ü uuf¬Þ²ƒIV›~š$“Œ¢@ mÜl~`Á­ûš¬EëÑH‘:‘õÄLd/ÞöY±!Óæ¯ÃOñ._¿È¬å¢g3(»Ò²ç¨ª©ƒB7¹«Jo’õ Ià€ †ùpáêMžÞ¤) IšFä8åX³ÏÊ{`|TÎ}ÍæoøTUƒUÕܾ}ÿÉOœ·ŽËHãÆ$ó Ћì:˜†ºä\ûûOò^gk; è¶‹•ïPL5r¶‚;¥PLÊú` £s®ÜdÅApÌLØsÝô‰åèÈ÷û8Ÿ ái‹¡ˆÈ‚6} ŸêÒeà76EdÛg/¢G`†FLç€õ»rça¤«À$ÛE™5DeTü¢’‡(ùs©‹Z¨WEö€Z—‰stø¼ÕÛù%ó¤?|îâ笱ÝZ`GÎ^ƒ!{%°Â/Zµ …ÅFªÉSä»!*[ µ˜±LúÑ4loT°I)5š½é÷–¾ÒÍߤf‘0<,Õ0(Ôà2\æÝöÁNó§ù¶RÖ ðl¾á­Þ# .z°K"èÏg“ÝŸÝVöFkkÚrÍmjÓ×W=ÈcÛ½@ZéN²tngœsbq¥Ýòa!e£ 8‹TjŸ¶C€oh²Yh『ŒÝpšíŒ2Òü$ª•ÚÔú¿5!<¥¾û}=ýûÒÒê܄ȪN~‘ ~¼©?@2àˆIEND®B`‚lombok-1.16.18/src/installer/lombok/installer/eclipse/rhds.png000066400000000000000000000066161312655740700243340ustar00rootroot00000000000000‰PNG  IHDRàw=øgAMA¯È7Šé$iCCPICC Profile8…UßoÛT>‰oR¤? XG‡ŠÅ¯US[¹­ÆI“¥íJ¥éØ*$ä:7‰©Û鶪O{7ü@ÙH§kk?ì<Ê»øÎí¾kktüqóÝ‹mÇ6°nÆ¶ÂøØ¯±-ümR;`zŠ–¡Êðv x#=\Ó% ëoàYÐÚRÚ±£¥êùÐ#&Á?È>ÌÒ¹áЪþ¢þ©n¨_¨Ôß;j„;¦$}*}+ý(}'}/ýLŠtYº"ý$]•¾‘.9»ï½Ÿ%Ø{¯_aÝŠ]hÕkŸ5'SNÊ{äå”ü¼ü²<°¹_“§ä½ðì öÍ ý½t ³jMµ{-ñ4%ׯTÅ„«tYÛŸ“¦R6ÈÆØô#§v\œå–Šx:žŠ'H‰ï‹OÄÇâ3·ž¼ø^ø&°¦õþ“0::àm,L%È3â:qVEô t›ÐÍ]~ߢI«vÖ6ÊWÙ¯ª¯) |ʸ2]ÕG‡Í4Ïå(6w¸½Â‹£$¾ƒ"ŽèAÞû¾EvÝ mî[D‡ÿÂ;ëVh[¨}íõ¿Ú†ðN|æ3¢‹õº½âç£Hä‘S:°ßûéKâÝt·Ñx€÷UÏ'D;7ÿ®7;_"ÿÑeó?Yqxl+ pHYs  šœdiTXtXML:com.adobe.xmp Adobe ImageReady åzIDATH eV lç}ÿÎìí½|¯mlccð(vR„–:)qAÂ@HKI”„Rµj¥MÒÖ!D%U’hÒ´Á† „BŒDŠp^0IØÆ^/>ðµë½wÖsôÛ-A•:Òhþùgæ}×ûÞ7LQüïÑÀ×¢(Rlï­5kjîœ=»Îf²Ô-ß¹#7"Ü­>ÂÈðð¬pé ‹[³s³Oÿ¼µõRìý“ \ÃÉ“2a>e׌z)öðí5uÎ[=|CÎêÊ­[QTU•ÍŠ„´4Œ;‡à™œ„³ý O4#@ßX ´ååÏݳ£µÕƒy€ù_#±ZÅ7cëÆ²²}»uFe/ÙºöäðÔä¬ Êt*¢QdQTÂ~¿25:"yæÌlÓºµòz÷gt¾»aËq¼¦¢Ä1¿µw¾±¤¤I†w©‡ñãóçÅô<€ääó‚À¡MMCtÆC%A41} _5·ˆ¡@7™Ìpöôü奎ŽçD¢°––nýúõRkã÷&%§îW¢‚h_´Ó30×-(îiÈ”€$ؾWy6 )"@6Ò ÏÈÂsÿRNü¡Q²ZùÌÂùûö8¯ÄêàX]]EQ}}ûõ“'1?-I©Þ€žnFäK8%Ï4Ôéé0•‚3šêí†po!ŽƒzE5¤Ì9ð{ýè¼Ô¦´7·0Õ…*þª(WyZcxÆ{ 0†æâEѾç7|dØy'RZ¸éI¨Õj˜¬DàãÓàssÀ ”þ^0{˜Bï;o"’˜Šy,g3ýR¼\~Ù¢?t%ÿî¦M5zA¨æ :¥þÂyÞ˜’ÅçƒÜÛ[ñBp2å<ýÊÕÛÐ,_Pw'·ïA¶Ú ¸\©N³Q]?†Õ/4r“SòÝ+íÇ7lXÅ[SR6k¢Qtì|NR~¹‹Ï^TŠ™#aðŽA¤¨¸ªBNK‡º¨’Å ÁïEÔlEâ¡WÀÛív\ìrtéYÐRä7ßOîüúUZqq=7ß3sØuå2–È¢Lïó€»ÛCZ.XÈ ~a9ü×ð\üšÚ'ÀB·¤þ~”>ûž„gÈ…`× h2s‘Nކœ¬¯ï.K0™ùàäÔ£!ÚP€l‰PË2™â D"™ŠfFhÛ9+¥+<ãÃØ¡&èJ3É‘dd­Z ß…Ëýûs¸«Bù¶íL“W[ÁüUÀÝÝK§ÏPô´—SQ)ƒºÓA]Y Û†ÍÐ>õÌÛw"åµýà2³¡Ë™‹Ñ×›(e*¨Šsгí9x¿î@´¯®µ Ðé´ÈxþYð÷ƒ°fe‚Òk͑۲úûÏZtkéÖ­J~Õw™›º×KŒÜ…¹|8“ÓŸ‡~Ù2/´CjgPAMüŒrx‘Á»`ĬÔÍOƒu]m_(¡”4¦Ë°;U_=z¶ßq )ss¥Ëo6aøÖmHf3î~z×Öm$¯ ‰ñ0ôÈÚþ ôònˆ´È㟜 Ñ€ò¥#ˆ†Ãïîù‘r)§¤sŠŠ>ãÖa®¶ö§I‰6öÍ;GYðf'’S¨õ¥‘qØÊÃh±`êÐX¿³ÖòÐeÛ¡6ãòÁRÌ0T­†d2¡ï½ãp^¿‰ÎîÖwç“}¾ßª~¯(—4²Ô¦3‰”£5Fow"{åʘŒCeL€ ‚È‹©Sƒûó6HB\zTA”h<ÖÑþ#GáJ&&ŠaðÌ87¿­qpðR\ì¶1¶bíÁƒ¿Ûk¯¾ª$RRæ--Aaý`Î/@ßÞ_A£Ñ‚'MbÄ.Ùé±v9TI);u‚M¯Æ„©YYqº=,D}Uºdqů/_¾Ê•tuq¿ëì¼wb÷îÙ…¯z<¯¶FJ̙Ò—±Ô¥åð‘¨ùì‚(ù lˆŠ«—Øâž†ÀÇ&ÜÊ@8")›*­¨ø…}Žö>”ëXéTv3ÖT°qã®Ô ʱ]ÇßæÍ¤õùuO@ñû0s§çbOÖ¦gÐ}ìƒøÈŒð*1˜›Ïg-)CRfæûO>¼%>pbÀ±º‹Í8ºÇOÛç^6Ð:™Œ&Иђ¼Ûk«Xröˆ4Í’KaVˆ*ƒ7nHŠÉÂI’Ä"<{FÆK›ßxãO1:âN;2ãFâ;dèÅG­vÝ; L»«µ$ÃLŠõ$âYXY<ê ǹO¡Öj¤æ“%±ÍÛݽ‡þFþoèÇNükŽ…ðà·ÅAËš_Ôxýud¸.<>0/—O¡Ú´~Ø<šwQ¯¶j œþ˜Èý¶Ð%F¸x6b{ÿßõ«gsÒèIEND®B`‚lombok-1.16.18/src/installer/lombok/installer/loading.gif000066400000000000000000000043101312655740700233330ustar00rootroot00000000000000GIF89a8óÿÿÿ$$$ªªª¦¦¦|||rrr€€€¨¨¨!ÿ NETSCAPE2.0!þCreated with ajaxload.info!ù ,8_ÈI«½8ëÍ»×B(Ždiž(Y…Cë¾p,Ï´RB­ïü+འö›ä†È^QrL:iK@óIõ«ØVtš}n»Ø/˜*;Ëf$:-\³y„-÷]‹G¥©¼~/úøÿ€‚!ù ,8lÈI«½8ëÍ»×B(Ždiž(Y…Cë¾p,Ï´RB­ïü+འö›ä†È^QrL:iK@óIõ«ØVtš}n»UÂì$Æä¡Ù€N÷Öì«›çô‚aogrñ0ulQR)†‡ˆ"‹ŒŽ!ù ,8†ÈI«½8ëÍ»×B(Ždiž(Y…Cë¾p,Ïô@!%Ô|ï߃@ç+]Ààp²;:kI%ñI…E¥ÌªÖVz…Ó­óê]Jšb#¹N÷Öì¬ûÝý~fz>ƒy{|Vuv‚„2~€-‹Œ/Ž‘:ƒ|•‰‘yz) ¡¢"¥¦§¨©!ù ,8›ÈI«½8ëÍ»×B(Ždiž(Y…Cë¾p,ÏDaÜ8~„”0ÿÀ_-G< ‚^p¹uG¤’I9Ÿ£+9ñU¿ƒëS»‚™âb´Ü=£mØìš-ñº…p,Æ­ßñqr2}v/i9{‰…‡ˆaycs.C‘–“jƒp˜™ŠP8Ÿˆ¡7Œš9`§‚V“<=)µ¶·"º»¼½¾!ù ,8¥ÈI«½8ëÍ»×B(Ždiž(Y…Cë¾p …aß÷ÈtH ² °EÃu¼šAð:_Ecn‹.›O§UЬ*mÌ 0+Ü©³/KöJ§IiX2nCÕ縜m˜q]ioWb}Dx€hwƒ„t†pnƒsud6‹“•—O™›.¢HŸm¦Š¥ˆ‘¨YªzoŸ ²\«‡Œ´•–)¿ÀÁ"ÄÅÆÇÈ!ù ,8®ÈI«½8ëÍ»×B(Ždiž(Y…Cë¾ð@FmÛËô}!Š`Gäù~ºØìˆÓ „Ee™Û-™†êà9F]Wj>j·Ð¯{~•}m®Ä}#­Só¸%ЉvMxXY{|i€yp†-5m.}dŠwR„’‰˜Œkbx›—lžŽ…ƒ¢n•‚£ £©«¥²§­°¦™Ÿzƒ6’^¹´½5AB)ÈÉÊ"ÍÎÏÐÑ!ù ,8°ÈI«½8ëÍ»×B(Ždiž(Y…Cë…!Ïó¸8Lï6þ!ŠÀ7Ðíj7¢ñhè)cз<:©Pæ5—•N†?¦l“[U¯\ÌZ“XqÎÝ©à*^ÖòÑn2wCz4gmr‡…QB‹cˆfŽƒ†“–HD‘Lƒ‰˜Ÿ›ŽMž~¢™§Ÿ¥{ª’®¦¬šO¡´¯²s°o»­-ƒ³q·Ã¦¿wx)ÊËÌ"ÏÐÑÒÓ!ù ,8±ÈI«½8ëÍ»×B(Ždiž(Y…Fë2Ìô@o×ô¿‡EðƒÉx6\шL.™‚áo‡ô-©Ø A1ØvƒjpÔzÐN‚6p\WÀ p €G@ †ÁK0Þi‚ð¢Aª¤™BÖZyCAP8ÅC‰’@ùÐ&¨*ƒª¡CP=ô#tº]ƒú Ð 4ý}„˜Óa ض€Ù°;GÂËàDxœÀÛáJ¸>·Âáð,…_“@ÈÑFXñDBX$!k‘"¤©Eš¤¹H‘q䇡a˜Æã‡YŒábVaÖbJ0Õ˜c˜VLæ6f3ù‚¥bÕ±¦X'¬?v 6›-ÄV``[°—±Øaì;ÇÀâp~¸\2n5®·׌»€ëà á&ñx¼*Þï‚Ásðb|!¾ ߯¿' Zk‚!– $l$Tçý„Â4Q¨Ot"†yÄ\b)±ŽØA¼I&N“I†$R$)™´TIj"]&=&½!“É:dGrY@^O®$Ÿ _%’?P”(&OJEBÙN9J¹@y@yC¥R ¨nÔXª˜ºZO½D}J}/G“3—ó—ãÉ­“«‘k•ë—{%O”×—w—_.Ÿ'_!Jþ¦ü¸QÁ@ÁS£°V¡Fá´Â=…IEš¢•bˆbšb‰bƒâ5ÅQ%¼’’·O©@é°Ò%¥!BÓ¥yÒ¸´M´:ÚeÚ0G7¤ûÓ“éÅôè½ô e%e[å(ååå³ÊRÂ0`ø3R¥Œ“Œ»Œó4æ¹ÏãÏÛ6¯i^ÿ¼)•ù*n*|•"•f••ªLUoÕÕªmªOÔ0j&jajÙjûÕ.«Ï§ÏwžÏ_4ÿäü‡ê°º‰z¸újõÃê=ꓚ¾U—4Æ5šnšÉšåšç4Ç´hZ µZåZçµ^0•™îÌTf%³‹9¡­®í§-Ñ>¤Ý«=­c¨³Xg£N³Î]’.[7A·\·SwBOK/X/_¯Qï¡>QŸ­Ÿ¤¿G¿[ÊÀÐ Ú`‹A›Á¨¡Š¡¿aža£ác#ª‘«Ñ*£Z£;Æ8c¶qŠñ>ã[&°‰I’IÉMSØÔÞT`ºÏ´Ï kæh&4«5»Ç¢°ÜYY¬FÖ 9Ã<È|£y›ù+ =‹X‹Ý_,í,S-ë,Y)YXm´ê°úÃÚÄšk]c}džjãc³Î¦Ýæµ­©-ßv¿í};š]°Ý»N»Ïöö"û&û1=‡x‡½÷Øtv(»„}Õëèá¸ÎñŒã'{'±ÓI§ßYÎ)ΠΣ ðÔ-rÑqá¸r‘.d.Œ_xp¡ÔUÛ•ãZëúÌM×çvÄmÄÝØ=Ùý¸û+K‘G‹Ç”§“çÏ ^ˆ—¯W‘W¯·’÷bïjï§>:>‰>>¾v¾«}/øaýývúÝó×ðçú×ûO8¬ è ¤FV> 2 uÃÁÁ»‚/Ò_$\ÔBüCv…< 5 ]ús.,4¬&ìy¸Ux~xw-bEDCÄ»HÈÒÈG‹KwFÉGÅEÕGME{E—EK—X,Y³äFŒZŒ ¦={$vr©÷ÒÝK‡ãìâ ãî.3\–³ìÚrµå©ËÏ®_ÁYq*ßÿ‰©åL®ô_¹wåד»‡û’çÆ+çñ]øeü‘—„²„ÑD—Ä]‰cI®IIãOAµàu²_òä©””£)3©Ñ©Íi„´ø´ÓB%aа+]3='½/Ã4£0CºÊiÕîU¢@Ñ‘L(sYf»˜ŽþLõHŒ$›%ƒY ³j²ÞgGeŸÊQÌæôäšänËÉóÉû~5f5wug¾vþ†üÁ5îk­…Ö®\Û¹Nw]Áºáõ¾ëm mHÙðËFËeßnŠÞÔQ Q°¾`h³ïæÆB¹BQá½-Î[lÅllíÝf³­jÛ—"^ÑõbËâŠâO%Ü’ëßY}WùÝÌö„í½¥ö¥ûwàvwÜÝéºóX™bY^ÙЮà]­åÌò¢ò·»Wì¾Va[q`id´2¨²½J¯jGÕ§ê¤êšæ½ê{·íÚÇÛ׿ßmÓÅ>¼È÷Pk­AmÅaÜá¬ÃÏë¢êº¿g_DíHñ‘ÏG…G¥ÇÂuÕ;Ô×7¨7”6’ƱãqÇoýàõC{«éP3£¹ø8!9ñâÇøïž <ÙyŠ}ªé'ýŸö¶ÐZŠZ¡ÖÜÖ‰¶¤6i{L{ßé€ÓÎ-?›ÿ|ôŒö™š³ÊgKϑΜ›9Ÿw~òBÆ…ñ‹‰‡:Wt>º´äÒ®°®ÞË—¯^ñ¹r©Û½ûüU—«g®9];}}½í†ýÖ»ž–_ì~iéµïm½ép³ý–ã­Ž¾}çú]û/Þöº}åŽÿ‹úî.¾{ÿ^Ü=é}ÞýÑ©^?Ìz8ýhýcìã¢' O*žª?­ýÕø×f©½ôì ×`ϳˆg†¸C/ÿ•ù¯OÃÏ©Ï+F´FêG­GÏŒùŒÝz±ôÅðËŒ—Óã…¿)þ¶÷•Ñ«Ÿ~wû½gbÉÄðkÑë™?JÞ¨¾9úÖömçdèäÓwi獵ŠÞ«¾?öý¡ûcôÇ‘éìOøO•Ÿ?w| üòx&mfæß÷„óû¥ò&" cHRMz&z&z&z&z&Éõ¤ pHYsÄÄ•+ IDATxí½ ¸$Y]'zbÉ=óîUukíê½z)¥Ù´Gx"ßè<}è‹nèFæ‰o—ÇÅ÷9ê8Œú |h³µ#Œ8 0OT6µÞ>n¡Û®^ªúR]Ë­ª[wË=3–÷ÿEÄÉ<‘™÷fddä½qºoEĉ'ÎùÇ?ÿç¿ÆâC †@ 1bĈ!C †@ 1bĈ!C †@ >úÜoW/±üñ”úRÃÔ– ¶¼´Äj>:ÑÍb àó½å-…—‰ä§ C^Dw’¬2“®2fžgIv^R´'ó…Ê—$];óÛKl%€WF¦‹†ü¼mæWu¦üŠdÊÉAº2%£!IæUEÖŸ0%ùYÙÐÎj {²zµø·ÿ8Û¤(µ‰h‡_ãeÍdõS¦©¼4g‡ÝtÄ[Þ™¿[¯'þÖ4Ô…<¾³G V‘}URØeY’žbÌxR£?Y1{è½Å3;ëtø§bÚ& yÞÖ¬¥S2¥œûQ‰™,3[aÉ|ƒnÑ•Nà5Û Öq-ÓpÚ8u&ž!îI,†ÖÙ‡iR—ô\«Ðµ¡K†’dÿåÿyý[õ!# éú𥥻’7/ý!k(?ƒí.Šª³ÜB™É Ý}+”k“™zM¿ñw—ØF(/t^Ò‰îa¾y‚ÞõàÛów^Z¿|Îl¨žÈ“ÌÕY~±86ä(%&ÍÜu˼?l°vÿ”ÂAÄß÷à¿›~‹VWÿ“$É÷P%ɰ—¬\Ó}«ë:•̱\zŽ)ŠÊ4½IËÎtScº®±Jm½«ýN*n?ü²ZÓ_øs?û×ßÞÉó;yFÝÉC{ᙥ¥%ùâÆï>l4Ô×KR÷ïLQ5–ÛGK–jôG*™g…ìS•T«â’ø§rû[÷ø IdL7ÁŒ&ñ8t$dC)UVy“®c]«¦ó¹ÅÒvÝQE7dFô¢Iêö~’²”z ŠÁÛ½ÆÌ6Xf®ÂHŸãuÛªKâä2s,¡fœ6@´`9†¦Vck›ç‰u·Ç±0};¶ÿ{ëÅK?ùöS÷ÿø.À1róÁ·Í¼Q/Ëï5dyÖu 2KÏTYŠl$ ¹o[×ÉD–(Î>Bœ´um)U×Xµ¾ÁLˆPT`§ß.Q6û§“%¼ “i™C¡3&Ë6Ò‘èNmT !9EÄ; D½¶ÊW¬ökÅólqöVy.·ð;T ÅȽýÏý?7÷QúPo0é³ ÕÖi?) 3ߢ8-=¥ê:«Õ7™AËQPKâLþ !“=D åFé"«7ÊÖ+f ‡ØÍ_LKÝú»ßôºÏÿZPïõë'F ‚Ì©_LÝšlfÿÔhªÿÌ P²2³UúhÝTG '•°ÕB^Gì“zø*‘¢“DEòbývÎAµ¦ YRÍZYW7–[ˆzË¡ƒ2­N%çnøñ¨²¾·Û¶ë—¶Ý&½ý›ß9õ3j­ðˆò@ÊÊΕ诛ßI&2lnê([˜¾ÁB|Ä­òUvmãœ%UñåJ€Ï7MCûÉ÷¾K{Y¡®ïcMöÏ©ÿß'þÅŸ+OÁ\¯o] eqÓª–å›:b-¨8õ, ×ë«ÿY|nç{–--1õÒÆìûͦü&Ï%+IRÖ|·”Ìq'Źn}L7ÒäÒól:·M–S¿¹ñÜ7‡Þi‹R—Ä8*j⤡š¯%¥õ+ˆÈÝ-Üî{šIN±©ü¢ÅC•iÉ,VÈ €Ê¡ù;ÙÙ;Ê¥ëÏ<ïÁÿadv´=‰@<0}³™Rÿ’Ì·y}¡ÔTe¦áÎÓ^²ì¥jžÇ^y8#2Ǫšb…̛ɦ¿õf³þÉ«çßùŽwá"xˆçÓyá<ø H?6âTU£åƒ®ÁÿÌä0‡ˆ'±Eö¦^ûB½Zù…7½á ñ~vr¶ï¤ÍçH¦V×ÊVª^¾éþ×~áçG­kÁ»Åò±¬>™.ÔþȪ#Ñmóâ4Ó›mZP&Ä7ÈX;KT¼Ñåµ§È€[¹åþû+~Yì'ˆó=ƒ@üBáÓ”æ@SHLW’Þ¾; îÍFK1‡g ’/Lgõzù›¥âúóö5þS¾þ+6£Á; ñxqyõ߇âu¼Nhëß¡›#:¡HKŒ¶3S‡Ñ‚}—tCÙDáßìc¯š r˜{y~CœšêRÉX·ñ‹…ѳфß.‡÷Ý „Z}öÉï{á°ÒU»×ŸýÕ_±z2ßü?yZ-ÁÊ×ÛN’µF‘Õ›eK[MÍÐr¼J:¢k=ùuþLÇ=@ >¦¦üK`¢¨.ÖClGÑô6/ óTf+Õ6þ’Ü<‚3l‰/ÞÁù‡ßí#jR{’?Zºšcͪ-écé-’ë¨ÑT~ŸåNriõ1¦0égß÷ñ¾?3ìqO b$Yä} ²û-_ÜoGÓêl%vhî.bNMƒ £¿5,Àƒ~^ÉÕ~Á$Úˆ~±”m\˜±Ž¸Öˆ¶Í2)±Z³Ä®¬)äÙ‡q?ˆ²ëèÕ÷³¹F“½F–šñ÷ L:ˆ;pš¿ƒÁ·§¡¿ýoïûûû‰Âù‡ÿëú_¤ Ïó±èu•m]¶µå¨+C o•¼îQÀPˆòƒÄP¿ÔªòŸ]@³Ó3¿æúó[¾K.á× %"Û+â ë‘=®ç+o”'™¬ºžcµM{)†G#iÆ…w›´_•³jî¿ •;>ÝÕêcÔÔûEèH²á»|ÁTÉ.°xÛÿ>5í­ë‚bq­øœÕŒrBü¯¦Ô4ü™íw-1]}‡ Kújý@Ý·Y‘TÀ%ÉÇ…rìjá E2>e \>à×äWÊ5{“M6{4­ü„_»~õ»ÞüŽ©×3S¶É\[9(T·N ›] ÆÒ+gÏÿ^«Áœ4MéA SÔ´»=%q¿Hši²™5ž«éŸ±.vðOÛ·ƒ‡£úˆl*º­\ð™QSîÚö `°%°¦ÅD§È9¬ÖØúìÒÒòF»U´Ï(åÌB­Æ¾£´©­=^DÁ’ º£@Q %cS«üÅ'—X©ãæ6.v%"ìÍnØÒ—ÿòÕÒÿ8ÒJ‚\:ˆýŽ»Ÿ(_k’ö C±¾©HmE>~xO¦’Y­ª]ý÷¼n'Ç]‡@d÷Z Åë~70Ä_¤û®y¸±®5é<ÁTú›´¢×åŸæcNZzE« ª ±Ù÷<øNùçßøÄÓbývÏwÑ/ð%¢Ý é'}¡¢Ø­-¸eÅUÐ âå·Ï¿M×–îñúÜÍ•[¤Bi ˜Î6ªÕµÿ›ßßéq×!é’_äFÒI%½JÂq"ƒêž‡(õz¥Úë™(Ý«W§øxRé m’}O7j÷s÷}ãËü™wiún`$úH_hŸp²ghZƒ¥œˆOw?Q½~ýëÓ7Òòu’/‘nky?‚úÌMc V ij`×!ÓáÉäµ×Sú`¡Ft§IªkP DdLRIæ „ JKÎJdýÔ§^/=ñ¦×|þsAÌqâÄøSǧYºþnÙ Ù\¡|Ì6·h°š¤êW5S?ŠL¼$-`ö^¾¸Ö ý t@(él¾î`ÕDïŸ%Šl=·¬þøQ`€m/E¥F? ³…£lsëê¯ñöÃ' €Ñ<¨_/tþúúپ𠃙}m/aOñÒŸ¼ñŽCo²*#øÏýo¡|Õ õ.>4,_ÙÛë|ÝT~?å'Ú² A} øvùÙ«0Ï­wò“¨OÝuød*ŸzÄ”ÙI„î~o>ÉnÉ$Z©LÄq¯g:ýÝ{¹nðç,¥¡cDm’z‘œvdc3 Û¯2óƒ÷ݾøW¯»yß-ü™¨M)ý›ðƒæ¥°¸eé¼p=•?`™d½ sõ!G²? :r¶ýv>ŠOÝqàY3¾Hز€¥ê……$;FK—W!†šUþDz} °|¥S«;„ÀX˜ ¿ˆX‹{§3¬ Ê?šL(ÜwÛ¡w-Ý˼à5¨Ö½úÕ¯V´JêåüìŒ"¶ÂyÖ·.Z±m >äÖ[½V{&PêƒwGî¿íÐOȦô O†ãeSi¶˜lIªC×)YmLiäåÒ.ýl_¼%_¾H´µª8?„ I7X0ïžO(ybÜãüÊâ#¯¿éà øóã:ÎüëŸ7tÙv X‘Í—Ž 6S¹}Všü ¨’í£ä›õfñ,=xÉ6Á8èH"Ð}wx‡)Ÿ¤É«ø€/N³µ=Ô­}MöÈo²s/(³«7ÕY3e²Õ\§­Gtgðƒ–*¤mÿOµAéZ¨´³ª’DW·ò$!ð‹ ivcÄGº;‘4¿vêÖƒ¿c©¬§Âÿ§^O¼¿‰°ŽóØ …3—k­œ‰È$’H¤4½l¼‡·òØþ*Aö:D_÷8´D¾<¿äÒàן–&t}íxƒiIƒ­¯³åï-³Glƒ]>Ö©¾WúäoF?ס'A‚Jî3Ãsüà¾X°„>¤>üal²ÂÞ!§«ßyí -ŒØ~”ç¾cîEZ%qïÀRßo'ØÌ¦giÉÒ­„öû%v’AÔk[Ÿ{ó›¿ð¬]ì¿‘B ûîXü¹[¾S6Êê»x|þ@É6óŸMϰÍÒJkÌ >ÉDÞ¨m]íõƒ_$èÔÉã3÷ÝvðÓ”·`r·eTöý­Ô9Ý•[j¤,dŒ2v±ë+³ìê…ë¯YkóG6òt~øÎ^ˆ†ÐVÀ`³bEpòûœ2j 6OL;Ú¹ x±{iYÅò jDˆô3Í)ã;§N,žr· úúïd9­ž|%ú…Î';W¶Æ8E¹©‘xY9ìbSrÉ}”r$žq*?ŒðË•«µ/;ÿ˜–ˆ;³v¥×lWo°ù’ÕK¦lzž69‘±÷DûC#óF¿’ {—D›oÕ(Ÿ X¸UžÂ…Åê®s Ï’„¶4á(„h‹dVùèOúsü º¨b«:ûK4WŠ?¢˜÷C6ß–ËÎß³fI‘ü5 >ö¤ñ«¼nDZ"Щã‡N4 Æ7èK¾€ëxlFÕ{ª›š¬ž×Yµœ¢ý#6³°ÉrS–-tZá,!¿H’)–„a6@BÂÙ{ZÌµÝ e³ÿ1©^ÿó¥‰û”…ã~¼)3S±üž!E‚ã‰Æù\ÌÞLîªÕïŒ"ÝŽcC (å”ùbbc%xQð5bšu ˜Ûº>ÅæöoP`œM% ­“Z(=|Ÿy_™Tžg«Å<ózP&s}°8BÎ\ƒ/J8DˆÃK¿»rèӼϠŽo}ë{õÔhœ§ïCÿC",±ä)Sl65K<Üw _ûvŸî»íÀ+d]·tõÌ;ïŒæ*4²ty ØÒ¤¤Ò.…„e[h²íÓzIùWÐ8«ÊíHD¸ç€Ø§>¥úÆÊg넾8š€Î—H¹ÿŽÄu<ðãÃl©Pœw¸É0õÅ;ª ¤5T–$Ò-¹—&Â¥z¹s ~™ÇxŸéD\J‚¾„ßaÖ²€«J¥Ì®_™eMRñlý0ìI”S‡•-} {ûéÎ3 ôY/&æ:)³4–íûn:ôÒÎVƒ]=øàI©ÊAhœa~Ñ…ô{bf,—Í•§õ_ëGyÞ ý¼éÜÅ…5MùuènðãጪøºÕb>j›º¬i°‹w!(‚–'BÕƒ1.maéj/_è¯Wò܇ÔR¥”^%¡8¡ÍÒ:›_\cH‘R[Xñ[¤ò¬lÕX©¤¬€ÚÞ;CYï)m&OZŽqƒ=Újõ°úÍý'V¾„ð$ì=æE á,4v•Úæ§—–N·™ÄV/£99‘f÷úIòã#˜ò`YQ‰$]Þ F¹¡³­ý;÷m)È yÐgq­søØQPrÒþã¾W†ÍH¼ á)¤™TS¤é%E¥L­r·ÎûmäFö”µíÏU"„oã»Ww­:Øò ,Ì©ê"ãv¢h\޽3—šµ1¹ÕsûÎòôC­éfå—Úµ£?ëü#xÙ©^³Äq?þÊB:AL¡É.NUÙ“/Ù²Ìö=ï¯TÞ"˜‹·U|R÷òw Ú~?~%éP Z½“B™$Tmþ/¤í&«¿Uˆ›­Ô4v…¾ÞlIs}CšÆ Ç8R4žBpÀ6Ê»Þõì?œ»óØU,Há{óÁY¡:º^þlع«GŠ@KÄÿdɉ†Ñ~E!K‹[§UkôÖÕ‹ŠãZ¾ `ëUÒä#lí²ãÓ¢1¨ÖN7Øj©L¶õâNŒm’¿ÐÕbmVmóJ«±ÏÉG¼‡¢ÑLWÛ§™oõWžýò¯™¿ëÊ‹ßOчØÇþ9»ã†—Óùa¢>’±º~•„”pKÿ/5ÄxΞ?xrFUlõýÀŸgåÖ:[y¥ý+ßÚPÙÚU{صKd §åÊ]ú1Ðhï%ú¢{"Þ½‡;}ܶJõv•žOHÔ®B¶Yn²Ëë´/E‡ô*P2rmµlÊÛ–Ê>¾Ä¶*µêÏÎŽØÙó9KPk¬ýß=øõoõzÿ(î‘%yt%™Ôï-8;»ßB;ô±õà ¶vXc— ²¥ËÉ9>Í3 MöÄ· –’lžì_(@ª­ë*Û\K°fSb,áKRläWÀû4z,_܆\Ê…p¢F ÌñCK/$ç³;tVøºÊÒçÚ¿?P£+$¥² ›Îø#?y6²âóho²[:Þ3àÅoøÜç?øß_ñ.…©wI²4MømÅÃ׫UKK=`75)S÷ò$¸Q§Àogã`“]?Ö`‡hWãrš•6 ,gTYnºÍ›$Èçgz¶É.œË°ÍëDJ é=Úý$È×™ÿòxß8Ê=ÙÇzñ?Úqec‹¨Ò¤I…P.¥É³O·k}Šæñ#M–X•Yþd–zÖ^¢!!m– bÒ r!*IÇ]ÈIDdL%÷ãŸYYv·éwýæý¥m/ýúÜé}T;íÂÿ9"ÿ÷äít5V£fÆdg Ì®ÔØÊÅ9¢&rÇØê@4$•ÄqVéÊ#"îgó©KP·· ƒd4tèSf)^åñô b„ø¹BÕr)näÉÀ[sìs¯ÔØÚÿÖ`#í¾¡¹¾¼^£(ˆnqŸ›9ð.CÓ_€ã$—‘!¬íÄVÌL ¾ÌÉŠÌ=‘¡(nJÀB />xÊ•5~ƒ–©3äÙµKþˀȃpà÷Z¾(M‹eûâmÝGh ±û`™ˆB’Sw3–ÊRòMZÊ6È VIµîCÄ/þmÒK>Ó9’6ñ—&f§BˆäF"øqê)«ê÷µ:™Ð“‘-aRÓ|)„næð9øTŠm-6YƒvÚ[½<Ëê´9HŠ–èTžù¹&Ðrµ“ÒKÃócžñ®iÚïÞÍ"Q²Þo/D»ÒÒ›¥Øù6%¼ñÛ9Ê+Ý?)\aa\…}Í4ïéý¶èßí®O@VôN«ÝÈ ×wôÛ뗜ΒËù%ƒ]Ј9Þi¡]k|å!Ë~ öÑÞï(kÝ@n#ý –0lÐËËÌåÃß Åv…µ„¹ãƒ>Õv#C Š˜¼×ÏÒž[WÙaZʦæJd$mëÓÒ®ÈR? éÍîaË=>|/Þ>@‡QÖ6*åà÷Öv=LI'‰ðè†ì«©h?Lgm>HZ܉Vº£³1_t‰„XvZ5ޤ{ô~èŸ(\‡V€$%C‚ƒÊH{9TZË×ÜãI–Úæ²;ëð…´š¥ÕZí¤{L“tÝãï|‰BòxÚk ã½b)»ñ[9ò.,±jÉfH§üM=ü1Ï#-—´´—ÏF>•È—ƒR­×Y­F‘}¸BMdž,$Γ۬T'%Ìãƒ/]| Ì<ÖÍ0䉿ƒF‚@²!ÿ€5%ˆðxâqêªÊŽ¿·œ†÷à3øñ@b¯GϰÕCEòú#Ý*)êŽÜ\%IŒ6x£_·_iT«+´!нäi5•Õ¶2Œv2îK‰@s:·ŸâÅo!­ñ>Ú­Âþë«6⮯ښî£7Q¶VžÌ4ª§,kËü“ Rzî¤`»…¢.ß½“ç£òL731äÈ^}Ë'ÂÌ(’zùÿô+Ås©•³ycÝr¡‰&B‰ t¯Ò ¾)CÞy¶²WbíÔ׬»Q3/åƒó'Øq2DÎä[ÚÊkk×ÙßþÍ3¬X´‘¿¯Q—ÙÚ58ÞÛTQ§eK#¤Õ©™BÌ:ôW3_ üD%‰Þ/±‚0O9™"/Îþx¿âºôçê„´’¹ð¿Þ]úÓË}Ñć#t8*4ÜC¦€4'ÑýæZ®Qœ×:Ë!ªr“-BÏÌ7ÙÆœm÷ò{’Õæf’ÍÎØˆ‡vº¦° í\Ü ÷×Ìt¥cc¹…¾Ô*uvvùqÒKdFI°ÕKÓ­¥páùþ}nc•lfDýàyq9eýMÍhä`ÖdSd^øÒðº IDATžDaÉËöêO&°Ž’™ÛÇ*W.Q¿®­Dk‰¤._;LTè⣮&q8‘€ôC`iD†$6* ¶U¥_!!ÃÔW(Ìæ†:E2Ð’V¯CtÃ)ÄjØÅ6×ÖGûjв·Y$_iÊÊŽgxÁ’Vª¶;¯db™DEÈÝŒšÐrGzœëvüžY¤X{ü¡r”?D Ÿó¬ÍÞÞ‘0¿«{áàß‘0ó u fˆŠîŸÔQb§A?GJG×Ft‡À¼ºåDÕ£s‚b®¬°5ZÚh–û0Ç[Ä'¡)n¾“ÂÑÛä§m,ü5êói²ò£= ”–hß·À•ÕÑnÏ~Aeê®iŒI•å)Þ+%¸©¸ûj·XþতÒL§%­‘Tcʸ›]b§û·V‹À(ÐÒ½L…¦—u-_½KÀ\>ÅŽÌeÙ>=Mš†„×§lžK…<à•<”~ ‚ÐnÏ’‹,/`À)œWÊ~«x«ã\%JÜ*;±Dl@ëzBN‚C 2 bÎÀD#jÝÑ÷ˆö¢^°IÐÒ”HRp¡àhæ×>íÖ%ùµ&ó×)Ámöì?e½‘ˆø/H‚éeA„#¼ZïÏØówkeŠìpÊôM·óÓ®£È‡žæ¹}Ç»E¼"0"‰Åâ ETŒE 8¹”ðAz%AL.’fÃWºBvÌ^bû Ë<‡s”¤?| ѹ3È/È[ØGÚý†úÕ˜D¾Ab)7ÚŒ¸XïuÞ,·C£Ss ,Mö±AJ*)Oœ>(0"O½E‰²PtÀ ¹$ò÷Ž ƒ” ż#¡\F‹›yvýò¥ñgצȌAU‡èN9 ÷¢øNP¬c·VÙÝß_d‡)ß"L!Ï=“é@"XùB ˜UẴÆÁkÄŸŸéA…xiAž8F:5w‰Öîó+6(r.'2„ç(©À …»‡Îìë̼*>¿µŽ RhY)éöÇ&ÉͽK±ØÞ}êµïPͬ³"i¡à¢>r©¿æ¶w¡21Ó©DÞÌh¿eù~Øóž¾é»úÈ׺L.m4S&Ð7(zúé¹EgÓòBì¤4i’ÈT¬–ªÊ^ðgs¬™%Fº¢\ :‡j¨N¤¨4YšU˜‘§Ôv¤èÓ‰ Q.BßÞÉeÔÊó£’¹TaXÓsí¥IkB@ŠFõáWÈõd6KÈ55Õj”Ç0—³Å1sà0+_:Ï»²Ž.PÑÍ“ &à""èV?‚@ª®ÏÄØÂ€*Qƒ¬WI¢pøƒšF[0º¹KµöÒ¤%–ÿ†ÂàŽQ»‘²ÓßQb¥ý e¼O³ÍU+¹¹ÑjL'5e¶Dq›ÏÁ7•%ÛñpÈÔ ¾ºhÀ/H,^Ë^Êci'>Ò_Ÿòy DA„3Èc8jêÓˆÙJS<5”–"µž£Õ)Yð—ßGKßóëìúÑ ÅÄSÖVʾé ”H%éL,ðõ™"IrµI™ò‰ÈaYë¥ Å³àvRLÍœ(I,ÒecÙÂòÝ4y'0 å™ôu…þV–̰ö[;¶ÉÊäûŒ’%U‚»d)a‚JÙ6ÀsÕ)®×½ŠVë¤@šcŸqŒýb¹ L#Ý Së{5·†¹o§#jÀ-ê*¥Ó;øTÚú+.hì*E‡¨ä.ëUÇq|š1khUÛÆû1µn³KÊãG—%‰yCŠÏzÀ#ZJDw&ŽK³t[pl½*„›¿‘cŠO’¤m¡¬`Lë“Ê*Éþú"/à㉧ZƒŠø‰×¶?db+ðŸ~ûŽþ‰”“ðr;oÏ lFZ" C×&&Ø0¢$Y0:¨;^Ï%(íÌ ¾=îñ`Ã&&Ew·Áu"myï’öQHªRro!)‚z…ñôcøwSÎ.ƒ;y3x§$IyMAÁèÕ²¢õ+R¼õE°ÝÜï٨܄1YO»¨ãœ Èýî¦à#ÄïuúñÚÉ:‚@˜r¹Ï/2l°€JÀ¸ä.IŠñÒ »ÛõºÆóýx(%ÝF_^YÒ:<{½0Â÷A ²`)Ó/²²Í_å(á‚%,ëò¹Æû ©¢@ Ó‰_QT è÷À„Ö‚@äócA«1*ä¥- Àc©ô+ƒð@n ¿¾¢\E·LÍkŽE>*r#Œ‡±~$Ã¥ÐôÛMÁ&/–¬H›#FðÝÎü¢Ï_xÇMÔ¬íLÖ«ƒº àÉ0ôéõÂÜz¼Ë+mG—õ"Pšö›T›“îÊç3˜Z™9é·ê2‰`'ŸZ„øÈAæ04‰/킉x{,çàS ©¶]*ŒUVÉtSÝe0j.dvû“`Û|éðoD¡¬ I£„걞"é0¹Ü…6VqW±¦k kíl¤;s&êzÃè+†F x#ŠÃ,FÑà 1e¸4-.Zõ @"Œø¹{¹j%f7å+¼MÔC#å(Ì2Š|†g)éˆä™£.È“8H©»ød|´245ÍÎÌQ\ÂðQ`…> Ô©…öC (_Ŷ?¹øîž@ÕäêiñåQd¤ùøiáµÁïuL ¸„5Ü´)Ð'g%ú}‰,Ж¹à–4x»q‘‡&d‰eñZ —V7euÃ(ÇdßCS †lB%2Òõ0˜ñå}Îa¥ß®%½O—]·ÕL÷öOn'{7DR®¼’îöQ½ ’”¡þ¯ù$EI,G»ãlènpñ–ã9B/4Êâ¥Ht¿¯êRh¦F<&÷ûƒº ê†ö >(0ÒÜ7ˆö¼!•=e×ùÂÁß>þãN ©p ¦$þWC ½ö ÅÇ·bº­]‰p bc‹6uÛ+EöÈ!d4Ú9·†%¬‚–<èoa`¦¤·˜é’@¢säí±it0è‰D©?/ ¤7(K¿Pê.dóJ Í"(©¬ñ'|Æk=΂"Fz/,cƒð?€QÍe3lR9'ä(=°~†°äæ.R  Åëj亰–1/W/\pS Úá‘%pBóêkœu"ÐÒiRòJìc˜,Íœ‘V 2m·–±A)›ßÉ’­ÎÍ1}w „—Ê é/øËE'ûEjî…el`Wa ƒUMeé×稦)“‡aÔ#a$¿I˘•¢Mt²#½–1_-´Ëû°&0ÑHÌ…=ÆšÎÎ>†l¬DqøøG ‡——)—©ô0^€­›x)#²Û—15ãíÊÑ"S±¼ ˆ2ûS2†lÞ3øÃ/ªÇÀ¥ä–Vºc #ËØn.²‚DèÝ¥IY[yqó?åQHw$®¼iä#A VO&‘}L4wÛ´Ò¿8ËXÑØ½JÅAì`nf›Ó€wr×G{h€#A ,cD…N⼓òdCïTª¡Ýn)ƒ P•~XbA8%•«&æ|$„ÙK†b);Šö2¶FâünU*ú2ÑJ4:ñÇÚÝ<Ð$–‘!ÞH~Ž ‘Á2¢“RœÐ_\¿<ró@¹TŠY;}öë<‚÷G†@ö2ÆN‹®”‰¹•`·Jcƒ(ë¢FH15EÉÎ)n¬Æõ@D¿! ðBÚðOE'{8—e>h·.c^†T7ð+‚JÄe33êuZÖ'Ï)h¤”.JŸÃ­(ü²ò»|“È(R--4ÙÀô •LGŠ@Øu>Bë´Ç/)G„ëݸŒ%¼ ¢B” æ-ò@È­­¨I‹¹V64|)Y³×Í?Ü4ÒœáÞ®\Æ<ââ«k×:ëÆP ”(ÐFÑ+uRw<á‹‘#fh_* z4Yæyf¯Ý&ùe%;÷Ù–›…òtÊð°ƒakpݱƒEW<‡6rºåèµåM’0¸ÞÈÃiŒhc¹x¨É”'ÅJw<|Žr-ª)Ú·u©æ5r‚PÓ4K›‚¡gÊa¤1€5ÒJ·9$ÔLnQRÖŽ='àNé2ï!šZs"á0r4Ij] ˆŒ4g×0ÓÄv‰ŠUا v2*œî9o¤HæÞõòúù‘vcUŒÒ(Èë mw8Ü{J`.€ˆ´ž§röމ:vzv mù´wý8Ä£)I”F’éýúxÚ Ë˜šîNmÇçÈE‰ž%+<ß”KØ$–P–0‰«e—’#m'vµ`¶[–1¯Ô¾Z¥sçBÑGj9‹H„×›´_k§p61¸ Q~ ¬ïb̼(‰Z»aóB f¹ØBH¢bFŽYÊš/+IfÒîŽÒh=ñ“pH—¿ 8ˆyƒ¸ežÃgÓœL)„G%ÝÖûÇó‚Wg`{,ø©¹ÜDº²ò9…‚@ÜI\¤@YÁ¤ÁPv¢P“Ép`&rÝ>=š€@¢Çá>PÒAw¤“!uRK8¤kV”FQБF¼˜X&]œWÝŠÄ•oþ¿­)Š™égHƒÞˆ1ÔS÷IRQK¨½&äJ†F:ë²\OzÜBsz‘žíx!7?‰v0̵“ôšý÷´šlé5@ÂE2ž—:õAˆ›dOÅ~®\™j)Êœ·u@æ{g†‚@ÍfÍ¢@ÀA1V áÎîr}‚îÁ÷*œœÁ¦wôŸœ°@Ú„R1×PèÖ[׈™m EdípK©(xì¹ïGõÚËÖ¥rü‚œMïZKepô‹Q¢ç¸BA TaÃD…"´Ñ`¦Åb)I¤Ÿ´â•TJÔAÆ ©û)á9J¢à˜15Êâ6™šÄί7¯{ºmb¸v+Q·®·íB¸ž„‚ÈRwu@܆¥ K(–×3î>¢~e±–08T‰ŒtÎÅH`[„@Ð MRñ\Âwª›&æLtÂa 1ÇIu&ÃØCC Ú˜·ea «n45‰Ë˜WeHãR %é8’yµŸ¤ºÐˆê304ä"-ê¼$1ÔO’4æŽÈu@5bê€DsÎò%‘ë«›gš4¡ß%4’dcÃ~%¨ Ò¾´·L{h¤Ñv’–17Bˆ: *°¦D”äô¬uÄ?† Ù$–ЈÛÃ8D©#G>Ò^Á2Vš¤£äóëd â ´ Á:ÉÅë»d>¢=Ìý "ãaÖ@»õ ‰ã†Q>7шÛÀàˆÂéq®‘z’KhdÛÃüA%†<‹­Öˆ‘æK€X¥sK)èã;u@†Å<ÃEÎ ž‹Žxj;‰%4‚=ŒT½•ôáƒÀ|F=z55=×5¥Ž%Œ„n@EÃt¡½Sºádåͺ:‹pEhÐÌW¿!F«ºáõœŠîå ão–6[ÓÀƈÀÄíôZçF0"Ëjº¥µouÑ“PˆÉÒ?8@™è7˜2ýJ£Lⓚã.<­/¬ð°ýíwødc•…Ökßþ†ûÑedwsWFõÚï›f¼FÛæ~Ì^þAhgÙÆ"ÌL«‚aã…ˆ‹çUZ¾ˆoç$ŠðhË ßÁ¢R¿Îë&á*‘ñ]Â,/Ã*âf„ÅùÌÜ>>Lë(ê€*„ýsŽù7½"7P/°ÐOâzRJ¨DI^z"PÁõƒ.Q-nHd ‹$eåÏ]îD†¹hÕJ×”dÙˆ)PTœ U“{jÍ’®( ±?)Ml3Žs/^ÔUˆî @ÄñRß\ã§­ˆUM)žiUNÀI¨ÈP{g0z¤Xˆê¶Øž"¼à´EéýæøDxM(„ºÂ4Íå‡/OŒ†ù„Š@ºÖè ѼÁ‰%îPÅW÷Q””ŸˆóH××m Ô ´”&Ë„Áç:Ñ‹}µÑšÏæçòÊ'1®c?œèy‘ Yµª;šj»˜eÂàó L;Õ €x4|(ªZèäLÛ·™Ïƒ/aÐíˆ$6Kí°/î­HÏŸæ}LÒ1|RŒš€šR0ˆ)ýžG½Èó÷s®¹çÉ©¶Y³ÜΛˆ% >@“È@c^¡#P/ƒª—Uê๭ð¨ãºìÂ#5Ûvc­oÙ DlÆe#Í{âô?|n¡#¬+WøËÝG/),ªü§UðrÏM $ä 4ß”üË&RÃÃG Æ<½½ŒªæÅ@‹: Œ1Ð åbcËáפ£Dˆ&΄Áç:™š·æµ|aQÕyñ?œæÀåGQ[ÝØXki y¼<“&OÍç:5¤¦§"Ñ‹Æ “áI›žG/#ª¨NæÛ‰D$»î0ЬšyTl?Iç¡#šP(¼§»ø‰ð~‡Ý=„[#êuø›ÅX0^‡c2Ÿo]Ö6l"g éÆD9Ñ·&✄Ž@îðk/%"Ä÷È Ô9zYáEê"6OdÛnmÚV Nš½8/œGæûx™1Ä}Üç5Œ¨¢o3‹¨âu8rh®æxš÷Ä2Ð˜ÛØÈÂK ýQ,^ËÆÉu@☱ß„Åb  ‰Pxš?U™\óÛró<^þÐ Ÿpg |œÅË /ú‰cKÑ~ܦʗ8Hœpá@Ñjé‰U"bücC ¼\,^Ƚ£Ø~œç^"¼Ÿˆo¨‚ñrÙÊlr¢Ÿ (T/˜G¼x ^a>^“ «.Ù'™‚8ŽÔÌ|ë’3Ð\ÿ#I“kÂà“Š ¹¥0 ,ª®¬)+¼Ÿ(5mQáÍèëä+me"]88òàróD½’-ˆǹ—ÕK„-0y&Ž9™½á Q݉æ"…@nMtT—/Äv1W2)’3È"B«™|+‡È#ñ%l’M|žÝÛåð;!ݶ°¨2Ð^ D€ÊK$êŠêŽâ;œÍ¬(Ô''ωÞ‘YÂÜRXTEx/+¼@m'1d1YŒ¨(|ù"o¡‰uáàóÃ1ÄYJq`QU"z%“òÓ%œlô"Ý^¾&/ Uü>ü<„­.Ý%ªfŒäLw(³V¶äÝsàÔJd ¹Q’ô˜¹¶Ók7 ¬Ž¬´Ç¶–ÍZwž5iíÆh$à^ˆú„e"óû¶‘`¢½Dx¿³FÔÔ´rBtı%§Úœ† Èr¢ß 4æ%ÌΓ‘"×">Xç*¶év6Kor ³X'\¹‘•S’Á&^ÿÃç r›1¢êÆšží¦>$×0s â˜v´Õ` E;å荒OÚ$;Ñ‹sÄy$È-ÂGÕ‘>áÁÿˆ^¹ùÖ |Ñ\̓'Ù‰óËØ¨NPäÅ­DŒj(Ojn?rDZî$Šâ•0a$œT.Í-›ú€÷Ùrvæa59^Â8°vzÓÙ¹Åø¨·§«ÐDÜK˜˜HªºvÍzüg ÉL¼ÜÕÏ„VŒ‰ðµ@ÈFYÞ+Y¥½±.ŸSj¶íÂÁh¾|™’ôè¤ûñyâ s#F5ŒFTw2)3È8ç…;œéMM"´&²±;L|®‘@ 1µfºG®h>èq9Oã~·—ž{!‚úð4v<Ф;Ñ»ç y TDé“3Ý[:˜Z¹ª…WuÂxxð>P"¢Lº=Ÿ#?†@59Í_΢–¨1-h–ù¸qlV:(AÊF%a+BëׯZM[ DJã2éNôâÜq:©icÑ=Q”p¥Eq·×ujÞ[„ת$Rª†CV[.¬“…êûÐÈkb]&¢¡Oñ86ª‘c0J‚÷(—ÌÂO ¬Nn¢èÔÔ4C©šCñv]™ì<@~ßhlÄù¸opÝ;Á‚ߠìÏì;äùºÒ¥ õÉ”u]]½Ê ÍNÉ÷Á SÍDnåÔ1AŸ‹±!8N…ܾÑb›q'ìî÷W¯^ꨂqÒ+*³IDAT ¥ºz¹UÏ} 'u+§ÖDzœDTŠ#;àCV:)w¸¯^µÅwÀœQ)EÙ®qauãR$HÌD{i¸Ç8¶k‹öðBÄv•z½Ö1.Pª:1ÏÜ:æ¹í¶;™[9uLÐç"Ä—0Œ1J䕉 c¬T×(XÂjë«öýËȬŠ]äDßš s #Í‹hãuã:æô|uéârG½í”dÜ|›\Cênr¢ï˜8]´¿œûNˆ×"9Ò}ˆo÷Uz¾ËuÉj\^¹Øñ|€0îò•6cÍè%f>¶›œè;&N‘@ qWæ¦`Úp6ìë´ “¿JBQÿƒúD.OÔ‡6QÑšV3xXrš|€&v >ç^Çh …E……–I–Þ×í…è6_¸ÈDV¾Ò¦J›”š3Цb<ÞëLú½H ˜Ìêe\Îø¸pT®µõ<|lŠX­ õ\ˆûrL8˜Fw‹|ÐèÞ4xÏ<9”û 7ÿ†Išg1>LD -Ž—07GqÍEy1Bcï´Ï̾nºYÜêÚ&ŒÚ–ÿ÷ͳY>@.oðúÝx } 3%³ûËd9#4Æ ðÜâá®×»©¤)k}üxhC2?Ëëwë1t¢Ôn]qa®êXå£ÀDûmçT^y® °•SEëEZ1Øÿìz`—U„Ž@~ðK:’XÓýZ¶>³Ï[èE¬ ¬µjk@UÇÍ D£‘ùjëÆ.=‰ µ=Çï”[ìö@ôâ$ÚÇÉ\Šë(âgw³‘ÿ¢ƒ@¢@IÍT¼¨–¯Úºÿ‡”3дÇÁçyÝn>FxZ1WиŸ]èæó›’ƆÝÅ›"ØdŸ×øÃ|otÈ i·1ÙUÅ=.øÇpû?£žç>ämª„ýV2‰}õ¡K—Ú¢o° ‘A ¾Có¸)§‘¢OEM3ÇÓèdø·x.ýo³Û‘A š;–S”õP V®^î aÆx¤XËåAD‘”ê®×ÿðy‡@¦Ôöùä£pŽ|°qj£U bÈÜúΧa1Ð&»ðá'Öãu»ý:©’YP<,C€0åǹŒ%=\XË.ÿgaȧá)ªçS•»ü"tâðÔ<<ÇxvÖq)Á@w%Òôáø<ø?0ДÂn×kŸùœq ê ©3¥—0Ñ­C¨íÔkùòã܃B <Œ§:³rÚ}o7_‡Ž@JÒôo¹g⸠Ӊ4½ˆ^q±Ü"òžZ¾‡ÐÈ ø¼Ž3Ñã 0Ìx(á°t­44¦4w¿ñ”+~Œ9Ñãã³û]FÔùŸ‹„<´ÏêGÎ]ÚõÆSŽ8ü:%·d_ƒÁß8Äxk/×vÞƒò?—hùb¦´gt?yp ú©ø¡Ly1Ѓð?¾®4 ¦Í=£}+‰/÷:4Ž%,ëá4ÿó˜gÓ¬ÉZ.¦@^4ì:Hbã`¢Snâ€üÏs5|)ÍÓ{Á÷Ç B_Â0Z¢|Íð[Œ‡ «›„ÿ)Óòµ¡¤}–ö”òPD¤± aeÎÂϹs=¿㘞ÛGYÈ”ŽW¹w!ì¸é\œ¯Û‰¤š•úž\¾†ñ ××pê°„…mÊð²yº‡}ÉB ó±_\ëLän¸‹¯Ç‚@äõì«¶15·x´ë÷“À`8µ(ÈÚõ𪠂øê‚ Ƈ하ÝßéÂêå@ïÆ‰óuÛ÷§ÙØý±_×cA &Éé¤Ï¶NBÑa;¯ “¿³õž ¶/:\ø£s—¿ÉŸÛ‹Ç± dš'sBF7àŒÃZƬ0í@(Žq…‡–?“)}I¬ß‹ç¡#Щ‹Ç‰À¤sBOìÁ…µŒy¹°ö£@é‹B—ÿ¤cà{ð"tR$óÀ9¯ø¿š»u„ñ=Üyûñ?–å½I™¡Š¨§N‡1Æ(¿Ãÿ+ŽhÔ¦©œ@׳ª? ‚cYXy‚2ó¤Jñ²pÕ} Ë;H’ŒÏìUí³•Ðˆ"§nÇÞmY&ƒKDþ}â8Gr®¤Ò,5=ßÑ·W2±Á³5[úÒLyOOEXàÞ³á»*‘`~"߇ÿáðOô0uð6ÃÓó´¡S$³F;ú• „ó˜U,–¾@…†@§îÊ-RJ¸ãs"Ð(ë‘…>w€Dx§ôÝÑä)QyzìØ¥¯[ñ?BC U/8 ô`¯„AuTÅÊB/¨®ŸùNÏW]p\7¶wé4©¨âÒ‚À`_³Õ|ç'šnK`ýDxþ$°U)¹¡Õ56Ïm–:óü´nÒ –/¾óò^HÛ+Î}óÐH–¤âGßË„!X1G‡@"ÿ³þôâk»ÎŸs,ï$ m;tåtWƒ=^2;ÑË€êþ£Bð?bͳþ£)wœ§ñœŽ—/÷W Ñ”'²~ DqxD±ÄËÀÎÁÿHÉ„Õ_ñ¹å®½OÅ­4)æÝ¾4C‹Åw8ιêQx•åDFÛJLõð ü¥>ŠÚçÍg{ë~àyhSKW§}ºÜÓÕá,aš0ÂøSÇn²^c4¬—í j„+ä8†b2ùsýbú­†{ðŸPˆ–#Ë q;<Ш¾EÆQ n.?ÍŒFÝ÷5׸ß3µ0u36žú@*‚¤/Aõâ3œÑVc Îÿ”úXÞ¿ëH_„>Ú^Ž<í÷EBA 8‘ ªÿé7àaîó dZ¹Üsùª‘ÙâçLöhl<õ‡úȨåD6  èÃßɰ‹Ïëiy‡ßOË”bîíÈÓ~P9QFh+Œg.X~ñ˜ÍgŸê nûB£½”u¾'P|nŽÒ†Æ3f „ø/ð?–ãXÄáp[åÊŠ<=z`ýŒìâj‚ÀèˆI}£0Âø|¹âùs=_×v#ÖŸIŸˆµÏ=Á5z‚YÄ÷”ÿµþToË;2Žñb/óóøè ‘S ²œØŽ Ã{˜ÃÕJä¤?uøFÖØ\g½GmQ¶±MÀPhùºéðêçì‹ø_?Œ Á‰lÜ"|jvÞâ6Îöfg`ºhK_Ò—âåËmÚõ#E 5]³èqS Ì‚í¾ºþŒ¿å y®Îýž‹'´‘¤×ÙHNdÐ>#uœ¥pô8«\¾À´rÑwíŒc´zʼn|áä¾1R’UóyQ0adæY¿¨ žq ÚËi{ÝÒïz¤D›¯· ò?«é4ƒñ´WáQ§hC¦—ØxÚ X½‘"Ĥ{ ãV Rü׿yŠyïey§ˆSØ¿xi”k{bËn>ßaŽ#C ž‰Ìτђv†ýÏÂqë\oÓÅÅ–å˜gÓ<O¬ÓddD»×Xa<^„µ!ă}°–XÂJ=L@d$âE‰'pP tɦt!Ì^Q´91ª£ñyg,L³zq³çò…v¸é ÏÖ›f¼|‰@ìs>2¢÷Þî—D¡Ê8ÄúYÞyØà„åëcg¯=Ófñm#C “’iΩÝT¦bj,¬$šÉü4«^¹(L·ó”'Ì䵆¡½—ŸÇÇÁ 0âNd^¨¨k,Ci|Ã(-_´m“_Y!§ynú"áý±Øöå)ÿú‘ w"óÒ5Câ@³FY7zqùÒLé·bÛW/hyß )ý$¶+(¸¼±|%FïAbÍ455Ó3e çkNØŽey?xùÞ Šk{A`$„\Ð9(ŒëZƒ*”XFÖ¬VzÍ›!Û|kù’÷ÆÔ§'¸|oŽ˜i¼Ðú–*Q  e` £ôʸ÷Ÿ«Ù–w$M(ÊW>Ƙvã;F‚@p"Ë»‚ÀJ†½|…¡ÿé÷¡²ÅÞë‹ §²ô{Ÿ|Üû©~}íõû#PÛ‰¬“ÒlMJ®ÎòÕï£rænê{_¿öñ}Ž@~NdÄÿäe;+†ÿp¹Ã†ÓòõûqÌûp0àDZÜPË)Yš|“Ç]VIò–¤÷јbþÞ¸Ç3éïü‹Â‰Ìí±®õ‘ù¹[36y¾CI2?ñð™•å°ß¿ÛÞ8ÙNdmDôµfÔ#Áÿ`,—Ý.«±Ù"lHHa<ínaºÐ‰[M‡$¾÷‚ OÙb2é³?~ñÑ^mã{ƒA ý¥kß³•‰LZœ6“[7ÖÒ••Æ/ñ”-RƒýVωÄ7†@ '2˜0¸ÄmÁxæNÌ^³·-ï÷E[5}äÜ¥¯zµ‰ë¶@Nd0 rbQo’³–É òø©fb)•u)æ}¶'¾OŠ@ô–Û§9öÐÅ&QH`ã.ÏQ¶yŸ3G]úì¸Ç²›Þ(!ô´…aK_6ÿ“3BÄ…ey—¥Øh0ö†@– ÃÊÄaw é ÛVFÿy’¶jÒLsŬ&?0üö|w!w"Ë9"üuÝ΀:nþZçeÚi™6Ñ|o¼MwðøÁ‰ t‚tˆ <œÿ)Œ™ÿy–Ü6 ÃÜÐÓÙØe#xüa‰G–™Ã@o‘å"<°3¯Œõ9KÔÇPŒ÷ýá£Ë#€ßžï20 „\Ðó ÛJެï¾`Û ÔG3Ìš$—Þ¿í‡ã‚@`ß×4¥{Àÿ@ײeÚÞ~㔾0Žg)]$›Ç{¼„ ;jq'2P >Ê8è™*vÚ1µFC‡;BÁ X¦zÌ3|€øò…ޱ„£ ââ)$Ë4äÅ‘¦£ý aÈ·$ȆR!ç1”qò?g‰÷$Exl4µ¾Æèþ D SMéHʵM÷¸–/PŸ³¤8DœûÃË—{gÕ\÷LÏP µÒ‚ ÌÞÔ˜–/P …å¿gÏ|Å1N4 DN)b:J6¤øwñ¥"õùÈ“+§Å{ñùh ’ i‘B[#ÔœÔ-ãðæÔG‘Í? ¸â^ÝÄN¡GáÔ‡D¯gޏò©qŒa/¾32eóˆ› ˜œúPî³_ãÜÃ~0dšjÞ,¦’²l_\‰]6B„} ÄÇË—/5äBdÚÀÆ$éÃ1õá_#œc D óbŠ˜hÎ@Òé€ó‡çã3D}eÃH'wÀÇâfA  omvé_ßnàë\&· dÙx8vÙè ¯ ¢¢À/B —"(è‘zôêód–S«ë±Ã˜ŒF]²—°Qµ»N}`4³ËwÃ'Œš`(3Ò¦£D cà"õièÚ¯‡ñÎøÝš½öðÜt =öû «ˆÔ'vÙ êÝï…¤EÅÜÖøîWWÓ¦>„´Š›-‚í¶{˜¢Ìlû­C>À©å²ñÄ•¯Ù]üøT]·z Ç“uˆáôT¤>±ËFxºÅÐD1WÖÈæ!_œÆb´¨“¾þ¡3±Ëƨ¤_ÿÃ#,uRG¥©q?1ïÓïë†ph±|…Q8õËFl4 âýßõÍð-Dê»l Ï z½½„qk|PƒûáÔFSVKÇ£ˆÀãùÐd*ùÙÝpk|Ðó©e4]^®ýޏ¿A`h2tszg¯ü)dW…Å=vÙfaµdIšI˜‡¶¢L "¦Ì~?vÙ 5{ÏÐdJmÌ3: ÂÖøƒË†ÖÔ><Ø´âVaA`xbl;Ô‚:CI¬ǹ‡…ÛzÏÐî²dRX³M‚–ÂDê»ll뻆Öxx dv§ OäTߢ>&ûRì²NlëEC#±?Gd×.aÏ6J­t¿ƒÎˆSÓ4—c‡±A¡6ÞvC!|ü†­.Ÿll²ª ;VÿR¤-AP(9øïÅY6úÃ, -†B M–,W®8< ¦)½¯j푊ÉÕÈÿâéF‘­9;÷ôšðÓÈïƒBxT”¯|Ⱦˆÿ:†²…)&[€:ãˆaû”4Ã_ƒx ,cØ/Û^.7ˬB”舚õ„|}àqhIzÿ'g%φqeä 0IŠ®šä¤ã.I ëÙ§¤¬?3a²%ߤ|¾Kˆt0‘a¸/dØ€×!)²k‰"{Ÿx/>6†B ÝŽôÓ![krFãH¢ÏæknéF‹ú’ñ¡‡.]Y6Èâщ ÐQº o2aO ±³²¼Í!ÄÍÇ a¾?Ñ )_'â]‘wRžnQÚ®NVcê³ Žù™¡™É°+Σe{‡ÂíÌH·ÒÔ¬GHoý›?~ñÑí<·†B >…Z†.:K¯ëw|†öó"Ý¡µ««¥ÞÓ¯}|?šØ1º+gÙÁø´#*4èR†vØŽ’ÖÀU–Iÿd¼7‡âäwŒ@؇ žø”±Cò?”êü²çZgl†KLø«ã8¯ž ŠüÍáÄxÙüÌ”¾Ægy­iX”寴Ýmƒªll”?%’¸Ö5Š0¥#²Ê›’ùÖØU•Cnr.­Ìö'rßm‡>ÊdóA†ó ™•Y*„@žÅ`ŸùÈS—Òó^\9QØñÆgiÈÆ{`‚à×Ê®C퇼üÜJÿ¶q‹I€ÀЄIÞv ü rä8fJÒYD)]4iˆhû7$Cþéž½ôUw}|=¹šò›úÅŒ=ýôÜbb*q„¶"˜1Œ¦úßž^ý¬_û¸>†@ 1bĈ!C †@ 1bĈ!C †@ 1v)þö¿íq‡Ðª}IEND®B`‚lombok-1.16.18/src/installer/lombok/installer/lombok.svg000066400000000000000000000320001312655740700232300ustar00rootroot00000000000000 image/svg+xml lombok-1.16.18/src/installer/lombok/installer/lombokIcon.png000066400000000000000000000014241312655740700240340ustar00rootroot00000000000000‰PNG  IHDR szzôtEXtSoftwareAdobe ImageReadyqÉe<¶IDATxÚìÕMHQðÿ{óæcgÝÖÕ uË,ÃŒ>ÌÖ¾ѱC‡:FA}u ̓A„„ :ÔMì’xªSP$d!¥5¨ëÇjºîèÎîÌûèùb‰‚^æ oo˜™ßüÿÿ÷$„€µÈøà|ÀÌéöýø¡ ûûyC3ŸÒ±HGcãgwÕ×o†Ñœ±'“bízöóHY†Mžh®Ëõ¬€¦œur÷Ýf·{fárC¨²ˆä¬³;×#ªÆ€¶çR ÑÀÕ CKj€‡‡²âÕƒžÄÀŠX<ÕHÌE½øYøÔ­ßU²N —”‚††¿~Oxà1Åñ`óƘàptGù´ÇÙ Ãù§¾áD[߸Òþв²ÿœ‚« áþ’XÁ]+¾4Þ2TUaЉj…-Ñ1 t¢F 7`M¢`D¢@A9M‚†dç[p¹ãŒÚœ=žÈBKSWï²€‹×ò˜ÞÊרNM“bFl “u¡ÐCPó:´°l8%HΩ“7ë@ïH25ÉX«'”ºÆN+µä.¨­ oeªºüŒ¡*B¦mÊÒ*ly€€Nd®ÐŠŠ-+ó5B½'i…\¹ñîÇÈ"ÀïÑt°´5°/wò£@Žp¨H(ÿf.zÇg d!‚*a:(  4{Í1ß`ÐìþâÈõçèË >w§Û²þú¬[ñM´jZ®Ì÷|ŸòdÃÊ0 iΩ,8#-…‘° àÀU!ß(w À=9©†DÔÄJQž‚Ô9¶‚86¢Ç¡mKƵ¾¦,`⸉QAK36jSxžœ"÷þ§ÂgÆ…m±h¥‰ÈS°ØË…dŽód€ÌŸïòÿ>Àø°æ€_ 7£]-^œPIEND®B`‚lombok-1.16.18/src/installer/lombok/installer/lombokText.png000066400000000000000000000057571312655740700241050ustar00rootroot00000000000000‰PNG  IHDR©9Œ=Ô¬ cHRMz&€„ú€èu0ê`:˜pœºQ<gAMA±Ž|ûQ“sRGB®ÎébKGDÿÿÿ ½§“ pHYsÄÄ•+ FIDATxÚíohV×ÇÛò"/„åE^X`)Uplc2!e)X°ÔR¥¡c†µiEÅÊ"u(tCË[t4%‚ZæhG Íh¤Âš2È‹¼ðE^ø"/ž±oï/Ëó4ÞsÏ}rÿœsï÷?½Ï“{ï¹÷œßŸó;¿óù¯$sÂÈ„B!ò]6!„*)B!„JŠB•!„B%E!„JŠB¡’"„B¨¤!„PIB!ùÐÅ&Hd£‘­F~®¿÷Ùàáu.Y4ò/#³*r>g¿‘Ï,ÇQ©d2 g}ÁȈå8ÚtOç7rÀó¶YÒwìK#72c¤YðX…þ7dä'F=í‹Í˜¾¸œóy1F]NøÌ;FÎüÌ~gdoŠï|`ätk{QIÅÓ0rX;F èÏ]úù]#ÔN“×K8`9~^µ»´:Ò+ Ÿ™ÏéÜ= íè ?5²ÃÈm‹"Œ¼cû¼H‰*P°»EÁ¯(ˆ¥œÎÙíÐ>=¶Áf#gŒ¾V Ô_62MOÊSÚC¦[-ôQ#Ûõ%(ã®ù™‘‡·:ïŸøÚ§6ŠÞ7ò¼‘çrôª¦ZûPéQâWFž. ÂQ6o9¦ýß…³jð€Ì½iß.Œž)“iµÜl`.fÀÑàBˆ0n­Õ¢Zþ Ku²üP ý–D›Ý±BGuÀ*M줒"¤x67,Ç] Ñbð´¥Òb=硲ó}oùJ¢’W¤ q]û›7Ã}ÄÆTÁÄí#´U½¤=1LJÅ>u2A†BmKž¯WVwÛµSúû%¾ÆÞ㺡'¶äU2ÓŠæTR$TŠÃ–òŸIü>;è8‘µ©Îx‡ß¶¼Ë˜‡:Q6BÊüí‚ÏÙ«žÒ©euA•è—|•½f%´î’凰9Â/JT@¶´ÅÚ ÷Ÿ<…×>3%kCz@ã%"ëŒóPƒì˳v(°cl.ïùzGÛR(!#_8*TR¤LŠ}Ët’«²ºõ6Ê([>Åy¨õsÃaPÛ)õØQ· ½iæ' ¸.õ¾ ¬F¨¤HÝû~õ¨z5¶8'áÏCùÄGÞÔ ›)šêUýXÜô¨Ž%#ï·ŠTR¤–'iLêbß›˜ã„롲fÞá3l¦à˜S¯êD ¯ª!QfgƒJŠÔ(™g:M\Šì#ýî›±pzØA‚…¼ÍUÍ9~§W=ªOó6N¨¤ˆ¯tZâPŠŽFYavlÇqZÜ“FÔ«‚’Ë%±‚JŠøÌŒ|’âóïªB:÷ªPùü鯔Ó#±b˜JŠÔ‰•B´.zsÚ¹!ëç¶zUgS|‰(™•ib•ñÌ1íQ ÏfýíÎCåI7› –^ÕAõªæS|¯aä¾d”XA%EBà®Ø”"m}–Í”+?`Ô‚~Bìk¿MŸ¬&V¬« •T»ÅÎ{ô¬yšŒùÖËŸ¾§µ¾G„Þ±¹åö”^ÕJb…놋kpýÒ÷%œ5KÒYØç¡¸` •‡_ÿ˜¾‡Ãúï9õ°Xö(_°‰ä–Ï·Xƒ6 µ/Þ–h® {½íw/Q‰e•^’(,ŸjCE×y\ìåg|‹Ò&:ü.½Í–ã=’CöJF<éð™ÐK-«RÕÏŠ}®ŠtÞu„i^Ô¾ï2VdU`vA= [™¥>ûâ+Þá Îæß$*.ìÎÃØú¹DÕ`Žºö]VAoç^‚’¦o·½·¦x´%ô:­ìɾ›¾¿wK’m¥lü­!ËñÑc%4¤;cyÈ&‰Ê“5R8F0zv«¢»–ôÎIµs§Â÷v—^É‘K’mصʉ03ºx¼á=#é´ð„Q,ú¯Iž•T;7¤º“¶ïðñ’œÀüJÖµ?”êÎ5V±/«Bà•”ßÃNH¬xUb–9PI­uÃ/Vð¾æ\ÜjB:a¾$û5jðüoV°½¦+ì%®¬i|NÒ%†`î!CÌWm¦’JæhÅtLfofÀ‘ì"ù…ä·cð>)~7â<™Ñ¼ê "µ©ƒqsþØÝàMiÉ—`âÄZ–Õ2ĶÙ´áBl'x…–¨þÝ#>V’aÿ€‡ó¡Fy?ðÎPí©Î¿5²1Ð6C$ã=‰êJÖe^ø¡Ž£H8#Ñ” k‘Þþ¼DÅ¢§»*f©€ùŒþÎ%lä¶UùIýéã¤PJ˜¸üZ½§Ù¼§å„÷'´¹˜p?÷r|g}ì‡MmÈ¿õþ‹NÀÁ5œSÙ¬F】i_ìö¸Í¾Öö*"«vÉáš/¡=®¨‰uRi+OÃ3þ›z LSdIEND®B`‚lombok-1.16.18/src/installer/lombok/installer/lombokText.svg000066400000000000000000000126371312655740700241130ustar00rootroot00000000000000 image/svg+xml lombok-1.16.18/src/installer/lombok/installer/package-info.java000066400000000000000000000027211312655740700244220ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * This package contains the lombok installer. It explains to any user that double-clicks the lombok.jar what * lombok is about, and has the ability to instrument (or remove existing Lombok instrumentation) from any * Eclipse installation. This package also contains the graphics uses in the installer in SVG format. */ package lombok.installer; lombok-1.16.18/src/javac-only-stubs/000077500000000000000000000000001312655740700171555ustar00rootroot00000000000000lombok-1.16.18/src/javac-only-stubs/com/000077500000000000000000000000001312655740700177335ustar00rootroot00000000000000lombok-1.16.18/src/javac-only-stubs/com/sun/000077500000000000000000000000001312655740700205405ustar00rootroot00000000000000lombok-1.16.18/src/javac-only-stubs/com/sun/tools/000077500000000000000000000000001312655740700217005ustar00rootroot00000000000000lombok-1.16.18/src/javac-only-stubs/com/sun/tools/javac/000077500000000000000000000000001312655740700227645ustar00rootroot00000000000000lombok-1.16.18/src/javac-only-stubs/com/sun/tools/javac/util/000077500000000000000000000000001312655740700237415ustar00rootroot00000000000000lombok-1.16.18/src/javac-only-stubs/com/sun/tools/javac/util/Context.java000066400000000000000000000010771312655740700262350ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.util; public class Context { public static class Key { } public interface Factory { T make(Context c); T make(); } public void put(Key key, Factory fac) { } public void put(Key key, T data) { } public void put(Class clazz, T data) { } public T get(Key key) { return null; } public T get(Class clazz) { return null; } } lombok-1.16.18/src/launch/000077500000000000000000000000001312655740700152265ustar00rootroot00000000000000lombok-1.16.18/src/launch/lombok/000077500000000000000000000000001312655740700165115ustar00rootroot00000000000000lombok-1.16.18/src/launch/lombok/launch/000077500000000000000000000000001312655740700177635ustar00rootroot00000000000000lombok-1.16.18/src/launch/lombok/launch/Agent.java000066400000000000000000000041011312655740700216600ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.launch; import java.lang.instrument.Instrumentation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; final class Agent { public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Throwable { runLauncher(agentArgs, instrumentation, true); } public static void premain(String agentArgs, Instrumentation instrumentation) throws Throwable { runLauncher(agentArgs, instrumentation, false); } private static void runLauncher(String agentArgs, Instrumentation instrumentation, boolean injected) throws Throwable { ClassLoader cl = Main.createShadowClassLoader(); try { Class c = cl.loadClass("lombok.core.AgentLauncher"); Method m = c.getDeclaredMethod("runAgents", String.class, Instrumentation.class, boolean.class, Class.class); m.invoke(null, agentArgs, instrumentation, injected, Agent.class); } catch (InvocationTargetException e) { throw e.getCause(); } } } lombok-1.16.18/src/launch/lombok/launch/AnnotationProcessor.java000066400000000000000000000077071312655740700246530ustar00rootroot00000000000000/* * Copyright (C) 2014-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.launch; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Completion; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import org.mapstruct.ap.spi.AstModifyingAnnotationProcessor; class AnnotationProcessorHider { public static class AstModificationNotifier implements AstModifyingAnnotationProcessor { @Override public boolean isTypeComplete(TypeMirror type) { if (System.getProperty("lombok.disable") != null) return true; return AstModificationNotifierData.lombokInvoked; } } static class AstModificationNotifierData { volatile static boolean lombokInvoked = false; } public static class AnnotationProcessor extends AbstractProcessor { private final AbstractProcessor instance = createWrappedInstance(); @Override public Set getSupportedOptions() { return instance.getSupportedOptions(); } @Override public Set getSupportedAnnotationTypes() { return instance.getSupportedAnnotationTypes(); } @Override public SourceVersion getSupportedSourceVersion() { return instance.getSupportedSourceVersion(); } @Override public void init(ProcessingEnvironment processingEnv) { AstModificationNotifierData.lombokInvoked = true; instance.init(processingEnv); super.init(processingEnv); } @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { return instance.process(annotations, roundEnv); } @Override public Iterable getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) { return instance.getCompletions(element, annotation, member, userText); } private static AbstractProcessor createWrappedInstance() { ClassLoader cl = Main.createShadowClassLoader(); try { Class mc = cl.loadClass("lombok.core.AnnotationProcessor"); return (AbstractProcessor) mc.newInstance(); } catch (Throwable t) { if (t instanceof Error) throw (Error) t; if (t instanceof RuntimeException) throw (RuntimeException) t; throw new RuntimeException(t); } } } @SupportedAnnotationTypes("lombok.*") public static class ClaimingProcessor extends AbstractProcessor { @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { return true; } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } } } lombok-1.16.18/src/launch/lombok/launch/Main.java000066400000000000000000000033431312655740700215150ustar00rootroot00000000000000/* * Copyright (C) 2014-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.launch; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; class Main { static ClassLoader createShadowClassLoader() { return new ShadowClassLoader(Main.class.getClassLoader(), "lombok", null, Arrays.asList(), Arrays.asList("lombok.patcher.Symbols")); } public static void main(String[] args) throws Throwable { ClassLoader cl = createShadowClassLoader(); Class mc = cl.loadClass("lombok.core.Main"); try { mc.getMethod("main", String[].class).invoke(null, new Object[] {args}); } catch (InvocationTargetException e) { throw e.getCause(); } } } lombok-1.16.18/src/launch/lombok/launch/ShadowClassLoader.java000066400000000000000000000451271312655740700242010ustar00rootroot00000000000000/* * Copyright (C) 2014-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.launch; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.WeakHashMap; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * The shadow classloader serves to completely hide almost all classes in a given jar file by using a different file ending. * * The shadow classloader also serves to link in a project as it is being developed (a 'bin' dir from an IDE for example). *

    * Classes loaded by the shadowloader use ".SCL.sclSuffix" in addition to ".class". In other words, most of the class files in a given jar end in this suffix, which * serves to hide them from any tool that isn't aware of the suffix (such as IDEs generating auto-complete dialogs, and javac's classpath in general). Only shadowloader can actually * load these classes. *

    * The shadowloader will pick up an alternate (priority) classpath, using normal class files, from the system property "shadow.override.sclSuffix". * This shadow classpath looks just like a normal java classpath; the path separator is applied (semi-colon on windows, colon elsewhere), and entries can consist of directories, * jar files, or directories ending in "/*" to pick up all jars inside it. *

    * Load order is as follows if at least one override is present: *

  • First, if the resource is found in one of the paths stated in the shadow classpath, find that. *
  • Next, ask the parent loader, which is passed during construction of the ShadowClassLoader. *
  • Notably, this jar's contents are always skipped! (The idea of the shadow classpath is that this jar only functions as a launcher, not as a source of your actual application). *
* * If no overrides are present, the load order is as follows: *
  • First, if the resource is found in our own jar (trying ".SCL.sclSuffix" first for any resource request ending in ".class"), return that. *
  • Next, ask the parent loader. * * * Use ShadowClassLoader to accomplish the following things:
      *
    • Avoid contaminating the namespace of any project using an SCL-based jar. Autocompleters in IDEs will NOT suggest anything other than actual public API. *
    • Like jarjar, allows folding in dependencies such as ASM without foisting these dependencies on projects that use this jar. shadowloader obviates the need for jarjar. *
    • Allows an agent (which MUST be in jar form) to still load everything except this loader infrastructure from class files generated by the IDE, which should * considerably help debugging, as you can now rely on the IDE's built-in auto-recompile features instead of having to run a full build everytime, and it should help * with hot code replace and the like (this is what the {@code shadow.override} feature is for). *
    * * Implementation note: {@code lombok.eclipse.agent.EclipseLoaderPatcher} relies on this class having no dependencies on any other class except the JVM boot class, notably * including any other classes in this package, including inner classes. So, don't write closures, anonymous inner class literals, * enums, or anything else that could cause the compilation of this file to produce more than 1 class file. In general, actually passing load control to this loader is a bit tricky * so ensure that this class has zero dependencies on anything except java core classes. */ class ShadowClassLoader extends ClassLoader { private static final String SELF_NAME = "lombok/launch/ShadowClassLoader.class"; private static final ConcurrentMap> highlanderMap = new ConcurrentHashMap>(); private final String SELF_BASE; private final File SELF_BASE_FILE; private final int SELF_BASE_LENGTH; private final List override = new ArrayList(); private final String sclSuffix; private final List parentExclusion = new ArrayList(); private final List highlanders = new ArrayList(); /** * @param source The 'parent' classloader. * @param sclSuffix The suffix of the shadowed class files in our own jar. For example, if this is {@code lombok}, then the class files in your jar should be {@code foo/Bar.SCL.lombok} and not {@code foo/Bar.class}. * @param selfBase The (preferably absolute) path to our own jar. This jar will be searched for class/SCL.sclSuffix files. * @param parentExclusion For example {@code "lombok."}; upon invocation of loadClass of this loader, the parent loader ({@code source}) will NOT be invoked if the class to be loaded begins with anything in the parent exclusion list. No exclusion is applied for getResource(s). * @param highlanders SCL will put in extra effort to ensure that these classes (in simple class spec, so {@code foo.bar.baz.ClassName}) are only loaded once as a class, even if many different classloaders try to load classes, such as equinox/OSGi. */ ShadowClassLoader(ClassLoader source, String sclSuffix, String selfBase, List parentExclusion, List highlanders) { super(source); this.sclSuffix = sclSuffix; if (parentExclusion != null) for (String pe : parentExclusion) { pe = pe.replace(".", "/"); if (!pe.endsWith("/")) pe = pe + "/"; this.parentExclusion.add(pe); } if (highlanders != null) for (String hl : highlanders) { this.highlanders.add(hl); } if (selfBase != null) { SELF_BASE = selfBase; SELF_BASE_LENGTH = selfBase.length(); } else { URL sclClassUrl = ShadowClassLoader.class.getResource("ShadowClassLoader.class"); String sclClassStr = sclClassUrl == null ? null : sclClassUrl.toString(); if (sclClassStr == null || !sclClassStr.endsWith(SELF_NAME)) { ClassLoader cl = ShadowClassLoader.class.getClassLoader(); throw new RuntimeException("ShadowLoader can't find itself. SCL loader type: " + (cl == null ? "*NULL*" : cl.getClass().toString())); } SELF_BASE_LENGTH = sclClassStr.length() - SELF_NAME.length(); String decoded; try { decoded = URLDecoder.decode(sclClassStr.substring(0, SELF_BASE_LENGTH), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new InternalError("UTF-8 not available"); } SELF_BASE = decoded; } if (SELF_BASE.startsWith("jar:file:") && SELF_BASE.endsWith("!/")) SELF_BASE_FILE = new File(SELF_BASE.substring(9, SELF_BASE.length() - 2)); else if (SELF_BASE.startsWith("file:")) SELF_BASE_FILE = new File(SELF_BASE.substring(5)); else SELF_BASE_FILE = new File(SELF_BASE); String scl = System.getProperty("shadow.override." + sclSuffix); if (scl != null && !scl.isEmpty()) { for (String part : scl.split("\\s*" + (File.pathSeparatorChar == ';' ? ";" : ":") + "\\s*")) { if (part.endsWith("/*") || part.endsWith(File.separator + "*")) { addOverrideJarDir(part.substring(0, part.length() - 2)); } else { addOverrideClasspathEntry(part); } } } } private final Map mapJarPathToTracker = new HashMap(); private static final Map mapTrackerToJarPath = new WeakHashMap(); private static final Map> mapTrackerToJarContents = new WeakHashMap>(); /** * This cache ensures that any given jar file is only opened once in order to determine the full contents of it. * We use 'trackers' to make sure that the bulk of the memory taken up by this cache (the list of strings representing the content of a jar file) * gets garbage collected if all ShadowClassLoaders that ever tried to request a listing of this jar file, are garbage collected. */ private Set getOrMakeJarListing(final String absolutePathToJar) { synchronized (mapTrackerToJarPath) { /* * 1) Check our private instance JarPath-to-Tracker Mappings: */ Object ourTracker = mapJarPathToTracker.get(absolutePathToJar); if (ourTracker != null) { /* * Yes, we are already tracking this Jar. Just return its contents... */ return mapTrackerToJarContents.get(ourTracker); } /* * 2) Not tracked by us as yet. Check statically whether others have tracked this JarPath: */ for (Entry entry : mapTrackerToJarPath.entrySet()) { if (entry.getValue().equals(absolutePathToJar)) { /* * Yes, 3rd party is tracking this jar. We must track too, then return its contents. */ Object otherTracker = entry.getKey(); mapJarPathToTracker.put(absolutePathToJar, otherTracker); return mapTrackerToJarContents.get(otherTracker); } } /* * 3) Not tracked by anyone so far. Build, publish, track & return Jar contents... */ Object newTracker = new Object(); Set jarMembers = getJarMemberSet(absolutePathToJar); mapTrackerToJarContents.put(newTracker, jarMembers); mapTrackerToJarPath.put(newTracker, absolutePathToJar); mapJarPathToTracker.put(absolutePathToJar, newTracker); return jarMembers; } } /** * Return a {@link Set} of members in the Jar identified by {@code absolutePathToJar}. * * @param absolutePathToJar Cache key * @return a Set with the Jar member-names */ private Set getJarMemberSet(String absolutePathToJar) { /* * Note: * Our implementation returns a HashSet. initialCapacity and loadFactor are carefully tweaked for speed and RAM optimization purposes. * * Benchmark: * The HashSet implementation is about 10% slower to build (only happens once) than the ArrayList. * The HashSet with shiftBits = 1 was about 33 times(!) faster than the ArrayList for retrievals. */ try { int shiftBits = 1; // (fast, but big) 0 <= shiftBits <= 5, say (slower & compact) JarFile jar = new JarFile(absolutePathToJar); /* * Find the first power of 2 >= JarSize (as calculated in HashSet constructor) */ int jarSizePower2 = Integer.highestOneBit(jar.size()); if (jarSizePower2 != jar.size()) jarSizePower2 <<= 1; if (jarSizePower2 == 0) jarSizePower2 = 1; Set jarMembers = new HashSet(jarSizePower2 >> shiftBits, 1 << shiftBits); try { Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (jarEntry.isDirectory()) continue; jarMembers.add(jarEntry.getName()); } } catch (Exception ignore) { // ignored; if the jar can't be read, treating it as if the jar contains no classes is just what we want. } finally { jar.close(); } return jarMembers; } catch (Exception newJarFileException) { return Collections.emptySet(); } } /** * Looks up {@code altName} in {@code location}, and if that isn't found, looks up {@code name}; {@code altName} can be null in which case it is skipped. */ private URL getResourceFromLocation(String name, String altName, File location) { if (location.isDirectory()) { try { if (altName != null) { File f = new File(location, altName); if (f.isFile() && f.canRead()) return f.toURI().toURL(); } File f = new File(location, name); if (f.isFile() && f.canRead()) return f.toURI().toURL(); return null; } catch (MalformedURLException e) { return null; } } if (!location.isFile() || !location.canRead()) return null; File absoluteFile; { try { absoluteFile = location.getCanonicalFile(); } catch (Exception e) { absoluteFile = location.getAbsoluteFile(); } } Set jarContents = getOrMakeJarListing(absoluteFile.getAbsolutePath()); String absoluteUri = absoluteFile.toURI().toString(); try { if (jarContents.contains(altName)) { return new URI("jar:" + absoluteUri + "!/" + altName).toURL(); } } catch (Exception ignore) { // intentional fallthrough } try { if (jarContents.contains(name)) { return new URI("jar:" + absoluteUri + "!/" + name).toURL(); } } catch(Exception ignore) { // intentional fallthrough } return null; } /** * Checks if the stated item is located inside the same classpath root as the jar that hosts ShadowClassLoader.class. {@code item} and {@code name} refer to the same thing. */ private boolean inOwnBase(URL item, String name) { if (item == null) return false; String itemString = item.toString(); return (itemString.length() == SELF_BASE_LENGTH + name.length()) && SELF_BASE.regionMatches(0, itemString, 0, SELF_BASE_LENGTH); } @Override public Enumeration getResources(String name) throws IOException { String altName = null; if (name.endsWith(".class")) altName = name.substring(0, name.length() - 6) + ".SCL." + sclSuffix; // Vector? Yes, we need one: // * We can NOT make inner classes here (this class is loaded with special voodoo magic in eclipse, as a one off, it's not a full loader. // * We need to return an enumeration. // * We can't make one on the fly. // * ArrayList can't make these. Vector vector = new Vector(); for (File ce : override) { URL url = getResourceFromLocation(name, altName, ce); if (url != null) vector.add(url); } if (override.isEmpty()) { URL fromSelf = getResourceFromLocation(name, altName, SELF_BASE_FILE); if (fromSelf != null) vector.add(fromSelf); } Enumeration sec = super.getResources(name); while (sec.hasMoreElements()) { URL item = sec.nextElement(); if (!inOwnBase(item, name)) vector.add(item); } if (altName != null) { Enumeration tern = super.getResources(altName); while (tern.hasMoreElements()) { URL item = tern.nextElement(); if (!inOwnBase(item, altName)) vector.add(item); } } return vector.elements(); } @Override public URL getResource(String name) { return getResource_(name, false); } private URL getResource_(String name, boolean noSuper) { String altName = null; if (name.endsWith(".class")) altName = name.substring(0, name.length() - 6) + ".SCL." + sclSuffix; for (File ce : override) { URL url = getResourceFromLocation(name, altName, ce); if (url != null) return url; } if (!override.isEmpty()) { if (noSuper) return null; if (altName != null) { try { URL res = getResourceSkippingSelf(altName); if (res != null) return res; } catch (IOException ignore) {} } try { return getResourceSkippingSelf(name); } catch (IOException e) { return null; } } URL url = getResourceFromLocation(name, altName, SELF_BASE_FILE); if (url != null) return url; if (altName != null) { URL res = super.getResource(altName); if (res != null && (!noSuper || inOwnBase(res, altName))) return res; } URL res = super.getResource(name); if (res != null && (!noSuper || inOwnBase(res, name))) return res; return null; } private boolean exclusionListMatch(String name) { for (String pe : parentExclusion) { if (name.startsWith(pe)) return true; } return false; } private URL getResourceSkippingSelf(String name) throws IOException { URL candidate = super.getResource(name); if (candidate == null) return null; if (!inOwnBase(candidate, name)) return candidate; Enumeration en = super.getResources(name); while (en.hasMoreElements()) { candidate = en.nextElement(); if (!inOwnBase(candidate, name)) return candidate; } return null; } @Override public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { { Class alreadyLoaded = findLoadedClass(name); if (alreadyLoaded != null) return alreadyLoaded; } if (highlanders.contains(name)) { Class c = highlanderMap.get(name); if (c != null) return c; } String fileNameOfClass = name.replace(".", "/") + ".class"; URL res = getResource_(fileNameOfClass, true); if (res == null) { if (!exclusionListMatch(fileNameOfClass)) return super.loadClass(name, resolve); throw new ClassNotFoundException(name); } byte[] b; int p = 0; try { InputStream in = res.openStream(); try { b = new byte[65536]; while (true) { int r = in.read(b, p, b.length - p); if (r == -1) break; p += r; if (p == b.length) { byte[] nb = new byte[b.length * 2]; System.arraycopy(b, 0, nb, 0, p); b = nb; } } } finally { in.close(); } } catch (IOException e) { throw new ClassNotFoundException("I/O exception reading class " + name, e); } Class c; try { c = defineClass(name, b, 0, p); } catch (LinkageError e) { if (highlanders.contains(name)) { Class alreadyDefined = highlanderMap.get(name); if (alreadyDefined != null) return alreadyDefined; } try { c = this.findLoadedClass(name); } catch (LinkageError e2) { throw e; } if (c == null) throw e; } if (highlanders.contains(name)) { Class alreadyDefined = highlanderMap.putIfAbsent(name, c); if (alreadyDefined != null) c = alreadyDefined; } if (resolve) resolveClass(c); return c; } public void addOverrideJarDir(String dir) { File f = new File(dir); for (File j : f.listFiles()) { if (j.getName().toLowerCase().endsWith(".jar") && j.canRead() && j.isFile()) override.add(j); } } public void addOverrideClasspathEntry(String entry) { override.add(new File(entry)); } } lombok-1.16.18/src/stubs/000077500000000000000000000000001312655740700151145ustar00rootroot00000000000000lombok-1.16.18/src/stubs/ABOUT000066400000000000000000000002131312655740700157050ustar00rootroot00000000000000These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. lombok-1.16.18/src/stubs/com/000077500000000000000000000000001312655740700156725ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/000077500000000000000000000000001312655740700164775ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/tools/000077500000000000000000000000001312655740700176375ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/tools/javac/000077500000000000000000000000001312655740700207235ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/tools/javac/file/000077500000000000000000000000001312655740700216425ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/tools/javac/file/BaseFileManager.java000066400000000000000000000004401312655740700254500ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.file; import javax.tools.JavaFileManager; public abstract class BaseFileManager implements JavaFileManager{} lombok-1.16.18/src/stubs/com/sun/tools/javac/file/BaseFileObject.java000066400000000000000000000005321312655740700253060ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.file; import javax.tools.JavaFileObject; public abstract class BaseFileObject implements JavaFileObject { protected BaseFileObject(JavacFileManager fileManager) {} } lombok-1.16.18/src/stubs/com/sun/tools/javac/file/JavacFileManager.java000066400000000000000000000003311312655740700256210ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.file; public class JavacFileManager {} lombok-1.16.18/src/stubs/com/sun/tools/javac/file/PathFileObject.java000066400000000000000000000006001312655740700253240ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.file; import java.nio.file.Path; import javax.tools.JavaFileObject; public abstract class PathFileObject implements JavaFileObject { protected PathFileObject(BaseFileManager fileManager, Path path) {} } lombok-1.16.18/src/stubs/com/sun/tools/javac/main/000077500000000000000000000000001312655740700216475ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/tools/javac/main/Option.java000066400000000000000000000003501312655740700237600ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.main; public enum Option { ; public String text; } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/000077500000000000000000000000001312655740700222175ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/DocCommentScanner.java000066400000000000000000000012601312655740700264230ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.parser; import java.nio.CharBuffer; public class DocCommentScanner extends Scanner { protected DocCommentScanner(Factory fac, CharBuffer buffer) { super(fac, buffer); } protected DocCommentScanner(Factory fac, char[] input, int inputLength) { super(fac, input, inputLength); } protected DocCommentScanner(ScannerFactory fac, CharBuffer buffer) { super(fac, buffer); } protected DocCommentScanner(ScannerFactory fac, char[] input, int inputLength) { super(fac, input, inputLength); } } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/EndPosParser.java000066400000000000000000000011221312655740700254230ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.parser; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; public class EndPosParser { public EndPosParser(Parser.Factory fac, Lexer S, boolean keepDocComments) { } public EndPosParser(ParserFactory fac, Lexer S, boolean keepDocComments, boolean keepLineMap) { } public JCCompilationUnit compilationUnit() { return null; } public JCCompilationUnit parseCompilationUnit() { return null; } } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/JavaTokenizer.java000066400000000000000000000007231312655740700256400ustar00rootroot00000000000000package com.sun.tools.javac.parser; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle; public class JavaTokenizer { protected UnicodeReader reader; protected JavaTokenizer(ScannerFactory fac, UnicodeReader reader) { } public com.sun.tools.javac.parser.Tokens.Token readToken() { return null; } protected Comment processComment(int pos, int endPos, CommentStyle style) { return null; } } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/JavacParser.java000066400000000000000000000004711312655740700252650ustar00rootroot00000000000000package com.sun.tools.javac.parser; import com.sun.tools.javac.tree.JCTree; public class JavacParser { protected JavacParser(ParserFactory fac, Lexer S, boolean keepDocComments, boolean keepLineMap, boolean keepEndPositions) { } public JCTree.JCCompilationUnit parseCompilationUnit() { return null; } } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/Lexer.java000066400000000000000000000003271312655740700241430ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.parser; public interface Lexer { } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/Parser.java000066400000000000000000000007661312655740700243270ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.parser; import com.sun.tools.javac.util.Context; public class Parser { public static class Factory { public static Context.Key parserFactoryKey; public Factory(Context context) { } public Parser newParser(Lexer S, boolean keepDocComments, boolean genEndPos) { return null; } } } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/ParserFactory.java000066400000000000000000000005571312655740700256550ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.parser; import com.sun.tools.javac.util.Context; public class ParserFactory { public static Context.Key parserFactoryKey; public ParserFactory(Context context) { } }lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/Scanner.java000066400000000000000000000025401312655740700244540ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.parser; import java.nio.CharBuffer; import com.sun.tools.javac.util.Context; public class Scanner implements Lexer { protected Scanner(Factory fac, CharBuffer buffer) { } protected Scanner(Factory fac, char[] input, int inputLength) { } protected Scanner(ScannerFactory fac, CharBuffer buffer) { } protected Scanner(ScannerFactory fac, char[] input, int inputLength) { } protected Scanner(ScannerFactory fac, JavaTokenizer tokenizer) { } public static class Factory { public static final Context.Key scannerFactoryKey = null; protected Factory(Context context) { } public Scanner newScanner(CharSequence input) { return null; } public Scanner newScanner(char[] input, int inputLength) { return null; } } public enum CommentStyle { LINE, BLOCK, JAVADOC, } protected void processComment(CommentStyle style) { } public int prevEndPos() { return -1; } public int endPos() { return -1; } public int pos() { return -1; } public char[] getRawCharacters(int beginIndex, int endIndex) { return null; } public void nextToken() { } public char[] getRawCharacters() { return new char[0]; } } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/ScannerFactory.java000066400000000000000000000012121312655740700257770ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.parser; import com.sun.tools.javac.util.Context; public class ScannerFactory { public static final Context.Key scannerFactoryKey = null; protected ScannerFactory(Context c) { } public static ScannerFactory instance(Context c) { return null; } public Scanner newScanner(CharSequence input, boolean keepDocComments) { return null; } public Scanner newScanner(char[] input, int inputLength, boolean keepDocComments) { return null; } } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/Tokens.java000066400000000000000000000004501312655740700243240ustar00rootroot00000000000000package com.sun.tools.javac.parser; public class Tokens { public static class Token { } public interface Comment { enum CommentStyle { LINE, BLOCK, JAVADOC, } String getText(); int getSourcePos(int index); CommentStyle getStyle(); boolean isDeprecated(); } } lombok-1.16.18/src/stubs/com/sun/tools/javac/parser/UnicodeReader.java000066400000000000000000000005431312655740700255750ustar00rootroot00000000000000package com.sun.tools.javac.parser; import java.nio.CharBuffer; public class UnicodeReader { protected int bp; protected UnicodeReader(ScannerFactory sf, char[] input, int inputLength) { } protected UnicodeReader(ScannerFactory sf, CharBuffer buffer) { } public char[] getRawCharacters(int beginIndex, int endIndex) { return null; } } lombok-1.16.18/src/stubs/com/sun/tools/javac/tree/000077500000000000000000000000001312655740700216625ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/tools/javac/tree/DocCommentTable.java000066400000000000000000000004161312655740700255260ustar00rootroot00000000000000package com.sun.tools.javac.tree; import com.sun.tools.javac.parser.Tokens.Comment; public interface DocCommentTable { boolean hasComment(JCTree tree); Comment getComment(JCTree tree); String getCommentText(JCTree tree); void putComment(JCTree tree, Comment c); } lombok-1.16.18/src/stubs/com/sun/tools/javac/util/000077500000000000000000000000001312655740700217005ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/tools/javac/util/BaseFileObject.java000066400000000000000000000004361312655740700253470ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.util; import javax.tools.JavaFileObject; public abstract class BaseFileObject implements JavaFileObject {} lombok-1.16.18/src/stubs/com/sun/tools/javadoc/000077500000000000000000000000001312655740700212465ustar00rootroot00000000000000lombok-1.16.18/src/stubs/com/sun/tools/javadoc/DocCommentScanner.java000066400000000000000000000013561312655740700254600ustar00rootroot00000000000000/* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javadoc; import java.nio.CharBuffer; import com.sun.tools.javac.parser.Scanner; import com.sun.tools.javac.util.Context; public class DocCommentScanner extends Scanner { protected DocCommentScanner(com.sun.tools.javadoc.DocCommentScanner.Factory fac, CharBuffer buffer) { super(fac, buffer); } protected DocCommentScanner(com.sun.tools.javadoc.DocCommentScanner.Factory fac, char[] input, int inputLength) { super(fac, input, inputLength); } public static class Factory extends Scanner.Factory { protected Factory(Context context) { super(context); } } } lombok-1.16.18/src/stubs/org/000077500000000000000000000000001312655740700157035ustar00rootroot00000000000000lombok-1.16.18/src/stubs/org/mapstruct/000077500000000000000000000000001312655740700177255ustar00rootroot00000000000000lombok-1.16.18/src/stubs/org/mapstruct/ap/000077500000000000000000000000001312655740700203255ustar00rootroot00000000000000lombok-1.16.18/src/stubs/org/mapstruct/ap/spi/000077500000000000000000000000001312655740700211205ustar00rootroot00000000000000lombok-1.16.18/src/stubs/org/mapstruct/ap/spi/AstModifyingAnnotationProcessor.java000066400000000000000000000041611312655740700303150ustar00rootroot00000000000000/** * Copyright 2012-2017 Gunnar Morling (http://www.gunnarmorling.de/) * and/or other contributors as indicated by the @authors tag. See the * copyright.txt file in the distribution for a full listing of all * contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mapstruct.ap.spi; import javax.lang.model.type.TypeMirror; /** * A contract to be implemented by other annotation processors which - against the design philosophy of JSR 269 - alter * the types under compilation. *

    * This contract will be queried by MapStruct when examining types referenced by mappers to be generated, most notably * the source and target types of mapping methods. If at least one AST-modifying processor announces further changes to * such type, the generation of the affected mapper(s) will be deferred to a future round in the annnotation processing * cycle. *

    * Implementations are discovered via the service loader, i.e. a JAR providing an AST-modifying processor needs to * declare its implementation in a file {@code META-INF/services/org.mapstruct.ap.spi.AstModifyingAnnotationProcessor}. * * @author Gunnar Morling */ //@org.mapstruct.util.Experimental public interface AstModifyingAnnotationProcessor { /** * Whether the specified type has been fully processed by this processor or not (i.e. this processor will amend the * given type's structure after this invocation). * * @param type The type of interest * @return {@code true} if this processor has fully processed the given type, {@code false} otherwise. */ boolean isTypeComplete(TypeMirror type); }lombok-1.16.18/src/stubsstubs/000077500000000000000000000000001312655740700161755ustar00rootroot00000000000000lombok-1.16.18/src/stubsstubs/com/000077500000000000000000000000001312655740700167535ustar00rootroot00000000000000lombok-1.16.18/src/stubsstubs/com/sun/000077500000000000000000000000001312655740700175605ustar00rootroot00000000000000lombok-1.16.18/src/stubsstubs/com/sun/tools/000077500000000000000000000000001312655740700207205ustar00rootroot00000000000000lombok-1.16.18/src/stubsstubs/com/sun/tools/javac/000077500000000000000000000000001312655740700220045ustar00rootroot00000000000000lombok-1.16.18/src/stubsstubs/com/sun/tools/javac/parser/000077500000000000000000000000001312655740700233005ustar00rootroot00000000000000lombok-1.16.18/src/stubsstubs/com/sun/tools/javac/parser/Parser.java000066400000000000000000000001351312655740700253760ustar00rootroot00000000000000package com.sun.tools.javac.parser; public class Parser { public static class Factory {} } lombok-1.16.18/src/stubsstubs/com/sun/tools/javac/tree/000077500000000000000000000000001312655740700227435ustar00rootroot00000000000000lombok-1.16.18/src/stubsstubs/com/sun/tools/javac/tree/JCTree.java000066400000000000000000000001641312655740700247230ustar00rootroot00000000000000package com.sun.tools.javac.tree; public class JCTree { public static class JCCompilationUnit extends JCTree {} } lombok-1.16.18/src/testAP/000077500000000000000000000000001312655740700151545ustar00rootroot00000000000000lombok-1.16.18/src/testAP/org/000077500000000000000000000000001312655740700157435ustar00rootroot00000000000000lombok-1.16.18/src/testAP/org/projectlombok/000077500000000000000000000000001312655740700206155ustar00rootroot00000000000000lombok-1.16.18/src/testAP/org/projectlombok/testAp/000077500000000000000000000000001312655740700220555ustar00rootroot00000000000000lombok-1.16.18/src/testAP/org/projectlombok/testAp/ExampleAnnotation.java000066400000000000000000000004501312655740700263450ustar00rootroot00000000000000package org.projectlombok.testAp; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) public @interface ExampleAnnotation {} lombok-1.16.18/src/testAP/org/projectlombok/testAp/TestAp.java000066400000000000000000000066201312655740700241240ustar00rootroot00000000000000/* * Copyright (C) 2016 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.projectlombok.testAp; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; @SupportedAnnotationTypes("org.projectlombok.testAp.ExampleAnnotation") public final class TestAp extends AbstractProcessor { private int roundCounter = 0; private static final long START = System.currentTimeMillis(); private void log(String txt) { System.out.printf("***[%3d]: %s\n", System.currentTimeMillis() - START, txt); } @Override public void init(ProcessingEnvironment processingEnv) { log("TestAP in init"); super.init(processingEnv); } @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { roundCounter++; log("TestAP in round " + roundCounter); boolean foundGetTest = false; int annotatedElemCount = 0; for (Element annotated : roundEnv.getElementsAnnotatedWith(ExampleAnnotation.class)) { annotatedElemCount++; for (Element child : annotated.getEnclosedElements()) { if (child.getSimpleName().toString().equals("getTest") && child.getKind() == ElementKind.METHOD) foundGetTest = true; if (child instanceof ExecutableElement) { TypeMirror returnType = ((ExecutableElement) child).getReturnType(); System.out.println("RETURN TYPE for " + child.getSimpleName() + ": " + returnType.getClass() + " -- " + returnType.toString()); } } } if (foundGetTest) log("RESULT: POSITIVE -- found the getTest method"); else if (annotatedElemCount > 0) log("RESULT: NEGATIVE -- found the example class but there's no getTest method in it according to the type mirror."); else log("RESULT: AMBIVALENT -- The example class is not provided by 'getElementsAnnotatedWith' in this round. Not an issue, unless previously you got a NEGATIVE result."); return false; } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } } lombok-1.16.18/src/useTestAP/000077500000000000000000000000001312655740700156315ustar00rootroot00000000000000lombok-1.16.18/src/useTestAP/UseTestAp.java000066400000000000000000000004421312655740700203510ustar00rootroot00000000000000@org.projectlombok.testAp.ExampleAnnotation //@lombok.experimental.Accessors(chain=true) public class UseTestAp { @lombok.Setter @lombok.Getter String test; public void confirmGetTestExists() { System.out.println(getTest()); } public UseTestAp returningSelf() { return this; } } lombok-1.16.18/src/utils/000077500000000000000000000000001312655740700151145ustar00rootroot00000000000000lombok-1.16.18/src/utils/lombok/000077500000000000000000000000001312655740700163775ustar00rootroot00000000000000lombok-1.16.18/src/utils/lombok/core/000077500000000000000000000000001312655740700173275ustar00rootroot00000000000000lombok-1.16.18/src/utils/lombok/core/FieldAugment.java000066400000000000000000000322331312655740700225410ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Map; import java.util.WeakHashMap; public abstract class FieldAugment { private static Object getDefaultValue(Class type) { if (type == boolean.class) return false; if (type == int.class) return 0; if (!type.isPrimitive()) return null; if (type == long.class) return 0L; if (type == short.class) return (short) 0; if (type == byte.class) return (byte) 0; if (type == char.class) return '\0'; if (type == float.class) return 0.0F; if (type == double.class) return 0.0D; // We can't get here unless java added some primitive types, but, hey. return null; } /** * (Virtually) adds a field to an existing type and returns an object that can be used to read and write this field. *

    * If the type already declares a non-final instance field with the given name and a compatible field type, that field will be used. * Otherwise the field will be provided virtually. *

    * WARNING: The values put into the augment should NOT reference in any way the object you've added the augment to, or memory leaks may occur. * If you do need to add such references, use {@link #circularSafeAugment(Class, Class, String, Object)} instead. *

    * This code assumes that for any combination of {@code type} and {@code name} this method is only called once. * Otherwise, whether state is shared is undefined. * * @param type to augment * @param fieldType type of the field * @param name of the field * @param defaultValue the value of the augment if it hasn't been set yet. * @throws NullPointerException if {@code type}, {@code fieldType} or {@code name} is {@code null} */ public static FieldAugment augment(Class type, Class fieldType, String name) { checkNotNull(type, "type"); checkNotNull(fieldType, "fieldType"); checkNotNull(name, "name"); @SuppressWarnings("unchecked") F defaultValue = (F) getDefaultValue(fieldType); FieldAugment ret = tryCreateReflectionAugment(type, fieldType, name, defaultValue); return ret != null ? ret : new MapFieldAugment(defaultValue); } /** * (Virtually) adds a field to an existing type and returns an object that can be used to read and write this field. *

    * This method does the same as {@link #augment(Class, Class, String, Object)}, except it is safe to set values that reference back to their containing object. */ public static FieldAugment circularSafeAugment(Class type, Class fieldType, String name) { checkNotNull(type, "type"); checkNotNull(fieldType, "fieldType"); checkNotNull(name, "name"); @SuppressWarnings("unchecked") F defaultValue = (F) getDefaultValue(fieldType); FieldAugment ret = tryCreateReflectionAugment(type, fieldType, name, defaultValue); return ret != null ? ret : new MapWeakFieldAugment(defaultValue); } /** * Creates a reflection-based augment which will directly access the listed field name. If this field does not exist or the field * is not capable of storing the requested type, {@code null} is returned instead. */ private static FieldAugment tryCreateReflectionAugment(Class type, Class fieldType, String name, F defaultValue) { Field f = findField(type, fieldType, name); if (f != null && typeIsAssignmentCompatible(f.getType(), fieldType)) return new ReflectionFieldAugment(f, fieldType, defaultValue); return null; } private static Field findField(Class type, Class wantedType, String name) { try { Field f = type.getDeclaredField(name); if (Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) return null; if (!typeIsAssignmentCompatible(f.getType(), wantedType)) return null; f.setAccessible(true); return f; } catch (Exception e) { return null; } } private static boolean typeIsAssignmentCompatible(Class fieldType, Class wantedType) { if (fieldType == java.lang.Object.class) return true; if (fieldType == wantedType) return true; if (fieldType.isPrimitive()) return fieldType == wantedType; if (wantedType == int.class && (fieldType == Number.class || fieldType == Integer.class)) return true; if (wantedType == long.class && (fieldType == Number.class || fieldType == Long.class)) return true; if (wantedType == short.class && (fieldType == Number.class || fieldType == Short.class)) return true; if (wantedType == byte.class && (fieldType == Number.class || fieldType == Byte.class)) return true; if (wantedType == char.class && (fieldType == Number.class || fieldType == Character.class)) return true; if (wantedType == float.class && (fieldType == Number.class || fieldType == Float.class)) return true; if (wantedType == double.class && (fieldType == Number.class || fieldType == Double.class)) return true; if (wantedType == boolean.class && fieldType == Boolean.class) return true; return fieldType.isAssignableFrom(wantedType); } private FieldAugment() { // prevent external instantiation } /** * @throws NullPointerException if {@code object} is {@code null} */ public abstract F get(T object); /** * @throws NullPointerException if {@code object} or {@code value} is {@code null} */ public final void set(T object, F value) { getAndSet(object, value); } /** * @return the value of the field before the operation. * @throws NullPointerException if {@code object} or {@code value} is {@code null}. */ public abstract F getAndSet(T object, F value); /** * @return the value of the field before the operation. * @throws NullPointerException if {@code object} is {@code null} */ public abstract F clear(T object); /** * @return the value of the field after the operation. If the value was equal to {@code expected} or already cleared {@code null}, otherwise the current value. * @throws NullPointerException if {@code object} or {@code expected} is {@code null} */ public abstract F compareAndClear(T object, F expected); /** * @return the value of the field after the operation. * @throws NullPointerException if {@code object} or {@code value} is {@code null} */ public abstract F setIfAbsent(T object, F value); /** * @return the value of the field after the operation. * @throws NullPointerException if {@code object}, {@code expected} or {@code value} is {@code null} */ public abstract F compareAndSet(T object, F expected, F value); private static class ReflectionFieldAugment extends FieldAugment { private final Object lock = new Object(); private final Field field; private final Class targetType; private final F defaultValue; @SuppressWarnings("unchecked") ReflectionFieldAugment(Field field, Class targetType, F defaultValue) { this.field = field; this.targetType = (Class) targetType; this.defaultValue = defaultValue; } @Override public F get(T object) { checkNotNull(object, "object"); try { F value; synchronized (lock) { value = targetType.cast(field.get(object)); } return value == null ? defaultValue : value; } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } @Override public F getAndSet(T object, F value) { checkNotNull(object, "object"); checkNotNull(value, "value"); try { F oldValue; synchronized (lock) { oldValue = targetType.cast(field.get(object)); field.set(object, value); } return oldValue == null ? defaultValue : oldValue; } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } @Override public F clear(T object) { checkNotNull(object, "object"); try { F oldValue; synchronized (lock) { oldValue = targetType.cast(field.get(object)); field.set(object, defaultValue); } return oldValue == null ? defaultValue : oldValue; } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } @Override public F compareAndClear(T object, F expected) { checkNotNull(object, "object"); checkNotNull(expected, "expected"); try { F oldValue; synchronized (lock) { oldValue = targetType.cast(field.get(object)); if (expected.equals(oldValue)) { field.set(object, defaultValue); return defaultValue; } } return oldValue; } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } @Override public F setIfAbsent(T object, F value) { checkNotNull(object, "object"); checkNotNull(value, "value"); try { synchronized (lock) { F oldValue = targetType.cast(field.get(object)); if (oldValue != null && !oldValue.equals(defaultValue)) return oldValue; field.set(object, value); return value; } } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } @Override public F compareAndSet(T object, F expected, F value) { checkNotNull(object, "object"); checkNotNull(expected, "expected"); checkNotNull(value, "value"); try { synchronized (lock) { F oldValue = targetType.cast(field.get(object)); if (!expected.equals(oldValue)) return oldValue == null ? defaultValue : oldValue; field.set(object, value); return value; } } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } } private static class MapFieldAugment extends FieldAugment { final Map values = new WeakHashMap(); final F defaultValue; MapFieldAugment(F defaultValue) { this.defaultValue = defaultValue; } @Override public F get(T object) { checkNotNull(object, "object"); synchronized (values) { return read(object); } } @Override public F getAndSet(T object, F value) { checkNotNull(object, "object"); checkNotNull(value, "value"); synchronized (values) { F result = read(object); write(object, value); return result; } } @Override public F clear(T object) { checkNotNull(object, "object"); synchronized (values) { F result = read(object); values.remove(object); return result; } } @Override public F compareAndClear(T object, F expected) { checkNotNull(object, "object"); checkNotNull(expected, "expected"); synchronized (values) { F result = read(object); if (result == null) { return null; } if (!expected.equals(result)) { return result; } values.remove(object); return null; } } @Override public F setIfAbsent(T object, F value) { checkNotNull(object, "object"); checkNotNull(value, "value"); synchronized (values) { F result = read(object); if (result != null) { return result; } write(object, value); return value; } } @Override public F compareAndSet(T object, F expected, F value) { checkNotNull(object, "object"); checkNotNull(expected, "expected"); checkNotNull(value, "value"); synchronized (values) { F result = read(object); if (!expected.equals(result)) { return result; } write(object, value); return value; } } @SuppressWarnings("unchecked") F read(T object) { F value = (F) values.get(object); return value == null ? defaultValue : value; } void write(T object, F value) { values.put(object, value); } } static class MapWeakFieldAugment extends MapFieldAugment { MapWeakFieldAugment(F defaultValue) { super(defaultValue); } @SuppressWarnings("unchecked") F read(T object) { WeakReference read = (WeakReference)values.get(object); if (read == null) return defaultValue; F result = read.get(); if (result == null) values.remove(object); return result == null ? defaultValue : result; } void write(T object, F value) { values.put(object, new WeakReference(value)); } } private static T checkNotNull(T object, String name) { if (object == null) throw new NullPointerException(name); return object; } } lombok-1.16.18/src/utils/lombok/core/JavaIdentifiers.java000066400000000000000000000045561312655740700232530ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; /** * Utility functions for validating potential java verifiers. */ public class JavaIdentifiers { private JavaIdentifiers() {} private static final LombokImmutableList KEYWORDS = LombokImmutableList.of( "public", "private", "protected", "default", "switch", "case", "for", "do", "goto", "const", "strictfp", "while", "if", "else", "byte", "short", "int", "long", "float", "double", "void", "boolean", "char", "null", "false", "true", "continue", "break", "return", "instanceof", "synchronized", "volatile", "transient", "final", "static", "interface", "class", "extends", "implements", "throws", "throw", "catch", "try", "finally", "abstract", "assert", "enum", "import", "package", "native", "new", "super", "this"); public static boolean isValidJavaIdentifier(String identifier) { if (identifier == null) return false; if (identifier.isEmpty()) return false; if (!Character.isJavaIdentifierStart(identifier.charAt(0))) return false; for (int i = 1; i < identifier.length(); i++) { if (!Character.isJavaIdentifierPart(identifier.charAt(i))) return false; } return !isKeyword(identifier); } public static boolean isKeyword(String keyword) { return KEYWORDS.contains(keyword); } } lombok-1.16.18/src/utils/lombok/core/LombokImmutableList.java000066400000000000000000000135161312655740700241170ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; public final class LombokImmutableList implements Iterable { private Object[] content; private static final LombokImmutableList EMPTY = new LombokImmutableList(new Object[0]); @SuppressWarnings("unchecked") public static LombokImmutableList of() { return (LombokImmutableList) EMPTY; } public static LombokImmutableList of(T a) { return new LombokImmutableList(new Object[] {a}); } public static LombokImmutableList of(T a, T b) { return new LombokImmutableList(new Object[] {a, b}); } public static LombokImmutableList of(T a, T b, T c) { return new LombokImmutableList(new Object[] {a, b, c}); } public static LombokImmutableList of(T a, T b, T c, T d) { return new LombokImmutableList(new Object[] {a, b, c, d}); } public static LombokImmutableList of(T a, T b, T c, T d, T e) { return new LombokImmutableList(new Object[] {a, b, c, d, e}); } public static LombokImmutableList of(T a, T b, T c, T d, T e, T f, T... g) { Object[] rest = g == null ? new Object[] {null} : g; Object[] val = new Object[rest.length + 6]; System.arraycopy(rest, 0, val, 6, rest.length); val[0] = a; val[1] = b; val[2] = c; val[3] = d; val[4] = e; val[5] = f; return new LombokImmutableList(val); } public static LombokImmutableList copyOf(Collection list) { return new LombokImmutableList(list.toArray()); } public static LombokImmutableList copyOf(Iterable iterable) { List list = new ArrayList(); for (T o : iterable) list.add(o); return copyOf(list); } public static LombokImmutableList copyOf(T[] array) { Object[] content = new Object[array.length]; System.arraycopy(array, 0, content, 0, array.length); return new LombokImmutableList(content); } private LombokImmutableList(Object[] content) { this.content = content; } public LombokImmutableList replaceElementAt(int idx, T newValue) { Object[] newContent = content.clone(); newContent[idx] = newValue; return new LombokImmutableList(newContent); } public LombokImmutableList append(T newValue) { int len = content.length; Object[] newContent = new Object[len + 1]; System.arraycopy(content, 0, newContent, 0, len); newContent[len] = newValue; return new LombokImmutableList(newContent); } public LombokImmutableList prepend(T newValue) { int len = content.length; Object[] newContent = new Object[len + 1]; System.arraycopy(content, 0, newContent, 1, len); newContent[0] = newValue; return new LombokImmutableList(newContent); } public int indexOf(T val) { int len = content.length; if (val == null) { for (int i = 0; i < len; i++) if (content[i] == null) return i; return -1; } for (int i = 0; i < len; i++) if (val.equals(content[i])) return i; return -1; } public LombokImmutableList removeElement(T val) { int idx = indexOf(val); return idx == -1 ? this : removeElementAt(idx); } public LombokImmutableList removeElementAt(int idx) { int len = content.length; Object[] newContent = new Object[len - 1]; if (idx > 0) System.arraycopy(content, 0, newContent, 0, idx); if (idx < len - 1) System.arraycopy(content, idx + 1, newContent, idx, len - idx - 1); return new LombokImmutableList(newContent); } public boolean isEmpty() { return content.length == 0; } public int size() { return content.length; } @SuppressWarnings("unchecked") public T get(int idx) { return (T) content[idx]; } public boolean contains(T in) { if (in == null) { for (Object e : content) if (e == null) return true; return false; } for (Object e : content) if (in.equals(e)) return true; return false; } public Iterator iterator() { return new Iterator() { private int idx = 0; @Override public boolean hasNext() { return idx < content.length; } @SuppressWarnings("unchecked") @Override public T next() { if (idx < content.length) return (T) content[idx++]; throw new NoSuchElementException(); } @Override public void remove() { throw new UnsupportedOperationException("List is immutable"); } }; } @Override public String toString() { return Arrays.toString(content); } @Override public boolean equals(Object obj) { if (!(obj instanceof LombokImmutableList)) return false; if (obj == this) return true; return Arrays.equals(content, ((LombokImmutableList) obj).content); } @Override public int hashCode() { return Arrays.hashCode(content); } } lombok-1.16.18/src/utils/lombok/core/SpiLoadUtil.java000066400000000000000000000153521312655740700223710ustar00rootroot00000000000000/* * Copyright (C) 2009-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * The java core libraries have a SPI discovery system, but it works only in Java 1.6 and up. For at least Eclipse, * lombok actually works in java 1.5, so we've rolled our own SPI discovery system. * * It is not API compatible with {@code ServiceLoader}. * * @see java.util.ServiceLoader */ public class SpiLoadUtil { private SpiLoadUtil() { //Prevent instantiation } /** * Method that conveniently turn the {@code Iterable}s returned by the other methods in this class to a * {@code List}. * * @see #findServices(Class) * @see #findServices(Class, ClassLoader) */ public static List readAllFromIterator(Iterable findServices) { List list = new ArrayList(); for (T t : findServices) list.add(t); return list; } /** * Returns an iterator of instances that, at least according to the spi discovery file, are implementations * of the stated class. * * Like ServiceLoader, each listed class is turned into an instance by calling the public no-args constructor. * * Convenience method that calls the more elaborate {@link #findServices(Class, ClassLoader)} method with * this {@link java.lang.Thread}'s context class loader as {@code ClassLoader}. * * @param target class to find implementations for. */ public static Iterable findServices(Class target) throws IOException { return findServices(target, Thread.currentThread().getContextClassLoader()); } /** * Returns an iterator of class objects that, at least according to the spi discovery file, are implementations * of the stated class. * * Like ServiceLoader, each listed class is turned into an instance by calling the public no-args constructor. * * @param target class to find implementations for. * @param loader The classloader object to use to both the spi discovery files, as well as the loader to use * to make the returned instances. */ public static Iterable findServices(final Class target, ClassLoader loader) throws IOException { if (loader == null) loader = ClassLoader.getSystemClassLoader(); Enumeration resources = loader.getResources("META-INF/services/" + target.getName()); final Set entries = new LinkedHashSet(); while (resources.hasMoreElements()) { URL url = resources.nextElement(); readServicesFromUrl(entries, url); } final Iterator names = entries.iterator(); final ClassLoader fLoader = loader; return new Iterable () { @Override public Iterator iterator() { return new Iterator() { @Override public boolean hasNext() { return names.hasNext(); } @Override public C next() { try { return target.cast(Class.forName(names.next(), true, fLoader).newInstance()); } catch (Exception e) { if (e instanceof RuntimeException) throw (RuntimeException)e; throw new RuntimeException(e); } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } private static void readServicesFromUrl(Collection list, URL url) throws IOException { InputStream in = url.openStream(); try { if (in == null) return; BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int idx = line.indexOf('#'); if (idx != -1) line = line.substring(0, idx); line = line.trim(); if (line.length() == 0) continue; list.add(line); } } finally { try { if (in != null) in.close(); } catch (Throwable ignore) {} } } /** * This method will find the @{code T} in {@code public class Foo extends BaseType}. * * It returns an annotation type because it is used exclusively to figure out which annotations are * being handled by {@link lombok.eclipse.EclipseAnnotationHandler} and {@link lombok.javac.JavacAnnotationHandler}. */ public static Class findAnnotationClass(Class c, Class base) { if (c == Object.class || c == null) return null; Class answer = null; answer = findAnnotationHelper(base, c.getGenericSuperclass()); if (answer != null) return answer; for (Type iface : c.getGenericInterfaces()) { answer = findAnnotationHelper(base, iface); if (answer != null) return answer; } Class potential = findAnnotationClass(c.getSuperclass(), base); if (potential != null) return potential; for (Class iface : c.getInterfaces()) { potential = findAnnotationClass(iface, base); if (potential != null) return potential; } return null; } @SuppressWarnings("unchecked") private static Class findAnnotationHelper(Class base, Type iface) { if (iface instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType)iface; if (!base.equals(p.getRawType())) return null; Type target = p.getActualTypeArguments()[0]; if (target instanceof Class) { if (Annotation.class.isAssignableFrom((Class) target)) { return (Class) target; } } throw new ClassCastException("Not an annotation type: " + target); } return null; } } lombok-1.16.18/src/utils/lombok/core/debug/000077500000000000000000000000001312655740700204155ustar00rootroot00000000000000lombok-1.16.18/src/utils/lombok/core/debug/FileLog.java000066400000000000000000000042111312655740700225770ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.debug; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; public class FileLog { private static FileOutputStream fos; public static void log(String message) { log(message, null); } public synchronized static void log(String message, Throwable t) { try { if (fos == null) { fos = new FileOutputStream(new File(System.getProperty("user.home"), "LOMBOK-DEBUG-OUT.txt")); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { fos.close(); } catch (Throwable ignore) {} } }); } fos.write(message.getBytes("UTF-8")); fos.write('\n'); if (t != null) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); fos.write(sw.toString().getBytes("UTF-8")); fos.write('\n'); } fos.flush(); } catch (IOException e) { throw new IllegalStateException("Internal lombok file-based debugging not possible", e); } } } lombok-1.16.18/src/utils/lombok/eclipse/000077500000000000000000000000001312655740700200235ustar00rootroot00000000000000lombok-1.16.18/src/utils/lombok/eclipse/Eclipse.java000066400000000000000000000222471312655740700222610ustar00rootroot00000000000000/* * Copyright (C) 2009-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.eclipse.jdt.internal.compiler.ast.Clinit; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.Literal; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.TryStatement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; public class Eclipse { private static final Annotation[] EMPTY_ANNOTATIONS_ARRAY = new Annotation[0]; /** * Eclipse's Parser class is instrumented to not attempt to fill in the body of any method or initializer * or field initialization if this flag is set. Set it on the flag field of * any method, field, or initializer you create! */ public static final int ECLIPSE_DO_NOT_TOUCH_FLAG = ASTNode.Bit24; private Eclipse() { //Prevent instantiation } /** * For 'speed' reasons, Eclipse works a lot with char arrays. I have my doubts this was a fruitful exercise, * but we need to deal with it. This turns [[java][lang][String]] into "java.lang.String". */ public static String toQualifiedName(char[][] typeName) { int len = typeName.length - 1; for (char[] c : typeName) len += c.length; StringBuilder sb = new StringBuilder(len); boolean first = true; for (char[] c : typeName) { sb.append(first ? "" : ".").append(c); first = false; } return sb.toString(); } public static char[][] fromQualifiedName(String typeName) { String[] split = typeName.split("\\."); char[][] result = new char[split.length][]; for (int i = 0; i < split.length; i++) { result[i] = split[i].toCharArray(); } return result; } public static long pos(ASTNode node) { return ((long) node.sourceStart << 32) | (node.sourceEnd & 0xFFFFFFFFL); } public static long[] poss(ASTNode node, int repeat) { long p = ((long) node.sourceStart << 32) | (node.sourceEnd & 0xFFFFFFFFL); long[] out = new long[repeat]; Arrays.fill(out, p); return out; } /** * Checks if an eclipse-style array-of-array-of-characters to represent a fully qualified name ('foo.bar.baz'), matches a plain * string containing the same fully qualified name with dots in the string. */ public static boolean nameEquals(char[][] typeName, String string) { int pos = 0, len = string.length(); for (int i = 0; i < typeName.length; i++) { char[] t = typeName[i]; if (i > 0) { if (pos == len) return false; if (string.charAt(pos++) != '.') return false; } for (int j = 0; j < t.length; j++) { if (pos == len) return false; if (string.charAt(pos++) != t[j]) return false; } } return true; } public static boolean hasClinit(TypeDeclaration parent) { if (parent.methods == null) return false; for (AbstractMethodDeclaration method : parent.methods) { if (method instanceof Clinit) return true; } return false; } /** * Searches the given field node for annotations and returns each one that matches the provided regular expression pattern. * * Only the simple name is checked - the package and any containing class are ignored. */ public static Annotation[] findAnnotations(FieldDeclaration field, Pattern namePattern) { List result = new ArrayList(); if (field.annotations == null) return EMPTY_ANNOTATIONS_ARRAY; for (Annotation annotation : field.annotations) { TypeReference typeRef = annotation.type; if (typeRef != null && typeRef.getTypeName() != null) { char[][] typeName = typeRef.getTypeName(); String suspect = new String(typeName[typeName.length - 1]); if (namePattern.matcher(suspect).matches()) { result.add(annotation); } } } return result.toArray(EMPTY_ANNOTATIONS_ARRAY); } /** Matches any of the 8 primitive names, such as {@code boolean}. */ private static final Pattern PRIMITIVE_TYPE_NAME_PATTERN = Pattern.compile( "^(boolean|byte|short|int|long|float|double|char)$"); /** * Checks if the given type reference represents a primitive type. */ public static boolean isPrimitive(TypeReference ref) { if (ref.dimensions() > 0) return false; return PRIMITIVE_TYPE_NAME_PATTERN.matcher(toQualifiedName(ref.getTypeName())).matches(); } /** * Returns the actual value of the given Literal or Literal-like node. */ public static Object calculateValue(Expression e) { if (e instanceof Literal) { ((Literal)e).computeConstant(); switch (e.constant.typeID()) { case TypeIds.T_int: return e.constant.intValue(); case TypeIds.T_byte: return e.constant.byteValue(); case TypeIds.T_short: return e.constant.shortValue(); case TypeIds.T_char: return e.constant.charValue(); case TypeIds.T_float: return e.constant.floatValue(); case TypeIds.T_double: return e.constant.doubleValue(); case TypeIds.T_boolean: return e.constant.booleanValue(); case TypeIds.T_long: return e.constant.longValue(); case TypeIds.T_JavaLangString: return e.constant.stringValue(); default: return null; } } else if (e instanceof ClassLiteralAccess) { return Eclipse.toQualifiedName(((ClassLiteralAccess)e).type.getTypeName()); } else if (e instanceof SingleNameReference) { return new String(((SingleNameReference)e).token); } else if (e instanceof QualifiedNameReference) { String qName = Eclipse.toQualifiedName(((QualifiedNameReference)e).tokens); int idx = qName.lastIndexOf('.'); return idx == -1 ? qName : qName.substring(idx+1); } return null; } private static long latestEcjCompilerVersionConstantCached = 0; public static long getLatestEcjCompilerVersionConstant() { if (latestEcjCompilerVersionConstantCached != 0) return latestEcjCompilerVersionConstantCached; int highestVersionSoFar = 0; for (Field f : ClassFileConstants.class.getDeclaredFields()) { try { if (f.getName().startsWith("JDK1_")) { int thisVersion = Integer.parseInt(f.getName().substring("JDK1_".length())); if (thisVersion > highestVersionSoFar) { highestVersionSoFar = thisVersion; latestEcjCompilerVersionConstantCached = (Long) f.get(null); } } } catch (Exception ignore) {} } if (highestVersionSoFar > 6 && !ecjSupportsJava7Features()) { latestEcjCompilerVersionConstantCached = ClassFileConstants.JDK1_6; } return latestEcjCompilerVersionConstantCached; } private static int ecjCompilerVersionCached = -1; public static int getEcjCompilerVersion() { if (ecjCompilerVersionCached >= 0) return ecjCompilerVersionCached; for (Field f : CompilerOptions.class.getDeclaredFields()) { try { if (f.getName().startsWith("VERSION_1_")) { ecjCompilerVersionCached = Math.max(ecjCompilerVersionCached, Integer.parseInt(f.getName().substring("VERSION_1_".length()))); } } catch (Exception ignore) {} } if (ecjCompilerVersionCached < 5) ecjCompilerVersionCached = 5; if (!ecjSupportsJava7Features()) ecjCompilerVersionCached = Math.min(6, ecjCompilerVersionCached); return ecjCompilerVersionCached; } /** * Certain ECJ versions that only go up to -source 6 report that they support -source 7 and even fail to error when -source 7 is applied. * We detect this and correctly say that no more than -source 6 is supported. (when this is the case, this method returns false). */ private static boolean ecjSupportsJava7Features() { try { TryStatement.class.getDeclaredField("resources"); return true; } catch (NoSuchFieldException e) { return false; } } } lombok-1.16.18/src/utils/lombok/javac/000077500000000000000000000000001312655740700174635ustar00rootroot00000000000000lombok-1.16.18/src/utils/lombok/javac/CommentCatcher.java000066400000000000000000000100501312655740700232160ustar00rootroot00000000000000/* * Copyright (C) 2011-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.List; import lombok.core.FieldAugment; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; public class CommentCatcher { private final JavaCompiler compiler; public static final FieldAugment> JCCompilationUnit_comments = FieldAugment.augment(JCCompilationUnit.class, List.class, "lombok$comments"); public static CommentCatcher create(Context context) { registerCommentsCollectingScannerFactory(context); JavaCompiler compiler = new JavaCompiler(context); setInCompiler(compiler, context); compiler.keepComments = true; compiler.genEndPos = true; return new CommentCatcher(compiler); } private CommentCatcher(JavaCompiler compiler) { this.compiler = compiler; } public JavaCompiler getCompiler() { return compiler; } public void setComments(JCCompilationUnit ast, List comments) { if (comments != null) { JCCompilationUnit_comments.set(ast, comments); } else { JCCompilationUnit_comments.clear(ast); } } public List getComments(JCCompilationUnit ast) { List list = JCCompilationUnit_comments.get(ast); return list == null ? Collections.emptyList() : list; } private static void registerCommentsCollectingScannerFactory(Context context) { try { Class scannerFactory; int javaCompilerVersion = Javac.getJavaCompilerVersion(); if (javaCompilerVersion <= 6) { scannerFactory = Class.forName("lombok.javac.java6.CommentCollectingScannerFactory"); } else if (javaCompilerVersion == 7) { scannerFactory = Class.forName("lombok.javac.java7.CommentCollectingScannerFactory"); } else { scannerFactory = Class.forName("lombok.javac.java8.CommentCollectingScannerFactory"); } scannerFactory.getMethod("preRegister", Context.class).invoke(null, context); } catch (InvocationTargetException e) { throw Javac.sneakyThrow(e.getCause()); } catch (Exception e) { throw Javac.sneakyThrow(e); } } private static void setInCompiler(JavaCompiler compiler, Context context) { try { Class parserFactory; int javaCompilerVersion = Javac.getJavaCompilerVersion(); if (javaCompilerVersion <= 6) { parserFactory = Class.forName("lombok.javac.java6.CommentCollectingParserFactory"); } else if (javaCompilerVersion == 7) { parserFactory = Class.forName("lombok.javac.java7.CommentCollectingParserFactory"); } else { parserFactory = Class.forName("lombok.javac.java8.CommentCollectingParserFactory"); } parserFactory.getMethod("setInCompiler", JavaCompiler.class, Context.class).invoke(null, compiler, context); } catch (InvocationTargetException e) { throw Javac.sneakyThrow(e.getCause()); } catch (Exception e) { throw Javac.sneakyThrow(e); } } } lombok-1.16.18/src/utils/lombok/javac/CommentInfo.java000066400000000000000000000053401312655740700225460ustar00rootroot00000000000000/* * Copyright (C) 2009-2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; public final class CommentInfo { public enum StartConnection { /* Comment's start immediately follows a newline. */ START_OF_LINE, /* Comment's start does not immediately follow a newline, but there is a newline between this * and the previous comment (or pos 0 if first comment). */ ON_NEXT_LINE, /* Comment's start immediately follows previous comment's end (or pos 0 if first comment). */ DIRECT_AFTER_PREVIOUS, /* Comment's start does not immediately follow previous comment's end, but there is no newline in * between this and previous comment (or pos 0 if first comment). */ AFTER_PREVIOUS } public enum EndConnection { /* Comment is followed immediately by another node (not whitespace, not newline). */ DIRECT_AFTER_COMMENT, /* Comment is followed by some non-newline whitespace then by another node. */ AFTER_COMMENT, /* Comment is followed by optionally some whitespace then a newline. */ ON_NEXT_LINE } public final int pos; public final int prevEndPos; public final String content; public final int endPos; public final StartConnection start; public final EndConnection end; public CommentInfo(int prevEndPos, int pos, int endPos, String content, StartConnection start, EndConnection end) { this.pos = pos; this.prevEndPos = prevEndPos; this.endPos = endPos; this.content = content; this.start = start; this.end = end; } public boolean isJavadoc() { return content.startsWith("/**") && content.length() > 4; } @Override public String toString() { return String.format("%d: %s (%s,%s)", pos, content, start, end); } } lombok-1.16.18/src/utils/lombok/javac/Javac.java000066400000000000000000000323021312655740700213520ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import static lombok.javac.JavacTreeMaker.TreeTag.treeTag; import static lombok.javac.JavacTreeMaker.TypeTag.typeTag; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.lang.model.type.NoType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeVisitor; import lombok.javac.JavacTreeMaker.TreeTag; import lombok.javac.JavacTreeMaker.TypeTag; import com.sun.tools.javac.code.Source; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; /** * Container for static utility methods relevant to lombok's operation on javac. */ public class Javac { private Javac() { // prevent instantiation } /** Matches any of the 8 primitive names, such as {@code boolean}. */ private static final Pattern PRIMITIVE_TYPE_NAME_PATTERN = Pattern.compile("^(boolean|byte|short|int|long|float|double|char)$"); private static final Pattern VERSION_PARSER = Pattern.compile("^(\\d{1,6})\\.(\\d{1,6}).*$"); private static final Pattern SOURCE_PARSER = Pattern.compile("^JDK(\\d{1,6})_(\\d{1,6}).*$"); private static final AtomicInteger compilerVersion = new AtomicInteger(-1); /** * Returns the version of this java compiler, i.e. the JDK that it shipped in. For example, for javac v1.7, this returns {@code 7}. */ public static int getJavaCompilerVersion() { int cv = compilerVersion.get(); if (cv != -1) return cv; /* Main algorithm: Use JavaCompiler's intended method to do this */ { Matcher m = VERSION_PARSER.matcher(JavaCompiler.version()); if (m.matches()) { int major = Integer.parseInt(m.group(1)); int minor = Integer.parseInt(m.group(2)); if (major == 1) { compilerVersion.set(minor); return minor; } } } /* Fallback algorithm one: Check Source's values. Lets hope oracle never releases a javac that recognizes future versions for -source */ { String name = Source.values()[Source.values().length - 1].name(); Matcher m = SOURCE_PARSER.matcher(name); if (m.matches()) { int major = Integer.parseInt(m.group(1)); int minor = Integer.parseInt(m.group(2)); if (major == 1) { compilerVersion.set(minor); return minor; } } } compilerVersion.set(6); return 6; } private static final Class DOCCOMMENTTABLE_CLASS; static { Class c = null; try { c = Class.forName("com.sun.tools.javac.tree.DocCommentTable"); } catch (Throwable ignore) {} DOCCOMMENTTABLE_CLASS = c; } public static boolean instanceOfDocCommentTable(Object o) { return DOCCOMMENTTABLE_CLASS != null && DOCCOMMENTTABLE_CLASS.isInstance(o); } /** * Checks if the given expression (that really ought to refer to a type * expression) represents a primitive type. */ public static boolean isPrimitive(JCExpression ref) { String typeName = ref.toString(); return PRIMITIVE_TYPE_NAME_PATTERN.matcher(typeName).matches(); } /** * Turns an expression into a guessed intended literal. Only works for * literals, as you can imagine. * * Will for example turn a TrueLiteral into 'Boolean.valueOf(true)'. */ public static Object calculateGuess(JCExpression expr) { if (expr instanceof JCLiteral) { JCLiteral lit = (JCLiteral) expr; if (lit.getKind() == com.sun.source.tree.Tree.Kind.BOOLEAN_LITERAL) { return ((Number) lit.value).intValue() == 0 ? false : true; } return lit.value; } else if (expr instanceof JCIdent || expr instanceof JCFieldAccess) { String x = expr.toString(); if (x.endsWith(".class")) x = x.substring(0, x.length() - 6); else { int idx = x.lastIndexOf('.'); if (idx > -1) x = x.substring(idx + 1); } return x; } else return null; } public static final TypeTag CTC_BOOLEAN = typeTag("BOOLEAN"); public static final TypeTag CTC_INT = typeTag("INT"); public static final TypeTag CTC_DOUBLE = typeTag("DOUBLE"); public static final TypeTag CTC_FLOAT = typeTag("FLOAT"); public static final TypeTag CTC_SHORT = typeTag("SHORT"); public static final TypeTag CTC_BYTE = typeTag("BYTE"); public static final TypeTag CTC_LONG = typeTag("LONG"); public static final TypeTag CTC_CHAR = typeTag("CHAR"); public static final TypeTag CTC_VOID = typeTag("VOID"); public static final TypeTag CTC_NONE = typeTag("NONE"); public static final TypeTag CTC_BOT = typeTag("BOT"); public static final TypeTag CTC_ERROR = typeTag("ERROR"); public static final TypeTag CTC_UNKNOWN = typeTag("UNKNOWN"); public static final TypeTag CTC_UNDETVAR = typeTag("UNDETVAR"); public static final TypeTag CTC_CLASS = typeTag("CLASS"); public static final TreeTag CTC_NOT_EQUAL = treeTag("NE"); public static final TreeTag CTC_LESS_THAN = treeTag("LT"); public static final TreeTag CTC_GREATER_THAN = treeTag("GT"); public static final TreeTag CTC_LESS_OR_EQUAL= treeTag("LE"); public static final TreeTag CTC_GREATER_OR_EQUAL = treeTag("GE"); public static final TreeTag CTC_POS = treeTag("POS"); public static final TreeTag CTC_NEG = treeTag("NEG"); public static final TreeTag CTC_NOT = treeTag("NOT"); public static final TreeTag CTC_COMPL = treeTag("COMPL"); public static final TreeTag CTC_BITXOR = treeTag("BITXOR"); public static final TreeTag CTC_UNSIGNED_SHIFT_RIGHT = treeTag("USR"); public static final TreeTag CTC_MUL = treeTag("MUL"); public static final TreeTag CTC_DIV = treeTag("DIV"); public static final TreeTag CTC_PLUS = treeTag("PLUS"); public static final TreeTag CTC_MINUS = treeTag("MINUS"); public static final TreeTag CTC_EQUAL = treeTag("EQ"); public static final TreeTag CTC_PREINC = treeTag("PREINC"); public static final TreeTag CTC_PREDEC = treeTag("PREDEC"); public static final TreeTag CTC_POSTINC = treeTag("POSTINC"); public static final TreeTag CTC_POSTDEC = treeTag("POSTDEC"); private static final Method getExtendsClause, getEndPosition, storeEnd; static { getExtendsClause = getMethod(JCClassDecl.class, "getExtendsClause", new Class[0]); getExtendsClause.setAccessible(true); if (getJavaCompilerVersion() < 8) { getEndPosition = getMethod(DiagnosticPosition.class, "getEndPosition", java.util.Map.class); storeEnd = getMethod(java.util.Map.class, "put", Object.class, Object.class); } else { getEndPosition = getMethod(DiagnosticPosition.class, "getEndPosition", "com.sun.tools.javac.tree.EndPosTable"); Method storeEndMethodTemp; Class endPosTable; try { endPosTable = Class.forName("com.sun.tools.javac.tree.EndPosTable"); } catch (ClassNotFoundException ex) { throw sneakyThrow(ex); } try { storeEndMethodTemp = endPosTable.getMethod("storeEnd", JCTree.class, int.class); } catch (NoSuchMethodException e) { try { endPosTable = Class.forName("com.sun.tools.javac.parser.JavacParser$AbstractEndPosTable"); storeEndMethodTemp = endPosTable.getDeclaredMethod("storeEnd", JCTree.class, int.class); } catch (NoSuchMethodException ex) { throw sneakyThrow(ex); } catch (ClassNotFoundException ex) { throw sneakyThrow(ex); } } storeEnd = storeEndMethodTemp; } getEndPosition.setAccessible(true); storeEnd.setAccessible(true); } private static Method getMethod(Class clazz, String name, Class... paramTypes) { try { return clazz.getMethod(name, paramTypes); } catch (NoSuchMethodException e) { throw sneakyThrow(e); } } private static Method getMethod(Class clazz, String name, String... paramTypes) { try { Class[] c = new Class[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) c[i] = Class.forName(paramTypes[i]); return clazz.getMethod(name, c); } catch (NoSuchMethodException e) { throw sneakyThrow(e); } catch (ClassNotFoundException e) { throw sneakyThrow(e); } } public static JCTree getExtendsClause(JCClassDecl decl) { try { return (JCTree) getExtendsClause.invoke(decl); } catch (IllegalAccessException e) { throw sneakyThrow(e); } catch (InvocationTargetException e) { throw sneakyThrow(e.getCause()); } } public static Object getDocComments(JCCompilationUnit cu) { try { return JCCOMPILATIONUNIT_DOCCOMMENTS.get(cu); } catch (IllegalAccessException e) { throw sneakyThrow(e); } } public static void initDocComments(JCCompilationUnit cu) { try { JCCOMPILATIONUNIT_DOCCOMMENTS.set(cu, new HashMap()); } catch (IllegalArgumentException e) { // That's fine - we're on JDK8, we'll fix that later. } catch (IllegalAccessException e) { throw sneakyThrow(e); } } public static int getEndPosition(DiagnosticPosition pos, JCCompilationUnit top) { try { Object endPositions = JCCOMPILATIONUNIT_ENDPOSITIONS.get(top); return (Integer) getEndPosition.invoke(pos, endPositions); } catch (IllegalAccessException e) { throw sneakyThrow(e); } catch (InvocationTargetException e) { throw sneakyThrow(e.getCause()); } } public static void storeEnd(JCTree tree, int pos, JCCompilationUnit top) { try { Object endPositions = JCCOMPILATIONUNIT_ENDPOSITIONS.get(top); storeEnd.invoke(endPositions, tree, pos); } catch (IllegalAccessException e) { throw sneakyThrow(e); } catch (InvocationTargetException e) { throw sneakyThrow(e.getCause()); } } private static final Class JC_VOID_TYPE, JC_NO_TYPE; static { Class c = null; try { c = Class.forName("com.sun.tools.javac.code.Type$JCVoidType"); } catch (Throwable ignore) {} JC_VOID_TYPE = c; c = null; try { c = Class.forName("com.sun.tools.javac.code.Type$JCNoType"); } catch (Throwable ignore) {} JC_NO_TYPE = c; } private static final Field symtabVoidType = getFieldIfExists(Symtab.class, "voidType"); private static Field getFieldIfExists(Class c, String fieldName) { try { return c.getField("voidType"); } catch (Exception e) { return null; } } public static Type createVoidType(Symtab symbolTable, TypeTag tag) { if (symtabVoidType != null) try { return (Type) symtabVoidType.get(symbolTable); } catch (IllegalAccessException ignore) {} if (Javac.getJavaCompilerVersion() < 8) { return new JCNoType(((Integer) tag.value).intValue()); } else { try { if (CTC_VOID.equals(tag)) { return (Type) JC_VOID_TYPE.newInstance(); } else { return (Type) JC_NO_TYPE.newInstance(); } } catch (IllegalAccessException e) { throw sneakyThrow(e); } catch (InstantiationException e) { throw sneakyThrow(e); } } } private static class JCNoType extends Type implements NoType { public JCNoType(int tag) { super(tag, null); } @Override public TypeKind getKind() { if (tag == ((Integer) CTC_VOID.value).intValue()) return TypeKind.VOID; if (tag == ((Integer) CTC_NONE.value).intValue()) return TypeKind.NONE; throw new AssertionError("Unexpected tag: " + tag); } @Override public R accept(TypeVisitor v, P p) { return v.visitNoType(this, p); } } private static final Field JCCOMPILATIONUNIT_ENDPOSITIONS, JCCOMPILATIONUNIT_DOCCOMMENTS; static { Field f = null; try { f = JCCompilationUnit.class.getDeclaredField("endPositions"); } catch (NoSuchFieldException e) {} JCCOMPILATIONUNIT_ENDPOSITIONS = f; f = null; try { f = JCCompilationUnit.class.getDeclaredField("docComments"); } catch (NoSuchFieldException e) {} JCCOMPILATIONUNIT_DOCCOMMENTS = f; } static RuntimeException sneakyThrow(Throwable t) { if (t == null) throw new NullPointerException("t"); Javac.sneakyThrow0(t); return null; } @SuppressWarnings("unchecked") private static void sneakyThrow0(Throwable t) throws T { throw (T)t; } } lombok-1.16.18/src/utils/lombok/javac/JavacTreeMaker.java000066400000000000000000000766271312655740700231740ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayAccess; import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; import com.sun.tools.javac.tree.JCTree.JCAssert; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCAssignOp; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCBreak; import com.sun.tools.javac.tree.JCTree.JCCase; import com.sun.tools.javac.tree.JCTree.JCCatch; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCConditional; import com.sun.tools.javac.tree.JCTree.JCContinue; import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop; import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop; import com.sun.tools.javac.tree.JCTree.JCErroneous; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCForLoop; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCIf; import com.sun.tools.javac.tree.JCTree.JCImport; import com.sun.tools.javac.tree.JCTree.JCInstanceOf; import com.sun.tools.javac.tree.JCTree.JCLabeledStatement; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCNewClass; import com.sun.tools.javac.tree.JCTree.JCParens; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCReturn; import com.sun.tools.javac.tree.JCTree.JCSkip; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCSwitch; import com.sun.tools.javac.tree.JCTree.JCSynchronized; import com.sun.tools.javac.tree.JCTree.JCThrow; import com.sun.tools.javac.tree.JCTree.JCTry; import com.sun.tools.javac.tree.JCTree.JCTypeApply; import com.sun.tools.javac.tree.JCTree.JCTypeCast; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCUnary; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWhileLoop; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.tree.JCTree.LetExpr; import com.sun.tools.javac.tree.JCTree.TypeBoundKind; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Name; public class JavacTreeMaker { private final TreeMaker tm; public JavacTreeMaker(TreeMaker tm) { this.tm = tm; } public TreeMaker getUnderlyingTreeMaker() { return tm; } public JavacTreeMaker at(int pos) { tm.at(pos); return this; } private static class MethodId { private final Class owner; private final String name; private final Class returnType; private final Class[] paramTypes; MethodId(Class owner, String name, Class returnType, Class... types) { this.owner = owner; this.name = name; this.paramTypes = types; this.returnType = returnType; } @Override public String toString() { StringBuilder out = new StringBuilder(); out.append(returnType.getName()).append(" ").append(owner.getName()).append(".").append(name).append("("); boolean f = true; for (Class p : paramTypes) { if (f) f = false; else out.append(", "); out.append(p.getName()); } return out.append(")").toString(); } } private static class SchroedingerType { final Object value; private SchroedingerType(Object value) { this.value = value; } @Override public int hashCode() { return value == null ? -1 : value.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof SchroedingerType) { Object other = ((SchroedingerType) obj).value; return value == null ? other == null : value.equals(other); } return false; } static Object getFieldCached(ConcurrentMap cache, String className, String fieldName) { Object value = cache.get(fieldName); if (value != null) return value; try { value = Class.forName(className).getField(fieldName).get(null); } catch (NoSuchFieldException e) { throw Javac.sneakyThrow(e); } catch (IllegalAccessException e) { throw Javac.sneakyThrow(e); } catch (ClassNotFoundException e) { throw Javac.sneakyThrow(e); } cache.putIfAbsent(fieldName, value); return value; } private static Field NOSUCHFIELDEX_MARKER; static { try { NOSUCHFIELDEX_MARKER = SchroedingerType.class.getDeclaredField("NOSUCHFIELDEX_MARKER"); } catch (NoSuchFieldException e) { throw Javac.sneakyThrow(e); } } static Object getFieldCached(ConcurrentMap, Field> cache, Object ref, String fieldName) throws NoSuchFieldException { Class c = ref.getClass(); Field field = cache.get(c); if (field == null) { try { field = c.getField(fieldName); } catch (NoSuchFieldException e) { cache.putIfAbsent(c, NOSUCHFIELDEX_MARKER); throw Javac.sneakyThrow(e); } field.setAccessible(true); Field old = cache.putIfAbsent(c, field); if (old != null) field = old; } if (field == NOSUCHFIELDEX_MARKER) throw new NoSuchFieldException(fieldName); try { return field.get(ref); } catch (IllegalAccessException e) { throw Javac.sneakyThrow(e); } } } public static class TypeTag extends SchroedingerType { private static final ConcurrentMap TYPE_TAG_CACHE = new ConcurrentHashMap(); private static final ConcurrentMap, Field> FIELD_CACHE = new ConcurrentHashMap, Field>(); private static final Method TYPE_TYPETAG_METHOD; static { Method m = null; try { m = Type.class.getDeclaredMethod("getTag"); m.setAccessible(true); } catch (NoSuchMethodException e) {} TYPE_TYPETAG_METHOD = m; } private TypeTag(Object value) { super(value); } public static TypeTag typeTag(JCTree o) { try { return new TypeTag(getFieldCached(FIELD_CACHE, o, "typetag")); } catch (NoSuchFieldException e) { throw Javac.sneakyThrow(e); } } public static TypeTag typeTag(Type t) { try { return new TypeTag(getFieldCached(FIELD_CACHE, t, "tag")); } catch (NoSuchFieldException e) { if (TYPE_TYPETAG_METHOD == null) throw new IllegalStateException("Type " + t.getClass() + " has neither 'tag' nor getTag()"); try { return new TypeTag(TYPE_TYPETAG_METHOD.invoke(t)); } catch (IllegalAccessException ex) { throw Javac.sneakyThrow(ex); } catch (InvocationTargetException ex) { throw Javac.sneakyThrow(ex.getCause()); } } } public static TypeTag typeTag(String identifier) { return new TypeTag(getFieldCached(TYPE_TAG_CACHE, Javac.getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.code.TypeTags" : "com.sun.tools.javac.code.TypeTag", identifier)); } } public static class TreeTag extends SchroedingerType { private static final ConcurrentMap TREE_TAG_CACHE = new ConcurrentHashMap(); private static final Field TAG_FIELD; private static final Method TAG_METHOD; private static final MethodId OP_PREC = MethodId(TreeInfo.class, "opPrec", int.class, TreeTag.class); static { Method m = null; try { m = JCTree.class.getDeclaredMethod("getTag"); m.setAccessible(true); } catch (NoSuchMethodException e) {} if (m != null) { TAG_FIELD = null; TAG_METHOD = m; } else { Field f = null; try { f = JCTree.class.getDeclaredField("tag"); f.setAccessible(true); } catch (NoSuchFieldException e) {} TAG_FIELD = f; TAG_METHOD = null; } } private TreeTag(Object value) { super(value); } public static TreeTag treeTag(JCTree o) { try { if (TAG_METHOD != null) return new TreeTag(TAG_METHOD.invoke(o)); else return new TreeTag(TAG_FIELD.get(o)); } catch (InvocationTargetException e) { throw Javac.sneakyThrow(e.getCause()); } catch (IllegalAccessException e) { throw Javac.sneakyThrow(e); } } public static TreeTag treeTag(String identifier) { return new TreeTag(getFieldCached(TREE_TAG_CACHE, Javac.getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.tree.JCTree" : "com.sun.tools.javac.tree.JCTree$Tag", identifier)); } public int getOperatorPrecedenceLevel() { return invokeAny(null, OP_PREC, value); } public boolean isPrefixUnaryOp() { return Javac.CTC_NEG.equals(this) || Javac.CTC_POS.equals(this) || Javac.CTC_NOT.equals(this) || Javac.CTC_COMPL.equals(this) || Javac.CTC_PREDEC.equals(this) || Javac.CTC_PREINC.equals(this); } } static MethodId MethodId(Class owner, String name, Class returnType, Class... types) { return new MethodId(owner, name, returnType, types); } /** * Creates a new method ID based on the name of the method to invoke, the return type of that method, and the types of the parameters. * * A method matches if the return type matches, and for each parameter the following holds: * * Either (A) the type listed here is the same as, or a subtype of, the type of the method in javac's TreeMaker, or * (B) the type listed here is a subtype of SchroedingerType. */ static MethodId MethodId(String name, Class returnType, Class... types) { return new MethodId(TreeMaker.class, name, returnType, types); } /** * Creates a new method ID based on the name of a method in this class, assuming the name of the method to invoke in TreeMaker has the same name, * the same return type, and the same parameters (under the same rules as the other MethodId method). */ static MethodId MethodId(String name) { for (Method m : JavacTreeMaker.class.getDeclaredMethods()) { if (m.getName().equals(name)) { @SuppressWarnings("unchecked") Class r = (Class) m.getReturnType(); Class[] p = m.getParameterTypes(); return new MethodId(TreeMaker.class, name, r, p); } } throw new InternalError("Not found: " + name); } private static final ConcurrentHashMap, Method> METHOD_CACHE = new ConcurrentHashMap, Method>(); private J invoke(MethodId m, Object... args) { return invokeAny(tm, m, args); } @SuppressWarnings("unchecked") private static J invokeAny(Object owner, MethodId m, Object... args) { Method method = METHOD_CACHE.get(m); if (method == null) method = addToCache(m); try { if (m.returnType.isPrimitive()) { Object res = method.invoke(owner, args); String sn = res.getClass().getSimpleName().toLowerCase(); if (!sn.startsWith(m.returnType.getSimpleName())) throw new ClassCastException(res.getClass() + " to " + m.returnType); return (J) res; } return m.returnType.cast(method.invoke(owner, args)); } catch (InvocationTargetException e) { throw Javac.sneakyThrow(e.getCause()); } catch (IllegalAccessException e) { throw Javac.sneakyThrow(e); } catch (IllegalArgumentException e) { System.err.println(method); throw Javac.sneakyThrow(e); } } private static Method addToCache(MethodId m) { Method found = null; outer: for (Method method : m.owner.getDeclaredMethods()) { if (!m.name.equals(method.getName())) continue; Class[] t = method.getParameterTypes(); if (t.length != m.paramTypes.length) continue; for (int i = 0; i < t.length; i++) { if (Symbol.class.isAssignableFrom(t[i])) continue outer; if (!SchroedingerType.class.isAssignableFrom(m.paramTypes[i])) { if (t[i].isPrimitive()) { if (t[i] != m.paramTypes[i]) continue outer; } else { if (!t[i].isAssignableFrom(m.paramTypes[i])) continue outer; } } } if (found == null) found = method; else throw new IllegalStateException("Lombok TreeMaker frontend issue: multiple matches when looking for method: " + m); } if (found == null) throw new IllegalStateException("Lombok TreeMaker frontend issue: no match when looking for method: " + m); found.setAccessible(true); Object marker = METHOD_CACHE.putIfAbsent(m, found); if (marker == null) return found; return METHOD_CACHE.get(m); } //javac versions: 6-8 private static final MethodId TopLevel = MethodId("TopLevel"); public JCCompilationUnit TopLevel(List packageAnnotations, JCExpression pid, List defs) { return invoke(TopLevel, packageAnnotations, pid, defs); } //javac versions: 6-8 private static final MethodId Import = MethodId("Import"); public JCImport Import(JCTree qualid, boolean staticImport) { return invoke(Import, qualid, staticImport); } //javac versions: 6-8 private static final MethodId ClassDef = MethodId("ClassDef"); public JCClassDecl ClassDef(JCModifiers mods, Name name, List typarams, JCExpression extending, List implementing, List defs) { return invoke(ClassDef, mods, name, typarams, extending, implementing, defs); } //javac versions: 6-8 private static final MethodId MethodDef = MethodId("MethodDef", JCMethodDecl.class, JCModifiers.class, Name.class, JCExpression.class, List.class, List.class, List.class, JCBlock.class, JCExpression.class); public JCMethodDecl MethodDef(JCModifiers mods, Name name, JCExpression resType, List typarams, List params, List thrown, JCBlock body, JCExpression defaultValue) { return invoke(MethodDef, mods, name, resType, typarams, params, thrown, body, defaultValue); } //javac versions: 8 private static final MethodId MethodDefWithRecvParam = MethodId("MethodDef", JCMethodDecl.class, JCModifiers.class, Name.class, JCExpression.class, List.class, JCVariableDecl.class, List.class, List.class, JCBlock.class, JCExpression.class); public JCMethodDecl MethodDef(JCModifiers mods, Name name, JCExpression resType, List typarams, JCVariableDecl recvparam, List params, List thrown, JCBlock body, JCExpression defaultValue) { return invoke(MethodDefWithRecvParam, mods, name, resType, recvparam, typarams, params, thrown, body, defaultValue); } //javac versions: 6-8 private static final MethodId VarDef = MethodId("VarDef"); public JCVariableDecl VarDef(JCModifiers mods, Name name, JCExpression vartype, JCExpression init) { return invoke(VarDef, mods, name, vartype, init); } //javac versions: 8 private static final MethodId ReceiverVarDef = MethodId("ReceiverVarDef"); public JCVariableDecl ReceiverVarDef(JCModifiers mods, JCExpression name, JCExpression vartype) { return invoke(ReceiverVarDef, mods, name, vartype); } //javac versions: 6-8 private static final MethodId Skip = MethodId("Skip"); public JCSkip Skip() { return invoke(Skip); } //javac versions: 6-8 private static final MethodId Block = MethodId("Block"); public JCBlock Block(long flags, List stats) { return invoke(Block, flags, stats); } //javac versions: 6-8 private static final MethodId DoLoop = MethodId("DoLoop"); public JCDoWhileLoop DoLoop(JCStatement body, JCExpression cond) { return invoke(DoLoop, body, cond); } //javac versions: 6-8 private static final MethodId WhileLoop = MethodId("WhileLoop"); public JCWhileLoop WhileLoop(JCExpression cond, JCStatement body) { return invoke(WhileLoop, cond, body); } //javac versions: 6-8 private static final MethodId ForLoop = MethodId("ForLoop"); public JCForLoop ForLoop(List init, JCExpression cond, List step, JCStatement body) { return invoke(ForLoop, init, cond, step, body); } //javac versions: 6-8 private static final MethodId ForeachLoop = MethodId("ForeachLoop"); public JCEnhancedForLoop ForeachLoop(JCVariableDecl var, JCExpression expr, JCStatement body) { return invoke(ForeachLoop, var, expr, body); } //javac versions: 6-8 private static final MethodId Labelled = MethodId("Labelled"); public JCLabeledStatement Labelled(Name label, JCStatement body) { return invoke(Labelled, label, body); } //javac versions: 6-8 private static final MethodId Switch = MethodId("Switch"); public JCSwitch Switch(JCExpression selector, List cases) { return invoke(Switch, selector, cases); } //javac versions: 6-8 private static final MethodId Case = MethodId("Case"); public JCCase Case(JCExpression pat, List stats) { return invoke(Case, pat, stats); } //javac versions: 6-8 private static final MethodId Synchronized = MethodId("Synchronized"); public JCSynchronized Synchronized(JCExpression lock, JCBlock body) { return invoke(Synchronized, lock, body); } //javac versions: 6-8 private static final MethodId Try = MethodId("Try", JCTry.class, JCBlock.class, List.class, JCBlock.class); public JCTry Try(JCBlock body, List catchers, JCBlock finalizer) { return invoke(Try, body, catchers, finalizer); } //javac versions: 7-8 private static final MethodId TryWithResources = MethodId("Try", JCTry.class, List.class, JCBlock.class, List.class, JCBlock.class); public JCTry Try(List resources, JCBlock body, List catchers, JCBlock finalizer) { return invoke(TryWithResources, resources, body, catchers, finalizer); } //javac versions: 6-8 private static final MethodId Catch = MethodId("Catch"); public JCCatch Catch(JCVariableDecl param, JCBlock body) { return invoke(Catch, param, body); } //javac versions: 6-8 private static final MethodId Conditional = MethodId("Conditional"); public JCConditional Conditional(JCExpression cond, JCExpression thenpart, JCExpression elsepart) { return invoke(Conditional, cond, thenpart, elsepart); } //javac versions: 6-8 private static final MethodId If = MethodId("If"); public JCIf If(JCExpression cond, JCStatement thenpart, JCStatement elsepart) { return invoke(If, cond, thenpart, elsepart); } //javac versions: 6-8 private static final MethodId Exec = MethodId("Exec"); public JCExpressionStatement Exec(JCExpression expr) { return invoke(Exec, expr); } //javac versions: 6-8 private static final MethodId Break = MethodId("Break"); public JCBreak Break(Name label) { return invoke(Break, label); } //javac versions: 6-8 private static final MethodId Continue = MethodId("Continue"); public JCContinue Continue(Name label) { return invoke(Continue, label); } //javac versions: 6-8 private static final MethodId Return = MethodId("Return"); public JCReturn Return(JCExpression expr) { return invoke(Return, expr); } //javac versions: 6-8 private static final MethodId Throw = MethodId("Throw"); public JCThrow Throw(JCExpression expr) { return invoke(Throw, expr); } //javac versions: 6-8 private static final MethodId Assert = MethodId("Assert"); public JCAssert Assert(JCExpression cond, JCExpression detail) { return invoke(Assert, cond, detail); } //javac versions: 6-8 private static final MethodId Apply = MethodId("Apply"); public JCMethodInvocation Apply(List typeargs, JCExpression fn, List args) { return invoke(Apply, typeargs, fn, args); } //javac versions: 6-8 private static final MethodId NewClass = MethodId("NewClass"); public JCNewClass NewClass(JCExpression encl, List typeargs, JCExpression clazz, List args, JCClassDecl def) { return invoke(NewClass, encl, typeargs, clazz, args, def); } //javac versions: 6-8 private static final MethodId NewArray = MethodId("NewArray"); public JCNewArray NewArray(JCExpression elemtype, List dims, List elems) { return invoke(NewArray, elemtype, dims, elems); } //javac versions: 8 // private static final MethodId Lambda = MethodId("Lambda"); // public JCLambda Lambda(List params, JCTree body) { // return invoke(Lambda, params, body); // } //javac versions: 6-8 private static final MethodId Parens = MethodId("Parens"); public JCParens Parens(JCExpression expr) { return invoke(Parens, expr); } //javac versions: 6-8 private static final MethodId Assign = MethodId("Assign"); public JCAssign Assign(JCExpression lhs, JCExpression rhs) { return invoke(Assign, lhs, rhs); } //javac versions: 6-8 //opcode = [6-7] int [8] JCTree.Tag private static final MethodId Assignop = MethodId("Assignop"); public JCAssignOp Assignop(TreeTag opcode, JCTree lhs, JCTree rhs) { return invoke(Assignop, opcode.value, lhs, rhs); } //javac versions: 6-8 //opcode = [6-7] int [8] JCTree.Tag private static final MethodId Unary = MethodId("Unary"); public JCUnary Unary(TreeTag opcode, JCExpression arg) { return invoke(Unary, opcode.value, arg); } //javac versions: 6-8 //opcode = [6-7] int [8] JCTree.Tag private static final MethodId Binary = MethodId("Binary"); public JCBinary Binary(TreeTag opcode, JCExpression lhs, JCExpression rhs) { return invoke(Binary, opcode.value, lhs, rhs); } //javac versions: 6-8 private static final MethodId TypeCast = MethodId("TypeCast"); public JCTypeCast TypeCast(JCTree expr, JCExpression type) { return invoke(TypeCast, expr, type); } //javac versions: 6-8 private static final MethodId TypeTest = MethodId("TypeTest"); public JCInstanceOf TypeTest(JCExpression expr, JCTree clazz) { return invoke(TypeTest, expr, clazz); } //javac versions: 6-8 private static final MethodId Indexed = MethodId("Indexed"); public JCArrayAccess Indexed(JCExpression indexed, JCExpression index) { return invoke(Indexed, indexed, index); } //javac versions: 6-8 private static final MethodId Select = MethodId("Select"); public JCFieldAccess Select(JCExpression selected, Name selector) { return invoke(Select, selected, selector); } //javac versions: 8 // private static final MethodId Reference = MethodId("Reference"); // public JCMemberReference Reference(JCMemberReference.ReferenceMode mode, Name name, JCExpression expr, List typeargs) { // return invoke(Reference, mode, name, expr, typeargs); // } //javac versions: 6-8 private static final MethodId Ident = MethodId("Ident", JCIdent.class, Name.class); public JCIdent Ident(Name idname) { return invoke(Ident, idname); } //javac versions: 6-8 //tag = [6-7] int [8] TypeTag private static final MethodId Literal = MethodId("Literal", JCLiteral.class, TypeTag.class, Object.class); public JCLiteral Literal(TypeTag tag, Object value) { return invoke(Literal, tag.value, value); } //javac versions: 6-8 //typetag = [6-7] int [8] TypeTag private static final MethodId TypeIdent = MethodId("TypeIdent"); public JCPrimitiveTypeTree TypeIdent(TypeTag typetag) { return invoke(TypeIdent, typetag.value); } //javac versions: 6-8 private static final MethodId TypeArray = MethodId("TypeArray"); public JCArrayTypeTree TypeArray(JCExpression elemtype) { return invoke(TypeArray, elemtype); } //javac versions: 6-8 private static final MethodId TypeApply = MethodId("TypeApply"); public JCTypeApply TypeApply(JCExpression clazz, List arguments) { return invoke(TypeApply, clazz, arguments); } //javac versions: 7-8 // private static final MethodId TypeUnion = MethodId("TypeUnion"); // public JCTypeUnion TypeUnion(List components) { // return invoke(TypeUnion, compoonents); // } //javac versions: 8 // private static final MethodId TypeIntersection = MethodId("TypeIntersection"); // public JCTypeIntersection TypeIntersection(List components) { // return invoke(TypeIntersection, components); // } //javac versions: 6-8 private static final MethodId TypeParameter = MethodId("TypeParameter", JCTypeParameter.class, Name.class, List.class); public JCTypeParameter TypeParameter(Name name, List bounds) { return invoke(TypeParameter, name, bounds); } //javac versions: 8 private static final MethodId TypeParameterWithAnnos = MethodId("TypeParameter", JCTypeParameter.class, Name.class, List.class, List.class); public JCTypeParameter TypeParameter(Name name, List bounds, List annos) { return invoke(TypeParameterWithAnnos, name, bounds, annos); } //javac versions: 6-8 private static final MethodId Wildcard = MethodId("Wildcard"); public JCWildcard Wildcard(TypeBoundKind kind, JCTree type) { return invoke(Wildcard, kind, type); } //javac versions: 6-8 private static final MethodId TypeBoundKind = MethodId("TypeBoundKind"); public TypeBoundKind TypeBoundKind(BoundKind kind) { return invoke(TypeBoundKind, kind); } //javac versions: 6-8 private static final MethodId Annotation = MethodId("Annotation", JCAnnotation.class, JCTree.class, List.class); public JCAnnotation Annotation(JCTree annotationType, List args) { return invoke(Annotation, annotationType, args); } //javac versions: 8 private static final MethodId TypeAnnotation = MethodId("TypeAnnotation", JCAnnotation.class, JCTree.class, List.class); public JCAnnotation TypeAnnotation(JCTree annotationType, List args) { return invoke(TypeAnnotation, annotationType, args); } //javac versions: 6-8 private static final MethodId ModifiersWithAnnotations = MethodId("Modifiers", JCModifiers.class, long.class, List.class); public JCModifiers Modifiers(long flags, List annotations) { return invoke(ModifiersWithAnnotations, flags, annotations); } //javac versions: 6-8 private static final MethodId Modifiers = MethodId("Modifiers", JCModifiers.class, long.class); public JCModifiers Modifiers(long flags) { return invoke(Modifiers, flags); } //javac versions: 8 // private static final MethodId AnnotatedType = MethodId("AnnotatedType"); // public JCAnnotatedType AnnotatedType(List annotations, JCExpression underlyingType) { // return invoke(AnnotatedType, annotations, underlyingType); // } //javac versions: 6-8 private static final MethodId Erroneous = MethodId("Erroneous", JCErroneous.class); public JCErroneous Erroneous() { return invoke(Erroneous); } //javac versions: 6-8 private static final MethodId ErroneousWithErrs = MethodId("Erroneous", JCErroneous.class, List.class); public JCErroneous Erroneous(List errs) { return invoke(ErroneousWithErrs, errs); } //javac versions: 6-8 private static final MethodId LetExpr = MethodId("LetExpr", LetExpr.class, List.class, JCTree.class); public LetExpr LetExpr(List defs, JCTree expr) { return invoke(LetExpr, defs, expr); } //javac versions: 6-8 private static final MethodId AnonymousClassDef = MethodId("AnonymousClassDef"); public JCClassDecl AnonymousClassDef(JCModifiers mods, List defs) { return invoke(AnonymousClassDef, mods, defs); } //javac versions: 6-8 private static final MethodId LetExprSingle = MethodId("LetExpr", LetExpr.class, JCVariableDecl.class, JCTree.class); public LetExpr LetExpr(JCVariableDecl def, JCTree expr) { return invoke(LetExprSingle, def, expr); } //javac versions: 6-8 private static final MethodId IdentVarDecl = MethodId("Ident", JCIdent.class, JCVariableDecl.class); public JCExpression Ident(JCVariableDecl param) { return invoke(IdentVarDecl, param); } //javac versions: 6-8 private static final MethodId> Idents = MethodId("Idents"); public List Idents(List params) { return invoke(Idents, params); } //javac versions: 6-8 private static final MethodId App2 = MethodId("App", JCMethodInvocation.class, JCExpression.class, List.class); public JCMethodInvocation App(JCExpression meth, List args) { return invoke(App2, meth, args); } //javac versions: 6-8 private static final MethodId App1 = MethodId("App", JCMethodInvocation.class, JCExpression.class); public JCMethodInvocation App(JCExpression meth) { return invoke(App1, meth); } //javac versions: 6-8 private static final MethodId> Annotations = MethodId("Annotations"); public List Annotations(List attributes) { return invoke(Annotations, attributes); } //javac versions: 6-8 private static final MethodId LiteralWithValue = MethodId("Literal", JCLiteral.class, Object.class); public JCLiteral Literal(Object value) { return invoke(LiteralWithValue, value); } //javac versions: 6-8 private static final MethodId AnnotationWithAttributeOnly = MethodId("Annotation", JCAnnotation.class, Attribute.class); public JCAnnotation Annotation(Attribute a) { return invoke(AnnotationWithAttributeOnly, a); } //javac versions: 8 private static final MethodId TypeAnnotationWithAttributeOnly = MethodId("TypeAnnotation", JCAnnotation.class, Attribute.class); public JCAnnotation TypeAnnotation(Attribute a) { return invoke(TypeAnnotationWithAttributeOnly, a); } //javac versions: 6-8 private static final MethodId Call = MethodId("Call"); public JCStatement Call(JCExpression apply) { return invoke(Call, apply); } //javac versions: 6-8 private static final MethodId Type = MethodId("Type"); public JCExpression Type(Type type) { return invoke(Type, type); } }lombok-1.16.18/src/utils/lombok/javac/TreeMirrorMaker.java000066400000000000000000000110671312655740700234050ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import static lombok.javac.Javac.*; import lombok.javac.JavacTreeMaker.TypeTag; import com.sun.source.tree.LabeledStatementTree; import com.sun.source.tree.VariableTree; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.TreeCopier; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; /** * Makes a copy of any AST node, with some exceptions. * Exceptions:
      *
    • The symbol ('sym') of a copied variable isn't copied. *
    • all labels are removed. *
    * * The purpose of this class is to make a copy, and then the copy is attributed (resolution info is added). These exceptions * are to work around apparent bugs (or at least inconsistencies) in javac sources. */ public class TreeMirrorMaker extends TreeCopier { private final IdentityHashMap originalToCopy = new IdentityHashMap(); public TreeMirrorMaker(JavacTreeMaker maker, Context context) { super(maker.getUnderlyingTreeMaker()); } @Override public T copy(T original) { T copy = super.copy(original); originalToCopy.put(original, copy); return copy; } @Override public T copy(T original, Void p) { T copy = super.copy(original, p); originalToCopy.put(original, copy); return copy; } @Override public List copy(List originals) { List copies = super.copy(originals); if (originals != null) { Iterator it1 = originals.iterator(); Iterator it2 = copies.iterator(); while (it1.hasNext()) originalToCopy.put(it1.next(), it2.next()); } return copies; } @Override public List copy(List originals, Void p) { List copies = super.copy(originals, p); if (originals != null) { Iterator it1 = originals.iterator(); Iterator it2 = copies.iterator(); while (it1.hasNext()) originalToCopy.put(it1.next(), it2.next()); } return copies; } public Map getOriginalToCopyMap() { return Collections.unmodifiableMap(originalToCopy); } // Monitor the following issues when making changes here. // - https://github.com/rzwitserloot/lombok/issues/278 // - https://github.com/rzwitserloot/lombok/issues/729 @Override public JCTree visitVariable(VariableTree node, Void p) { JCVariableDecl original = node instanceof JCVariableDecl ? (JCVariableDecl) node : null; JCVariableDecl copy = (JCVariableDecl) super.visitVariable(node, p); if (original == null) return copy; copy.sym = original.sym; if (copy.sym != null) copy.type = original.type; if (copy.type != null) { boolean wipeSymAndType = copy.type.isErroneous(); if (!wipeSymAndType) { TypeTag typeTag = TypeTag.typeTag(copy.type); wipeSymAndType = (CTC_NONE.equals(typeTag) || CTC_ERROR.equals(typeTag) || CTC_UNKNOWN.equals(typeTag) || CTC_UNDETVAR.equals(typeTag)); } if (wipeSymAndType) { copy.sym = null; copy.type = null; } } return copy; } // Fix for NPE in HandleVal. See https://github.com/rzwitserloot/lombok/issues/372 // This and visitVariable is rather hacky but we're working around evident bugs or at least inconsistencies in javac. @Override public JCTree visitLabeledStatement(LabeledStatementTree node, Void p) { return node.getStatement().accept(this, p); } } lombok-1.16.18/src/utils/lombok/javac/java6/000077500000000000000000000000001312655740700204725ustar00rootroot00000000000000lombok-1.16.18/src/utils/lombok/javac/java6/CommentCollectingParser.java000066400000000000000000000037771312655740700261360ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java6; import static lombok.javac.CommentCatcher.JCCompilationUnit_comments; import lombok.javac.CommentInfo; import com.sun.tools.javac.parser.EndPosParser; import com.sun.tools.javac.parser.Lexer; import com.sun.tools.javac.parser.Parser; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.List; class CommentCollectingParser extends EndPosParser { private final Lexer lexer; protected CommentCollectingParser(Parser.Factory fac, Lexer S, boolean keepDocComments) { super(fac, S, keepDocComments); lexer = S; } @Override public JCCompilationUnit compilationUnit() { JCCompilationUnit result = super.compilationUnit(); if (lexer instanceof CommentCollectingScanner) { List comments = ((CommentCollectingScanner)lexer).getComments(); JCCompilationUnit_comments.set(result, comments); } return result; } }lombok-1.16.18/src/utils/lombok/javac/java6/CommentCollectingParserFactory.java000066400000000000000000000046541312655740700274610ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java6; import java.lang.reflect.Field; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.parser.Lexer; import com.sun.tools.javac.parser.Parser; import com.sun.tools.javac.util.Context; public class CommentCollectingParserFactory extends Parser.Factory { static Context.Key key() { return parserFactoryKey; } protected CommentCollectingParserFactory(Context context) { super(context); } @Override public Parser newParser(Lexer S, boolean keepDocComments, boolean genEndPos) { Object x = new CommentCollectingParser(this, S, true); return (Parser) x; // CCP is based on a stub which extends nothing, but at runtime the stub is replaced with either //javac6's EndPosParser which extends Parser, or javac7's EndPosParser which implements Parser. //Either way this will work out. } public static void setInCompiler(JavaCompiler compiler, Context context) { context.put(CommentCollectingParserFactory.key(), (Parser.Factory)null); Field field; try { field = JavaCompiler.class.getDeclaredField("parserFactory"); field.setAccessible(true); field.set(compiler, new CommentCollectingParserFactory(context)); } catch (Exception e) { throw new IllegalStateException("Could not set comment sensitive parser in the compiler", e); } } }lombok-1.16.18/src/utils/lombok/javac/java6/CommentCollectingScanner.java000066400000000000000000000066161312655740700262660ustar00rootroot00000000000000/* * Copyright (C) 2011-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java6; import java.nio.CharBuffer; import lombok.javac.CommentInfo; import lombok.javac.CommentInfo.EndConnection; import lombok.javac.CommentInfo.StartConnection; import com.sun.tools.javac.parser.Scanner; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; public class CommentCollectingScanner extends Scanner { private final ListBuffer comments = new ListBuffer(); private int endComment = 0; public CommentCollectingScanner(CommentCollectingScannerFactory factory, CharBuffer charBuffer) { super(factory, charBuffer); } public CommentCollectingScanner(CommentCollectingScannerFactory factory, char[] input, int inputLength) { super(factory, input, inputLength); } @Override protected void processComment(CommentStyle style) { int prevEndPos = Math.max(prevEndPos(), endComment); int pos = pos(); int endPos = endPos(); endComment = endPos; String content = new String(getRawCharacters(pos, endPos)); StartConnection start = determineStartConnection(prevEndPos, pos); EndConnection end = determineEndConnection(endPos); CommentInfo comment = new CommentInfo(prevEndPos, pos, endPos, content, start, end); comments.append(comment); super.processComment(style); } private EndConnection determineEndConnection(int pos) { boolean first = true; for (int i = pos;; i++) { char c; try { c = getRawCharacters(i, i + 1)[0]; } catch (IndexOutOfBoundsException e) { c = '\n'; } if (isNewLine(c)) { return EndConnection.ON_NEXT_LINE; } if (Character.isWhitespace(c)) { first = false; continue; } return first ? EndConnection.DIRECT_AFTER_COMMENT : EndConnection.AFTER_COMMENT; } } private StartConnection determineStartConnection(int from, int to) { if (from == to) { return StartConnection.DIRECT_AFTER_PREVIOUS; } char[] between = getRawCharacters(from, to); if (isNewLine(between[between.length - 1])) { return StartConnection.START_OF_LINE; } for (char c : between) { if (isNewLine(c)) { return StartConnection.ON_NEXT_LINE; } } return StartConnection.AFTER_PREVIOUS; } private boolean isNewLine(char c) { return c == '\n' || c == '\r'; } public List getComments() { return comments.toList(); } } lombok-1.16.18/src/utils/lombok/javac/java6/CommentCollectingScannerFactory.java000066400000000000000000000075321312655740700276140ustar00rootroot00000000000000/* * Copyright (C) 2011-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java6; import java.nio.CharBuffer; import com.sun.tools.javac.parser.Scanner; import com.sun.tools.javac.util.Context; public class CommentCollectingScannerFactory extends Scanner.Factory { @SuppressWarnings("all") public static void preRegister(final Context context) { if (context.get(scannerFactoryKey) == null) { // Careful! There is voodoo magic here! // // Context.Factory is parameterized. make() is for javac6 and below; make(Context) is for javac7 and up. // this anonymous inner class definition is intentionally 'raw' - the return type of both 'make' methods is 'T', // which means the compiler will only generate the correct "real" override method (with returntype Object, which is // the lower bound for T, as a synthetic accessor for the make with returntype ScannerFactory) for that make method which // is actually on the classpath (either make() for javac6-, or make(Context) for javac7+). // // We normally solve this issue via src/stubs, with BOTH make methods listed, but for some reason the presence of a stubbed out // Context (or even a complete copy, it doesn't matter) results in a really strange eclipse bug, where any mention of any kind // of com.sun.tools.javac.tree.TreeMaker in a source file disables ALL usage of 'go to declaration' and auto-complete in the entire // source file. // // Thus, in short: // * Do NOT parameterize the anonymous inner class literal. // * Leave the return types as 'j.l.Object'. // * Leave both make methods intact; deleting one has no effect on javac6- / javac7+, but breaks the other. Hard to test for. // * Do not stub com.sun.tools.javac.util.Context or any of its inner types, like Factory. @SuppressWarnings("all") class MyFactory implements Context.Factory { // This overrides the javac6- version of make. public Object make() { return new CommentCollectingScannerFactory(context); } // This overrides the javac7+ version of make. public Object make(Context c) { return new CommentCollectingScannerFactory(c); } } @SuppressWarnings("unchecked") Context.Factory factory = new MyFactory(); context.put(scannerFactoryKey, factory); } } /** Create a new scanner factory. */ protected CommentCollectingScannerFactory(Context context) { super(context); } @Override public Scanner newScanner(CharSequence input) { if (input instanceof CharBuffer) { return new CommentCollectingScanner(this, (CharBuffer)input); } char[] array = input.toString().toCharArray(); return newScanner(array, array.length); } @Override public Scanner newScanner(char[] input, int inputLength) { return new CommentCollectingScanner(this, input, inputLength); } }lombok-1.16.18/src/utils/lombok/javac/java7/000077500000000000000000000000001312655740700204735ustar00rootroot00000000000000lombok-1.16.18/src/utils/lombok/javac/java7/CommentCollectingParser.java000066400000000000000000000040351312655740700261230ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java7; import static lombok.javac.CommentCatcher.JCCompilationUnit_comments; import java.util.List; import lombok.javac.CommentInfo; import com.sun.tools.javac.parser.EndPosParser; import com.sun.tools.javac.parser.Lexer; import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; class CommentCollectingParser extends EndPosParser { private final Lexer lexer; protected CommentCollectingParser(ParserFactory fac, Lexer S, boolean keepDocComments, boolean keepLineMap) { super(fac, S, keepDocComments, keepLineMap); lexer = S; } public JCCompilationUnit parseCompilationUnit() { JCCompilationUnit result = super.parseCompilationUnit(); if (lexer instanceof CommentCollectingScanner) { List comments = ((CommentCollectingScanner)lexer).getComments(); JCCompilationUnit_comments.set(result, comments); } return result; } }lombok-1.16.18/src/utils/lombok/javac/java7/CommentCollectingParserFactory.java000066400000000000000000000053541312655740700274600ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java7; import java.lang.reflect.Field; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.parser.Lexer; import com.sun.tools.javac.parser.Parser; import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.util.Context; public class CommentCollectingParserFactory extends ParserFactory { private final Context context; static Context.Key key() { return parserFactoryKey; } protected CommentCollectingParserFactory(Context context) { super(context); this.context = context; } public Parser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap) { ScannerFactory scannerFactory = ScannerFactory.instance(context); Lexer lexer = scannerFactory.newScanner(input, true); Object x = new CommentCollectingParser(this, lexer, true, keepLineMap); return (Parser) x; // CCP is based on a stub which extends nothing, but at runtime the stub is replaced with either //javac6's EndPosParser which extends Parser, or javac7's EndPosParser which implements Parser. //Either way this will work out. } public static void setInCompiler(JavaCompiler compiler, Context context) { context.put(CommentCollectingParserFactory.key(), (ParserFactory)null); Field field; try { field = JavaCompiler.class.getDeclaredField("parserFactory"); field.setAccessible(true); field.set(compiler, new CommentCollectingParserFactory(context)); } catch (Exception e) { throw new IllegalStateException("Could not set comment sensitive parser in the compiler", e); } } }lombok-1.16.18/src/utils/lombok/javac/java7/CommentCollectingScanner.java000066400000000000000000000066211312655740700262630ustar00rootroot00000000000000/* * Copyright (C) 2011-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java7; import java.nio.CharBuffer; import lombok.javac.CommentInfo; import lombok.javac.CommentInfo.EndConnection; import lombok.javac.CommentInfo.StartConnection; import com.sun.tools.javac.parser.Scanner; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; public class CommentCollectingScanner extends Scanner { private final ListBuffer comments = new ListBuffer(); private int endComment = 0; public CommentCollectingScanner(CommentCollectingScannerFactory factory, CharBuffer charBuffer) { super(factory, charBuffer); } public CommentCollectingScanner(CommentCollectingScannerFactory factory, char[] input, int inputLength) { super(factory, input, inputLength); } @Override protected void processComment(CommentStyle style) { int prevEndPos = Math.max(prevEndPos(), endComment); int pos = pos(); int endPos = endPos(); endComment = endPos; String content = new String(getRawCharacters(pos, endPos)); StartConnection start = determineStartConnection(prevEndPos, pos); EndConnection end = determineEndConnection(endPos); CommentInfo comment = new CommentInfo(prevEndPos, pos, endPos, content, start, end); comments.append(comment); super.processComment(style); } private EndConnection determineEndConnection(int pos) { boolean first = true; for (int i = pos;; i++) { char c; try { c = getRawCharacters(i, i + 1)[0]; } catch (IndexOutOfBoundsException e) { c = '\n'; } if (isNewLine(c)) { return EndConnection.ON_NEXT_LINE; } if (Character.isWhitespace(c)) { first = false; continue; } return first ? EndConnection.DIRECT_AFTER_COMMENT : EndConnection.AFTER_COMMENT; } } private StartConnection determineStartConnection(int from, int to) { if (from == to) { return StartConnection.DIRECT_AFTER_PREVIOUS; } char[] between = getRawCharacters(from, to); if (isNewLine(between[between.length - 1])) { return StartConnection.START_OF_LINE; } for (char c : between) { if (isNewLine(c)) { return StartConnection.ON_NEXT_LINE; } } return StartConnection.AFTER_PREVIOUS; } private boolean isNewLine(char c) { return c == '\n' || c == '\r'; } public List getComments() { return comments.toList(); } } lombok-1.16.18/src/utils/lombok/javac/java7/CommentCollectingScannerFactory.java000066400000000000000000000077021312655740700276140ustar00rootroot00000000000000/* * Copyright (C) 2011-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java7; import java.nio.CharBuffer; import com.sun.tools.javac.parser.Scanner; import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.util.Context; public class CommentCollectingScannerFactory extends ScannerFactory { @SuppressWarnings("all") public static void preRegister(final Context context) { if (context.get(scannerFactoryKey) == null) { // Careful! There is voodoo magic here! // // Context.Factory is parameterized. make() is for javac6 and below; make(Context) is for javac7 and up. // this anonymous inner class definition is intentionally 'raw' - the return type of both 'make' methods is 'T', // which means the compiler will only generate the correct "real" override method (with returntype Object, which is // the lower bound for T, as a synthetic accessor for the make with returntype ScannerFactory) for that make method which // is actually on the classpath (either make() for javac6-, or make(Context) for javac7+). // // We normally solve this issue via src/stubs, with BOTH make methods listed, but for some reason the presence of a stubbed out // Context (or even a complete copy, it doesn't matter) results in a really strange eclipse bug, where any mention of any kind // of com.sun.tools.javac.tree.TreeMaker in a source file disables ALL usage of 'go to declaration' and auto-complete in the entire // source file. // // Thus, in short: // * Do NOT parameterize the anonymous inner class literal. // * Leave the return types as 'j.l.Object'. // * Leave both make methods intact; deleting one has no effect on javac6- / javac7+, but breaks the other. Hard to test for. // * Do not stub com.sun.tools.javac.util.Context or any of its inner types, like Factory. @SuppressWarnings("all") class MyFactory implements Context.Factory { // This overrides the javac6- version of make. public Object make() { return new CommentCollectingScannerFactory(context); } // This overrides the javac7+ version. public Object make(Context c) { return new CommentCollectingScannerFactory(c); } } @SuppressWarnings("unchecked") Context.Factory factory = new MyFactory(); context.put(scannerFactoryKey, factory); } } /** Create a new scanner factory. */ protected CommentCollectingScannerFactory(Context context) { super(context); } @Override public Scanner newScanner(CharSequence input, boolean keepDocComments) { if (input instanceof CharBuffer) { return new CommentCollectingScanner(this, (CharBuffer)input); } char[] array = input.toString().toCharArray(); return newScanner(array, array.length, keepDocComments); } @Override public Scanner newScanner(char[] input, int inputLength, boolean keepDocComments) { return new CommentCollectingScanner(this, input, inputLength); } } lombok-1.16.18/src/utils/lombok/javac/java8/000077500000000000000000000000001312655740700204745ustar00rootroot00000000000000lombok-1.16.18/src/utils/lombok/javac/java8/CommentCollectingParser.java000066400000000000000000000041071312655740700261240ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java8; import static lombok.javac.CommentCatcher.JCCompilationUnit_comments; import java.util.List; import lombok.javac.CommentInfo; import com.sun.tools.javac.parser.JavacParser; import com.sun.tools.javac.parser.Lexer; import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; class CommentCollectingParser extends JavacParser { private final Lexer lexer; protected CommentCollectingParser(ParserFactory fac, Lexer S, boolean keepDocComments, boolean keepLineMap, boolean keepEndPositions) { super(fac, S, keepDocComments, keepLineMap, keepEndPositions); lexer = S; } public JCCompilationUnit parseCompilationUnit() { JCCompilationUnit result = super.parseCompilationUnit(); if (lexer instanceof CommentCollectingScanner) { List comments = ((CommentCollectingScanner)lexer).getComments(); JCCompilationUnit_comments.set(result, comments); } return result; } }lombok-1.16.18/src/utils/lombok/javac/java8/CommentCollectingParserFactory.java000066400000000000000000000054071312655740700274600ustar00rootroot00000000000000/* * Copyright (C) 2013-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java8; import java.lang.reflect.Field; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.parser.JavacParser; import com.sun.tools.javac.parser.Lexer; import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.util.Context; public class CommentCollectingParserFactory extends ParserFactory { private final Context context; static Context.Key key() { return parserFactoryKey; } protected CommentCollectingParserFactory(Context context) { super(context); this.context = context; } public JavacParser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap) { ScannerFactory scannerFactory = ScannerFactory.instance(context); Lexer lexer = scannerFactory.newScanner(input, true); Object x = new CommentCollectingParser(this, lexer, true, keepLineMap, keepEndPos); return (JavacParser) x; // CCP is based on a stub which extends nothing, but at runtime the stub is replaced with either //javac6's EndPosParser which extends Parser, or javac8's JavacParser which implements Parser. //Either way this will work out. } public static void setInCompiler(JavaCompiler compiler, Context context) { context.put(CommentCollectingParserFactory.key(), (ParserFactory) null); Field field; try { field = JavaCompiler.class.getDeclaredField("parserFactory"); field.setAccessible(true); field.set(compiler, new CommentCollectingParserFactory(context)); } catch (Exception e) { throw new IllegalStateException("Could not set comment sensitive parser in the compiler", e); } } }lombok-1.16.18/src/utils/lombok/javac/java8/CommentCollectingScanner.java000066400000000000000000000032061312655740700262600ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java8; import lombok.javac.CommentInfo; import com.sun.tools.javac.parser.Scanner; import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.util.List; public class CommentCollectingScanner extends Scanner { private CommentCollectingTokenizer tokenizer; public CommentCollectingScanner(ScannerFactory fac, CommentCollectingTokenizer tokenizer) { super(fac, tokenizer); this.tokenizer = tokenizer; } public List getComments() { return tokenizer.getComments(); } }lombok-1.16.18/src/utils/lombok/javac/java8/CommentCollectingScannerFactory.java000066400000000000000000000100501312655740700276030ustar00rootroot00000000000000/* * Copyright (C) 2011-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java8; import java.nio.CharBuffer; import com.sun.tools.javac.parser.Scanner; import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.util.Context; public class CommentCollectingScannerFactory extends ScannerFactory { @SuppressWarnings("all") public static void preRegister(final Context context) { if (context.get(scannerFactoryKey) == null) { // Careful! There is voodoo magic here! // // Context.Factory is parameterized. make() is for javac6 and below; make(Context) is for javac7 and up. // this anonymous inner class definition is intentionally 'raw' - the return type of both 'make' methods is 'T', // which means the compiler will only generate the correct "real" override method (with returntype Object, which is // the lower bound for T, as a synthetic accessor for the make with returntype ScannerFactory) for that make method which // is actually on the classpath (either make() for javac6-, or make(Context) for javac7+). // // We normally solve this issue via src/stubs, with BOTH make methods listed, but for some reason the presence of a stubbed out // Context (or even a complete copy, it doesn't matter) results in a really strange eclipse bug, where any mention of any kind // of com.sun.tools.javac.tree.TreeMaker in a source file disables ALL usage of 'go to declaration' and auto-complete in the entire // source file. // // Thus, in short: // * Do NOT parameterize the anonymous inner class literal. // * Leave the return types as 'j.l.Object'. // * Leave both make methods intact; deleting one has no effect on javac6- / javac7+, but breaks the other. Hard to test for. // * Do not stub com.sun.tools.javac.util.Context or any of its inner types, like Factory. @SuppressWarnings("all") class MyFactory implements Context.Factory { // This overrides the javac6- version of make. public Object make() { return new CommentCollectingScannerFactory(context); } // This overrides the javac7+ version. public Object make(Context c) { return new CommentCollectingScannerFactory(c); } } @SuppressWarnings("unchecked") Context.Factory factory = new MyFactory(); context.put(scannerFactoryKey, factory); } } /** Create a new scanner factory. */ protected CommentCollectingScannerFactory(Context context) { super(context); } @Override public Scanner newScanner(CharSequence input, boolean keepDocComments) { if (input instanceof CharBuffer) { CharBuffer buf = (CharBuffer) input; return new CommentCollectingScanner(this, new CommentCollectingTokenizer(this, buf)); } char[] array = input.toString().toCharArray(); return newScanner(array, array.length, keepDocComments); } @Override public Scanner newScanner(char[] input, int inputLength, boolean keepDocComments) { return new CommentCollectingScanner(this, new CommentCollectingTokenizer(this, input, inputLength)); } } lombok-1.16.18/src/utils/lombok/javac/java8/CommentCollectingTokenizer.java000066400000000000000000000102371312655740700266430ustar00rootroot00000000000000/* * Copyright (C) 2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.java8; import java.nio.CharBuffer; import lombok.javac.CommentInfo; import lombok.javac.CommentInfo.EndConnection; import lombok.javac.CommentInfo.StartConnection; import com.sun.tools.javac.parser.JavaTokenizer; import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.Token; import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle; import com.sun.tools.javac.parser.UnicodeReader; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; class CommentCollectingTokenizer extends JavaTokenizer { private int prevEndPosition = 0; private final ListBuffer comments = new ListBuffer(); private int endComment = 0; CommentCollectingTokenizer(ScannerFactory fac, char[] buf, int inputLength) { super(fac, new PositionUnicodeReader(fac, buf, inputLength)); } CommentCollectingTokenizer(ScannerFactory fac, CharBuffer buf) { super(fac, new PositionUnicodeReader(fac, buf)); } @Override public Token readToken() { Token token = super.readToken(); prevEndPosition = ((PositionUnicodeReader)reader).pos(); return token; } @Override protected Comment processComment(int pos, int endPos, CommentStyle style) { int prevEndPos = Math.max(prevEndPosition, endComment); endComment = endPos; String content = new String(reader.getRawCharacters(pos, endPos)); StartConnection start = determineStartConnection(prevEndPos, pos); EndConnection end = determineEndConnection(endPos); CommentInfo comment = new CommentInfo(prevEndPos, pos, endPos, content, start, end); comments.append(comment); return super.processComment(pos, endPos, style); } private EndConnection determineEndConnection(int pos) { boolean first = true; for (int i = pos;; i++) { char c; try { c = reader.getRawCharacters(i, i + 1)[0]; } catch (IndexOutOfBoundsException e) { c = '\n'; } if (isNewLine(c)) { return EndConnection.ON_NEXT_LINE; } if (Character.isWhitespace(c)) { first = false; continue; } return first ? EndConnection.DIRECT_AFTER_COMMENT : EndConnection.AFTER_COMMENT; } } private StartConnection determineStartConnection(int from, int to) { if (from == to) { return StartConnection.DIRECT_AFTER_PREVIOUS; } char[] between = reader.getRawCharacters(from, to); if (isNewLine(between[between.length - 1])) { return StartConnection.START_OF_LINE; } for (char c : between) { if (isNewLine(c)) { return StartConnection.ON_NEXT_LINE; } } return StartConnection.AFTER_PREVIOUS; } private boolean isNewLine(char c) { return c == '\n' || c == '\r'; } public List getComments() { return comments.toList(); } static class PositionUnicodeReader extends UnicodeReader { protected PositionUnicodeReader(ScannerFactory sf, char[] input, int inputLength) { super(sf, input, inputLength); } public PositionUnicodeReader(ScannerFactory sf, CharBuffer buffer) { super(sf, buffer); } int pos() { return bp; } } }lombok-1.16.18/test/000077500000000000000000000000001312655740700141445ustar00rootroot00000000000000lombok-1.16.18/test/bytecode/000077500000000000000000000000001312655740700157425ustar00rootroot00000000000000lombok-1.16.18/test/bytecode/resource/000077500000000000000000000000001312655740700175715ustar00rootroot00000000000000lombok-1.16.18/test/bytecode/resource/Bar.java000066400000000000000000000001311312655740700211330ustar00rootroot00000000000000public interface Bar extends java.util.RandomAccess, java.util.Map { String getName(); }lombok-1.16.18/test/bytecode/resource/Baz.java000066400000000000000000000000301312655740700211410ustar00rootroot00000000000000public interface Baz { }lombok-1.16.18/test/bytecode/resource/Buux.java000066400000000000000000000002411312655740700213540ustar00rootroot00000000000000public class Buux extends java.util.ArrayList { public Buux() { super(7); addSomething(); } public void addSomething() { super.add("H\u3404l\0"); } }lombok-1.16.18/test/bytecode/resource/Foo.java000066400000000000000000000014431312655740700211610ustar00rootroot00000000000000public class Foo implements java.util.RandomAccess { private static final long LONG = 123L; private static final long LONG_OVERFLOW = 0x1FFFFFFFFL; private static final String ONE = "E\u00e9n"; private static final int INT = 123; private static final double DOUBLE = 1.23; private static final double DOUBLE_NAN = Double.NaN; private static final double DOUBLE_INF = Double.POSITIVE_INFINITY; private static final double DOUBLE_NEG_INF = Double.NEGATIVE_INFINITY; private static final float FLOAT = 1.23F; private static final float FLOAT_NAN = Float.NaN; private static final float FLOAT_INF = Float.POSITIVE_INFINITY; private static final float FLOAT_NEG_INF = Float.NEGATIVE_INFINITY; { String value = toString(); System.out.print(value); System.out.print("Two" + "Four"); } }lombok-1.16.18/test/bytecode/resource/PostCompileSneaky.java000066400000000000000000000001571312655740700240500ustar00rootroot00000000000000public class PostCompileSneaky { public void test() { throw lombok.Lombok.sneakyThrow(new Exception()); } }lombok-1.16.18/test/bytecode/src/000077500000000000000000000000001312655740700165315ustar00rootroot00000000000000lombok-1.16.18/test/bytecode/src/lombok/000077500000000000000000000000001312655740700200145ustar00rootroot00000000000000lombok-1.16.18/test/bytecode/src/lombok/bytecode/000077500000000000000000000000001312655740700216125ustar00rootroot00000000000000lombok-1.16.18/test/bytecode/src/lombok/bytecode/RunBytecodeTests.java000066400000000000000000000025651312655740700257330ustar00rootroot00000000000000/* * Copyright (C) 2011 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({TestClassFileMetaData.class, TestPostCompiler.class}) public class RunBytecodeTests { } lombok-1.16.18/test/bytecode/src/lombok/bytecode/TestClassFileMetaData.java000066400000000000000000000206041312655740700265650ustar00rootroot00000000000000/* * Copyright (C) 2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.tools.Diagnostic; import javax.tools.DiagnosticListener; import javax.tools.JavaCompiler; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; import lombok.Lombok; import org.junit.Test; public class TestClassFileMetaData { private static ClassFileMetaData foo = create(new File("test/bytecode/resource/Foo.java")); private static ClassFileMetaData bar = create(new File("test/bytecode/resource/Bar.java")); private static ClassFileMetaData baz = create(new File("test/bytecode/resource/Baz.java")); private static ClassFileMetaData buux = create(new File("test/bytecode/resource/Buux.java")); @Test public void testGetClassName() { assertTrue(foo.containsUtf8("Foo")); assertEquals("Foo", foo.getClassName()); assertTrue(bar.containsUtf8("Bar")); assertEquals("Bar", bar.getClassName()); assertTrue(baz.containsUtf8("Baz")); assertEquals("Baz", baz.getClassName()); } @Test public void testGetSuperClassName() { assertTrue(foo.containsUtf8("java/lang/Object")); assertEquals("java/lang/Object", foo.getSuperClassName()); assertEquals("java/lang/Object", bar.getSuperClassName()); assertEquals("java/lang/Object", baz.getSuperClassName()); assertEquals("java/util/ArrayList", buux.getSuperClassName()); } @Test public void testUsesClass() { assertTrue(foo.usesClass("java/lang/System")); // assertTrue(foo.usesClass("java/lang/String")); } @Test public void testUsesField() { assertTrue(foo.usesField("java/lang/System", "out")); } @Test public void testUsesMethodWithName() { assertTrue(foo.usesMethod("java/io/PrintStream", "print")); assertTrue(buux.usesMethod("java/util/ArrayList", "")); assertTrue(buux.usesMethod("java/util/ArrayList", "add")); assertTrue(buux.usesMethod("Buux", "addSomething")); } @Test public void testUsesMethodWithNameAndDescriptor() { assertTrue(foo.usesMethod("java/io/PrintStream", "print", "(Ljava/lang/String;)V")); assertTrue(buux.usesMethod("java/util/ArrayList", "", "(I)V")); assertTrue(buux.usesMethod("java/util/ArrayList", "add", "(Ljava/lang/Object;)Z")); assertTrue(buux.usesMethod("Buux", "addSomething", "()V")); } @Test public void testGetInterfaces() { assertTrue(foo.containsUtf8("java/util/RandomAccess")); List fooInterfaces = foo.getInterfaces(); assertEquals(1, fooInterfaces.size()); assertEquals("java/util/RandomAccess", fooInterfaces.get(0)); assertTrue(bar.containsUtf8("java/util/RandomAccess")); assertTrue(bar.containsUtf8("java/util/Map")); List barInterfaces = bar.getInterfaces(); assertEquals(2, barInterfaces.size()); assertEquals("java/util/RandomAccess", barInterfaces.get(0)); assertEquals("java/util/Map", barInterfaces.get(1)); } @Test public void testContainsStringConstant() { assertTrue(foo.containsStringConstant("Eén")); assertTrue(foo.containsStringConstant("TwoFour")); assertTrue(buux.containsStringConstant("H\u3404l\0")); assertFalse(foo.containsStringConstant("Seven")); } @Test public void testContainsDouble() { assertTrue(foo.containsDouble(1.23)); assertTrue(foo.containsDouble(Double.NaN)); assertTrue(foo.containsDouble(Double.POSITIVE_INFINITY)); assertTrue(foo.containsDouble(Double.NEGATIVE_INFINITY)); assertFalse(foo.containsDouble(1.0)); assertFalse(buux.containsDouble(1.0)); assertFalse(buux.containsDouble(Double.NaN)); assertFalse(buux.containsDouble(Double.POSITIVE_INFINITY)); assertFalse(buux.containsDouble(Double.NEGATIVE_INFINITY)); } @Test public void testContainsFloat() { assertTrue(foo.containsFloat(1.23F)); assertTrue(foo.containsFloat(Float.NaN)); assertTrue(foo.containsFloat(Float.POSITIVE_INFINITY)); assertTrue(foo.containsFloat(Float.NEGATIVE_INFINITY)); assertFalse(foo.containsFloat(1.0F)); assertFalse(buux.containsFloat(1.0F)); assertFalse(buux.containsFloat(Float.NaN)); assertFalse(buux.containsFloat(Float.POSITIVE_INFINITY)); assertFalse(buux.containsFloat(Float.NEGATIVE_INFINITY)); } @Test public void testContainsInteger() { assertTrue(foo.containsInteger(123)); assertFalse(foo.containsInteger(1)); assertFalse(buux.containsInteger(1)); } @Test public void testContainsLong() { assertTrue(foo.containsLong(123)); assertTrue(foo.containsLong(0x1FFFFFFFFL)); assertFalse(foo.containsLong(1)); assertFalse(buux.containsLong(1)); } private static ClassFileMetaData create(File file) { return new ClassFileMetaData(compile(file)); } static byte[] compile(File file) { try { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); File tempDir = getTempDir(); tempDir.mkdirs(); List options = Arrays.asList("-proc:none", "-d", tempDir.getAbsolutePath()); StringWriter captureWarnings = new StringWriter(); final StringBuilder compilerErrors = new StringBuilder(); DiagnosticListener diagnostics = new DiagnosticListener() { @Override public void report(Diagnostic diagnostic) { compilerErrors.append(diagnostic.toString()).append("\n"); } }; CompilationTask task = compiler.getTask(captureWarnings, null, diagnostics, options, null, Collections.singleton(new ContentBasedJavaFileObject(file.getPath(), readFileAsString(file)))); Boolean taskResult = task.call(); assertTrue("Compilation task didn't succeed: \n\n" + compilerErrors.toString() + "\n", taskResult); return PostCompilerApp.readFile(new File(tempDir, file.getName().replaceAll("\\.java$", ".class"))); } catch (Exception e) { throw Lombok.sneakyThrow(e); } } private static File getTempDir() { String[] rawDirs = { System.getProperty("java.io.tmpdir"), "/tmp", "C:\\Windows\\Temp" }; for (String dir : rawDirs) { if (dir == null) continue; File f = new File(dir); if (!f.isDirectory()) continue; return new File(f, "lombok.bytecode-test"); } return new File("./build/tmp"); } static class ContentBasedJavaFileObject extends SimpleJavaFileObject { private final String content; protected ContentBasedJavaFileObject(String name, String content) { super(new File(name).toURI(), Kind.SOURCE); this.content = content; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return content; } } private static String readFileAsString(File file) { try { FileInputStream in = new FileInputStream(file); try { BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringWriter writer = new StringWriter(); String line = reader.readLine(); while(line != null) { writer.append(line).append("\n"); line = reader.readLine(); } reader.close(); writer.close(); return writer.toString(); } finally { in.close(); } } catch (Exception e) { throw Lombok.sneakyThrow(e); } } } lombok-1.16.18/test/bytecode/src/lombok/bytecode/TestPostCompiler.java000066400000000000000000000047031312655740700257410ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.bytecode; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import lombok.core.DiagnosticsReceiver; import lombok.core.PostCompiler; import org.junit.Test; public class TestPostCompiler { @Test public void testPostCompiler() throws IOException { byte[] compiled = TestClassFileMetaData.compile(new File("test/bytecode/resource/PostCompileSneaky.java")); DiagnosticsReceiver receiver = new DiagnosticsReceiver() { @Override public void addWarning(String message) { fail("Warning during post compilation processing of a sneakyThrow call: " + message); } @Override public void addError(String message) { fail("Error during post compilation processing of a sneakyThrow call: " + message); } }; assertTrue("Before post compilation, expected lombok.Lombok.sneakyThrow() call in compiled code, but it's not there", new ClassFileMetaData(compiled).usesMethod("lombok/Lombok", "sneakyThrow")); byte[] transformed = PostCompiler.applyTransformations(compiled, "PostCompileSneaky.java", receiver); assertNotSame("Post-compiler did not do anything; we expected it to remove a Lombok.sneakyThrow() call.", compiled, transformed); assertTrue("After removing a sneakyThrow the classfile got... bigger (or stayed equal in size). Huh?", transformed.length < compiled.length); } } lombok-1.16.18/test/configuration/000077500000000000000000000000001312655740700170135ustar00rootroot00000000000000lombok-1.16.18/test/configuration/resource/000077500000000000000000000000001312655740700206425ustar00rootroot00000000000000lombok-1.16.18/test/configuration/resource/configurationRoot/000077500000000000000000000000001312655740700243555ustar00rootroot00000000000000lombok-1.16.18/test/configuration/resource/configurationRoot/d1/000077500000000000000000000000001312655740700246615ustar00rootroot00000000000000lombok-1.16.18/test/configuration/resource/configurationRoot/d1/d11/000077500000000000000000000000001312655740700252465ustar00rootroot00000000000000lombok-1.16.18/test/configuration/resource/configurationRoot/d1/d11/d111/000077500000000000000000000000001312655740700257145ustar00rootroot00000000000000lombok-1.16.18/test/configuration/resource/configurationRoot/d1/d11/d111/f1.txt000066400000000000000000000000001312655740700267510ustar00rootroot00000000000000lombok-1.16.18/test/configuration/resource/configurationRoot/d1/d11/d111/lombok.config000066400000000000000000000000721312655740700303650ustar00rootroot00000000000000clear lombok.accessors.chain lombok.accessors.prefix += m_lombok-1.16.18/test/configuration/resource/configurationRoot/d1/d11/lombok.config000066400000000000000000000001701312655740700277160ustar00rootroot00000000000000config.stopBubbling=true lombok.accessors.chain = false lombok.accessors.flagUsage = ERROR lombok.accessors.prefix += flombok-1.16.18/test/configuration/resource/configurationRoot/d1/d12/000077500000000000000000000000001312655740700252475ustar00rootroot00000000000000lombok-1.16.18/test/configuration/resource/configurationRoot/d1/d12/lombok.config000066400000000000000000000000671312655740700277240ustar00rootroot00000000000000config.stopBubbling=true lombok.accessors.chain = truelombok-1.16.18/test/configuration/resource/configurationRoot/d1/lombok.config000066400000000000000000000001101312655740700273230ustar00rootroot00000000000000config.stopBubbling=true # this file shouldn't be read no error expectedlombok-1.16.18/test/configuration/resource/configurationRoot/err.txt000066400000000000000000000000001312655740700256740ustar00rootroot00000000000000lombok-1.16.18/test/configuration/resource/configurationRoot/out.txt000066400000000000000000000051251312655740700257300ustar00rootroot00000000000000Configuration for 'BASE/d1/d11'. # Emit a warning or error if @Accessors is used. lombok.accessors.flagUsage = ERROR # BASE/d1/lombok.config: # <'lombok.accessors.flagUsage' not mentioned> # # BASE/d1/d11/lombok.config: # 4: lombok.accessors.flagUsage = ERROR # Generate setters that return 'this' instead of 'void' (default: false). lombok.accessors.chain = false # BASE/d1/lombok.config: # <'lombok.accessors.chain' not mentioned> # # BASE/d1/d11/lombok.config: # 3: lombok.accessors.chain = false # Strip this field prefix, like 'f' or 'm_', from the names of generated getters and setters. lombok.accessors.prefix += f # BASE/d1/lombok.config: # <'lombok.accessors.prefix' not mentioned> # # BASE/d1/d11/lombok.config: # 5: lombok.accessors.prefix += f # Use this name for the generated logger fields (default: 'log'). clear lombok.log.fieldName Configuration for: - BASE/d1/d11/d111 - BASE/d1/d11/d111/f1.txt # Emit a warning or error if @Accessors is used. lombok.accessors.flagUsage = ERROR # BASE/d1/lombok.config: # <'lombok.accessors.flagUsage' not mentioned> # # BASE/d1/d11/lombok.config: # 4: lombok.accessors.flagUsage = ERROR # # BASE/d1/d11/d111/lombok.config: # <'lombok.accessors.flagUsage' not mentioned> # Generate setters that return 'this' instead of 'void' (default: false). clear lombok.accessors.chain # BASE/d1/lombok.config: # <'lombok.accessors.chain' not mentioned> # # BASE/d1/d11/lombok.config: # 3: lombok.accessors.chain = false # # BASE/d1/d11/d111/lombok.config: # 1: clear lombok.accessors.chain # Strip this field prefix, like 'f' or 'm_', from the names of generated getters and setters. lombok.accessors.prefix += f lombok.accessors.prefix += m_ # BASE/d1/lombok.config: # <'lombok.accessors.prefix' not mentioned> # # BASE/d1/d11/lombok.config: # 5: lombok.accessors.prefix += f # # BASE/d1/d11/d111/lombok.config: # 2: lombok.accessors.prefix += m_ # Use this name for the generated logger fields (default: 'log'). clear lombok.log.fieldName Configuration for 'BASE/d1/d12'. # Emit a warning or error if @Accessors is used. clear lombok.accessors.flagUsage # Generate setters that return 'this' instead of 'void' (default: false). lombok.accessors.chain = true # BASE/d1/lombok.config: # <'lombok.accessors.chain' not mentioned> # # BASE/d1/d12/lombok.config: # 3: lombok.accessors.chain = true # Strip this field prefix, like 'f' or 'm_', from the names of generated getters and setters. clear lombok.accessors.prefix # Use this name for the generated logger fields (default: 'log'). clear lombok.log.fieldNamelombok-1.16.18/test/configuration/src/000077500000000000000000000000001312655740700176025ustar00rootroot00000000000000lombok-1.16.18/test/configuration/src/lombok/000077500000000000000000000000001312655740700210655ustar00rootroot00000000000000lombok-1.16.18/test/configuration/src/lombok/core/000077500000000000000000000000001312655740700220155ustar00rootroot00000000000000lombok-1.16.18/test/configuration/src/lombok/core/configuration/000077500000000000000000000000001312655740700246645ustar00rootroot00000000000000lombok-1.16.18/test/configuration/src/lombok/core/configuration/RunConfigurationTests.java000066400000000000000000000025501312655740700320500ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({TestConfiguration.class}) public class RunConfigurationTests { } lombok-1.16.18/test/configuration/src/lombok/core/configuration/TestConfiguration.java000066400000000000000000000074101312655740700312000ustar00rootroot00000000000000/* * Copyright (C) 2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core.configuration; import static lombok.ConfigurationKeys.*; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Collection; import java.util.regex.Pattern; import org.junit.Test; public class TestConfiguration { @Test public void testDisplayVerbose() throws Exception { @SuppressWarnings("unchecked") Collection> keys = Arrays.asList(ACCESSORS_FLAG_USAGE, ACCESSORS_CHAIN, ACCESSORS_PREFIX, LOG_ANY_FIELD_NAME); String baseName = "test/configuration/resource/configurationRoot/"; File directory = new File(baseName); String normalizedName = new File(directory.getAbsoluteFile().toURI().normalize()).toString().replace('\\', '/') + "/"; Collection paths = Arrays.asList(normalizedName + "d1/d11", normalizedName + "d1/d12", normalizedName + "d1/d11/d111", normalizedName + "d1/d11/d111/f1.txt"); ByteArrayOutputStream rawOut = new ByteArrayOutputStream(); ByteArrayOutputStream rawErr = new ByteArrayOutputStream(); PrintStream outStream = new PrintStream(rawOut); PrintStream errStream = new PrintStream(rawErr); int result = new ConfigurationApp().redirectOutput(outStream, errStream).display(keys, true, paths, true); outStream.flush(); errStream.flush(); String out = new String(rawOut.toByteArray()).replace("\r\n", "\n").replace('\\', '/').replaceAll(Pattern.quote(normalizedName) + "|" + Pattern.quote(baseName), "BASE/").trim(); String err = new String(rawErr.toByteArray()).replace("\r\n", "\n").replace('\\', '/').replaceAll(Pattern.quote(normalizedName) + "|" + Pattern.quote(baseName), "BASE/").trim(); checkContent(directory, out, "out"); checkContent(directory, err, "err"); assertEquals(0, result); } private void checkContent(File dir, String actual, String type) throws Exception { String expected = fileToString(new File(dir, type + ".txt")).trim(); if (!expected.equals(actual)) { System.out.printf("**** Expected %s:\n", type); System.out.println(expected); System.out.printf("**** Actual %s:\n", type); System.out.println(actual); System.out.println("****"); } assertEquals(expected, actual); } static String fileToString(File configFile) throws Exception { byte[] b = new byte[65536]; FileInputStream fis = new FileInputStream(configFile); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); while (true) { int r = fis.read(b); if (r == -1) break; out.write(b, 0, r); } return new String(out.toByteArray(), "UTF-8"); } finally { fis.close(); } } } lombok-1.16.18/test/core/000077500000000000000000000000001312655740700150745ustar00rootroot00000000000000lombok-1.16.18/test/core/src/000077500000000000000000000000001312655740700156635ustar00rootroot00000000000000lombok-1.16.18/test/core/src/lombok/000077500000000000000000000000001312655740700171465ustar00rootroot00000000000000lombok-1.16.18/test/core/src/lombok/AbstractRunTests.java000066400000000000000000000251301312655740700232650ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import org.junit.Assert; import lombok.DirectoryRunner.FileTester; import lombok.core.AST; import lombok.core.LombokConfiguration; import lombok.core.LombokImmutableList; import lombok.core.configuration.ConfigurationKeysLoader; import lombok.core.configuration.ConfigurationResolver; import lombok.core.configuration.ConfigurationResolverFactory; import lombok.javac.CapturingDiagnosticListener.CompilerMessage; public abstract class AbstractRunTests { private final File dumpActualFilesHere; public AbstractRunTests() { this.dumpActualFilesHere = findPlaceToDumpActualFiles(); } public final FileTester createTester(final DirectoryRunner.TestParams params, final File file, String platform, int version) throws IOException { ConfigurationKeysLoader.LoaderLoader.loadAllConfigurationKeys(); AssertionError directiveFailure = null; LombokTestSource sourceDirectives = null; try { sourceDirectives = LombokTestSource.readDirectives(file); if (sourceDirectives.isIgnore()) return null; if (!sourceDirectives.versionWithinLimit(version)) return null; if (!sourceDirectives.runOnPlatform(platform)) return null; } catch (AssertionError ae) { directiveFailure = ae; } String fileName = file.getName(); final LombokTestSource expected = LombokTestSource.read(params.getAfterDirectory(), params.getMessagesDirectory(), fileName); if (expected.isIgnore()) return null; if (!expected.versionWithinLimit(params.getVersion())) return null; if (!expected.versionWithinLimit(version)) return null; final LombokTestSource sourceDirectives_ = sourceDirectives; final AssertionError directiveFailure_ = directiveFailure; return new FileTester() { @Override public void runTest() throws Throwable { if (directiveFailure_ != null) throw directiveFailure_; LinkedHashSet messages = new LinkedHashSet(); StringWriter writer = new StringWriter(); LombokConfiguration.overrideConfigurationResolverFactory(new ConfigurationResolverFactory() { @Override public ConfigurationResolver createResolver(AST ast) { return sourceDirectives_.getConfiguration(); } }); boolean changed = transformCode(messages, writer, file, sourceDirectives_.getSpecifiedEncoding(), sourceDirectives_.getFormatPreferences()); boolean forceUnchanged = sourceDirectives_.forceUnchanged() || sourceDirectives_.isSkipCompareContent(); if (params.expectChanges() && !forceUnchanged && !changed) messages.add(new CompilerMessage(-1, -1, true, "not flagged modified")); if (!params.expectChanges() && changed) messages.add(new CompilerMessage(-1, -1, true, "unexpected modification")); compare(file.getName(), expected, writer.toString(), messages, params.printErrors(), sourceDirectives_.isSkipCompareContent() || expected.isSkipCompareContent()); } }; } protected abstract boolean transformCode(Collection messages, StringWriter result, File file, String encoding, Map formatPreferences) throws Throwable; protected String readFile(File file) throws IOException { BufferedReader reader; try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { return null; } StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); result.append("\n"); } reader.close(); return result.toString(); } private static File findPlaceToDumpActualFiles() { String location = System.getProperty("lombok.tests.dump_actual_files"); if (location != null) { File dumpActualFilesHere = new File(location); dumpActualFilesHere.mkdirs(); return dumpActualFilesHere; } return null; } private static void dumpToFile(File file, String content) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { fos.write(content.getBytes("UTF-8")); } finally { fos.close(); } } private static void dumpToFile(File file, Collection content) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { for (CompilerMessage message : content) { fos.write(CompilerMessageMatcher.asCompilerMessageMatcher(message).toString().getBytes("UTF-8")); fos.write('\n'); } } finally { fos.close(); } } private void compare(String name, LombokTestSource expected, String actualFile, LinkedHashSet actualMessages, boolean printErrors, boolean skipCompareContent) throws Throwable { if (!skipCompareContent) try { compareContent(name, expected.getContent(), actualFile); } catch (Throwable e) { if (printErrors) { System.out.println("***** " + name + " *****"); System.out.println(e.getMessage()); System.out.println("**** Expected ******"); System.out.println(expected.getContent()); System.out.println("**** Actual ******"); System.out.println(actualFile); if (actualMessages != null && !actualMessages.isEmpty()) { System.out.println("**** Actual Errors *****"); for (CompilerMessage actualMessage : actualMessages) { System.out.println(actualMessage); } } System.out.println("*******************"); } if (dumpActualFilesHere != null) { dumpToFile(new File(dumpActualFilesHere, name), actualFile); } throw e; } try { compareMessages(name, expected.getMessages(), actualMessages); } catch (Throwable e) { if (printErrors) { System.out.println("***** " + name + " *****"); System.out.println(e.getMessage()); System.out.println("**** Expected ******"); for (CompilerMessageMatcher expectedMessage : expected.getMessages()) { System.out.println(expectedMessage); } System.out.println("**** Actual ******"); for (CompilerMessage actualMessage : actualMessages) { System.out.println(actualMessage); } System.out.println("*******************"); } if (dumpActualFilesHere != null) { dumpToFile(new File(dumpActualFilesHere, name + ".messages"), actualMessages); } throw e; } } @SuppressWarnings("null") /* eclipse bug; it falsely thinks stuffAc will always be null or some such hogwash. */ private static void compareMessages(String name, LombokImmutableList expected, LinkedHashSet actual) { Iterator expectedIterator = expected.iterator(); Iterator actualIterator = actual.iterator(); CompilerMessage stuffAc = null; while (true) { boolean exHasNext = expectedIterator.hasNext(); boolean acHasNext = stuffAc != null || actualIterator.hasNext(); if (!exHasNext && !acHasNext) break; if (exHasNext && acHasNext) { CompilerMessageMatcher cmm = expectedIterator.next(); CompilerMessage cm = stuffAc == null ? actualIterator.next() : stuffAc; if (cmm.matches(cm)) continue; if (cmm.isOptional()) stuffAc = cm; fail(String.format("[%s] Expected message '%s' but got message '%s'", name, cmm, cm)); throw new AssertionError("fail should have aborted already."); } while (expectedIterator.hasNext()) { CompilerMessageMatcher next = expectedIterator.next(); if (next.isOptional()) continue; fail(String.format("[%s] Expected message '%s' but ran out of actual messages", name, next)); } if (acHasNext) fail(String.format("[%s] Unexpected message: %s", name, actualIterator.next())); break; } } private static void compareContent(String name, String expectedFile, String actualFile) { String[] expectedLines = expectedFile.split("(\\r?\\n)"); String[] actualLines = actualFile.split("(\\r?\\n)"); for (int i = 0; i < expectedLines.length; i++) { if (expectedLines[i].isEmpty() || expectedLines[i].startsWith("//")) expectedLines[i] = ""; else break; } for (int i = 0; i < actualLines.length; i++) { if (actualLines[i].isEmpty() || actualLines[i].startsWith("//")) actualLines[i] = ""; else break; } expectedLines = removeBlanks(expectedLines); actualLines = removeBlanks(actualLines); int size = Math.min(expectedLines.length, actualLines.length); if (size == 0 && expectedLines.length + actualLines.length > 0) { Assert.fail("Missing / empty expected file."); } for (int i = 0; i < size; i++) { String expected = trimRight(expectedLines[i]); String actual = trimRight(actualLines[i]); assertEquals(String.format("Difference in %s on line %d", name, i + 1), expected, actual); } if (expectedLines.length > actualLines.length) { fail(String.format("Missing line %d in generated %s: %s", size + 1, name, expectedLines[size])); } if (expectedLines.length < actualLines.length) { fail(String.format("Extra line %d in generated %s: %s", size + 1, name, actualLines[size])); } } private static String trimRight(String in) { int endIdx = in.length() - 1; while (endIdx > -1 && Character.isWhitespace(in.charAt(endIdx))) { endIdx--; } return in.substring(0, endIdx); } private static String[] removeBlanks(String[] in) { List out = new ArrayList(); for (String s : in) { if (!s.trim().isEmpty()) out.add(s); } return out.toArray(new String[0]); } } lombok-1.16.18/test/core/src/lombok/CompilerMessageMatcher.java000066400000000000000000000077131312655740700244040ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import lombok.javac.CapturingDiagnosticListener.CompilerMessage; public class CompilerMessageMatcher { /** Line Number (starting at 1) */ private final List lineNumbers = new ArrayList(); private final List> messages = new ArrayList>(); private boolean optional; private CompilerMessageMatcher() {} public boolean isOptional() { return optional; } public static CompilerMessageMatcher asCompilerMessageMatcher(CompilerMessage message) { CompilerMessageMatcher cmm = new CompilerMessageMatcher(); cmm.lineNumbers.add((int) message.getLine()); cmm.messages.add(Arrays.asList(message.getMessage().split("\\s+"))); return cmm; } @Override public String toString() { StringBuilder out = new StringBuilder(); for (int i = 0; i < lineNumbers.size(); i++) { out.append(lineNumbers.get(i)).append(" "); for (String part : messages.get(i)) out.append(part).append(" "); if (out.length() > 0) out.setLength(out.length() - 1); out.append(" |||| "); } if (out.length() > 0) out.setLength(out.length() - 6); return out.toString(); } public boolean matches(CompilerMessage message) { outer: for (int i = 0; i < lineNumbers.size(); i++) { if (message.getLine() != lineNumbers.get(i)) continue; for (String token : messages.get(i)) { if (!message.getMessage().contains(token)) continue outer; } return true; } return false; } public static List readAll(InputStream rawIn) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(rawIn, "UTF-8")); List out = new ArrayList(); for (String line = in.readLine(); line != null; line = in.readLine()) { CompilerMessageMatcher cmm = read(line); if (cmm != null) out.add(cmm); } return out; } private static final Pattern PATTERN = Pattern.compile("^(\\d+) (.*)$"); private static CompilerMessageMatcher read(String line) { line = line.trim(); if (line.isEmpty()) return null; boolean optional = false; if (line.startsWith("OPTIONAL ")) { line = line.substring(9); optional = true; } String[] parts = line.split("\\s*\\|\\|\\|\\|\\s*"); CompilerMessageMatcher cmm = new CompilerMessageMatcher(); cmm.optional = optional; for (String part : parts) { Matcher m = PATTERN.matcher(part); if (!m.matches()) throw new IllegalArgumentException("Typo in test file: " + line); cmm.lineNumbers.add(Integer.parseInt(m.group(1))); cmm.messages.add(Arrays.asList(m.group(2).split("\\s+"))); } return cmm; } } lombok-1.16.18/test/core/src/lombok/DirectoryRunner.java000066400000000000000000000122011312655740700231430ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Map; import java.util.TreeMap; import lombok.eclipse.Eclipse; import lombok.javac.Javac; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; public class DirectoryRunner extends Runner { public enum Compiler { DELOMBOK { @Override public int getVersion() { return Javac.getJavaCompilerVersion(); } }, JAVAC { @Override public int getVersion() { return DELOMBOK.getVersion(); } }, ECJ { @Override public int getVersion() { return Eclipse.getEcjCompilerVersion(); } }; public abstract int getVersion(); } public static abstract class TestParams { public abstract Compiler getCompiler(); public abstract boolean printErrors(); public abstract File getBeforeDirectory(); public abstract File getAfterDirectory(); public abstract File getMessagesDirectory(); /** Version of the JDK dialect that the compiler can understand; for example, if you return '7', you should know what try-with-resources is. */ public int getVersion() { return getCompiler().getVersion(); } public boolean accept(File file) { return true; } public abstract boolean expectChanges(); } private static final FileFilter JAVA_FILE_FILTER = new FileFilter() { @Override public boolean accept(File file) { return file.isFile() && file.getName().endsWith(".java"); } }; private final Description description; private final Map tests = new TreeMap(); private final Throwable failure; private final TestParams params; public DirectoryRunner(Class testClass) throws Exception { description = Description.createSuiteDescription(testClass); this.params = (TestParams) testClass.newInstance(); Throwable error = null; try { addTests(testClass); } catch (Throwable t) { error = t; } this.failure = error; } private void addTests(Class testClass) throws Exception { for (File file : params.getBeforeDirectory().listFiles(JAVA_FILE_FILTER)) { if (!params.accept(file)) continue; Description testDescription = Description.createTestDescription(testClass, file.getName()); description.addChild(testDescription); tests.put(file.getName(), testDescription); } } @Override public Description getDescription() { return description; } @Override public void run(RunNotifier notifier) { if (failure != null) { reportInitializationFailure(notifier, description, failure); return; } for (Map.Entry entry : tests.entrySet()) { Description testDescription = entry.getValue(); FileTester tester; try { tester = createTester(entry.getKey()); } catch (IOException e) { reportInitializationFailure(notifier, testDescription, e); continue; } if (tester == null) { notifier.fireTestIgnored(testDescription); continue; } notifier.fireTestStarted(testDescription); try { tester.runTest(); } catch (Throwable t) { notifier.fireTestFailure(new Failure(testDescription, t)); } notifier.fireTestFinished(testDescription); } } private void reportInitializationFailure(RunNotifier notifier, Description description, Throwable throwable) { notifier.fireTestStarted(description); notifier.fireTestFailure(new Failure(description, throwable)); notifier.fireTestFinished(description); } private FileTester createTester(String fileName) throws IOException { File file = new File(params.getBeforeDirectory(), fileName); switch (params.getCompiler()) { case DELOMBOK: return new RunTestsViaDelombok().createTester(params, file, "javac", params.getVersion()); case ECJ: return new RunTestsViaEcj().createTester(params, file, "ecj", params.getVersion()); default: case JAVAC: throw new UnsupportedOperationException(); } } public interface FileTester { void runTest() throws Throwable; } } lombok-1.16.18/test/core/src/lombok/LombokTestSource.java000066400000000000000000000261371312655740700232660ustar00rootroot00000000000000/* * Copyright (C) 2014-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Assert; import lombok.core.LombokImmutableList; import lombok.core.configuration.BubblingConfigurationResolver; import lombok.core.configuration.ConfigurationProblemReporter; import lombok.core.configuration.ConfigurationResolver; import lombok.core.configuration.StringConfigurationSource; public class LombokTestSource { private final File file; private final String content; private final LombokImmutableList messages; private final Map formatPreferences; private final boolean ignore; private final boolean skipCompareContent; private final boolean unchanged; private final int versionLowerLimit, versionUpperLimit; private final ConfigurationResolver configuration; private final String specifiedEncoding; private final List platforms; public boolean runOnPlatform(String platform) { if (platforms == null || platforms.isEmpty()) return true; for (String pl : platforms) if (pl.equalsIgnoreCase(platform)) return true; return false; } public boolean versionWithinLimit(int version) { return version >= versionLowerLimit && version <= versionUpperLimit; } public File getFile() { return file; } public String getContent() { return content; } public LombokImmutableList getMessages() { return messages; } public boolean isIgnore() { return ignore; } public boolean forceUnchanged() { return unchanged; } public boolean isSkipCompareContent() { return skipCompareContent; } public String getSpecifiedEncoding() { return specifiedEncoding; } public ConfigurationResolver getConfiguration() { return configuration; } public Map getFormatPreferences() { return formatPreferences; } private static final Pattern VERSION_STYLE_1 = Pattern.compile("^(\\d+)$"); private static final Pattern VERSION_STYLE_2 = Pattern.compile("^\\:(\\d+)$"); private static final Pattern VERSION_STYLE_3 = Pattern.compile("^(\\d+):$"); private static final Pattern VERSION_STYLE_4 = Pattern.compile("^(\\d+):(\\d+)$"); private int[] parseVersionLimit(String spec) { /* Single version: '5' */ { Matcher m = VERSION_STYLE_1.matcher(spec); if (m.matches()) { int v = Integer.parseInt(m.group(1)); return new int[] {v, v}; } } /* Upper bound: ':5' (inclusive) */ { Matcher m = VERSION_STYLE_2.matcher(spec); if (m.matches()) return new int[] {0, Integer.parseInt(m.group(1))}; } /* Lower bound '5:' (inclusive) */ { Matcher m = VERSION_STYLE_3.matcher(spec); if (m.matches()) return new int[] {Integer.parseInt(m.group(1)), Integer.MAX_VALUE}; } /* Range '7:8' (inclusive) */ { Matcher m = VERSION_STYLE_4.matcher(spec); if (m.matches()) return new int[] {Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2))}; } return null; } private static final Pattern IGNORE_PATTERN = Pattern.compile("^\\s*ignore\\s*(?:[-:].*)?$", Pattern.CASE_INSENSITIVE); private static final Pattern UNCHANGED_PATTERN = Pattern.compile("^\\s*unchanged\\s*(?:[-:].*)?$", Pattern.CASE_INSENSITIVE); private static final Pattern SKIP_COMPARE_CONTENT_PATTERN = Pattern.compile("^\\s*skip[- ]?compare[- ]?contents?\\s*(?:[-:].*)?$", Pattern.CASE_INSENSITIVE); private LombokTestSource(File file, String content, List messages, List directives) { this.file = file; this.content = content; this.messages = messages == null ? LombokImmutableList.of() : LombokImmutableList.copyOf(messages); StringBuilder conf = new StringBuilder(); int versionLower = 0; int versionUpper = Integer.MAX_VALUE; boolean ignore = false; boolean skipCompareContent = false; boolean unchanged = false; String encoding = null; Map formats = new HashMap(); String[] platformLimit = null; for (String directive : directives) { directive = directive.trim(); String lc = directive.toLowerCase(); if (IGNORE_PATTERN.matcher(directive).matches()) { ignore = true; continue; } if (UNCHANGED_PATTERN.matcher(directive).matches()) { unchanged = true; continue; } if (SKIP_COMPARE_CONTENT_PATTERN.matcher(directive).matches()) { skipCompareContent = true; continue; } if (lc.startsWith("platform ")) { String platformDesc = lc.substring("platform ".length()); int idx = platformDesc.indexOf(':'); if (idx != -1) platformDesc = platformDesc.substring(0, idx).trim(); platformLimit = platformDesc.split("\\s*,\\s*"); continue; } if (lc.startsWith("version ")) { int[] limits = parseVersionLimit(lc.substring(7).trim()); if (limits == null) { Assert.fail("Directive line \"" + directive + "\" in '" + file.getAbsolutePath() + "' invalid: version must be followed by a single integer."); throw new RuntimeException(); } versionLower = limits[0]; versionUpper = limits[1]; continue; } if (lc.startsWith("conf:")) { String confLine = directive.substring(5).trim(); conf.append(confLine).append("\n"); continue; } if (lc.startsWith("encoding:")) { encoding = directive.substring(9).trim(); continue; } if (lc.startsWith("format:")) { String formatLine = directive.substring(7).trim(); int idx = formatLine.indexOf('='); if (idx == -1) throw new IllegalArgumentException("To add a format directive, use: \"//FORMAT: javaLangAsFQN = skip\""); String key = formatLine.substring(0, idx).trim(); String value = formatLine.substring(idx + 1).trim(); formats.put(key.toLowerCase(), value); continue; } if (lc.startsWith("issue ")) continue; Assert.fail("Directive line \"" + directive + "\" in '" + file.getAbsolutePath() + "' invalid: unrecognized directive."); throw new RuntimeException(); } this.specifiedEncoding = encoding; this.versionLowerLimit = versionLower; this.versionUpperLimit = versionUpper; this.ignore = ignore; this.skipCompareContent = skipCompareContent; this.unchanged = unchanged; this.platforms = platformLimit == null ? null : Arrays.asList(platformLimit); ConfigurationProblemReporter reporter = new ConfigurationProblemReporter() { @Override public void report(String sourceDescription, String problem, int lineNumber, CharSequence line) { Assert.fail("Problem on directive line: " + problem + " at conf line #" + lineNumber + " (" + line + ")"); } }; this.configuration = new BubblingConfigurationResolver(Collections.singleton(StringConfigurationSource.forString(conf, reporter, file.getAbsolutePath()))); this.formatPreferences = Collections.unmodifiableMap(formats); } public static LombokTestSource readDirectives(File file) throws IOException { List directives = new ArrayList(); { InputStream rawIn = new FileInputStream(file); try { BufferedReader in = new BufferedReader(new InputStreamReader(rawIn, "UTF-8")); try { for (String i = in.readLine(); i != null; i = in.readLine()) { if (i.isEmpty()) continue; if (i.startsWith("//")) { directives.add(i.substring(2)); } else { break; } } } finally { in.close(); } } finally { rawIn.close(); } } return new LombokTestSource(file, "", null, directives); } public static LombokTestSource read(File sourceFolder, File messagesFolder, String fileName) throws IOException { return read0(sourceFolder, messagesFolder, fileName, "UTF-8"); } private static LombokTestSource read0(File sourceFolder, File messagesFolder, String fileName, String encoding) throws IOException { StringBuilder content = null; List directives = new ArrayList(); File sourceFile = new File(sourceFolder, fileName); if (sourceFile.exists()) { InputStream rawIn = new FileInputStream(sourceFile); try { BufferedReader in = new BufferedReader(new InputStreamReader(rawIn, encoding)); try { for (String i = in.readLine(); i != null; i = in.readLine()) { if (content != null) { content.append(i).append("\n"); continue; } if (i.isEmpty()) continue; if (i.startsWith("//")) { directives.add(i.substring(2)); } else { content = new StringBuilder(); content.append(i).append("\n"); } } } finally { in.close(); } } finally { rawIn.close(); } } if (content == null) content = new StringBuilder(); List messages = null; if (messagesFolder != null) { File messagesFile = new File(messagesFolder, fileName + ".messages"); try { InputStream rawIn = new FileInputStream(messagesFile); try { messages = CompilerMessageMatcher.readAll(rawIn); } finally { rawIn.close(); } } catch (FileNotFoundException e) { messages = null; } } LombokTestSource source = new LombokTestSource(sourceFile, content.toString(), messages, directives); String specifiedEncoding = source.getSpecifiedEncoding(); // The source file has an 'encoding' header to test encoding issues. Of course, reading the encoding header // requires knowing the encoding of the file first. In practice we get away with it, because UTF-8 and US-ASCII are compatible enough. // The fix is therefore to read in as UTF-8 initially, and if the file requests that it should be read as another encoding, toss it all // and reread that way. if (specifiedEncoding == null || specifiedEncoding.equalsIgnoreCase(encoding)) return source; return read0(sourceFolder, messagesFolder, fileName, specifiedEncoding); } } lombok-1.16.18/test/core/src/lombok/RunAllTests.java000066400000000000000000000027401312655740700222340ustar00rootroot00000000000000/* * Copyright (C) 2011-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({lombok.transform.RunTransformTests.class, lombok.bytecode.RunBytecodeTests.class, lombok.core.configuration.RunConfigurationTests.class, lombok.core.RunCoreTests.class}) public class RunAllTests { } lombok-1.16.18/test/core/src/lombok/RunTestsViaDelombok.java000066400000000000000000000060221312655740700237150ustar00rootroot00000000000000/* * Copyright (C) 2009-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.Locale; import java.util.Map; import lombok.delombok.Delombok; import lombok.javac.CapturingDiagnosticListener; import lombok.javac.CapturingDiagnosticListener.CompilerMessage; public class RunTestsViaDelombok extends AbstractRunTests { private Delombok delombok = new Delombok(); @Override public boolean transformCode(Collection messages, StringWriter result, final File file, String encoding, Map formatPreferences) throws Throwable { delombok.setVerbose(true); ChangedChecker cc = new ChangedChecker(); delombok.setFeedback(cc.feedback); delombok.setForceProcess(true); delombok.setCharset(encoding == null ? "UTF-8" : encoding); delombok.setFormatPreferences(formatPreferences); delombok.setDiagnosticsListener(new CapturingDiagnosticListener(file, messages)); delombok.addFile(file.getAbsoluteFile().getParentFile(), file.getName()); delombok.setSourcepath(file.getAbsoluteFile().getParent()); String bcp = System.getProperty("delombok.bootclasspath"); if (bcp != null) delombok.setBootclasspath(bcp); delombok.setWriter(result); Locale originalLocale = Locale.getDefault(); try { Locale.setDefault(Locale.ENGLISH); delombok.delombok(); return cc.isChanged(); } finally { Locale.setDefault(originalLocale); } } static class ChangedChecker { private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); private final PrintStream feedback; ChangedChecker() throws UnsupportedEncodingException { feedback = new PrintStream(bytes, true, "UTF-8"); } boolean isChanged() throws UnsupportedEncodingException { feedback.flush(); return bytes.toString("UTF-8").endsWith("[delomboked]\n"); } } } lombok-1.16.18/test/core/src/lombok/RunTestsViaEcj.java000066400000000000000000000154031312655740700226650ustar00rootroot00000000000000/* * Copyright (C) 2010-2014 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.io.File; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import lombok.eclipse.Eclipse; import lombok.javac.CapturingDiagnosticListener.CompilerMessage; import org.eclipse.jdt.core.compiler.CategorizedProblem; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.Compiler; import org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; public class RunTestsViaEcj extends AbstractRunTests { protected CompilerOptions ecjCompilerOptions() { CompilerOptions options = new CompilerOptions(); options.complianceLevel = Eclipse.getLatestEcjCompilerVersionConstant(); options.sourceLevel = Eclipse.getLatestEcjCompilerVersionConstant(); options.targetJDK = Eclipse.getLatestEcjCompilerVersionConstant(); options.docCommentSupport = false; options.parseLiteralExpressionsAsConstants = true; options.inlineJsrBytecode = true; options.reportUnusedDeclaredThrownExceptionExemptExceptionAndThrowable = false; options.reportUnusedDeclaredThrownExceptionIncludeDocCommentReference = false; options.reportUnusedDeclaredThrownExceptionWhenOverriding = false; options.reportUnusedParameterIncludeDocCommentReference = false; options.reportUnusedParameterWhenImplementingAbstract = false; options.reportUnusedParameterWhenOverridingConcrete = false; options.reportDeadCodeInTrivialIfStatement = false; options.generateClassFiles = false; Map warnings = new HashMap(); warnings.put(CompilerOptions.OPTION_ReportUnusedLocal, "ignore"); warnings.put(CompilerOptions.OPTION_ReportUnusedLabel, "ignore"); warnings.put(CompilerOptions.OPTION_ReportUnusedImport, "ignore"); warnings.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, "ignore"); warnings.put(CompilerOptions.OPTION_Source, "1." + Eclipse.getEcjCompilerVersion()); options.set(warnings); return options; } protected IErrorHandlingPolicy ecjErrorHandlingPolicy() { return new IErrorHandlingPolicy() { public boolean stopOnFirstError() { return true; } public boolean proceedOnErrors() { return false; } @SuppressWarnings("all") // Added to the interface in later ecj version. public boolean ignoreAllErrors() { return false; } }; } @Override public boolean transformCode(Collection messages, StringWriter result, File file, String encoding, Map formatPreferences) throws Throwable { final AtomicReference compilationResult_ = new AtomicReference(); final AtomicReference compilationUnit_ = new AtomicReference(); ICompilerRequestor bitbucketRequestor = new ICompilerRequestor() { @Override public void acceptResult(CompilationResult result) { compilationResult_.set(result); } }; String source = readFile(file); final CompilationUnit sourceUnit = new CompilationUnit(source.toCharArray(), file.getName(), encoding == null ? "UTF-8" : encoding); Compiler ecjCompiler = new Compiler(createFileSystem(file), ecjErrorHandlingPolicy(), ecjCompilerOptions(), bitbucketRequestor, new DefaultProblemFactory(Locale.ENGLISH)) { @Override protected synchronized void addCompilationUnit(ICompilationUnit inUnit, CompilationUnitDeclaration parsedUnit) { if (inUnit == sourceUnit) compilationUnit_.set(parsedUnit); super.addCompilationUnit(inUnit, parsedUnit); } }; ecjCompiler.compile(new ICompilationUnit[] {sourceUnit}); CompilationResult compilationResult = compilationResult_.get(); CategorizedProblem[] problems = compilationResult.getAllProblems(); if (problems != null) for (CategorizedProblem p : problems) { messages.add(new CompilerMessage(p.getSourceLineNumber(), p.getSourceStart(), p.isError(), p.getMessage())); } CompilationUnitDeclaration cud = compilationUnit_.get(); if (cud == null) result.append("---- NO CompilationUnit provided by ecj ----"); else result.append(cud.toString()); return true; } private FileSystem createFileSystem(File file) { List classpath = new ArrayList(); classpath.addAll(Arrays.asList(System.getProperty("sun.boot.class.path").split(File.pathSeparator))); for (Iterator i = classpath.iterator(); i.hasNext();) { if (FileSystem.getClasspath(i.next(), "UTF-8", null) == null) { i.remove(); } } classpath.add("bin"); classpath.add("dist/lombok.jar"); classpath.add("lib/test/commons-logging-commons-logging.jar"); classpath.add("lib/test/org.slf4j-slf4j-api.jar"); classpath.add("lib/test/org.slf4j-slf4j-ext.jar"); classpath.add("lib/test/log4j-log4j.jar"); classpath.add("lib/test/org.apache.logging.log4j-log4j-api.jar"); classpath.add("lib/test/org.jboss.logging-jboss-logging.jar"); classpath.add("lib/test/com.google.guava-guava.jar"); classpath.add("lib/test/com.google.code.findbugs-findbugs.jar"); return new FileSystem(classpath.toArray(new String[0]), new String[] {file.getAbsolutePath()}, "UTF-8"); } } lombok-1.16.18/test/core/src/lombok/core/000077500000000000000000000000001312655740700200765ustar00rootroot00000000000000lombok-1.16.18/test/core/src/lombok/core/RunCoreTests.java000066400000000000000000000025151312655740700233440ustar00rootroot00000000000000/* * Copyright (C) 2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({TestSingulars.class}) public class RunCoreTests { } lombok-1.16.18/test/core/src/lombok/core/TestSingulars.java000066400000000000000000000050121312655740700235460ustar00rootroot00000000000000/* * Copyright (C) 2015-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import static lombok.core.handlers.Singulars.autoSingularize; import static org.junit.Assert.*; import org.junit.Test; public class TestSingulars { @Test public void testSingulars() { assertNull("axes", autoSingularize("axes")); assertEquals("adjective", autoSingularize("adjectives")); assertEquals("bus", autoSingularize("buses")); assertEquals("octopus", autoSingularize("octopodes")); assertNull("octopi", autoSingularize("octopi")); assertEquals("elf", autoSingularize("elves")); assertEquals("jack", autoSingularize("jacks")); assertEquals("colloquy", autoSingularize("colloquies")); assertNull("series", autoSingularize("series")); assertEquals("man", autoSingularize("men")); assertNull("highwaymen", autoSingularize("highwaymen")); assertEquals("caveMan", autoSingularize("caveMen")); assertNull("jackss", autoSingularize("jackss")); assertNull("virus", autoSingularize("virus")); assertEquals("quiz", autoSingularize("quizzes")); assertEquals("database", autoSingularize("databases")); assertEquals("dataBase", autoSingularize("dataBases")); assertEquals("Query", autoSingularize("Queries")); assertEquals("Movie", autoSingularize("Movies")); assertEquals("cafe", autoSingularize("cafes")); assertNull("caves", autoSingularize("caves")); assertEquals("leaf", autoSingularize("leaves")); assertEquals("autosave", autoSingularize("autosaves")); } } lombok-1.16.18/test/ecj/000077500000000000000000000000001312655740700147055ustar00rootroot00000000000000lombok-1.16.18/test/ecj/.gitignore000066400000000000000000000000071312655740700166720ustar00rootroot00000000000000*.classlombok-1.16.18/test/ecj/SimpleTest.java000066400000000000000000000003041312655740700176360ustar00rootroot00000000000000@lombok.Data public class SimpleTest { private final String test; private final int foo; public String bar() { int val = getFoo() + 5; return new SimpleTest("", 0).toString() + val; } } lombok-1.16.18/test/pretty/000077500000000000000000000000001312655740700154735ustar00rootroot00000000000000lombok-1.16.18/test/pretty/resource/000077500000000000000000000000001312655740700173225ustar00rootroot00000000000000lombok-1.16.18/test/pretty/resource/after/000077500000000000000000000000001312655740700204235ustar00rootroot00000000000000lombok-1.16.18/test/pretty/resource/after/Annotation.java000066400000000000000000000004721312655740700234030ustar00rootroot00000000000000@SuppressWarnings("all") class Annotation { @Override public String toString() { return super.toString(); } public void method(@SuppressWarnings("unused") int x) { } public void method2(@SuppressWarnings({"unused"}) int y) { } public void method3(@SuppressWarnings({"unused", "unchecked"}) int z) { } } lombok-1.16.18/test/pretty/resource/after/Cast.java000066400000000000000000000002131312655740700221540ustar00rootroot00000000000000import java.util.*; public class Cast { public void test(List list) { RandomAccess r = (/*before*/ RandomAccess /*after*/) list; } }lombok-1.16.18/test/pretty/resource/after/CastWithIntersection.java000066400000000000000000000002351312655740700254030ustar00rootroot00000000000000import java.util.*; public class CastWithIntersection { public void test(List list) { RandomAccess r = (RandomAccess & java.io.Serializable) list; } }lombok-1.16.18/test/pretty/resource/after/DefaultMethod.java000066400000000000000000000002001312655740700240030ustar00rootroot00000000000000interface DefaultMethod { int size(); default boolean isEmpty() { return size() == 0; } strictfp default void run() { } }lombok-1.16.18/test/pretty/resource/after/Enum.java000066400000000000000000000007261312655740700221770ustar00rootroot00000000000000enum Ranks { CLUBS, HEARTS, DIAMONDS, SPADES; } enum Complex { RED("ff0000"), GREEN("00ff00"), BLUE("0000f"); private final String webColour; Complex(String webColour) { this.webColour = webColour; } public String getWebColour() { return webColour; } } enum Complexer { RED { public void foo() { } public void bar() { } }, GREEN("foo") { public void foo() { } }; public abstract void foo(); Complexer(String colour) { } Complexer() { } } lombok-1.16.18/test/pretty/resource/after/ExoticJava.java000066400000000000000000000020551312655740700233250ustar00rootroot00000000000000import static java.lang.String.*; import java.io.*; class ExoticJava { public ExoticJava(T genericsInConstructor, V genericsInType) { System.out.println(new ExoticJava("Hello", 5)); } public void test() { int x = 5; int[] y = {10}; ; class MethodLocal implements Serializable, java.util.RandomAccess { @SuppressWarnings({"unchecked", "rawtypes"}) public final strictfp int foo() { int x = super.hashCode(); x <<= 5; do { x <<= 5; } while (Boolean.FALSE); return x; } } for (int i = 10, j[] = {20}; i < 5; i++, j[0]++) { String z = ""; try ( PrintWriter pw = new PrintWriter(System.out); PrintWriter p2 = new PrintWriter(System.out)) { pw.println(); } finally { synchronized (z) { System.out.println(z); } } if ((y == null)) { } if (((y == null))) ; { ; } java.util.List list = new java.util.ArrayList<>(); assert Boolean.TRUE : "That\'s weird"; double d = -1.8E12; long loooong = 305441741; int octal = 87; } } }lombok-1.16.18/test/pretty/resource/after/ForEach.java000066400000000000000000000002221312655740700225710ustar00rootroot00000000000000import java.util.Arrays; public class ForEach { { for (int i : Arrays.asList(1, 2, 3)) { System.out.println(i); // Do something } } } lombok-1.16.18/test/pretty/resource/after/ForLoop.java000066400000000000000000000004321312655740700226450ustar00rootroot00000000000000public class ForLoop { public static void main(String[] args) { // before loop for (int i = 0; i < 10; i++) { // start of block System.out.println(i); // end of block } // after loop } { int i; for (i = 0; i < 10; i++) { System.out.println(i); } } } lombok-1.16.18/test/pretty/resource/after/Interfaces.java000066400000000000000000000002261312655740700233510ustar00rootroot00000000000000@SuppressWarnings("all") interface Interfaces { enum Ranks { CLUBS, HEARTS, DIAMONDS, SPADES; } int x = 10; void y(); int a = 20; void b(); } lombok-1.16.18/test/pretty/resource/after/Lambda.java000066400000000000000000000012221312655740700224430ustar00rootroot00000000000000public class Lambda { Runnable r = () -> System.out.println(); java.util.Comparator c1 = (a, b) -> a - b; java.util.Comparator c2 = (Integer a, Integer b) -> { return a - b; }; java.util.function.Function fnc = (String c) -> c; void testLambdaInArgsList(String name, java.util.function.Function f) { } void testLambdaInArgsList2(java.util.function.Function f, String name) { } void test() { testLambdaInArgsList("hello", (String c) -> c); testLambdaInArgsList("hello", c -> c); testLambdaInArgsList2((String c) -> c, "hello"); testLambdaInArgsList2(c -> c, "hello"); } } lombok-1.16.18/test/pretty/resource/after/MethodReference.java000066400000000000000000000015411312655740700243260ustar00rootroot00000000000000class MethodReference { public MethodReference() { } public MethodReference(T in) { } public void simpleInstanceReference() { Runnable r = this::foo; } public void simpleConstructorReference() { Runnable r = MethodReference::new; } public void simpleStaticReference() { Runnable r = MethodReference::staticFoo; } public void generifiedStaticReference() { StringConverter sc = MethodReference::generifiedStaticFoo; } public void generifiedConstructorReference() { FooConverter fc = MethodReference::new; } public void foo() { } private static void staticFoo() { } public static T generifiedStaticFoo(T foo) { return foo; } @FunctionalInterface public interface StringConverter { String hello(String x); } @FunctionalInterface public interface FooConverter { K hello(String x); } }lombok-1.16.18/test/pretty/resource/after/MultiCatch.java000066400000000000000000000002621312655740700233230ustar00rootroot00000000000000public class MultiCatch { public void test() { try { System.out.println(); } catch (IllegalArgumentException | IllegalStateException e) { e.printStackTrace(); } } }lombok-1.16.18/test/pretty/resource/after/TryWithResources.java000066400000000000000000000002351312655740700245730ustar00rootroot00000000000000//version 7: import java.io.PrintWriter; public class TryWithResources { { try (PrintWriter pw = new PrintWriter(System.out)) { pw.println(); } } } lombok-1.16.18/test/pretty/resource/after/TypeAnnotations.java000066400000000000000000000011031312655740700244200ustar00rootroot00000000000000import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.util.List; import java.util.Map; public class TypeAnnotations { @Target({ElementType.TYPE_USE, ElementType.LOCAL_VARIABLE}) @interface Foo { } @Target(ElementType.TYPE_USE) @interface Bar { } public List<@Foo String> test(@Foo String param) { @Bar String local = "bar"; @Foo java.io.@Foo File[] array = {}; return new java.util.@Foo ArrayList(); } public <@Foo T extends java.lang.@Foo Number> T test2(@Bar String... varargs) { return null; } } lombok-1.16.18/test/pretty/resource/after/WithComments.java000066400000000000000000000002121312655740700237020ustar00rootroot00000000000000/* Try out pretty comments. */ package test; // Cool Comments public class WithComments { // Also inside the body // On start of line }lombok-1.16.18/test/pretty/resource/before/000077500000000000000000000000001312655740700205645ustar00rootroot00000000000000lombok-1.16.18/test/pretty/resource/before/Annotation.java000066400000000000000000000005001312655740700235340ustar00rootroot00000000000000@SuppressWarnings("all") class Annotation { @Override public String toString() { return super.toString(); } public void method(@SuppressWarnings("unused") int x) { } public void method2(@SuppressWarnings(value={"unused"}) int y) { } public void method3(@SuppressWarnings({"unused", "unchecked"}) int z) { } } lombok-1.16.18/test/pretty/resource/before/Cast.java000066400000000000000000000002131312655740700223150ustar00rootroot00000000000000import java.util.*; public class Cast { public void test(List list) { RandomAccess r = (/*before*/ RandomAccess /*after*/) list; } }lombok-1.16.18/test/pretty/resource/before/CastWithIntersection.java000066400000000000000000000002531312655740700255440ustar00rootroot00000000000000// version 8: import java.util.*; public class CastWithIntersection { public void test(List list) { RandomAccess r = (RandomAccess & java.io.Serializable) list; } }lombok-1.16.18/test/pretty/resource/before/DefaultMethod.java000066400000000000000000000002221312655740700241500ustar00rootroot00000000000000// version 8: interface DefaultMethod { int size(); default boolean isEmpty() { return size() == 0; } default strictfp void run() { } }lombok-1.16.18/test/pretty/resource/before/Enum.java000066400000000000000000000007371312655740700223420ustar00rootroot00000000000000enum Ranks { CLUBS, HEARTS, DIAMONDS, SPADES;; } enum Complex { RED("ff0000"), GREEN("00ff00"), BLUE("0000f"); private final String webColour; Complex(String webColour) { this.webColour = webColour; } public String getWebColour() { return webColour; } } enum Complexer { RED { public void foo() { } public void bar() { } }, GREEN("foo") { public void foo() { } }; public abstract void foo(); Complexer(String colour) { } Complexer() { } } lombok-1.16.18/test/pretty/resource/before/ExoticJava.java000066400000000000000000000020571312655740700234700ustar00rootroot00000000000000//VERSION 7: import static java.lang.String.*; import java.io.*; class ExoticJava { public ExoticJava(T genericsInConstructor, V genericsInType) { System.out.println(new ExoticJava("Hello", 5)); } ;;;; public void test() { int x = 5, y[] = {10}; ; class MethodLocal implements Serializable, java.util.RandomAccess { @SuppressWarnings({"unchecked", "rawtypes"}) strictfp public final int foo() { int x = super.hashCode(); x <<= 5; do { x <<= 5; } while (Boolean.FALSE); return x; } } for (int i = 10, j[] = {20}; i < 5; i++, j[0]++) { String z = ""; try (PrintWriter pw = new PrintWriter(System.out); PrintWriter p2 = new PrintWriter(System.out)) { pw.println(); } finally { synchronized (z) { System.out.println(z); } } if ((y == null)) {} if (((y == null))) ; {;} java.util.List list = new java.util.ArrayList<>(); assert Boolean.TRUE : "That's weird"; double d = -1.8e12; long loooong = 0x1234ABCD; int octal = 0127; } } }lombok-1.16.18/test/pretty/resource/before/ForEach.java000066400000000000000000000002221312655740700227320ustar00rootroot00000000000000import java.util.Arrays; public class ForEach { { for (int i : Arrays.asList(1, 2, 3)) { System.out.println(i); // Do something } } } lombok-1.16.18/test/pretty/resource/before/ForLoop.java000066400000000000000000000004321312655740700230060ustar00rootroot00000000000000public class ForLoop { public static void main(String[] args) { // before loop for (int i = 0; i < 10; i++) { // start of block System.out.println(i); // end of block } // after loop } { int i; for (i = 0; i < 10; i++) { System.out.println(i); } } } lombok-1.16.18/test/pretty/resource/before/Interfaces.java000066400000000000000000000003061312655740700235110ustar00rootroot00000000000000@SuppressWarnings("all") interface Interfaces { enum Ranks { CLUBS, HEARTS, DIAMONDS, SPADES; } ; ; int x = 10; void y(); public static final int a = 20; public abstract void b(); } lombok-1.16.18/test/pretty/resource/before/Lambda.java000066400000000000000000000012541312655740700226110ustar00rootroot00000000000000// version 8: public class Lambda { Runnable r = () -> System.out.println(); java.util.Comparator c1 = (a, b) -> a - b; java.util.Comparator c2 = (Integer a, Integer b) -> { return a - b; }; java.util.function.Function fnc = (String c) -> c; void testLambdaInArgsList(String name, java.util.function.Function f) { } void testLambdaInArgsList2(java.util.function.Function f, String name) { } void test() { testLambdaInArgsList("hello", (String c) -> c); testLambdaInArgsList("hello", c -> c); testLambdaInArgsList2((String c) -> c, "hello"); testLambdaInArgsList2(c -> c, "hello"); } } lombok-1.16.18/test/pretty/resource/before/MethodReference.java000066400000000000000000000016241312655740700244710ustar00rootroot00000000000000// version 8: class MethodReference { public MethodReference() { } public MethodReference(T in) { } public void simpleInstanceReference() { Runnable r = this::foo; } public void simpleConstructorReference() { Runnable r = MethodReference::new; } public void simpleStaticReference() { Runnable r = MethodReference::staticFoo; } public void generifiedStaticReference() { StringConverter sc = MethodReference::generifiedStaticFoo; } public void generifiedConstructorReference() { FooConverter fc = MethodReference::new; } public void foo() { } private static void staticFoo() { } public static T generifiedStaticFoo(T foo) { return foo; } @FunctionalInterface public interface StringConverter { public String hello(String x); } @FunctionalInterface public interface FooConverter { public K hello(String x); } } lombok-1.16.18/test/pretty/resource/before/MultiCatch.java000066400000000000000000000003001312655740700234550ustar00rootroot00000000000000// version 7: public class MultiCatch { public void test() { try { System.out.println(); } catch (IllegalArgumentException | IllegalStateException e) { e.printStackTrace(); } } }lombok-1.16.18/test/pretty/resource/before/TryWithResources.java000066400000000000000000000002351312655740700247340ustar00rootroot00000000000000//version 7: import java.io.PrintWriter; public class TryWithResources { { try (PrintWriter pw = new PrintWriter(System.out)) { pw.println(); } } } lombok-1.16.18/test/pretty/resource/before/TypeAnnotations.java000066400000000000000000000011201312655740700245600ustar00rootroot00000000000000// version 8: import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.util.List; import java.util.Map; public class TypeAnnotations { @Target({ElementType.TYPE_USE, ElementType.LOCAL_VARIABLE}) @interface Foo {} @Target(ElementType.TYPE_USE) @interface Bar {} public List<@Foo String> test(@Foo String param) { @Bar String local = "bar"; @Foo java.io.@Foo File[] array = {}; return new java.util.@Foo ArrayList(); } public <@Foo T extends java.lang.@Foo Number> T test2(@Bar String... varargs) { return null; } } lombok-1.16.18/test/pretty/resource/before/WithComments.java000066400000000000000000000002131312655740700240440ustar00rootroot00000000000000/* Try out pretty comments. */ package test; // Cool Comments public class WithComments { // Also inside the body // On start of line } lombok-1.16.18/test/transform/000077500000000000000000000000001312655740700161575ustar00rootroot00000000000000lombok-1.16.18/test/transform/knownBroken/000077500000000000000000000000001312655740700204545ustar00rootroot00000000000000lombok-1.16.18/test/transform/knownBroken/before/000077500000000000000000000000001312655740700217165ustar00rootroot00000000000000lombok-1.16.18/test/transform/knownBroken/before/I1132RecursiveGenerics.java000066400000000000000000000013011312655740700266230ustar00rootroot00000000000000// Compile with javac, it'll think the T in the generated build() method isn't type compatible. // Yet, when you take the delomboked output (which delombok will give, but with errors), THAT does compile. public class I1132RecursiveGenerics { public static class Recursive> {} public static final class Rec extends Recursive {} @lombok.Builder(builderClassName = "MethodBuilder") public static > T create() { return null; } public static void main(String[] args) { final MethodBuilder builder = I1132RecursiveGenerics.builder(); final Rec rec = builder.build(); // final Rec rec = I1132RecursiveGenerics.builder().build(); } } lombok-1.16.18/test/transform/knownBroken/before/I1302BuilderInInstanceInnerClass.java000066400000000000000000000001741312655740700305260ustar00rootroot00000000000000public class I1302BuilderInInstanceInnerClass { @lombok.Builder public class NonStaticInner { private int test; } } lombok-1.16.18/test/transform/resource/000077500000000000000000000000001312655740700200065ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/after-delombok/000077500000000000000000000000001312655740700227015ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/after-delombok/Accessors.java000066400000000000000000000075021312655740700254750ustar00rootroot00000000000000class AccessorsFluent { private String fieldName = ""; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String fieldName() { return this.fieldName; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public AccessorsFluent fieldName(final String fieldName) { this.fieldName = fieldName; return this; } } class AccessorsFluentOnClass { private String fieldName = ""; private String otherFieldWithOverride = ""; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String fieldName() { return this.fieldName; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getOtherFieldWithOverride() { return this.otherFieldWithOverride; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public AccessorsFluentOnClass fieldName(final String fieldName) { this.fieldName = fieldName; return this; } } class AccessorsChain { private boolean isRunning; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public AccessorsChain setRunning(final boolean isRunning) { this.isRunning = isRunning; return this; } } class AccessorsPrefix { private String fieldName; private String fActualField; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setActualField(final String fActualField) { this.fActualField = fActualField; } } class AccessorsPrefix2 { private String fieldName; private String fActualField; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setFieldName(final String fieldName) { this.fieldName = fieldName; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setActualField(final String fActualField) { this.fActualField = fActualField; } } class AccessorsPrefix3 { private String fName; private String getName() { return fName; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "AccessorsPrefix3(fName=" + this.getName() + ")"; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof AccessorsPrefix3)) return false; final AccessorsPrefix3 other = (AccessorsPrefix3) o; if (!other.canEqual((java.lang.Object) this)) return false; final java.lang.Object this$fName = this.getName(); final java.lang.Object other$fName = other.getName(); if (this$fName == null ? other$fName != null : !this$fName.equals(other$fName)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof AccessorsPrefix3; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $fName = this.getName(); result = result * PRIME + ($fName == null ? 43 : $fName.hashCode()); return result; } } class AccessorsFluentGenerics { private String name; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public AccessorsFluentGenerics name(final String name) { this.name = name; return this; } } class AccessorsFluentNoChaining { private String name; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void name(final String name) { this.name = name; } } class AccessorsFluentStatic { private static String name; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static void name(final String name) { AccessorsFluentStatic.name = name; } } lombok-1.16.18/test/transform/resource/after-delombok/AccessorsConfiguration.java000066400000000000000000000015401312655740700302210ustar00rootroot00000000000000class AccessorsConfiguration { private String m_FieldName = ""; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String fieldName() { return this.m_FieldName; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void fieldName(final String m_FieldName) { this.m_FieldName = m_FieldName; } } class AccessorsConfiguration2 { private String m_FieldName = ""; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setM_FieldName(final String m_FieldName) { this.m_FieldName = m_FieldName; } } class AccessorsConfiguration3 { private String fFieldName = ""; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public AccessorsConfiguration3 setFieldName(final String fFieldName) { this.fFieldName = fFieldName; return this; } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderChainAndFluent.java000066400000000000000000000024071312655740700277010ustar00rootroot00000000000000class BuilderChainAndFluent { private final int yes; @java.beans.ConstructorProperties({"yes"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderChainAndFluent(final int yes) { this.yes = yes; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderChainAndFluentBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int yes; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderChainAndFluentBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setYes(final int yes) { this.yes = yes; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderChainAndFluent build() { return new BuilderChainAndFluent(yes); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderChainAndFluent.BuilderChainAndFluentBuilder(yes=" + this.yes + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderChainAndFluentBuilder builder() { return new BuilderChainAndFluentBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderComplex.java000066400000000000000000000041271312655740700264660ustar00rootroot00000000000000import java.util.List; class BuilderComplex { private static void testVoidWithGenerics(T number, int arg2, String arg3, BuilderComplex selfRef) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class VoidBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private T number; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int arg2; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private String arg3; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private BuilderComplex selfRef; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") VoidBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public VoidBuilder number(final T number) { this.number = number; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public VoidBuilder arg2(final int arg2) { this.arg2 = arg2; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public VoidBuilder arg3(final String arg3) { this.arg3 = arg3; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public VoidBuilder selfRef(final BuilderComplex selfRef) { this.selfRef = selfRef; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void execute() { BuilderComplex.testVoidWithGenerics(number, arg2, arg3, selfRef); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderComplex.VoidBuilder(number=" + this.number + ", arg2=" + this.arg2 + ", arg3=" + this.arg3 + ", selfRef=" + this.selfRef + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static VoidBuilder builder() { return new VoidBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderDefaults.java000066400000000000000000000101171312655740700266220ustar00rootroot00000000000000public final class BuilderDefaults { private final int x; private final String name; private final long z; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static int $default$x() { return 10; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static long $default$z() { return System.currentTimeMillis(); } @java.beans.ConstructorProperties({"x", "name", "z"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaults(final int x, final String name, final long z) { this.x = x; this.name = name; this.z = z; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderDefaultsBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private boolean x$set; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int x; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private String name; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private boolean z$set; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private long z; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaultsBuilder x(final int x) { this.x = x; x$set = true; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaultsBuilder name(final String name) { this.name = name; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaultsBuilder z(final long z) { this.z = z; z$set = true; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaults build() { return new BuilderDefaults(x$set ? x : BuilderDefaults.$default$x(), name, z$set ? z : BuilderDefaults.$default$z()); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderDefaults.BuilderDefaultsBuilder(x=" + this.x + ", name=" + this.name + ", z=" + this.z + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderDefaultsBuilder builder() { return new BuilderDefaultsBuilder(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getName() { return this.name; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public long getZ() { return this.z; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof BuilderDefaults)) return false; final BuilderDefaults other = (BuilderDefaults) o; if (this.getX() != other.getX()) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; if (this.getZ() != other.getZ()) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); final long $z = this.getZ(); result = result * PRIME + (int) ($z >>> 32 ^ $z); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderDefaults(x=" + this.getX() + ", name=" + this.getName() + ", z=" + this.getZ() + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderDefaultsWarnings.java000066400000000000000000000076141312655740700303430ustar00rootroot00000000000000public class BuilderDefaultsWarnings { long x = System.currentTimeMillis(); final int y = 5; int z; java.util.List items; @java.beans.ConstructorProperties({"x", "z", "items"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarnings(final long x, final int z, final java.util.List items) { this.x = x; this.z = z; this.items = items; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderDefaultsWarningsBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private long x; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int z; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList items; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarningsBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaultsWarningsBuilder x(final long x) { this.x = x; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaultsWarningsBuilder z(final int z) { this.z = z; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaultsWarningsBuilder item(final String item) { if (this.items == null) this.items = new java.util.ArrayList(); this.items.add(item); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaultsWarningsBuilder items(final java.util.Collection items) { if (this.items == null) this.items = new java.util.ArrayList(); this.items.addAll(items); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaultsWarningsBuilder clearItems() { if (this.items != null) this.items.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderDefaultsWarnings build() { java.util.List items; switch (this.items == null ? 0 : this.items.size()) { case 0: items = java.util.Collections.emptyList(); break; case 1: items = java.util.Collections.singletonList(this.items.get(0)); break; default: items = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.items)); } return new BuilderDefaultsWarnings(x, z, items); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderDefaultsWarnings.BuilderDefaultsWarningsBuilder(x=" + this.x + ", z=" + this.z + ", items=" + this.items + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderDefaultsWarningsBuilder builder() { return new BuilderDefaultsWarningsBuilder(); } } class NoBuilderButHasDefaults { private final long z = 5; public NoBuilderButHasDefaults() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class NoBuilderButHasDefaultsBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") NoBuilderButHasDefaultsBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public NoBuilderButHasDefaults build() { return new NoBuilderButHasDefaults(); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "NoBuilderButHasDefaults.NoBuilderButHasDefaultsBuilder()"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static NoBuilderButHasDefaultsBuilder builder() { return new NoBuilderButHasDefaultsBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderInstanceMethod.java000066400000000000000000000040041312655740700277560ustar00rootroot00000000000000import java.util.List; class BuilderInstanceMethod { public String create(int show, final int yes, List also, int $andMe) { return "" + show + yes + also + $andMe; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public class StringBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int show; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int yes; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private List also; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int $andMe; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StringBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public StringBuilder show(final int show) { this.show = show; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public StringBuilder yes(final int yes) { this.yes = yes; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public StringBuilder also(final List also) { this.also = also; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public StringBuilder $andMe(final int $andMe) { this.$andMe = $andMe; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String build() { return BuilderInstanceMethod.this.create(show, yes, also, $andMe); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderInstanceMethod.StringBuilder(show=" + this.show + ", yes=" + this.yes + ", also=" + this.also + ", $andMe=" + this.$andMe + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public StringBuilder builder() { return new StringBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderSimple.java000066400000000000000000000032671312655740700263140ustar00rootroot00000000000000import java.util.List; class BuilderSimple { private final int noshow = 0; private final int yes; private List also; private int $butNotMe; @java.beans.ConstructorProperties({"yes", "also"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSimple(final int yes, final List also) { this.yes = yes; this.also = also; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderSimpleBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int yes; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private List also; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSimpleBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSimpleBuilder yes(final int yes) { this.yes = yes; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSimpleBuilder also(final List also) { this.also = also; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSimple build() { return new BuilderSimple(yes, also); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderSimple.BuilderSimpleBuilder(yes=" + this.yes + ", also=" + this.also + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderSimpleBuilder builder() { return new BuilderSimpleBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderSingularGuavaListsSets.java000066400000000000000000000172761312655740700315160ustar00rootroot00000000000000import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableTable; class BuilderSingularGuavaListsSets { private ImmutableList cards; private ImmutableCollection frogs; @SuppressWarnings("all") private ImmutableSet rawSet; private ImmutableSortedSet passes; private ImmutableTable users; @java.beans.ConstructorProperties({"cards", "frogs", "rawSet", "passes", "users"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSets(final ImmutableList cards, final ImmutableCollection frogs, final ImmutableSet rawSet, final ImmutableSortedSet passes, final ImmutableTable users) { this.cards = cards; this.frogs = frogs; this.rawSet = rawSet; this.passes = passes; this.users = users; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderSingularGuavaListsSetsBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableList.Builder cards; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableList.Builder frogs; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableSet.Builder rawSet; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableSortedSet.Builder passes; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableTable.Builder users; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder card(final T card) { if (this.cards == null) this.cards = com.google.common.collect.ImmutableList.builder(); this.cards.add(card); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder cards(final java.lang.Iterable cards) { if (this.cards == null) this.cards = com.google.common.collect.ImmutableList.builder(); this.cards.addAll(cards); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder clearCards() { this.cards = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder frog(final Number frog) { if (this.frogs == null) this.frogs = com.google.common.collect.ImmutableList.builder(); this.frogs.add(frog); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder frogs(final java.lang.Iterable frogs) { if (this.frogs == null) this.frogs = com.google.common.collect.ImmutableList.builder(); this.frogs.addAll(frogs); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder clearFrogs() { this.frogs = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder rawSet(final java.lang.Object rawSet) { if (this.rawSet == null) this.rawSet = com.google.common.collect.ImmutableSet.builder(); this.rawSet.add(rawSet); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder rawSet(final java.lang.Iterable rawSet) { if (this.rawSet == null) this.rawSet = com.google.common.collect.ImmutableSet.builder(); this.rawSet.addAll(rawSet); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder clearRawSet() { this.rawSet = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder pass(final String pass) { if (this.passes == null) this.passes = com.google.common.collect.ImmutableSortedSet.naturalOrder(); this.passes.add(pass); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder passes(final java.lang.Iterable passes) { if (this.passes == null) this.passes = com.google.common.collect.ImmutableSortedSet.naturalOrder(); this.passes.addAll(passes); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder clearPasses() { this.passes = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder user(final Number rowKey, final Number columnKey, final String value) { if (this.users == null) this.users = com.google.common.collect.ImmutableTable.builder(); this.users.put(rowKey, columnKey, value); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder users(final com.google.common.collect.Table users) { if (this.users == null) this.users = com.google.common.collect.ImmutableTable.builder(); this.users.putAll(users); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSetsBuilder clearUsers() { this.users = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaListsSets build() { com.google.common.collect.ImmutableList cards = this.cards == null ? com.google.common.collect.ImmutableList.of() : this.cards.build(); com.google.common.collect.ImmutableCollection frogs = this.frogs == null ? com.google.common.collect.ImmutableList.of() : this.frogs.build(); com.google.common.collect.ImmutableSet rawSet = this.rawSet == null ? com.google.common.collect.ImmutableSet.of() : this.rawSet.build(); com.google.common.collect.ImmutableSortedSet passes = this.passes == null ? com.google.common.collect.ImmutableSortedSet.of() : this.passes.build(); com.google.common.collect.ImmutableTable users = this.users == null ? com.google.common.collect.ImmutableTable.of() : this.users.build(); return new BuilderSingularGuavaListsSets(cards, frogs, rawSet, passes, users); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderSingularGuavaListsSets.BuilderSingularGuavaListsSetsBuilder(cards=" + this.cards + ", frogs=" + this.frogs + ", rawSet=" + this.rawSet + ", passes=" + this.passes + ", users=" + this.users + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderSingularGuavaListsSetsBuilder builder() { return new BuilderSingularGuavaListsSetsBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderSingularGuavaMaps.java000066400000000000000000000123321312655740700304450ustar00rootroot00000000000000import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableSortedMap; class BuilderSingularGuavaMaps { private ImmutableMap battleaxes; private ImmutableSortedMap vertices; @SuppressWarnings("all") private ImmutableBiMap rawMap; @java.beans.ConstructorProperties({"battleaxes", "vertices", "rawMap"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMaps(final ImmutableMap battleaxes, final ImmutableSortedMap vertices, final ImmutableBiMap rawMap) { this.battleaxes = battleaxes; this.vertices = vertices; this.rawMap = rawMap; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderSingularGuavaMapsBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableMap.Builder battleaxes; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableSortedMap.Builder vertices; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableBiMap.Builder rawMap; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMapsBuilder battleaxe(final K key, final V value) { if (this.battleaxes == null) this.battleaxes = com.google.common.collect.ImmutableMap.builder(); this.battleaxes.put(key, value); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMapsBuilder battleaxes(final java.util.Map battleaxes) { if (this.battleaxes == null) this.battleaxes = com.google.common.collect.ImmutableMap.builder(); this.battleaxes.putAll(battleaxes); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMapsBuilder clearBattleaxes() { this.battleaxes = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMapsBuilder vertex(final Integer key, final V value) { if (this.vertices == null) this.vertices = com.google.common.collect.ImmutableSortedMap.naturalOrder(); this.vertices.put(key, value); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMapsBuilder vertices(final java.util.Map vertices) { if (this.vertices == null) this.vertices = com.google.common.collect.ImmutableSortedMap.naturalOrder(); this.vertices.putAll(vertices); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMapsBuilder clearVertices() { this.vertices = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMapsBuilder rawMap(final java.lang.Object key, final java.lang.Object value) { if (this.rawMap == null) this.rawMap = com.google.common.collect.ImmutableBiMap.builder(); this.rawMap.put(key, value); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMapsBuilder rawMap(final java.util.Map rawMap) { if (this.rawMap == null) this.rawMap = com.google.common.collect.ImmutableBiMap.builder(); this.rawMap.putAll(rawMap); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMapsBuilder clearRawMap() { this.rawMap = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularGuavaMaps build() { com.google.common.collect.ImmutableMap battleaxes = this.battleaxes == null ? com.google.common.collect.ImmutableMap.of() : this.battleaxes.build(); com.google.common.collect.ImmutableSortedMap vertices = this.vertices == null ? com.google.common.collect.ImmutableSortedMap.of() : this.vertices.build(); com.google.common.collect.ImmutableBiMap rawMap = this.rawMap == null ? com.google.common.collect.ImmutableBiMap.of() : this.rawMap.build(); return new BuilderSingularGuavaMaps(battleaxes, vertices, rawMap); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderSingularGuavaMaps.BuilderSingularGuavaMapsBuilder(battleaxes=" + this.battleaxes + ", vertices=" + this.vertices + ", rawMap=" + this.rawMap + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderSingularGuavaMapsBuilder builder() { return new BuilderSingularGuavaMapsBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderSingularLists.java000066400000000000000000000124321312655740700276600ustar00rootroot00000000000000import java.util.List; import java.util.Collection; class BuilderSingularLists { private List children; private Collection scarves; @SuppressWarnings("all") private List rawList; @java.beans.ConstructorProperties({"children", "scarves", "rawList"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularLists(final List children, final Collection scarves, final List rawList) { this.children = children; this.scarves = scarves; this.rawList = rawList; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderSingularListsBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList children; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList scarves; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList rawList; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularListsBuilder child(final T child) { if (this.children == null) this.children = new java.util.ArrayList(); this.children.add(child); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularListsBuilder children(final java.util.Collection children) { if (this.children == null) this.children = new java.util.ArrayList(); this.children.addAll(children); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularListsBuilder clearChildren() { if (this.children != null) this.children.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularListsBuilder scarf(final Number scarf) { if (this.scarves == null) this.scarves = new java.util.ArrayList(); this.scarves.add(scarf); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularListsBuilder scarves(final java.util.Collection scarves) { if (this.scarves == null) this.scarves = new java.util.ArrayList(); this.scarves.addAll(scarves); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularListsBuilder clearScarves() { if (this.scarves != null) this.scarves.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularListsBuilder rawList(final java.lang.Object rawList) { if (this.rawList == null) this.rawList = new java.util.ArrayList(); this.rawList.add(rawList); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularListsBuilder rawList(final java.util.Collection rawList) { if (this.rawList == null) this.rawList = new java.util.ArrayList(); this.rawList.addAll(rawList); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularListsBuilder clearRawList() { if (this.rawList != null) this.rawList.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularLists build() { java.util.List children; switch (this.children == null ? 0 : this.children.size()) { case 0: children = java.util.Collections.emptyList(); break; case 1: children = java.util.Collections.singletonList(this.children.get(0)); break; default: children = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.children)); } java.util.Collection scarves; switch (this.scarves == null ? 0 : this.scarves.size()) { case 0: scarves = java.util.Collections.emptyList(); break; case 1: scarves = java.util.Collections.singletonList(this.scarves.get(0)); break; default: scarves = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.scarves)); } java.util.List rawList; switch (this.rawList == null ? 0 : this.rawList.size()) { case 0: rawList = java.util.Collections.emptyList(); break; case 1: rawList = java.util.Collections.singletonList(this.rawList.get(0)); break; default: rawList = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.rawList)); } return new BuilderSingularLists(children, scarves, rawList); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderSingularLists.BuilderSingularListsBuilder(children=" + this.children + ", scarves=" + this.scarves + ", rawList=" + this.rawList + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderSingularListsBuilder builder() { return new BuilderSingularListsBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderSingularMaps.java000066400000000000000000000205271312655740700274660ustar00rootroot00000000000000import java.util.Map; import java.util.SortedMap; class BuilderSingularMaps { private Map women; private SortedMap men; @SuppressWarnings("all") private Map rawMap; private Map stringMap; @java.beans.ConstructorProperties({"women", "men", "rawMap", "stringMap"}) @SuppressWarnings("all") BuilderSingularMaps(Map women, SortedMap men, Map rawMap, Map stringMap) { this.women = women; this.men = men; this.rawMap = rawMap; this.stringMap = stringMap; } @SuppressWarnings("all") public static class BuilderSingularMapsBuilder { @SuppressWarnings("all") private java.util.ArrayList women$key; @SuppressWarnings("all") private java.util.ArrayList women$value; @SuppressWarnings("all") private java.util.ArrayList men$key; @SuppressWarnings("all") private java.util.ArrayList men$value; @SuppressWarnings("all") private java.util.ArrayList rawMap$key; @SuppressWarnings("all") private java.util.ArrayList rawMap$value; @SuppressWarnings("all") private java.util.ArrayList stringMap$key; @SuppressWarnings("all") private java.util.ArrayList stringMap$value; @SuppressWarnings("all") BuilderSingularMapsBuilder() { } @SuppressWarnings("all") public BuilderSingularMapsBuilder woman(K womanKey, V womanValue) { if (this.women$key == null) { this.women$key = new java.util.ArrayList(); this.women$value = new java.util.ArrayList(); } this.women$key.add(womanKey); this.women$value.add(womanValue); return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder women(java.util.Map women) { if (this.women$key == null) { this.women$key = new java.util.ArrayList(); this.women$value = new java.util.ArrayList(); } for (java.util.Map.Entry $lombokEntry : women.entrySet()) { this.women$key.add($lombokEntry.getKey()); this.women$value.add($lombokEntry.getValue()); } return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder clearWomen() { if (this.women$key != null) { this.women$key.clear(); this.women$value.clear(); } return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder man(K manKey, Number manValue) { if (this.men$key == null) { this.men$key = new java.util.ArrayList(); this.men$value = new java.util.ArrayList(); } this.men$key.add(manKey); this.men$value.add(manValue); return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder men(java.util.Map men) { if (this.men$key == null) { this.men$key = new java.util.ArrayList(); this.men$value = new java.util.ArrayList(); } for (java.util.Map.Entry $lombokEntry : men.entrySet()) { this.men$key.add($lombokEntry.getKey()); this.men$value.add($lombokEntry.getValue()); } return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder clearMen() { if (this.men$key != null) { this.men$key.clear(); this.men$value.clear(); } return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder rawMap(Object rawMapKey, Object rawMapValue) { if (this.rawMap$key == null) { this.rawMap$key = new java.util.ArrayList(); this.rawMap$value = new java.util.ArrayList(); } this.rawMap$key.add(rawMapKey); this.rawMap$value.add(rawMapValue); return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder rawMap(java.util.Map rawMap) { if (this.rawMap$key == null) { this.rawMap$key = new java.util.ArrayList(); this.rawMap$value = new java.util.ArrayList(); } for (java.util.Map.Entry $lombokEntry : rawMap.entrySet()) { this.rawMap$key.add($lombokEntry.getKey()); this.rawMap$value.add($lombokEntry.getValue()); } return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder clearRawMap() { if (this.rawMap$key != null) { this.rawMap$key.clear(); this.rawMap$value.clear(); } return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder stringMap(String stringMapKey, V stringMapValue) { if (this.stringMap$key == null) { this.stringMap$key = new java.util.ArrayList(); this.stringMap$value = new java.util.ArrayList(); } this.stringMap$key.add(stringMapKey); this.stringMap$value.add(stringMapValue); return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder stringMap(java.util.Map stringMap) { if (this.stringMap$key == null) { this.stringMap$key = new java.util.ArrayList(); this.stringMap$value = new java.util.ArrayList(); } for (java.util.Map.Entry $lombokEntry : stringMap.entrySet()) { this.stringMap$key.add($lombokEntry.getKey()); this.stringMap$value.add($lombokEntry.getValue()); } return this; } @SuppressWarnings("all") public BuilderSingularMapsBuilder clearStringMap() { if (this.stringMap$key != null) { this.stringMap$key.clear(); this.stringMap$value.clear(); } return this; } @SuppressWarnings("all") public BuilderSingularMaps build() { java.util.Map women; switch (this.women$key == null ? 0 : this.women$key.size()) { case 0: women = java.util.Collections.emptyMap(); break; case 1: women = java.util.Collections.singletonMap(this.women$key.get(0), this.women$value.get(0)); break; default: women = new java.util.LinkedHashMap(this.women$key.size() < 1073741824 ? 1 + this.women$key.size() + (this.women$key.size() - 3) / 3 : Integer.MAX_VALUE); for (int $i = 0; $i < this.women$key.size(); $i++) women.put(this.women$key.get($i), (V) this.women$value.get($i)); women = java.util.Collections.unmodifiableMap(women); } java.util.SortedMap men = new java.util.TreeMap(); if (this.men$key != null) for (int $i = 0; $i < (this.men$key == null ? 0 : this.men$key.size()); $i++) men.put(this.men$key.get($i), (Number) this.men$value.get($i)); men = java.util.Collections.unmodifiableSortedMap(men); java.util.Map rawMap; switch (this.rawMap$key == null ? 0 : this.rawMap$key.size()) { case 0: rawMap = java.util.Collections.emptyMap(); break; case 1: rawMap = java.util.Collections.singletonMap(this.rawMap$key.get(0), this.rawMap$value.get(0)); break; default: rawMap = new java.util.LinkedHashMap(this.rawMap$key.size() < 1073741824 ? 1 + this.rawMap$key.size() + (this.rawMap$key.size() - 3) / 3 : Integer.MAX_VALUE); for (int $i = 0; $i < this.rawMap$key.size(); $i++) rawMap.put(this.rawMap$key.get($i), (Object) this.rawMap$value.get($i)); rawMap = java.util.Collections.unmodifiableMap(rawMap); } java.util.Map stringMap; switch (this.stringMap$key == null ? 0 : this.stringMap$key.size()) { case 0: stringMap = java.util.Collections.emptyMap(); break; case 1: stringMap = java.util.Collections.singletonMap(this.stringMap$key.get(0), this.stringMap$value.get(0)); break; default: stringMap = new java.util.LinkedHashMap(this.stringMap$key.size() < 1073741824 ? 1 + this.stringMap$key.size() + (this.stringMap$key.size() - 3) / 3 : Integer.MAX_VALUE); for (int $i = 0; $i < this.stringMap$key.size(); $i++) stringMap.put(this.stringMap$key.get($i), (V) this.stringMap$value.get($i)); stringMap = java.util.Collections.unmodifiableMap(stringMap); } return new BuilderSingularMaps(women, men, rawMap, stringMap); } @Override @SuppressWarnings("all") public String toString() { return "BuilderSingularMaps.BuilderSingularMapsBuilder(women$key=" + this.women$key + ", women$value=" + this.women$value + ", men$key=" + this.men$key + ", men$value=" + this.men$value + ", rawMap$key=" + this.rawMap$key + ", rawMap$value=" + this.rawMap$value + ", stringMap$key=" + this.stringMap$key + ", stringMap$value=" + this.stringMap$value + ")"; } } @SuppressWarnings("all") public static BuilderSingularMapsBuilder builder() { return new BuilderSingularMapsBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderSingularNoAuto.java000066400000000000000000000120731312655740700277700ustar00rootroot00000000000000import java.util.List; class BuilderSingularNoAuto { private List things; private List widgets; private List items; @java.beans.ConstructorProperties({"things", "widgets", "items"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAuto(final List things, final List widgets, final List items) { this.things = things; this.widgets = widgets; this.items = items; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderSingularNoAutoBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList things; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList widgets; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList items; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder things(final String things) { if (this.things == null) this.things = new java.util.ArrayList(); this.things.add(things); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder things(final java.util.Collection things) { if (this.things == null) this.things = new java.util.ArrayList(); this.things.addAll(things); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder clearThings() { if (this.things != null) this.things.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder widget(final String widget) { if (this.widgets == null) this.widgets = new java.util.ArrayList(); this.widgets.add(widget); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder widgets(final java.util.Collection widgets) { if (this.widgets == null) this.widgets = new java.util.ArrayList(); this.widgets.addAll(widgets); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder clearWidgets() { if (this.widgets != null) this.widgets.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder items(final String items) { if (this.items == null) this.items = new java.util.ArrayList(); this.items.add(items); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder items(final java.util.Collection items) { if (this.items == null) this.items = new java.util.ArrayList(); this.items.addAll(items); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder clearItems() { if (this.items != null) this.items.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAuto build() { java.util.List things; switch (this.things == null ? 0 : this.things.size()) { case 0: things = java.util.Collections.emptyList(); break; case 1: things = java.util.Collections.singletonList(this.things.get(0)); break; default: things = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.things)); } java.util.List widgets; switch (this.widgets == null ? 0 : this.widgets.size()) { case 0: widgets = java.util.Collections.emptyList(); break; case 1: widgets = java.util.Collections.singletonList(this.widgets.get(0)); break; default: widgets = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.widgets)); } java.util.List items; switch (this.items == null ? 0 : this.items.size()) { case 0: items = java.util.Collections.emptyList(); break; case 1: items = java.util.Collections.singletonList(this.items.get(0)); break; default: items = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.items)); } return new BuilderSingularNoAuto(things, widgets, items); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderSingularNoAuto.BuilderSingularNoAutoBuilder(things=" + this.things + ", widgets=" + this.widgets + ", items=" + this.items + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderSingularNoAutoBuilder builder() { return new BuilderSingularNoAutoBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderSingularRedirectToGuava.java000066400000000000000000000120401312655740700316050ustar00rootroot00000000000000import java.util.Set; import java.util.NavigableMap; import java.util.Collection; class BuilderSingularRedirectToGuava { private Set dangerMice; private NavigableMap things; private Collection> doohickeys; @java.beans.ConstructorProperties({"dangerMice", "things", "doohickeys"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuava(final Set dangerMice, final NavigableMap things, final Collection> doohickeys) { this.dangerMice = dangerMice; this.things = things; this.doohickeys = doohickeys; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderSingularRedirectToGuavaBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableSet.Builder dangerMice; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableSortedMap.Builder things; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableList.Builder> doohickeys; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuavaBuilder dangerMouse(final String dangerMouse) { if (this.dangerMice == null) this.dangerMice = com.google.common.collect.ImmutableSet.builder(); this.dangerMice.add(dangerMouse); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuavaBuilder dangerMice(final java.lang.Iterable dangerMice) { if (this.dangerMice == null) this.dangerMice = com.google.common.collect.ImmutableSet.builder(); this.dangerMice.addAll(dangerMice); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuavaBuilder clearDangerMice() { this.dangerMice = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuavaBuilder thing(final Integer key, final Number value) { if (this.things == null) this.things = com.google.common.collect.ImmutableSortedMap.naturalOrder(); this.things.put(key, value); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuavaBuilder things(final java.util.Map things) { if (this.things == null) this.things = com.google.common.collect.ImmutableSortedMap.naturalOrder(); this.things.putAll(things); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuavaBuilder clearThings() { this.things = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuavaBuilder doohickey(final Class doohickey) { if (this.doohickeys == null) this.doohickeys = com.google.common.collect.ImmutableList.builder(); this.doohickeys.add(doohickey); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuavaBuilder doohickeys(final java.lang.Iterable> doohickeys) { if (this.doohickeys == null) this.doohickeys = com.google.common.collect.ImmutableList.builder(); this.doohickeys.addAll(doohickeys); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuavaBuilder clearDoohickeys() { this.doohickeys = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularRedirectToGuava build() { java.util.Set dangerMice = this.dangerMice == null ? com.google.common.collect.ImmutableSet.of() : this.dangerMice.build(); java.util.NavigableMap things = this.things == null ? com.google.common.collect.ImmutableSortedMap.of() : this.things.build(); java.util.Collection> doohickeys = this.doohickeys == null ? com.google.common.collect.ImmutableList.>of() : this.doohickeys.build(); return new BuilderSingularRedirectToGuava(dangerMice, things, doohickeys); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderSingularRedirectToGuava.BuilderSingularRedirectToGuavaBuilder(dangerMice=" + this.dangerMice + ", things=" + this.things + ", doohickeys=" + this.doohickeys + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderSingularRedirectToGuavaBuilder builder() { return new BuilderSingularRedirectToGuavaBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderSingularSets.java000066400000000000000000000162011312655740700274760ustar00rootroot00000000000000import java.util.Set; import java.util.SortedSet; class BuilderSingularSets { private Set dangerMice; private SortedSet octopodes; @SuppressWarnings("all") private Set rawSet; private Set stringSet; @java.beans.ConstructorProperties({"dangerMice", "octopodes", "rawSet", "stringSet"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSets(final Set dangerMice, final SortedSet octopodes, final Set rawSet, final Set stringSet) { this.dangerMice = dangerMice; this.octopodes = octopodes; this.rawSet = rawSet; this.stringSet = stringSet; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderSingularSetsBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList dangerMice; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList octopodes; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList rawSet; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList stringSet; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder dangerMouse(final T dangerMouse) { if (this.dangerMice == null) this.dangerMice = new java.util.ArrayList(); this.dangerMice.add(dangerMouse); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder dangerMice(final java.util.Collection dangerMice) { if (this.dangerMice == null) this.dangerMice = new java.util.ArrayList(); this.dangerMice.addAll(dangerMice); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder clearDangerMice() { if (this.dangerMice != null) this.dangerMice.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder octopus(final Number octopus) { if (this.octopodes == null) this.octopodes = new java.util.ArrayList(); this.octopodes.add(octopus); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder octopodes(final java.util.Collection octopodes) { if (this.octopodes == null) this.octopodes = new java.util.ArrayList(); this.octopodes.addAll(octopodes); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder clearOctopodes() { if (this.octopodes != null) this.octopodes.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder rawSet(final java.lang.Object rawSet) { if (this.rawSet == null) this.rawSet = new java.util.ArrayList(); this.rawSet.add(rawSet); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder rawSet(final java.util.Collection rawSet) { if (this.rawSet == null) this.rawSet = new java.util.ArrayList(); this.rawSet.addAll(rawSet); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder clearRawSet() { if (this.rawSet != null) this.rawSet.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder stringSet(final String stringSet) { if (this.stringSet == null) this.stringSet = new java.util.ArrayList(); this.stringSet.add(stringSet); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder stringSet(final java.util.Collection stringSet) { if (this.stringSet == null) this.stringSet = new java.util.ArrayList(); this.stringSet.addAll(stringSet); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSetsBuilder clearStringSet() { if (this.stringSet != null) this.stringSet.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularSets build() { java.util.Set dangerMice; switch (this.dangerMice == null ? 0 : this.dangerMice.size()) { case 0: dangerMice = java.util.Collections.emptySet(); break; case 1: dangerMice = java.util.Collections.singleton(this.dangerMice.get(0)); break; default: dangerMice = new java.util.LinkedHashSet(this.dangerMice.size() < 1073741824 ? 1 + this.dangerMice.size() + (this.dangerMice.size() - 3) / 3 : java.lang.Integer.MAX_VALUE); dangerMice.addAll(this.dangerMice); dangerMice = java.util.Collections.unmodifiableSet(dangerMice); } java.util.SortedSet octopodes = new java.util.TreeSet(); if (this.octopodes != null) octopodes.addAll(this.octopodes); octopodes = java.util.Collections.unmodifiableSortedSet(octopodes); java.util.Set rawSet; switch (this.rawSet == null ? 0 : this.rawSet.size()) { case 0: rawSet = java.util.Collections.emptySet(); break; case 1: rawSet = java.util.Collections.singleton(this.rawSet.get(0)); break; default: rawSet = new java.util.LinkedHashSet(this.rawSet.size() < 1073741824 ? 1 + this.rawSet.size() + (this.rawSet.size() - 3) / 3 : java.lang.Integer.MAX_VALUE); rawSet.addAll(this.rawSet); rawSet = java.util.Collections.unmodifiableSet(rawSet); } java.util.Set stringSet; switch (this.stringSet == null ? 0 : this.stringSet.size()) { case 0: stringSet = java.util.Collections.emptySet(); break; case 1: stringSet = java.util.Collections.singleton(this.stringSet.get(0)); break; default: stringSet = new java.util.LinkedHashSet(this.stringSet.size() < 1073741824 ? 1 + this.stringSet.size() + (this.stringSet.size() - 3) / 3 : java.lang.Integer.MAX_VALUE); stringSet.addAll(this.stringSet); stringSet = java.util.Collections.unmodifiableSet(stringSet); } return new BuilderSingularSets(dangerMice, octopodes, rawSet, stringSet); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderSingularSets.BuilderSingularSetsBuilder(dangerMice=" + this.dangerMice + ", octopodes=" + this.octopodes + ", rawSet=" + this.rawSet + ", stringSet=" + this.stringSet + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderSingularSetsBuilder builder() { return new BuilderSingularSetsBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderSingularWithPrefixes.java000066400000000000000000000045721312655740700312110ustar00rootroot00000000000000class BuilderSingularWithPrefixes { private java.util.List _elems; @java.beans.ConstructorProperties({"elems"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularWithPrefixes(final java.util.List elems) { this._elems = elems; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderSingularWithPrefixesBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList elems; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularWithPrefixesBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularWithPrefixesBuilder elem(final String elem) { if (this.elems == null) this.elems = new java.util.ArrayList(); this.elems.add(elem); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularWithPrefixesBuilder elems(final java.util.Collection elems) { if (this.elems == null) this.elems = new java.util.ArrayList(); this.elems.addAll(elems); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularWithPrefixesBuilder clearElems() { if (this.elems != null) this.elems.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularWithPrefixes build() { java.util.List elems; switch (this.elems == null ? 0 : this.elems.size()) { case 0: elems = java.util.Collections.emptyList(); break; case 1: elems = java.util.Collections.singletonList(this.elems.get(0)); break; default: elems = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.elems)); } return new BuilderSingularWithPrefixes(elems); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderSingularWithPrefixes.BuilderSingularWithPrefixesBuilder(elems=" + this.elems + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderSingularWithPrefixesBuilder builder() { return new BuilderSingularWithPrefixesBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderValueData.java000066400000000000000000000074201312655740700267240ustar00rootroot00000000000000import java.util.List; final class BuilderAndValue { private final int zero = 0; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndValue() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderAndValueBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndValueBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderAndValue build() { return new BuilderAndValue(); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderAndValue.BuilderAndValueBuilder()"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderAndValueBuilder builder() { return new BuilderAndValueBuilder(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getZero() { return this.zero; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof BuilderAndValue)) return false; final BuilderAndValue other = (BuilderAndValue) o; if (this.getZero() != other.getZero()) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getZero(); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderAndValue(zero=" + this.getZero() + ")"; } } class BuilderAndData { private final int zero = 0; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndData() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderAndDataBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndDataBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderAndData build() { return new BuilderAndData(); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderAndData.BuilderAndDataBuilder()"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderAndDataBuilder builder() { return new BuilderAndDataBuilder(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getZero() { return this.zero; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof BuilderAndData)) return false; final BuilderAndData other = (BuilderAndData) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getZero() != other.getZero()) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof BuilderAndData; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getZero(); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderAndData(zero=" + this.getZero() + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderWithAccessors.java000066400000000000000000000046441312655740700276440ustar00rootroot00000000000000class BuilderWithAccessors { private final int plower; private final int pUpper; private int _foo; private int __bar; @java.beans.ConstructorProperties({"plower", "upper", "foo", "_bar"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessors(final int plower, final int upper, final int foo, final int _bar) { this.plower = plower; this.pUpper = upper; this._foo = foo; this.__bar = _bar; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderWithAccessorsBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int plower; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int upper; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int foo; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int _bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessorsBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithAccessorsBuilder plower(final int plower) { this.plower = plower; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithAccessorsBuilder upper(final int upper) { this.upper = upper; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithAccessorsBuilder foo(final int foo) { this.foo = foo; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithAccessorsBuilder _bar(final int _bar) { this._bar = _bar; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithAccessors build() { return new BuilderWithAccessors(plower, upper, foo, _bar); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderWithAccessors.BuilderWithAccessorsBuilder(plower=" + this.plower + ", upper=" + this.upper + ", foo=" + this.foo + ", _bar=" + this._bar + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderWithAccessorsBuilder builder() { return new BuilderWithAccessorsBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderWithDeprecated.java000066400000000000000000000111371312655740700277520ustar00rootroot00000000000000import com.google.common.collect.ImmutableList; public class BuilderWithDeprecated { /** * @deprecated */ String dep1; @Deprecated int dep2; @Deprecated java.util.List strings; @Deprecated ImmutableList numbers; @java.beans.ConstructorProperties({"dep1", "dep2", "strings", "numbers"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecated(final String dep1, final int dep2, final java.util.List strings, final ImmutableList numbers) { this.dep1 = dep1; this.dep2 = dep2; this.strings = strings; this.numbers = numbers; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderWithDeprecatedBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private String dep1; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int dep2; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList strings; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private com.google.common.collect.ImmutableList.Builder numbers; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder() { } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithDeprecatedBuilder dep1(final String dep1) { this.dep1 = dep1; return this; } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithDeprecatedBuilder dep2(final int dep2) { this.dep2 = dep2; return this; } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithDeprecatedBuilder string(final String string) { if (this.strings == null) this.strings = new java.util.ArrayList(); this.strings.add(string); return this; } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithDeprecatedBuilder strings(final java.util.Collection strings) { if (this.strings == null) this.strings = new java.util.ArrayList(); this.strings.addAll(strings); return this; } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithDeprecatedBuilder clearStrings() { if (this.strings != null) this.strings.clear(); return this; } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithDeprecatedBuilder number(final Integer number) { if (this.numbers == null) this.numbers = com.google.common.collect.ImmutableList.builder(); this.numbers.add(number); return this; } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithDeprecatedBuilder numbers(final java.lang.Iterable numbers) { if (this.numbers == null) this.numbers = com.google.common.collect.ImmutableList.builder(); this.numbers.addAll(numbers); return this; } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithDeprecatedBuilder clearNumbers() { this.numbers = null; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithDeprecated build() { java.util.List strings; switch (this.strings == null ? 0 : this.strings.size()) { case 0: strings = java.util.Collections.emptyList(); break; case 1: strings = java.util.Collections.singletonList(this.strings.get(0)); break; default: strings = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.strings)); } com.google.common.collect.ImmutableList numbers = this.numbers == null ? com.google.common.collect.ImmutableList.of() : this.numbers.build(); return new BuilderWithDeprecated(dep1, dep2, strings, numbers); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderWithDeprecated.BuilderWithDeprecatedBuilder(dep1=" + this.dep1 + ", dep2=" + this.dep2 + ", strings=" + this.strings + ", numbers=" + this.numbers + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderWithDeprecatedBuilder builder() { return new BuilderWithDeprecatedBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderWithExistingBuilderClass.java000066400000000000000000000033761312655740700320070ustar00rootroot00000000000000class BuilderWithExistingBuilderClass { public static BuilderWithExistingBuilderClass staticMethod(Z arg1, boolean arg2, String arg3) { return null; } public static class BuilderWithExistingBuilderClassBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private boolean arg2; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private String arg3; private Z arg1; public void arg2(boolean arg) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithExistingBuilderClassBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithExistingBuilderClassBuilder arg1(final Z arg1) { this.arg1 = arg1; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithExistingBuilderClassBuilder arg3(final String arg3) { this.arg3 = arg3; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithExistingBuilderClass build() { return BuilderWithExistingBuilderClass.staticMethod(arg1, arg2, arg3); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderWithExistingBuilderClass.BuilderWithExistingBuilderClassBuilder(arg1=" + this.arg1 + ", arg2=" + this.arg2 + ", arg3=" + this.arg3 + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderWithExistingBuilderClassBuilder builder() { return new BuilderWithExistingBuilderClassBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderWithRecursiveGenerics.java000066400000000000000000000070771312655740700313510ustar00rootroot00000000000000import java.util.Set; public class BuilderWithRecursiveGenerics { interface Inter> { } public static final class Test, Quz extends Inter> { private final Foo foo; private final Bar bar; @java.beans.ConstructorProperties({"foo", "bar"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Test(final Foo foo, final Bar bar) { this.foo = foo; this.bar = bar; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class TestBuilder, Quz extends Inter> { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private Foo foo; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private Bar bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") TestBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public TestBuilder foo(final Foo foo) { this.foo = foo; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public TestBuilder bar(final Bar bar) { this.bar = bar; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Test build() { return new Test(foo, bar); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderWithRecursiveGenerics.Test.TestBuilder(foo=" + this.foo + ", bar=" + this.bar + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static , Quz extends Inter> TestBuilder builder() { return new TestBuilder(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Foo getFoo() { return this.foo; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Bar getBar() { return this.bar; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof BuilderWithRecursiveGenerics.Test)) return false; final BuilderWithRecursiveGenerics.Test other = (BuilderWithRecursiveGenerics.Test) o; final java.lang.Object this$foo = this.getFoo(); final java.lang.Object other$foo = other.getFoo(); if (this$foo == null ? other$foo != null : !this$foo.equals(other$foo)) return false; final java.lang.Object this$bar = this.getBar(); final java.lang.Object other$bar = other.getBar(); if (this$bar == null ? other$bar != null : !this$bar.equals(other$bar)) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $foo = this.getFoo(); result = result * PRIME + ($foo == null ? 43 : $foo.hashCode()); final java.lang.Object $bar = this.getBar(); result = result * PRIME + ($bar == null ? 43 : $bar.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderWithRecursiveGenerics.Test(foo=" + this.getFoo() + ", bar=" + this.getBar() + ")"; } } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderWithToBuilder.java000066400000000000000000000164521312655740700276100ustar00rootroot00000000000000import java.util.List; class BuilderWithToBuilder { private String mOne; private String mTwo; private T foo; private List bars; public static K rrr(BuilderWithToBuilder x) { return x.foo; } @java.beans.ConstructorProperties({"one", "two", "foo", "bars"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilder(final String one, final String two, final T foo, final List bars) { this.mOne = one; this.mTwo = two; this.foo = foo; this.bars = bars; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderWithToBuilderBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private String one; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private String two; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private T foo; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList bars; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithToBuilderBuilder one(final String one) { this.one = one; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithToBuilderBuilder two(final String two) { this.two = two; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithToBuilderBuilder foo(final T foo) { this.foo = foo; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithToBuilderBuilder bar(final T bar) { if (this.bars == null) this.bars = new java.util.ArrayList(); this.bars.add(bar); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithToBuilderBuilder bars(final java.util.Collection bars) { if (this.bars == null) this.bars = new java.util.ArrayList(); this.bars.addAll(bars); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithToBuilderBuilder clearBars() { if (this.bars != null) this.bars.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithToBuilder build() { java.util.List bars; switch (this.bars == null ? 0 : this.bars.size()) { case 0: bars = java.util.Collections.emptyList(); break; case 1: bars = java.util.Collections.singletonList(this.bars.get(0)); break; default: bars = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.bars)); } return new BuilderWithToBuilder(one, two, foo, bars); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderWithToBuilder.BuilderWithToBuilderBuilder(one=" + this.one + ", two=" + this.two + ", foo=" + this.foo + ", bars=" + this.bars + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderWithToBuilderBuilder builder() { return new BuilderWithToBuilderBuilder(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithToBuilderBuilder toBuilder() { return new BuilderWithToBuilderBuilder().one(this.mOne).two(this.mTwo).foo(BuilderWithToBuilder.rrr(this)).bars(this.bars); } } class ConstructorWithToBuilder { private String mOne; private String mTwo; private T foo; @lombok.Singular private List bars; public ConstructorWithToBuilder(String mOne, T bar) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class ConstructorWithToBuilderBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private String mOne; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private T bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConstructorWithToBuilderBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ConstructorWithToBuilderBuilder mOne(final String mOne) { this.mOne = mOne; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ConstructorWithToBuilderBuilder bar(final T bar) { this.bar = bar; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ConstructorWithToBuilder build() { return new ConstructorWithToBuilder(mOne, bar); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ConstructorWithToBuilder.ConstructorWithToBuilderBuilder(mOne=" + this.mOne + ", bar=" + this.bar + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static ConstructorWithToBuilderBuilder builder() { return new ConstructorWithToBuilderBuilder(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ConstructorWithToBuilderBuilder toBuilder() { return new ConstructorWithToBuilderBuilder().mOne(this.mOne).bar(this.foo); } } class StaticWithToBuilder { private String mOne; private String mTwo; private T foo; private K bar; @lombok.Singular private List bars; public static StaticWithToBuilder test(String mOne, Z bar) { return new StaticWithToBuilder(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class StaticWithToBuilderBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private String mOne; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private Z bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StaticWithToBuilderBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public StaticWithToBuilderBuilder mOne(final String mOne) { this.mOne = mOne; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public StaticWithToBuilderBuilder bar(final Z bar) { this.bar = bar; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public StaticWithToBuilder build() { return StaticWithToBuilder.test(mOne, bar); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "StaticWithToBuilder.StaticWithToBuilderBuilder(mOne=" + this.mOne + ", bar=" + this.bar + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static StaticWithToBuilderBuilder builder() { return new StaticWithToBuilderBuilder(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public StaticWithToBuilderBuilder toBuilder() { return new StaticWithToBuilderBuilder().mOne(this.mOne).bar(this.foo); } } lombok-1.16.18/test/transform/resource/after-delombok/BuilderWithTolerate.java000066400000000000000000000027441312655740700274750ustar00rootroot00000000000000import lombok.experimental.Tolerate; public class BuilderWithTolerate { private final int value; public static void main(String[] args) { BuilderWithTolerate.builder().value("42").build(); } public static class BuilderWithTolerateBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private int value; @Tolerate public BuilderWithTolerateBuilder value(String s) { return this.value(Integer.parseInt(s)); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithTolerateBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithTolerateBuilder value(final int value) { this.value = value; return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderWithTolerate build() { return new BuilderWithTolerate(value); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderWithTolerate.BuilderWithTolerateBuilder(value=" + this.value + ")"; } } @java.beans.ConstructorProperties({"value"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithTolerate(final int value) { this.value = value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderWithTolerateBuilder builder() { return new BuilderWithTolerateBuilder(); } } lombok-1.16.18/test/transform/resource/after-delombok/ClassNamedAfterGetter.java000066400000000000000000000002331312655740700277110ustar00rootroot00000000000000class GetFoo { private int foo; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getFoo() { return this.foo; } } lombok-1.16.18/test/transform/resource/after-delombok/CleanupName.java000066400000000000000000000006171312655740700257400ustar00rootroot00000000000000class CleanupName { void test() { Object o = "Hello World!"; try { System.out.println(o); } finally { if (java.util.Collections.singletonList(o).get(0) != null) { o.toString(); } } } void test2() { Object o = "Hello World too!"; try { System.out.println(o); } finally { if (java.util.Collections.singletonList(o).get(0) != null) { o.toString(); } } } } lombok-1.16.18/test/transform/resource/after-delombok/CleanupPlain.java000066400000000000000000000007131312655740700261200ustar00rootroot00000000000000import java.io.*; class CleanupPlain { void test() throws Exception { InputStream in = new FileInputStream("in"); try { OutputStream out = new FileOutputStream("out"); try { if (in.markSupported()) { out.flush(); } } finally { if (java.util.Collections.singletonList(out).get(0) != null) { out.close(); } } } finally { if (java.util.Collections.singletonList(in).get(0) != null) { in.close(); } } } } lombok-1.16.18/test/transform/resource/after-delombok/CommentsInterspersed.java000066400000000000000000000006501312655740700277220ustar00rootroot00000000000000/* cmt *//* cmt2 */ /* cmt3 */ /*bla */ public class CommentsInterspersed { /** * javadoc for field */ private int x; /* bla2 */ private String test = "foo"; //$NON-NLS-1$ /** * Javadoc on method */ public native void gwtTest(); /*-{ javascript; }-*/ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getTest() { return this.test; } } //haha! //hahaha! //hahahaha! lombok-1.16.18/test/transform/resource/after-delombok/ConflictingStaticConstructorNames.java000066400000000000000000000021501312655740700324030ustar00rootroot00000000000000class ConflictingStaticConstructorNames { @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof ConflictingStaticConstructorNames)) return false; final ConflictingStaticConstructorNames other = (ConflictingStaticConstructorNames) o; if (!other.canEqual((java.lang.Object) this)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof ConflictingStaticConstructorNames; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ConflictingStaticConstructorNames()"; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ConflictingStaticConstructorNames() { } } lombok-1.16.18/test/transform/resource/after-delombok/Constructors.java000066400000000000000000000064531312655740700262640ustar00rootroot00000000000000class RequiredArgsConstructor1 { final int x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public RequiredArgsConstructor1(final int x) { this.x = x; } } class RequiredArgsConstructorAccess { final int x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected RequiredArgsConstructorAccess(final int x) { this.x = x; } } class RequiredArgsConstructorStaticName { final int x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private RequiredArgsConstructorStaticName(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static RequiredArgsConstructorStaticName staticname(final int x) { return new RequiredArgsConstructorStaticName(x); } } class RequiredArgsConstructorWithAnnotations { final int x; String name; @java.beans.ConstructorProperties({"x"}) @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public RequiredArgsConstructorWithAnnotations(final int x) { this.x = x; } } class AllArgsConstructor1 { final int x; String name; @java.beans.ConstructorProperties({"x", "name"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public AllArgsConstructor1(final int x, final String name) { this.x = x; this.name = name; } } class NoArgsConstructor1 { int x; String name; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public NoArgsConstructor1() { } } class RequiredArgsConstructorStaticNameGenerics { final T x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private RequiredArgsConstructorStaticNameGenerics(final T x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static RequiredArgsConstructorStaticNameGenerics of(final T x) { return new RequiredArgsConstructorStaticNameGenerics(x); } } class RequiredArgsConstructorStaticNameGenerics2 { final Class x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private RequiredArgsConstructorStaticNameGenerics2(final Class x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static RequiredArgsConstructorStaticNameGenerics2 of(final Class x) { return new RequiredArgsConstructorStaticNameGenerics2(x); } } class AllArgsConstructorPackageAccess { final String x; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") AllArgsConstructorPackageAccess(final String x) { this.x = x; } } class NoArgsConstructor2 { final int x; final double y; final char c; final boolean b; final float f; final String s; byte z; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public NoArgsConstructor2() { this.x = 0; this.y = 0.0; this.c = '\000'; this.b = false; this.f = 0.0F; this.s = null; } } lombok-1.16.18/test/transform/resource/after-delombok/ConstructorsConfiguration.java000066400000000000000000000002711312655740700310040ustar00rootroot00000000000000class ConstructorsConfiguration { int x; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ConstructorsConfiguration(final int x) { this.x = x; } } lombok-1.16.18/test/transform/resource/after-delombok/ConstructorsWithAccessors.java000066400000000000000000000006551312655740700307640ustar00rootroot00000000000000class ConstructorsWithAccessors { int plower; int pUpper; int _huh; int __huh2; @java.beans.ConstructorProperties({"plower", "upper", "huh", "_huh2"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ConstructorsWithAccessors(final int plower, final int upper, final int huh, final int _huh2) { this.plower = plower; this.pUpper = upper; this._huh = huh; this.__huh2 = _huh2; } } lombok-1.16.18/test/transform/resource/after-delombok/DataConfiguration.java000066400000000000000000000024061312655740700271470ustar00rootroot00000000000000class DataConfiguration { final int x; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public DataConfiguration(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof DataConfiguration)) return false; final DataConfiguration other = (DataConfiguration) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.x != other.x) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof DataConfiguration; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "DataConfiguration(x=" + this.x + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/DataExtended.java000066400000000000000000000025201312655740700260750ustar00rootroot00000000000000class DataExtended { int x; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public DataExtended() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setX(final int x) { this.x = x; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof DataExtended)) return false; final DataExtended other = (DataExtended) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getX() != other.getX()) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof DataExtended; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "DataExtended(x=" + this.x + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/DataIgnore.java000066400000000000000000000024421312655740700255630ustar00rootroot00000000000000class DataIgnore { final int x; String $name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public DataIgnore(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof DataIgnore)) return false; final DataIgnore other = (DataIgnore) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getX() != other.getX()) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof DataIgnore; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "DataIgnore(x=" + this.getX() + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/DataOnEnum.java000066400000000000000000000011431312655740700255360ustar00rootroot00000000000000public enum DataOnEnum { A("hello"); private final String someField; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getSomeField() { return this.someField; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "DataOnEnum(someField=" + this.getSomeField() + ")"; } @java.beans.ConstructorProperties({"someField"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private DataOnEnum(final String someField) { this.someField = someField; } } lombok-1.16.18/test/transform/resource/after-delombok/DataOnLocalClass.java000066400000000000000000000125371312655740700266630ustar00rootroot00000000000000class DataOnLocalClass1 { public static void main(String[] args) { class Local { final int x; String name; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Local(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getName() { return this.name; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setName(final String name) { this.name = name; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Local)) return false; final Local other = (Local) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getX() != other.getX()) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof Local; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Local(x=" + this.getX() + ", name=" + this.getName() + ")"; } } } } class DataOnLocalClass2 { { class Local { final int x; class InnerLocal { @lombok.NonNull String name; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public InnerLocal(@lombok.NonNull final String name) { if (name == null) { throw new java.lang.NullPointerException("name"); } this.name = name; } @lombok.NonNull @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getName() { return this.name; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setName(@lombok.NonNull final String name) { if (name == null) { throw new java.lang.NullPointerException("name"); } this.name = name; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Local.InnerLocal)) return false; final Local.InnerLocal other = (Local.InnerLocal) o; if (!other.canEqual((java.lang.Object) this)) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof Local.InnerLocal; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Local.InnerLocal(name=" + this.getName() + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Local(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Local)) return false; final Local other = (Local) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getX() != other.getX()) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof Local; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Local(x=" + this.getX() + ")"; } } } } lombok-1.16.18/test/transform/resource/after-delombok/DataPlain.java000066400000000000000000000203131312655740700254000ustar00rootroot00000000000000class Data1 { final int x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Data1(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getName() { return this.name; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setName(final String name) { this.name = name; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data1)) return false; final Data1 other = (Data1) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getX() != other.getX()) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof Data1; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Data1(x=" + this.getX() + ", name=" + this.getName() + ")"; } } class Data2 { final int x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Data2(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getName() { return this.name; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setName(final String name) { this.name = name; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data2)) return false; final Data2 other = (Data2) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getX() != other.getX()) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof Data2; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Data2(x=" + this.getX() + ", name=" + this.getName() + ")"; } } final class Data3 { final int x; String name; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Data3(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getName() { return this.name; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setName(final String name) { this.name = name; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data3)) return false; final Data3 other = (Data3) o; if (this.getX() != other.getX()) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Data3(x=" + this.getX() + ", name=" + this.getName() + ")"; } } final class Data4 extends java.util.Timer { int x; Data4() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setX(final int x) { this.x = x; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Data4(x=" + this.getX() + ")"; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data4)) return false; final Data4 other = (Data4) o; if (!other.canEqual((java.lang.Object) this)) return false; if (!super.equals(o)) return false; if (this.getX() != other.getX()) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof Data4; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + super.hashCode(); result = result * PRIME + this.getX(); return result; } } class Data5 { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Data5() { } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data5)) return false; final Data5 other = (Data5) o; if (!other.canEqual((java.lang.Object) this)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof Data5; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Data5()"; } } final class Data6 { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Data6() { } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Data6)) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Data6()"; } } lombok-1.16.18/test/transform/resource/after-delombok/DataWithGetter.java000066400000000000000000000043441312655740700264310ustar00rootroot00000000000000class DataWithGetter { private int x; private int y; private final String z; @java.beans.ConstructorProperties({"z"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public DataWithGetter(final String z) { this.z = z; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setX(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setY(final int y) { this.y = y; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof DataWithGetter)) return false; final DataWithGetter other = (DataWithGetter) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getX() != other.getX()) return false; if (this.getY() != other.getY()) return false; final java.lang.Object this$z = this.getZ(); final java.lang.Object other$z = other.getZ(); if (this$z == null ? other$z != null : !this$z.equals(other$z)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof DataWithGetter; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); result = result * PRIME + this.getY(); final java.lang.Object $z = this.getZ(); result = result * PRIME + ($z == null ? 43 : $z.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "DataWithGetter(x=" + this.getX() + ", y=" + this.getY() + ", z=" + this.getZ() + ")"; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getY() { return this.y; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getZ() { return this.z; } } lombok-1.16.18/test/transform/resource/after-delombok/DataWithGetterNone.java000066400000000000000000000035451312655740700272530ustar00rootroot00000000000000class DataWithGetterNone { private int x; private int y; private final String z; @java.beans.ConstructorProperties({"z"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public DataWithGetterNone(final String z) { this.z = z; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setX(final int x) { this.x = x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setY(final int y) { this.y = y; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof DataWithGetterNone)) return false; final DataWithGetterNone other = (DataWithGetterNone) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.x != other.x) return false; if (this.y != other.y) return false; final java.lang.Object this$z = this.z; final java.lang.Object other$z = other.z; if (this$z == null ? other$z != null : !this$z.equals(other$z)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof DataWithGetterNone; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; result = result * PRIME + this.y; final java.lang.Object $z = this.z; result = result * PRIME + ($z == null ? 43 : $z.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "DataWithGetterNone(x=" + this.x + ", y=" + this.y + ", z=" + this.z + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/DelegateOnGetter.java000066400000000000000000000022241312655740700267260ustar00rootroot00000000000000class DelegateOnGetter { private final java.util.concurrent.atomic.AtomicReference bar = new java.util.concurrent.atomic.AtomicReference(); private interface Bar { void setList(java.util.ArrayList list); int getInt(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Bar getBar() { java.lang.Object value = this.bar.get(); if (value == null) { synchronized (this.bar) { value = this.bar.get(); if (value == null) { final Bar actualValue = new Bar() { public void setList(java.util.ArrayList list) { } public int getInt() { return 42; } }; value = actualValue == null ? this.bar : actualValue; this.bar.set(value); } } } return (Bar) (value == this.bar ? null : value); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setList(final java.util.ArrayList list) { this.getBar().setList(list); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getInt() { return this.getBar().getInt(); } } lombok-1.16.18/test/transform/resource/after-delombok/DelegateOnGetterNone.java000066400000000000000000000007301312655740700275460ustar00rootroot00000000000000class DelegateOnGetterNone { private final Bar bar = null; private interface Bar { void setList(java.util.ArrayList list); int getInt(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setList(final java.util.ArrayList list) { this.bar.setList(list); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getInt() { return this.bar.getInt(); } } lombok-1.16.18/test/transform/resource/after-delombok/DelegateOnMethods.java000066400000000000000000000005241312655740700271000ustar00rootroot00000000000000abstract class DelegateOnMethods { public abstract Bar getBar(); public static interface Bar { void bar(java.util.ArrayList list); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void bar(final java.util.ArrayList list) { this.getBar().bar(list); } } lombok-1.16.18/test/transform/resource/after-delombok/DelegateTypesAndExcludes.java000066400000000000000000000014671312655740700304330ustar00rootroot00000000000000class DelegatePlain { private final BarImpl bar = new BarImpl(); private final FooImpl foo = new FooImpl(); private static class FooImpl implements Foo { public void foo() { } public void bar(java.util.ArrayList list) { } } private static class BarImpl implements Bar { public void bar(java.util.ArrayList list) { } } private static interface Foo extends Bar { void foo(); } private static interface Bar { void bar(java.util.ArrayList list); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void bar(final java.util.ArrayList list) { this.bar.bar(list); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void foo() { this.foo.foo(); } } lombok-1.16.18/test/transform/resource/after-delombok/DelegateWithDeprecated.java000066400000000000000000000012541312655740700300750ustar00rootroot00000000000000class DelegateWithDeprecated { private Bar bar; private interface Bar { @Deprecated void deprecatedAnnotation(); /** * @deprecated */ void deprecatedComment(); void notDeprecated(); } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void deprecatedAnnotation() { this.bar.deprecatedAnnotation(); } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void deprecatedComment() { this.bar.deprecatedComment(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void notDeprecated() { this.bar.notDeprecated(); } } lombok-1.16.18/test/transform/resource/after-delombok/DelegateWithVarargs.java000066400000000000000000000016571312655740700274510ustar00rootroot00000000000000class DelegateWithVarargs { private Bar bar; private interface Bar { void justOneParameter(int... varargs); void multipleParameters(String first, int... varargs); void array(int[] array); void arrayVarargs(int[]... arrayVarargs); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void justOneParameter(final int... varargs) { this.bar.justOneParameter(varargs); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void multipleParameters(final java.lang.String first, final int... varargs) { this.bar.multipleParameters(first, varargs); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void array(final int[] array) { this.bar.array(array); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void arrayVarargs(final int[]... arrayVarargs) { this.bar.arrayVarargs(arrayVarargs); } } lombok-1.16.18/test/transform/resource/after-delombok/EncodingUsAscii.java000066400000000000000000000004511312655740700265530ustar00rootroot00000000000000//ENCODING: US-ASCII class EncodingUsAscii { String foo\u0e51\u0e51 = "\016\t\b "; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "EncodingUsAscii(foo\u0e51\u0e51=" + this.foo\u0e51\u0e51 + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/EncodingUtf8.java000066400000000000000000000003741312655740700260450ustar00rootroot00000000000000class EncodingUtf8 { String foo๑๑ = "\016\t\b "; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "EncodingUtf8(foo๑๑=" + this.foo๑๑ + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/EqualsAndHashCode.java000066400000000000000000000106441312655740700270250ustar00rootroot00000000000000class EqualsAndHashCode { int x; boolean[] y; Object[] z; String a; String b; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCode)) return false; final EqualsAndHashCode other = (EqualsAndHashCode) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.x != other.x) return false; if (!java.util.Arrays.equals(this.y, other.y)) return false; if (!java.util.Arrays.deepEquals(this.z, other.z)) return false; final java.lang.Object this$a = this.a; final java.lang.Object other$a = other.a; if (this$a == null ? other$a != null : !this$a.equals(other$a)) return false; final java.lang.Object this$b = this.b; final java.lang.Object other$b = other.b; if (this$b == null ? other$b != null : !this$b.equals(other$b)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCode; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; result = result * PRIME + java.util.Arrays.hashCode(this.y); result = result * PRIME + java.util.Arrays.deepHashCode(this.z); final java.lang.Object $a = this.a; result = result * PRIME + ($a == null ? 43 : $a.hashCode()); final java.lang.Object $b = this.b; result = result * PRIME + ($b == null ? 43 : $b.hashCode()); return result; } } final class EqualsAndHashCode2 { int x; long y; float f; double d; boolean b; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCode2)) return false; final EqualsAndHashCode2 other = (EqualsAndHashCode2) o; if (this.x != other.x) return false; if (this.y != other.y) return false; if (java.lang.Float.compare(this.f, other.f) != 0) return false; if (java.lang.Double.compare(this.d, other.d) != 0) return false; if (this.b != other.b) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; final long $y = this.y; result = result * PRIME + (int) ($y >>> 32 ^ $y); result = result * PRIME + java.lang.Float.floatToIntBits(this.f); final long $d = java.lang.Double.doubleToLongBits(this.d); result = result * PRIME + (int) ($d >>> 32 ^ $d); result = result * PRIME + (this.b ? 79 : 97); return result; } } final class EqualsAndHashCode3 extends EqualsAndHashCode { @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCode3)) return false; final EqualsAndHashCode3 other = (EqualsAndHashCode3) o; if (!other.canEqual((java.lang.Object) this)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCode3; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } } class EqualsAndHashCode4 extends EqualsAndHashCode { @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCode4)) return false; final EqualsAndHashCode4 other = (EqualsAndHashCode4) o; if (!other.canEqual((java.lang.Object) this)) return false; if (!super.equals(o)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCode4; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + super.hashCode(); return result; } } lombok-1.16.18/test/transform/resource/after-delombok/EqualsAndHashCodeConfigKeys1.java000066400000000000000000000033501312655740700310640ustar00rootroot00000000000000class EqualsAndHashCodeConfigKeys1Parent { @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeConfigKeys1Parent)) return false; final EqualsAndHashCodeConfigKeys1Parent other = (EqualsAndHashCodeConfigKeys1Parent) o; if (!other.canEqual((java.lang.Object) this)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCodeConfigKeys1Parent; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } } class EqualsAndHashCodeConfigKeys1 extends EqualsAndHashCodeConfigKeys1Parent { int x; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeConfigKeys1)) return false; final EqualsAndHashCodeConfigKeys1 other = (EqualsAndHashCodeConfigKeys1) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.x != other.x) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCodeConfigKeys1; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; return result; } } lombok-1.16.18/test/transform/resource/after-delombok/EqualsAndHashCodeConfigKeys2.java000066400000000000000000000052031312655740700310640ustar00rootroot00000000000000class EqualsAndHashCodeConfigKeys2Object extends Object { @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeConfigKeys2Object)) return false; final EqualsAndHashCodeConfigKeys2Object other = (EqualsAndHashCodeConfigKeys2Object) o; if (!other.canEqual((java.lang.Object) this)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCodeConfigKeys2Object; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } } class EqualsAndHashCodeConfigKeys2Parent { @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeConfigKeys2Parent)) return false; final EqualsAndHashCodeConfigKeys2Parent other = (EqualsAndHashCodeConfigKeys2Parent) o; if (!other.canEqual((java.lang.Object) this)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCodeConfigKeys2Parent; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } } class EqualsAndHashCodeConfigKeys2 extends EqualsAndHashCodeConfigKeys2Parent { int x; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeConfigKeys2)) return false; final EqualsAndHashCodeConfigKeys2 other = (EqualsAndHashCodeConfigKeys2) o; if (!other.canEqual((java.lang.Object) this)) return false; if (!super.equals(o)) return false; if (this.x != other.x) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCodeConfigKeys2; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + super.hashCode(); result = result * PRIME + this.x; return result; } } lombok-1.16.18/test/transform/resource/after-delombok/EqualsAndHashCodeNestedShadow.java000066400000000000000000000036411312655740700313350ustar00rootroot00000000000000interface EqualsAndHashCodeNestedShadow { interface Foo { } class Bar { public static class Foo extends Bar implements EqualsAndHashCodeNestedShadow.Foo { @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeNestedShadow.Bar.Foo)) return false; final EqualsAndHashCodeNestedShadow.Bar.Foo other = (EqualsAndHashCodeNestedShadow.Bar.Foo) o; if (!other.canEqual((java.lang.Object) this)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCodeNestedShadow.Bar.Foo; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } } } class Baz { public static class Foo extends Bar implements EqualsAndHashCodeNestedShadow.Foo { @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeNestedShadow.Baz.Foo)) return false; final EqualsAndHashCodeNestedShadow.Baz.Foo other = (EqualsAndHashCodeNestedShadow.Baz.Foo) o; if (!other.canEqual((java.lang.Object) this)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCodeNestedShadow.Baz.Foo; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } } } } lombok-1.16.18/test/transform/resource/after-delombok/EqualsAndHashCodeWithExistingMethods.java000066400000000000000000000022021312655740700327070ustar00rootroot00000000000000class EqualsAndHashCodeWithExistingMethods { int x; public int hashCode() { return 42; } } final class EqualsAndHashCodeWithExistingMethods2 { int x; public boolean equals(Object other) { return false; } } final class EqualsAndHashCodeWithExistingMethods3 extends EqualsAndHashCodeWithExistingMethods { int x; private boolean canEqual(Object other) { return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeWithExistingMethods3)) return false; final EqualsAndHashCodeWithExistingMethods3 other = (EqualsAndHashCodeWithExistingMethods3) o; if (!other.canEqual((java.lang.Object) this)) return false; if (!super.equals(o)) return false; if (this.x != other.x) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + super.hashCode(); result = result * PRIME + this.x; return result; } } lombok-1.16.18/test/transform/resource/after-delombok/EqualsAndHashCodeWithOnParam.java000066400000000000000000000033751312655740700311420ustar00rootroot00000000000000@interface Nullable { } class EqualsAndHashCodeWithOnParam { int x; boolean[] y; Object[] z; String a; String b; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(@Nullable final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeWithOnParam)) return false; final EqualsAndHashCodeWithOnParam other = (EqualsAndHashCodeWithOnParam) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.x != other.x) return false; if (!java.util.Arrays.equals(this.y, other.y)) return false; if (!java.util.Arrays.deepEquals(this.z, other.z)) return false; final java.lang.Object this$a = this.a; final java.lang.Object other$a = other.a; if (this$a == null ? other$a != null : !this$a.equals(other$a)) return false; final java.lang.Object this$b = this.b; final java.lang.Object other$b = other.b; if (this$b == null ? other$b != null : !this$b.equals(other$b)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(@Nullable final java.lang.Object other) { return other instanceof EqualsAndHashCodeWithOnParam; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; result = result * PRIME + java.util.Arrays.hashCode(this.y); result = result * PRIME + java.util.Arrays.deepHashCode(this.z); final java.lang.Object $a = this.a; result = result * PRIME + ($a == null ? 43 : $a.hashCode()); final java.lang.Object $b = this.b; result = result * PRIME + ($b == null ? 43 : $b.hashCode()); return result; } } lombok-1.16.18/test/transform/resource/after-delombok/EqualsAndHashCodeWithSomeExistingMethods.java000066400000000000000000000055711312655740700335470ustar00rootroot00000000000000import lombok.*; import static lombok.AccessLevel.NONE; class EqualsAndHashCodeWithSomeExistingMethods { int x; public int hashCode() { return 42; } @java.lang.SuppressWarnings("all") public EqualsAndHashCodeWithSomeExistingMethods() { } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "EqualsAndHashCodeWithSomeExistingMethods(x=" + this.x + ")"; } } class EqualsAndHashCodeWithSomeExistingMethods2 { int x; protected boolean canEqual(Object other) { return false; } @java.lang.SuppressWarnings("all") public EqualsAndHashCodeWithSomeExistingMethods2() { } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeWithSomeExistingMethods2)) return false; final EqualsAndHashCodeWithSomeExistingMethods2 other = (EqualsAndHashCodeWithSomeExistingMethods2) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.x != other.x) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "EqualsAndHashCodeWithSomeExistingMethods2(x=" + this.x + ")"; } } class EqualsAndHashCodeWithAllExistingMethods { int x; public int hashCode() { return 42; } public boolean equals(Object other) { return false; } @java.lang.SuppressWarnings("all") public EqualsAndHashCodeWithAllExistingMethods() { } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "EqualsAndHashCodeWithAllExistingMethods(x=" + this.x + ")"; } } class EqualsAndHashCodeWithNoExistingMethods { int x; @java.lang.SuppressWarnings("all") public EqualsAndHashCodeWithNoExistingMethods() { } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeWithNoExistingMethods)) return false; final EqualsAndHashCodeWithNoExistingMethods other = (EqualsAndHashCodeWithNoExistingMethods) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.x != other.x) return false; return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof EqualsAndHashCodeWithNoExistingMethods; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "EqualsAndHashCodeWithNoExistingMethods(x=" + this.x + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/EqualsAndHashcodeOfExclude.java000066400000000000000000000023621312655740700306620ustar00rootroot00000000000000final class EqualsAndHashCodeOf { int x; int y; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeOf)) return false; final EqualsAndHashCodeOf other = (EqualsAndHashCodeOf) o; if (this.x != other.x) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; return result; } } final class EqualsAndHashCodeExclude { int x; int y; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeExclude)) return false; final EqualsAndHashCodeExclude other = (EqualsAndHashCodeExclude) o; if (this.x != other.x) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.x; return result; } } lombok-1.16.18/test/transform/resource/after-delombok/ExtensionMethodPlain.java000066400000000000000000000010471312655740700276470ustar00rootroot00000000000000class ExtensionMethodPlain { public String test() { int[] intArray = {5, 3, 8, 2}; java.util.Arrays.sort(intArray); String iAmNull = null; return ExtensionMethodPlain.Extensions.or(iAmNull, ExtensionMethodPlain.Extensions.toTitleCase("hELlO, WORlD!")); } static class Extensions { public static T or(T obj, T ifNull) { return obj != null ? obj : ifNull; } public static String toTitleCase(String in) { if (in.isEmpty()) return in; return "" + Character.toTitleCase(in.charAt(0)) + in.substring(1).toLowerCase(); } } } lombok-1.16.18/test/transform/resource/after-delombok/FieldDefaults.java000066400000000000000000000002721312655740700262600ustar00rootroot00000000000000class FieldDefaults1 { static int STATIC = 3; final int x; int y; FieldDefaults1(int x) { this.x = x; } } class FieldDefaults2 { static int STATIC = 3; int x; private int y; } lombok-1.16.18/test/transform/resource/after-delombok/FieldDefaultsNoop.java000066400000000000000000000000341312655740700271100ustar00rootroot00000000000000class FieldDefaultsNoop { } lombok-1.16.18/test/transform/resource/after-delombok/FieldDefaultsViaConfig.java000066400000000000000000000003131312655740700300420ustar00rootroot00000000000000class FieldDefaultsViaConfig1 { private final int x; private int y; FieldDefaultsViaConfig1(int x) { this.x = x; } } class FieldDefaultsViaConfig2 { final int x = 2; protected final int y = 0; } FieldDefaultsViaConfigAndRequiredArgsConstructor.java000066400000000000000000000004271312655740700352000ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/after-delombokclass FieldDefaultsViaConfigAndRequiredArgsConstructor { final int x; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public FieldDefaultsViaConfigAndRequiredArgsConstructor(final int x) { this.x = x; } } lombok-1.16.18/test/transform/resource/after-delombok/GenerateSuppressFBWarnings.java000066400000000000000000000004051312655740700307630ustar00rootroot00000000000000//VERSION 7: class GenerateSuppressFBWarnings { int y; @java.lang.SuppressWarnings("all") @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(justification = "generated code") @javax.annotation.Generated("lombok") public int getY() { return this.y; } } lombok-1.16.18/test/transform/resource/after-delombok/GeneratedJavaxOff.java000066400000000000000000000001611312655740700270650ustar00rootroot00000000000000class GeneratedJavaxOff { int x; @java.lang.SuppressWarnings("all") public int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-delombok/GeneratedJavaxOnLombokOn.java000066400000000000000000000002621312655740700303720ustar00rootroot00000000000000class GeneratedJavaxOnLombokOn { int x; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") @lombok.Generated public int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-delombok/GeneratedOff.java000066400000000000000000000001541312655740700260750ustar00rootroot00000000000000class GeneratedOff { int x; @java.lang.SuppressWarnings("all") public int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-delombok/GeneratedOffJavaxOn.java000066400000000000000000000002321312655740700273610ustar00rootroot00000000000000class GeneratedOffJavaxOn { int x; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-delombok/GeneratedOffLombokOn.java000066400000000000000000000002071312655740700275350ustar00rootroot00000000000000class GeneratedOffLombokOn { int x; @java.lang.SuppressWarnings("all") @lombok.Generated public int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterAccessLevel.java000066400000000000000000000027131312655740700271130ustar00rootroot00000000000000class GetterAccessLevel { boolean isNone; boolean isPrivate; boolean isPackage; boolean isProtected; boolean isPublic; String noneString; String privateString; String packageString; String protectedString; String publicString; String value; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private boolean isPrivate() { return this.isPrivate; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPackage() { return this.isPackage; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean isProtected() { return this.isProtected; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isPublic() { return this.isPublic; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private String getPrivateString() { return this.privateString; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getPackageString() { return this.packageString; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected String getProtectedString() { return this.protectedString; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getPublicString() { return this.publicString; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getValue() { return this.value; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterAlreadyExists.java000066400000000000000000000047551312655740700275130ustar00rootroot00000000000000class Getter1 { boolean foo; boolean hasFoo() { return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isFoo() { return this.foo; } } class Getter2 { boolean foo; boolean isFoo() { return true; } } class Getter3 { boolean foo; boolean getFoo() { return true; } } class Getter4 { String foo; String hasFoo() { return null; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getFoo() { return this.foo; } } class Getter5 { String foo; String isFoo() { return null; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getFoo() { return this.foo; } } class Getter6 { String foo; String getFoo() { return null; } } class Getter7 { String foo; boolean hasFoo() { return false; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getFoo() { return this.foo; } } class Getter8 { String foo; boolean isFoo() { return false; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getFoo() { return this.foo; } } class Getter9 { String foo; boolean getFoo() { return false; } } class Getter10 { boolean foo; static boolean hasFoo() { return false; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isFoo() { return this.foo; } } class Getter11 { boolean foo; static boolean isFoo() { return false; } } class Getter12 { boolean foo; static boolean getFoo() { return false; } } class Getter13 { String foo; static boolean hasFoo() { return false; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getFoo() { return this.foo; } } class Getter14 { String foo; static boolean isFoo() { return false; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getFoo() { return this.foo; } } class Getter15 { String foo; static boolean getFoo() { return false; } } class Getter16 { String foo; static String hasFoo() { return ""; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getFoo() { return this.foo; } } class Getter17 { String foo; static String isFoo() { return ""; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getFoo() { return this.foo; } } class Getter18 { String foo; static String getFoo() { return ""; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterBoolean.java000066400000000000000000000013111312655740700262720ustar00rootroot00000000000000class Getter { boolean foo; boolean isBar; boolean hasBaz; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isFoo() { return this.foo; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isBar() { return this.isBar; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isHasBaz() { return this.hasBaz; } } class MoreGetter { boolean foo; boolean hasFoo() { return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isFoo() { return this.foo; } } class YetMoreGetter { boolean foo; boolean getFoo() { return true; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterDeprecated.java000066400000000000000000000006571312655740700267670ustar00rootroot00000000000000class GetterDeprecated { @Deprecated int annotation; /** * @deprecated */ int javadoc; @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getAnnotation() { return this.annotation; } /** * @deprecated */ @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getJavadoc() { return this.javadoc; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterEnum.java000066400000000000000000000010461312655740700256240ustar00rootroot00000000000000enum GetterEnum { ONE(1, "One"); private final int id; private final String name; @java.beans.ConstructorProperties({"id", "name"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private GetterEnum(final int id, final String name) { this.id = id; this.name = name; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getId() { return this.id; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getName() { return this.name; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterLazy.java000066400000000000000000000013121312655740700256330ustar00rootroot00000000000000class GetterLazy { static class ValueType { } private final java.util.concurrent.atomic.AtomicReference fieldName = new java.util.concurrent.atomic.AtomicReference(); @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ValueType getFieldName() { java.lang.Object value = this.fieldName.get(); if (value == null) { synchronized (this.fieldName) { value = this.fieldName.get(); if (value == null) { final ValueType actualValue = new ValueType(); value = actualValue == null ? this.fieldName : actualValue; this.fieldName.set(value); } } } return (ValueType) (value == this.fieldName ? null : value); } } lombok-1.16.18/test/transform/resource/after-delombok/GetterLazyBoolean.java000066400000000000000000000045741312655740700271500ustar00rootroot00000000000000class GetterLazyBoolean { private final java.util.concurrent.atomic.AtomicReference booleanValue = new java.util.concurrent.atomic.AtomicReference(); private final java.util.concurrent.atomic.AtomicReference otherBooleanValue = new java.util.concurrent.atomic.AtomicReference(); private static boolean calculateBoolean() { return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof GetterLazyBoolean)) return false; final GetterLazyBoolean other = (GetterLazyBoolean) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.isBooleanValue() != other.isBooleanValue()) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof GetterLazyBoolean; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + (this.isBooleanValue() ? 79 : 97); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "GetterLazyBoolean(booleanValue=" + this.isBooleanValue() + ")"; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isBooleanValue() { java.lang.Object value = this.booleanValue.get(); if (value == null) { synchronized (this.booleanValue) { value = this.booleanValue.get(); if (value == null) { final boolean actualValue = calculateBoolean(); value = actualValue; this.booleanValue.set(value); } } } return (java.lang.Boolean) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isOtherBooleanValue() { java.lang.Object value = this.otherBooleanValue.get(); if (value == null) { synchronized (this.otherBooleanValue) { value = this.otherBooleanValue.get(); if (value == null) { final boolean actualValue = !calculateBoolean(); value = actualValue; this.otherBooleanValue.set(value); } } } return (java.lang.Boolean) value; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterLazyEahcToString.java000066400000000000000000000046501312655740700301160ustar00rootroot00000000000000class GetterLazyEahcToString { private final java.util.concurrent.atomic.AtomicReference value = new java.util.concurrent.atomic.AtomicReference(); private final String value2 = ""; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof GetterLazyEahcToString)) return false; final GetterLazyEahcToString other = (GetterLazyEahcToString) o; if (!other.canEqual((java.lang.Object) this)) return false; final java.lang.Object this$value = this.getValue(); final java.lang.Object other$value = other.getValue(); if (this$value == null ? other$value != null : !this$value.equals(other$value)) return false; final java.lang.Object this$value2 = this.value2; final java.lang.Object other$value2 = other.value2; if (this$value2 == null ? other$value2 != null : !this$value2.equals(other$value2)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof GetterLazyEahcToString; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $value = this.getValue(); result = result * PRIME + ($value == null ? 43 : $value.hashCode()); final java.lang.Object $value2 = this.value2; result = result * PRIME + ($value2 == null ? 43 : $value2.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "GetterLazyEahcToString(value=" + this.getValue() + ", value2=" + this.value2 + ")"; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getValue() { java.lang.Object value = this.value.get(); if (value == null) { synchronized (this.value) { value = this.value.get(); if (value == null) { final String actualValue = ""; value = actualValue == null ? this.value : actualValue; this.value.set(value); } } } return (String) (value == this.value ? null : value); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getValue2() { return this.value2; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterLazyInvalid.java000066400000000000000000000011341312655740700271440ustar00rootroot00000000000000class GetterLazyInvalidNotFinal { private String fieldName = ""; } class GetterLazyInvalidNotPrivate { final String fieldName = ""; } class GetterLazyInvalidNotPrivateFinal { String fieldName = ""; } class GetterLazyInvalidNone { private final String fieldName = ""; } class GetterLazyInvalidClass { private final String fieldName = ""; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getFieldName() { return this.fieldName; } } class GetterLazyInvalidNoInit { private final String fieldName; GetterLazyInvalidNoInit() { this.fieldName = "foo"; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterLazyNative.java000066400000000000000000000123451312655740700270120ustar00rootroot00000000000000class GetterLazyNative { private final java.util.concurrent.atomic.AtomicReference booleanField = new java.util.concurrent.atomic.AtomicReference(); private final java.util.concurrent.atomic.AtomicReference byteField = new java.util.concurrent.atomic.AtomicReference(); private final java.util.concurrent.atomic.AtomicReference shortField = new java.util.concurrent.atomic.AtomicReference(); private final java.util.concurrent.atomic.AtomicReference intField = new java.util.concurrent.atomic.AtomicReference(); private final java.util.concurrent.atomic.AtomicReference longField = new java.util.concurrent.atomic.AtomicReference(); private final java.util.concurrent.atomic.AtomicReference floatField = new java.util.concurrent.atomic.AtomicReference(); private final java.util.concurrent.atomic.AtomicReference doubleField = new java.util.concurrent.atomic.AtomicReference(); private final java.util.concurrent.atomic.AtomicReference charField = new java.util.concurrent.atomic.AtomicReference(); private final java.util.concurrent.atomic.AtomicReference intArrayField = new java.util.concurrent.atomic.AtomicReference(); @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isBooleanField() { java.lang.Object value = this.booleanField.get(); if (value == null) { synchronized (this.booleanField) { value = this.booleanField.get(); if (value == null) { final boolean actualValue = true; value = actualValue; this.booleanField.set(value); } } } return (java.lang.Boolean) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public byte getByteField() { java.lang.Object value = this.byteField.get(); if (value == null) { synchronized (this.byteField) { value = this.byteField.get(); if (value == null) { final byte actualValue = 1; value = actualValue; this.byteField.set(value); } } } return (java.lang.Byte) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public short getShortField() { java.lang.Object value = this.shortField.get(); if (value == null) { synchronized (this.shortField) { value = this.shortField.get(); if (value == null) { final short actualValue = 1; value = actualValue; this.shortField.set(value); } } } return (java.lang.Short) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getIntField() { java.lang.Object value = this.intField.get(); if (value == null) { synchronized (this.intField) { value = this.intField.get(); if (value == null) { final int actualValue = 1; value = actualValue; this.intField.set(value); } } } return (java.lang.Integer) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public long getLongField() { java.lang.Object value = this.longField.get(); if (value == null) { synchronized (this.longField) { value = this.longField.get(); if (value == null) { final long actualValue = 1; value = actualValue; this.longField.set(value); } } } return (java.lang.Long) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public float getFloatField() { java.lang.Object value = this.floatField.get(); if (value == null) { synchronized (this.floatField) { value = this.floatField.get(); if (value == null) { final float actualValue = 1.0F; value = actualValue; this.floatField.set(value); } } } return (java.lang.Float) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public double getDoubleField() { java.lang.Object value = this.doubleField.get(); if (value == null) { synchronized (this.doubleField) { value = this.doubleField.get(); if (value == null) { final double actualValue = 1.0; value = actualValue; this.doubleField.set(value); } } } return (java.lang.Double) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public char getCharField() { java.lang.Object value = this.charField.get(); if (value == null) { synchronized (this.charField) { value = this.charField.get(); if (value == null) { final char actualValue = '1'; value = actualValue; this.charField.set(value); } } } return (java.lang.Character) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int[] getIntArrayField() { java.lang.Object value = this.intArrayField.get(); if (value == null) { synchronized (this.intArrayField) { value = this.intArrayField.get(); if (value == null) { final int[] actualValue = new int[] {1}; value = actualValue == null ? this.intArrayField : actualValue; this.intArrayField.set(value); } } } return (int[]) (value == this.intArrayField ? null : value); } } lombok-1.16.18/test/transform/resource/after-delombok/GetterLazyTransient.java000066400000000000000000000016171312655740700275330ustar00rootroot00000000000000class GetterLazyTransient { private final java.util.concurrent.atomic.AtomicReference nonTransientField = new java.util.concurrent.atomic.AtomicReference(); private final transient int transientField = 2; private final transient int nonLazyTransientField = 3; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getNonTransientField() { java.lang.Object value = this.nonTransientField.get(); if (value == null) { synchronized (this.nonTransientField) { value = this.nonTransientField.get(); if (value == null) { final int actualValue = 1; value = actualValue; this.nonTransientField.set(value); } } } return (java.lang.Integer) value; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getNonLazyTransientField() { return this.nonLazyTransientField; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterNone.java000066400000000000000000000002331312655740700256140ustar00rootroot00000000000000class GetterNone { int i; int foo; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getI() { return this.i; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterOnClass.java000066400000000000000000000027151312655740700262660ustar00rootroot00000000000000class GetterOnClass1 { boolean isNone; boolean isPublic; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isPublic() { return this.isPublic; } } class GetterOnClass2 { boolean isNone; boolean isProtected; boolean isPackage; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean isProtected() { return this.isProtected; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPackage() { return this.isPackage; } } class GetterOnClass3 { boolean isNone; boolean isPackage; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPackage() { return this.isPackage; } } class GetterOnClass4 { boolean isNone; boolean isPrivate; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private boolean isPrivate() { return this.isPrivate; } } class GetterOnClass5 { boolean isNone; boolean isPublic; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean isPublic() { return this.isPublic; } } class GetterOnClass6 { String couldBeNull; @lombok.NonNull String nonNull; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getCouldBeNull() { return this.couldBeNull; } @lombok.NonNull @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getNonNull() { return this.nonNull; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterOnMethod.java000066400000000000000000000007631312655740700264420ustar00rootroot00000000000000class GetterOnMethod { int i; int j; int k; public @interface Test { } @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getI() { return this.i; } @java.lang.Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getJ() { return this.j; } @java.lang.Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getK() { return this.k; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterOnMethodErrors.java000066400000000000000000000003361312655740700276330ustar00rootroot00000000000000class PlaceFillerToMakeSurePositionIsRelevant { } class GetterOnMethodErrors { private int test; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getTest() { return this.test; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterOnMethodErrors2.java000066400000000000000000000023371312655740700277200ustar00rootroot00000000000000class GetterOnMethodErrors2 { private int bad1; private int bad2; private int bad3; private int bad4; private int good1; private int good2; private int good3; private int good4; public @interface Test { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getBad1() { return this.bad1; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getBad2() { return this.bad2; } @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getBad3() { return this.bad3; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getBad4() { return this.bad4; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getGood1() { return this.good1; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getGood2() { return this.good2; } @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getGood3() { return this.good3; } @Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getGood4() { return this.good4; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterOnStatic.java000066400000000000000000000004741312655740700264500ustar00rootroot00000000000000class Getter { static boolean foo; static int bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static boolean isFoo() { return Getter.foo; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static int getBar() { return Getter.bar; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterPlain.java000066400000000000000000000004241312655740700257620ustar00rootroot00000000000000class GetterPlain { int i; int foo; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getI() { return this.i; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getFoo() { return this.foo; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterSetterJavadoc.java000066400000000000000000000071701312655740700274620ustar00rootroot00000000000000class GetterSetterJavadoc1 { /** * Some text */ private int fieldName; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public GetterSetterJavadoc1() { } /** * Getter section * * @return Sky is blue1 */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getFieldName() { return this.fieldName; } /** * Some text * * @param fieldName Hello, World1 */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setFieldName(final int fieldName) { this.fieldName = fieldName; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof GetterSetterJavadoc1)) return false; final GetterSetterJavadoc1 other = (GetterSetterJavadoc1) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getFieldName() != other.getFieldName()) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof GetterSetterJavadoc1; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getFieldName(); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "GetterSetterJavadoc1(fieldName=" + this.getFieldName() + ")"; } } class GetterSetterJavadoc2 { /** * Some text */ private int fieldName; /** * Some text * * @return Sky is blue2 */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getFieldName() { return this.fieldName; } /** * Some text * * @param fieldName Hello, World2 */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setFieldName(final int fieldName) { this.fieldName = fieldName; } } class GetterSetterJavadoc3 { /** * Some text */ private int fieldName; /** * Getter section * @return Sky is blue3 */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getFieldName() { return this.fieldName; } /** * Setter section * @param fieldName Hello, World3 */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setFieldName(final int fieldName) { this.fieldName = fieldName; } } class GetterSetterJavadoc4 { /** * Some text */ private int fieldName; /** * Some text * * @return Sky is blue4 */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int fieldName() { return this.fieldName; } /** * Some text * * @param fieldName Hello, World5 * @return this */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public GetterSetterJavadoc4 fieldName(final int fieldName) { this.fieldName = fieldName; return this; } } class GetterSetterJavadoc5 { /** * Some text */ private int fieldName; /** * Getter section * @return Sky is blue5 */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int fieldName() { return this.fieldName; } /** * Setter section * @param fieldName Hello, World5 * @return Sky is blue5 */ @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public GetterSetterJavadoc5 fieldName(final int fieldName) { this.fieldName = fieldName; return this; } } lombok-1.16.18/test/transform/resource/after-delombok/GetterWithDollar.java000066400000000000000000000006621312655740700267740ustar00rootroot00000000000000class GetterWithDollar1 { int $i; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int get$i() { return this.$i; } } class GetterWithDollar2 { int $i; int i; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int get$i() { return this.$i; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getI() { return this.i; } } lombok-1.16.18/test/transform/resource/after-delombok/Helper.java000066400000000000000000000004151312655740700247630ustar00rootroot00000000000000class HelperTest { { final int z = 5; if (Boolean.TRUE) { class H1 { void foo(int x) { System.out.println("Hello, " + (x + z)); } } final H1 $H1 = new H1(); $H1.foo(10); class H2 { void bar() { $H1.foo(12); } } } } } lombok-1.16.18/test/transform/resource/after-delombok/InjectField.java000066400000000000000000000034071312655740700257300ustar00rootroot00000000000000import java.util.logging.Level; enum InjectField1 { A, B; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(InjectField1.class.getName()); @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private final java.lang.Object $lock = new java.lang.Object[0]; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final java.lang.Object $LOCK = new java.lang.Object[0]; private static final String LOG_MESSAGE = "static initializer"; private String fieldA; static { log.log(Level.FINE, LOG_MESSAGE); } private String fieldB; void generateLockField() { synchronized (this.$lock) { System.out.println("lock field"); } } static void generateStaticLockField() { synchronized (InjectField1.$LOCK) { System.out.println("static lock field"); } } } class InjectField2 { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(InjectField2.class.getName()); @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private final java.lang.Object $lock = new java.lang.Object[0]; private static final String LOG_MESSAGE = "static initializer"; static { log.log(Level.FINE, LOG_MESSAGE); } void generateLockField() { synchronized (this.$lock) { System.out.println("lock field"); } } } class InjectField3 { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(InjectField3.class.getName()); static { log.log(Level.FINE, "static initializer"); } } lombok-1.16.18/test/transform/resource/after-delombok/JavadocGenerally.java000066400000000000000000000004321312655740700267550ustar00rootroot00000000000000/** * Doc on package */ package testPackage; /** Weird doc */ /** * Doc on class */ class JavadocGenerally { /** * Doc on field */ private int someField; /** * Doc on method */ public void test() { } /** * Doc on inner */ public interface TestingInner { } } lombok-1.16.18/test/transform/resource/after-delombok/LoggerCommons.java000066400000000000000000000013041312655740700263150ustar00rootroot00000000000000class LoggerCommons { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LoggerCommons.class); } class LoggerCommonsWithImport { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LoggerCommonsWithImport.class); } class LoggerCommonsWithDifferentName { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("DifferentName"); } lombok-1.16.18/test/transform/resource/after-delombok/LoggerConfig.java000066400000000000000000000003141312655740700261070ustar00rootroot00000000000000class LoggerWithConfig { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private final org.slf4j.Logger myLogger = org.slf4j.LoggerFactory.getLogger(LoggerWithConfig.class); } lombok-1.16.18/test/transform/resource/after-delombok/LoggerJBossLog.java000066400000000000000000000016151312655740700263710ustar00rootroot00000000000000class LoggerJBossLog { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(LoggerJBossLog.class); } class LoggerJBossLogWithImport { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(LoggerJBossLogWithImport.class); } class LoggerJBossLogOuter { static class Inner { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(Inner.class); } } class LoggerJBossLogWithDifferentLoggerName { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger("DifferentLogger"); } lombok-1.16.18/test/transform/resource/after-delombok/LoggerJul.java000066400000000000000000000012241312655740700254350ustar00rootroot00000000000000class LoggerJul { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LoggerJul.class.getName()); } class LoggerJulWithImport { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LoggerJulWithImport.class.getName()); } class LoggerJulWithDifferentName { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger("DifferentName"); } lombok-1.16.18/test/transform/resource/after-delombok/LoggerLog4j.java000066400000000000000000000012041312655740700256600ustar00rootroot00000000000000class LoggerLog4j { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LoggerLog4j.class); } class LoggerLog4jWithImport { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LoggerLog4jWithImport.class); } class LoggerLog4jWithDifferentName { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("DifferentName"); } lombok-1.16.18/test/transform/resource/after-delombok/LoggerLog4j2.java000066400000000000000000000013051312655740700257440ustar00rootroot00000000000000class LoggerLog4j2 { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LoggerLog4j2.class); } class LoggerLog4j2WithImport { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LoggerLog4j2WithImport.class); } class LoggerLog4j2WithDifferentName { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger("DifferentName"); } lombok-1.16.18/test/transform/resource/after-delombok/LoggerSlf4j.java000066400000000000000000000015271312655740700256730ustar00rootroot00000000000000class LoggerSlf4j { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4j.class); } class LoggerSlf4jWithImport { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4jWithImport.class); } class LoggerSlf4jOuter { static class Inner { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Inner.class); } } class LoggerSlf4jWithDifferentLoggerName { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("DifferentLogger"); } lombok-1.16.18/test/transform/resource/after-delombok/LoggerSlf4jAlreadyExists.java000066400000000000000000000000551312655740700303700ustar00rootroot00000000000000class LoggerSlf4jAlreadyExists { int log; } lombok-1.16.18/test/transform/resource/after-delombok/LoggerSlf4jTypes.java000066400000000000000000000014051312655740700267130ustar00rootroot00000000000000interface LoggerSlf4jTypesInterface { } @interface LoggerSlf4jTypesAnnotation { } enum LoggerSlf4jTypesEnum { ; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4jTypesEnum.class); } enum LoggerSlf4jTypesEnumWithElement { FOO; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4jTypesEnumWithElement.class); } interface LoggerSlf4jTypesInterfaceOuter { class Inner { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Inner.class); } } lombok-1.16.18/test/transform/resource/after-delombok/LoggerSlf4jWithPackage.java000066400000000000000000000007241312655740700300010ustar00rootroot00000000000000package before; class LoggerSlf4jWithPackage { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4jWithPackage.class); } class LoggerSlf4jWithPackageOuter { static class Inner { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Inner.class); } } lombok-1.16.18/test/transform/resource/after-delombok/LoggerXSlf4j.java000066400000000000000000000012251312655740700260160ustar00rootroot00000000000000class LoggerXSlf4j { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LoggerXSlf4j.class); } class LoggerXSlf4jWithImport { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LoggerXSlf4jWithImport.class); } class LoggerXSlf4jWithDifferentName { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger("DifferentName"); } lombok-1.16.18/test/transform/resource/after-delombok/MixGetterVal.java000066400000000000000000000004121312655740700261140ustar00rootroot00000000000000class MixGetterVal { private int x; public void m(int z) { } public void test() { final int y = x; m(y); final int a = getX(); m(a); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-delombok/MultiFieldGetter.java000066400000000000000000000010371312655740700267560ustar00rootroot00000000000000class MultiFieldGetter { int x; int y; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected int getY() { return this.y; } } class MultiFieldGetter2 { int x; int y; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getY() { return this.y; } } lombok-1.16.18/test/transform/resource/after-delombok/NoArgsConstructorForce.java000066400000000000000000000005101312655740700301560ustar00rootroot00000000000000 public class NoArgsConstructorForce { private final int[] i; private final Object[] o; private final java.util.List[] fullQualifiedList; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public NoArgsConstructorForce() { this.i = null; this.o = null; this.fullQualifiedList = null; } } lombok-1.16.18/test/transform/resource/after-delombok/NonNullOnParameter.java000066400000000000000000000027131312655740700272720ustar00rootroot00000000000000class NonNullOnParameter extends Thread { NonNullOnParameter(@lombok.NonNull String arg) { this(arg, ""); if (arg == null) { throw new java.lang.NullPointerException("arg"); } } NonNullOnParameter(@lombok.NonNull String arg, @lombok.NonNull String arg2) { super(arg); if (arg2 == null) { throw new java.lang.NullPointerException("arg2"); } if (arg == null) throw new NullPointerException(); } public void test2(@lombok.NonNull String arg, @lombok.NonNull String arg2, @lombok.NonNull String arg3) { if (arg == null) { throw new java.lang.NullPointerException("arg"); } if (arg3 == null) { throw new java.lang.NullPointerException("arg3"); } if (arg2 == null) { throw new NullPointerException("arg2"); } if (arg == null) System.out.println("Hello"); } public void test3(@lombok.NonNull String arg) { if (arg == null) { throw new java.lang.NullPointerException("arg"); } if (arg != null) throw new IllegalStateException(); } public void test(@lombok.NonNull String stringArg, @lombok.NonNull String arg2, @lombok.NonNull int primitiveArg) { if (stringArg == null) { throw new java.lang.NullPointerException("stringArg"); } if (arg2 == null) { throw new java.lang.NullPointerException("arg2"); } } public void test(@lombok.NonNull String arg) { if (arg == null) { throw new java.lang.NullPointerException("arg"); } System.out.println("Hey"); if (arg == null) throw new NullPointerException(); } } lombok-1.16.18/test/transform/resource/after-delombok/NonNullOnParameterAbstract.java000066400000000000000000000004061312655740700307530ustar00rootroot00000000000000abstract class NonNullOnParameterAbstract { public void test(@lombok.NonNull String arg) { if (arg == null) { throw new java.lang.NullPointerException("arg"); } System.out.println("Hey"); } public abstract void test2(@lombok.NonNull String arg); } lombok-1.16.18/test/transform/resource/after-delombok/NonNullOnParameterOfDefaultMethod.java000066400000000000000000000004031312655740700322170ustar00rootroot00000000000000// version 8: interface NonNullOnParameterOfDefaultMethod { void test(@lombok.NonNull String arg); default void test2(@lombok.NonNull String arg) { if (arg == null) { throw new java.lang.NullPointerException("arg"); } System.out.println(arg); } } lombok-1.16.18/test/transform/resource/after-delombok/NonNullPlain.java000066400000000000000000000027101312655740700261150ustar00rootroot00000000000000import java.lang.annotation.*; class NonNullPlain { @lombok.NonNull int i; @lombok.NonNull String s; @NotNull Object o; @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) @Retention(RetentionPolicy.CLASS) public @interface NotNull { } @java.beans.ConstructorProperties({"i", "s"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public NonNullPlain(@lombok.NonNull final int i, @lombok.NonNull final String s) { if (s == null) { throw new java.lang.NullPointerException("s"); } this.i = i; this.s = s; } @lombok.NonNull @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getI() { return this.i; } @lombok.NonNull @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getS() { return this.s; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Object getO() { return this.o; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setI(@lombok.NonNull final int i) { this.i = i; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setS(@lombok.NonNull final String s) { if (s == null) { throw new java.lang.NullPointerException("s"); } this.s = s; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setO(final Object o) { this.o = o; } } lombok-1.16.18/test/transform/resource/after-delombok/NonNullWithAlternateException.java000066400000000000000000000007721312655740700315120ustar00rootroot00000000000000public class NonNullWithAlternateException { @lombok.NonNull private String test; public void testMethod(@lombok.NonNull String arg) { if (arg == null) { throw new java.lang.IllegalArgumentException("arg is null"); } System.out.println(arg); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setTest(@lombok.NonNull final String test) { if (test == null) { throw new java.lang.IllegalArgumentException("test is null"); } this.test = test; } } lombok-1.16.18/test/transform/resource/after-delombok/NonNullWithSneakyThrows.java000066400000000000000000000004271312655740700303520ustar00rootroot00000000000000class NonNullWithSneakyThrows { void test(@lombok.NonNull String in) { try { if (in == null) { throw new java.lang.NullPointerException("in"); } System.out.println(in); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } } lombok-1.16.18/test/transform/resource/after-delombok/OnXJava7Style.java000066400000000000000000000015731312655740700261700ustar00rootroot00000000000000//version :7 public class OnXJava7Style { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } String a; String b; String c; String d; String e; @Foo @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getA() { return this.a; } @Foo @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setB(final String b) { this.b = b; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setC(@Foo("a") final String c) { this.c = c; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setD(@Bar(stuff = "b") final String d) { this.d = d; } @Foo("c") @Bar(stuff = "d") @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getE() { return this.e; } } lombok-1.16.18/test/transform/resource/after-delombok/OnXJava8Style.java000066400000000000000000000015731312655740700261710ustar00rootroot00000000000000//version 8: public class OnXJava8Style { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } String a; String b; String c; String d; String e; @Foo @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getA() { return this.a; } @Foo @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setB(final String b) { this.b = b; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setC(@Foo("a") final String c) { this.c = c; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setD(@Bar(stuff = "b") final String d) { this.d = d; } @Foo("c") @Bar(stuff = "d") @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getE() { return this.e; } } lombok-1.16.18/test/transform/resource/after-delombok/SetterAccessLevel.java000066400000000000000000000016341312655740700271300ustar00rootroot00000000000000class SetterAccessLevel { boolean isNone; boolean isPrivate; boolean isPackage; boolean isProtected; boolean isPublic; boolean value; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private void setPrivate(final boolean isPrivate) { this.isPrivate = isPrivate; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPackage(final boolean isPackage) { this.isPackage = isPackage; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected void setProtected(final boolean isProtected) { this.isProtected = isProtected; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setPublic(final boolean isPublic) { this.isPublic = isPublic; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setValue(final boolean value) { this.value = value; } } lombok-1.16.18/test/transform/resource/after-delombok/SetterAlreadyExists.java000066400000000000000000000015151312655740700275160ustar00rootroot00000000000000class Setter1 { boolean foo; void setFoo(boolean foo) { } } class Setter2 { boolean foo; void setFoo(String foo) { } } class Setter3 { String foo; void setFoo(boolean foo) { } } class Setter4 { String foo; void setFoo(String foo) { } } class Setter5 { String foo; void setFoo() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setFoo(final String foo) { this.foo = foo; } } class Setter6 { String foo; void setFoo(String foo, int x) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setFoo(final String foo) { this.foo = foo; } } class Setter7 { String foo; void setFoo(String foo, Object... x) { } } class Setter8 { boolean isFoo; void setIsFoo(boolean foo) { } } class Setter9 { boolean isFoo; void setFoo(boolean foo) { } } lombok-1.16.18/test/transform/resource/after-delombok/SetterDeprecated.java000066400000000000000000000007371312655740700270020ustar00rootroot00000000000000class SetterDeprecated { @Deprecated int annotation; /** * @deprecated */ int javadoc; @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setAnnotation(final int annotation) { this.annotation = annotation; } /** * @deprecated */ @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setJavadoc(final int javadoc) { this.javadoc = javadoc; } } lombok-1.16.18/test/transform/resource/after-delombok/SetterOnClass.java000066400000000000000000000033571312655740700263050ustar00rootroot00000000000000class SetterOnClass1 { boolean isNone; boolean isPublic; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setPublic(final boolean isPublic) { this.isPublic = isPublic; } } class SetterOnClass2 { boolean isNone; boolean isProtected; boolean isPackage; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected void setProtected(final boolean isProtected) { this.isProtected = isProtected; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPackage(final boolean isPackage) { this.isPackage = isPackage; } } class SetterOnClass3 { boolean isNone; boolean isPackage; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPackage(final boolean isPackage) { this.isPackage = isPackage; } } class SetterOnClass4 { boolean isNone; boolean isPrivate; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private void setPrivate(final boolean isPrivate) { this.isPrivate = isPrivate; } } class SetterOnClass5 { boolean isNone; boolean isPublic; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setPublic(final boolean isPublic) { this.isPublic = isPublic; } } class SetterOnClass6 { String couldBeNull; @lombok.NonNull String nonNull; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setCouldBeNull(final String couldBeNull) { this.couldBeNull = couldBeNull; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setNonNull(@lombok.NonNull final String nonNull) { if (nonNull == null) { throw new java.lang.NullPointerException("nonNull"); } this.nonNull = nonNull; } } lombok-1.16.18/test/transform/resource/after-delombok/SetterOnMethodOnParam.java000066400000000000000000000010411312655740700277220ustar00rootroot00000000000000class SetterOnMethodOnParam { int i; int j; int k; public @interface Test { } @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setI(final int i) { this.i = i; } @java.lang.Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setJ(@Test final int j) { this.j = j; } @java.lang.Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setK(@Test final int k) { this.k = k; } } lombok-1.16.18/test/transform/resource/after-delombok/SetterOnStatic.java000066400000000000000000000005271312655740700264630ustar00rootroot00000000000000class Setter { static boolean foo; static int bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static void setFoo(final boolean foo) { Setter.foo = foo; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static void setBar(final int bar) { Setter.bar = bar; } } lombok-1.16.18/test/transform/resource/after-delombok/SetterPlain.java000066400000000000000000000004521312655740700257770ustar00rootroot00000000000000class SetterPlain { int i; int foo; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setI(final int i) { this.i = i; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setFoo(final int foo) { this.foo = foo; } } lombok-1.16.18/test/transform/resource/after-delombok/SetterWithDollar.java000066400000000000000000000007351312655740700270110ustar00rootroot00000000000000class SetterWithDollar1 { int $i; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void set$i(final int $i) { this.$i = $i; } } class SetterWithDollar2 { int $i; int i; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void set$i(final int $i) { this.$i = $i; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setI(final int i) { this.i = i; } } lombok-1.16.18/test/transform/resource/after-delombok/SimpleTypeResolution.java000066400000000000000000000003461312655740700277260ustar00rootroot00000000000000class SimpleTypeResolutionFail { @Getter private int x; } class SimpleTypeResolutionSuccess { private int x; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-delombok/SneakyThrowsMultiple.java000066400000000000000000000017671312655740700277340ustar00rootroot00000000000000import java.awt.AWTException; import java.io.IOException; import java.util.Random; class SneakyThrowsMultiple { public void test() { try { try { System.out.println("test1"); throw new IOException(); } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } catch (final Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public void test2() { try { try { System.out.println("test2"); if (new Random().nextBoolean()) { throw new IOException(); } else { throw new AWTException("WHAT"); } } catch (final AWTException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public void test3() { try { try { System.out.println("test3"); throw new IOException(); } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } catch (final Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } } lombok-1.16.18/test/transform/resource/after-delombok/SneakyThrowsPlain.java000066400000000000000000000012431312655740700271710ustar00rootroot00000000000000class SneakyThrowsPlain { SneakyThrowsPlain() { try { System.out.println("constructor"); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } SneakyThrowsPlain(int x) { this(); try { System.out.println("constructor2"); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public void test() { try { System.out.println("test1"); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public void test2() { try { System.out.println("test2"); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } } lombok-1.16.18/test/transform/resource/after-delombok/SneakyThrowsSingle.java000066400000000000000000000010471312655740700273510ustar00rootroot00000000000000import java.io.IOException; class SneakyThrowsSingle { public void test() { try { System.out.println("test1"); } catch (final Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public void test2() { try { System.out.println("test2"); throw new IOException(); } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public void test3() { try { System.out.println("test3"); throw new IOException(); } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } } lombok-1.16.18/test/transform/resource/after-delombok/SynchronizedName.java000066400000000000000000000005461312655740700270310ustar00rootroot00000000000000class SynchronizedName { private Object read = new Object(); private static Object READ = new Object(); void test1() { synchronized (this.read) { System.out.println("one"); } } void test4() { synchronized (this.READ) { System.out.println("four"); } } void test5() { synchronized (this.read) { System.out.println("five"); } } } lombok-1.16.18/test/transform/resource/after-delombok/SynchronizedNameNoSuchField.java000066400000000000000000000002471312655740700311130ustar00rootroot00000000000000class SynchronizedNameNoSuchField { private Object read = new Object(); private static Object READ = new Object(); void test2() { System.out.println("two"); } } lombok-1.16.18/test/transform/resource/after-delombok/SynchronizedNameStaticToInstanceRef.java000066400000000000000000000003711312655740700326220ustar00rootroot00000000000000class SynchronizedNameStaticToInstanceRef { private Object read = new Object(); private static Object READ = new Object(); static void test3() { synchronized (SynchronizedNameStaticToInstanceRef.read) { System.out.println("three"); } } } lombok-1.16.18/test/transform/resource/after-delombok/SynchronizedPlain.java000066400000000000000000000013201312655740700272030ustar00rootroot00000000000000class SynchronizedPlain1 { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private final java.lang.Object $lock = new java.lang.Object[0]; void test() { synchronized (this.$lock) { System.out.println("one"); } } void test2() { synchronized (this.$lock) { System.out.println("two"); } } } class SynchronizedPlain2 { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private static final java.lang.Object $LOCK = new java.lang.Object[0]; static void test() { synchronized (SynchronizedPlain2.$LOCK) { System.out.println("three"); } } static void test2() { synchronized (SynchronizedPlain2.$LOCK) { System.out.println("four"); } } } lombok-1.16.18/test/transform/resource/after-delombok/TestOperators.java000066400000000000000000000011361312655740700263630ustar00rootroot00000000000000class TestOperators { int x = 10; public void test() { x = 12; int a = +x; boolean d = true; boolean e = false; boolean b; a = -x; b = !d; a = ~x; a = ++x; a = --x; a = x++; a = x--; b = d || e; b = d && e; a = x | a; a = x ^ a; a = x & a; b = a == x; b = a != x; b = a < x; b = a > x; b = a <= x; b = a >= x; a = a << x; a = a >> x; a = a >>> x; a = a + x; a = a - x; a = a * x; a = a / x; a = a % x; a |= x; a ^= x; a &= x; a <<= x; a >>= x; a >>>= x; a += x; a -= x; a *= x; a /= x; a %= x; a = a > x ? 1 : 0; } } lombok-1.16.18/test/transform/resource/after-delombok/ToStringConfiguration.java000066400000000000000000000016341312655740700300510ustar00rootroot00000000000000class ToStringConfiguration { int x; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ToStringConfiguration(" + this.x + ")"; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } } class ToStringConfiguration2 { int x; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ToStringConfiguration2(x=" + this.x + ")"; } } class ToStringConfiguration3 { int x; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ToStringConfiguration3(" + this.getX() + ")"; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-delombok/ToStringInner.java000066400000000000000000000020331312655740700263070ustar00rootroot00000000000000class ToStringOuter { int x; String name; class ToStringInner { int y; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ToStringOuter.ToStringInner(y=" + this.y + ")"; } } static class ToStringStaticInner { int y; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ToStringOuter.ToStringStaticInner(y=" + this.y + ")"; } } class ToStringMiddle { class ToStringMoreInner { String name; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ToStringOuter.ToStringMiddle.ToStringMoreInner(name=" + this.name + ")"; } } } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ToStringOuter(x=" + this.x + ", name=" + this.name + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/ToStringPlain.java000066400000000000000000000007461312655740700263100ustar00rootroot00000000000000class ToString1 { int x; String name; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ToString1(x=" + this.x + ", name=" + this.name + ")"; } } class ToString2 { int x; String name; @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ToString2(x=" + this.x + ", name=" + this.name + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/Tolerate.java000066400000000000000000000025551312655740700253320ustar00rootroot00000000000000import java.util.regex.Pattern; class Tolerate { private Pattern pattern; @lombok.experimental.Tolerate public void setPattern(String pattern) { setPattern(Pattern.compile(pattern)); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public void setPattern(final Pattern pattern) { this.pattern = pattern; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Pattern getPattern() { return this.pattern; } } class Tolerate2 { private final Pattern pattern; @lombok.experimental.Tolerate public Tolerate2 withPattern(String pattern) { return withPattern(Pattern.compile(pattern)); } public Tolerate2 withPattern(String nameGlob, String extensionGlob) { return withPattern(nameGlob.replace("*", ".*") + "\\." + extensionGlob.replace("*", ".*")); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Pattern getPattern() { return this.pattern; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Tolerate2 withPattern(final Pattern pattern) { return this.pattern == pattern ? this : new Tolerate2(pattern); } @java.beans.ConstructorProperties({"pattern"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Tolerate2(final Pattern pattern) { this.pattern = pattern; } } lombok-1.16.18/test/transform/resource/after-delombok/TrickyTypeResolution.java000066400000000000000000000014211312655740700277350ustar00rootroot00000000000000import lombok.*; class TrickyDoNothing { @interface Getter { } @Getter int x; } class TrickyDoNothing2 { @Getter int x; @interface Getter { } } class TrickySuccess { int x; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } } class TrickyDoNothing3 { void test() { class val { } val x = null; } } class TrickyDoSomething { void test() { final java.lang.Object x = null; class val { } } } class DoubleTrickyDoNothing { void test() { class val { } for (int i = 10; i < 20; i++) { val y = null; } } } class DoubleTrickyDoSomething { void test() { for (int j = 10; j < 20; j++) { class val { } } for (int i = 10; i < 20; i++) { final java.lang.Object y = null; } } } lombok-1.16.18/test/transform/resource/after-delombok/TrickyTypeResolution2.java000066400000000000000000000001421312655740700300160ustar00rootroot00000000000000import lombok.*; class DoNothingDueToTopLevel { void test() { val x = null; } } class val { } lombok-1.16.18/test/transform/resource/after-delombok/UtilityClass.java000066400000000000000000000026061312655740700262010ustar00rootroot00000000000000final class UtilityClass { private static long someField = System.currentTimeMillis(); static void someMethod() { System.out.println(); } protected static class InnerClass { private String innerInnerMember; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private UtilityClass() { throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } } class UtilityInner { static class InnerInner { static final class InnerInnerInner { static int member; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private InnerInnerInner() { throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } } } enum UtilityInsideEnum { FOO, BAR; static final class InsideEnum { static int member; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private InsideEnum() { throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } } } interface UtilityInsideInterface { final class InsideInterface { static int member; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private InsideInterface() { throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } } } } lombok-1.16.18/test/transform/resource/after-delombok/UtilityClassErrors.java000066400000000000000000000004661312655740700274000ustar00rootroot00000000000000final class UtilityClassErrors1 { private static String someField; protected UtilityClassErrors1() { } static void method() { class MethodLocalClass { } } } enum UtilityClassErrors2 { ; } class UtilityClassErrors3 { class NonStaticInner { class ThisShouldFail { private String member; } } } lombok-1.16.18/test/transform/resource/after-delombok/ValAnonymousSubclassWithGenerics.java000066400000000000000000000005751312655740700322220ustar00rootroot00000000000000import java.util.*; public class ValAnonymousSubclassWithGenerics { Object object = new Object() { void foo() { final int j = 1; } }; void bar() { final int k = super.hashCode(); int x = k; } java.util.List names = new java.util.ArrayList() { public String get(int i) { final java.lang.String result = super.get(i); return result; } }; } lombok-1.16.18/test/transform/resource/after-delombok/ValComplex.java000066400000000000000000000010501312655740700256120ustar00rootroot00000000000000public class ValComplex { private String field = ""; private static final int CONSTANT = 20; public void testComplex() { final char[] shouldBeCharArray = field.toCharArray(); final int shouldBeInt = CONSTANT; final java.lang.Object lock = new Object(); synchronized (lock) { final int field = 20; //Shadowing final int inner = 10; switch (field) { case 5: final char[] shouldBeCharArray2 = shouldBeCharArray; final int innerInner = inner; } } final java.lang.String shouldBeString = field; //Unshadowing } } lombok-1.16.18/test/transform/resource/after-delombok/ValDefault.java000066400000000000000000000001761312655740700255770ustar00rootroot00000000000000// version 8: interface ValDefault { int size(); default void method() { final int x = 1; final int size = size(); } } lombok-1.16.18/test/transform/resource/after-delombok/ValErrors.java000066400000000000000000000002451312655740700254640ustar00rootroot00000000000000public class ValErrors { public void unresolvableExpression() { final java.lang.Object c = d; } public void arrayInitializer() { val e = {"foo", "bar"}; } } lombok-1.16.18/test/transform/resource/after-delombok/ValFinal.java000066400000000000000000000001071312655740700252360ustar00rootroot00000000000000public class ValFinal { public void test() { final int x = 10; } } lombok-1.16.18/test/transform/resource/after-delombok/ValInBasicFor.java000066400000000000000000000003611312655740700261660ustar00rootroot00000000000000import lombok.val; public class ValInBasicFor { public void basicFor() { java.util.List list = java.util.Arrays.asList("Hello, World!"); for (val shouldBe = 1, marked = "", error = 1.0; ; ) { System.out.println(""); } } } lombok-1.16.18/test/transform/resource/after-delombok/ValInFor.java000066400000000000000000000004601312655740700252240ustar00rootroot00000000000000public class ValInFor { public void enhancedFor() { java.util.List list = java.util.Arrays.asList("Hello, World!"); for (final java.lang.String shouldBeString : list) { System.out.println(shouldBeString.toLowerCase()); final java.lang.String shouldBeString2 = shouldBeString; } } } lombok-1.16.18/test/transform/resource/after-delombok/ValInLambda.java000066400000000000000000000005461312655740700256630ustar00rootroot00000000000000// version 8: class ValInLambda { Runnable foo = (Runnable) () -> { final int i = 1; }; public void easyLambda() { Runnable foo = (Runnable) () -> { final int i = 1; }; } public void easyIntersectionLambda() { Runnable foo = (Runnable) () -> { final int i = 1; }; } } lombok-1.16.18/test/transform/resource/after-delombok/ValInMultiDeclaration.java000066400000000000000000000001651312655740700277400ustar00rootroot00000000000000public class ValInMultiDeclaration { public void test() { final int x = 10; final java.lang.String y = ""; } } lombok-1.16.18/test/transform/resource/after-delombok/ValInTryWithResources.java000066400000000000000000000004641312655740700300070ustar00rootroot00000000000000//version 7: import java.io.IOException; public class ValInTryWithResources { public void whyTryInsteadOfCleanup() throws IOException { try (java.io.InputStream in = getClass().getResourceAsStream("ValInTryWithResources.class")) { final java.io.InputStream i = in; final int j = in.read(); } } } lombok-1.16.18/test/transform/resource/after-delombok/ValLambda.java000066400000000000000000000013161312655740700253700ustar00rootroot00000000000000// version 8: class ValLambda { public void easyLambda() { final java.lang.Runnable foo = (Runnable) () -> { }; } public void easyIntersectionLambda() { final java.lang.Object foo = (Runnable & java.io.Serializable) () -> { }; final java.lang.Object bar = (java.io.Serializable & Runnable) () -> { }; } public void easyLubLambda() { final java.lang.Runnable foo = (System.currentTimeMillis() > 0) ? (Runnable) () -> { } : (Runnable) System.out::println; } // public void castLubLambda() { // Runnable foo = (Runnable) ((System.currentTimeMillis() > 0) ? () -> {} : System.out::println); // lombok.val foo = (Runnable) ((System.currentTimeMillis() > 0) ? () -> {} : System.out::println); // } } lombok-1.16.18/test/transform/resource/after-delombok/ValLessSimple.java000066400000000000000000000012321312655740700262650ustar00rootroot00000000000000public class ValLessSimple { private short field2 = 5; private String method() { return "method"; } private double method2() { return 2.0; } { System.out.println("Hello"); final int z = 20; final int x = 10; final int a = z; final short y = field2; } private void testVal(String param) { final java.lang.String fieldV = field; final int a = 10; final int b = 20; { final java.lang.String methodV = method(); final java.lang.String foo = fieldV + methodV; } } private void testValInCatchBlock() { try { final int x = 1 / 0; } catch (ArithmeticException e) { final int y = 0; } } private String field = "field"; } lombok-1.16.18/test/transform/resource/after-delombok/ValLub.java000066400000000000000000000015041312655740700247310ustar00rootroot00000000000000class ValLub { public void easyLub() { java.util.Map m = java.util.Collections.emptyMap(); final java.util.Map foo = (System.currentTimeMillis() > 0) ? m : java.util.Collections.emptyMap(); } public void sillyLubWithUnboxingThatProducesErrorThatVarIsPrimitive() { Integer i = 20; Double d = 20.0; final double thisShouldBePrimitiveDouble = (System.currentTimeMillis() > 0) ? i : d; } public void hardLub() { java.util.List list = new java.util.ArrayList(); java.util.Set set = new java.util.HashSet(); final java.util.Collection thisShouldBeCollection = (System.currentTimeMillis() > 0) ? list : set; thisShouldBeCollection.add(""); String foo = thisShouldBeCollection.iterator().next(); } } lombok-1.16.18/test/transform/resource/after-delombok/ValNullInit.java000066400000000000000000000001151312655740700257420ustar00rootroot00000000000000class ValNullInit { void method() { final java.lang.Object x = null; } } lombok-1.16.18/test/transform/resource/after-delombok/ValOutersWithGenerics.java000066400000000000000000000021711312655740700300050ustar00rootroot00000000000000import java.util.*; public class ValOutersWithGenerics { class Inner { } class InnerWithGenerics { } public void testOutersWithGenerics() { final java.lang.String foo = ""; List list = new ArrayList(); final ValOutersWithGenerics.Inner elem = list.get(0); } public void testLocalClasses() { class Local { } final Local q = new Local(); } public static void test() { final ValOutersWithGenerics outer = new ValOutersWithGenerics(); final ValOutersWithGenerics.Inner inner1 = outer.new Inner(); final ValOutersWithGenerics.InnerWithGenerics inner2 = outer.new InnerWithGenerics(); } static class SubClass extends ValOutersWithGenerics { public void testSubClassOfOutersWithGenerics() { List list = new ArrayList(); final ValOutersWithGenerics.Inner elem = list.get(0); } } public static void loop(Map map) { for (final java.util.Map.Entry e : map.entrySet()) { } } } lombok-1.16.18/test/transform/resource/after-delombok/ValRawType.java000066400000000000000000000005461312655740700256070ustar00rootroot00000000000000import java.util.List; public class ValRawType { public void test() { Element propElement = new Element(); for (final java.lang.Object attribute : propElement.attributes()) { final ValRawType.Attribute attr = (Attribute) attribute; } } static class Element { public List attributes() { return null; } } static class Attribute { } } lombok-1.16.18/test/transform/resource/after-delombok/ValSimple.java000066400000000000000000000011121312655740700254330ustar00rootroot00000000000000public class ValSimple { private String field = "field"; private short field2 = 5; private String method() { return "method"; } private double method2() { return 2.0; } private void testVal(String param) { final java.lang.String fieldV = field; final java.lang.String methodV = method(); final java.lang.String paramV = param; final java.lang.String valOfVal = fieldV; final java.lang.String operatorV = fieldV + valOfVal; final short fieldW = field2; final double methodW = method2(); byte localVar = 3; final int operatorW = fieldW + localVar; } } lombok-1.16.18/test/transform/resource/after-delombok/ValWeirdTypes.java000066400000000000000000000041121312655740700263040ustar00rootroot00000000000000import java.util.*; public class ValWeirdTypes { private List fieldList; public void testGenerics() { List list = new ArrayList(); list.add("Hello, World!"); final java.lang.String shouldBeString = list.get(0); final java.util.List shouldBeListOfString = list; final java.util.List shouldBeListOfStringToo = Arrays.asList("hello", "world"); final java.lang.String shouldBeString2 = shouldBeListOfString.get(0); } public void testGenericsInference() { final java.util.List huh = Collections.emptyList(); final java.util.List huh2 = Collections.emptyList(); } public void testPrimitives() { final int x = 10; final long y = 5 + 3L; } public void testAnonymousInnerClass() { final java.lang.Runnable y = new Runnable() { public void run() { } }; } public void testTypeParams(List param) { final T t = param.get(0); final Z z = fieldList.get(0); final java.util.List k = param; final java.util.List y = fieldList; } public void testBounds(List lower, List upper) { final java.lang.Number a = lower.get(0); final java.lang.Object b = upper.get(0); final java.util.List c = lower; final java.util.List d = upper; List unbound = lower; final java.util.List e = unbound; } public void testCompound() { final java.util.ArrayList a = new ArrayList(); final java.util.Vector b = new Vector(); final boolean c = 1 < System.currentTimeMillis(); final java.util.AbstractList d = c ? a : b; java.util.RandomAccess confirm = c ? a : b; } public void nullType() { final java.lang.Object nully = null; } public void testArrays() { final int[] intArray = new int[] {1, 2, 3}; final java.lang.Object[][] multiDimArray = new Object[][] {{}}; final int[] copy = intArray; final java.lang.Object[] single = multiDimArray[0]; final int singleInt = copy[0]; } } lombok-1.16.18/test/transform/resource/after-delombok/ValWithLabel.java000066400000000000000000000002371312655740700260640ustar00rootroot00000000000000public class ValWithLabel { { LABEL: for (final java.lang.String x : new String[0]) { if (x.toLowerCase() == null) { continue LABEL; } } } } lombok-1.16.18/test/transform/resource/after-delombok/ValWithLocalClasses.java000066400000000000000000000002421312655740700274110ustar00rootroot00000000000000class ValWithLocalClasses1 { { final ValWithLocalClasses2 f2 = new ValWithLocalClasses2() { }; } } class ValWithLocalClasses2 { { final int f3 = 0; } } lombok-1.16.18/test/transform/resource/after-delombok/ValueCallSuper.java000066400000000000000000000021771312655740700264420ustar00rootroot00000000000000class ValueParent { } final class ValueCallSuper extends ValueParent { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ValueCallSuper() { } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof ValueCallSuper)) return false; final ValueCallSuper other = (ValueCallSuper) o; if (!other.canEqual((java.lang.Object) this)) return false; if (!super.equals(o)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof ValueCallSuper; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + super.hashCode(); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ValueCallSuper()"; } } lombok-1.16.18/test/transform/resource/after-delombok/ValueExperimental.java000066400000000000000000000026501312655740700272010ustar00rootroot00000000000000final class ValueExperimental1 { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ValueExperimental1() { } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof ValueExperimental1)) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ValueExperimental1()"; } } final class ValueExperimental2 { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ValueExperimental2() { } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof ValueExperimental2)) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ValueExperimental2()"; } } lombok-1.16.18/test/transform/resource/after-delombok/ValueExperimentalStarImport.java000066400000000000000000000014311312655740700312220ustar00rootroot00000000000000import lombok.experimental.*; final class ValueExperimentalStarImport { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ValueExperimentalStarImport() { } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof ValueExperimentalStarImport)) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ValueExperimentalStarImport()"; } } lombok-1.16.18/test/transform/resource/after-delombok/ValuePlain.java000066400000000000000000000112171312655740700256060ustar00rootroot00000000000000final class Value1 { private final int x; private final String name; @java.beans.ConstructorProperties({"x", "name"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Value1(final int x, final String name) { this.x = x; this.name = name; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getName() { return this.name; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Value1)) return false; final Value1 other = (Value1) o; if (this.getX() != other.getX()) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Value1(x=" + this.getX() + ", name=" + this.getName() + ")"; } } class Value2 { public final int x; private final String name; @java.beans.ConstructorProperties({"x", "name"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Value2(final int x, final String name) { this.x = x; this.name = name; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public String getName() { return this.name; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Value2)) return false; final Value2 other = (Value2) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.getX() != other.getX()) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; return true; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected boolean canEqual(final java.lang.Object other) { return other instanceof Value2; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Value2(x=" + this.getX() + ", name=" + this.getName() + ")"; } } final class Value3 { private int x; private final int y; @java.beans.ConstructorProperties({"x", "y"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Value3(final int x, final int y) { this.x = x; this.y = y; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int getY() { return this.y; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof Value3)) return false; final Value3 other = (Value3) o; if (this.getX() != other.getX()) return false; if (this.getY() != other.getY()) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); result = result * PRIME + this.getY(); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "Value3(x=" + this.getX() + ", y=" + this.getY() + ")"; } } lombok-1.16.18/test/transform/resource/after-delombok/ValueStaticField.java000066400000000000000000000014041312655740700267330ustar00rootroot00000000000000final class ValueStaticField { static int x; static String PASSWORD = "Ken sent me"; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public ValueStaticField() { } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof ValueStaticField)) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { int result = 1; return result; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "ValueStaticField()"; } } lombok-1.16.18/test/transform/resource/after-delombok/VarComplex.java000066400000000000000000000007701312655740700256300ustar00rootroot00000000000000public class VarComplex { private String field = ""; private static final int CONSTANT = 20; public void testComplex() { char[] shouldBeCharArray = field.toCharArray(); int shouldBeInt = CONSTANT; java.lang.Object lock = new Object(); synchronized (lock) { int field = 20; //Shadowing int inner = 10; switch (field) { case 5: char[] shouldBeCharArray2 = shouldBeCharArray; int innerInner = inner; } } java.lang.String shouldBeString = field; //Unshadowing } } lombok-1.16.18/test/transform/resource/after-delombok/VarInFor.java000066400000000000000000000003071312655740700252320ustar00rootroot00000000000000public class VarInFor { public void enhancedFor() { int[] list = new int[] {1, 2}; for (int shouldBeInt : list) { System.out.println(shouldBeInt); int shouldBeInt2 = shouldBeInt; } } } lombok-1.16.18/test/transform/resource/after-delombok/VarInForOld.java000066400000000000000000000001701312655740700256670ustar00rootroot00000000000000public class VarInForOld { public void oldFor() { for (int i = 0; i < 100; ++i) { System.out.println(i); } } } lombok-1.16.18/test/transform/resource/after-delombok/VarModifier.java000066400000000000000000000003101312655740700257450ustar00rootroot00000000000000public class VarModifier { private String field = ""; public void testComplex() { final char[] shouldBeFinalCharArray = field.toCharArray(); char[] shouldBeCharArray = field.toCharArray(); } } lombok-1.16.18/test/transform/resource/after-delombok/VarNullInit.java000066400000000000000000000001171312655740700257520ustar00rootroot00000000000000 public class VarNullInit { void method() { java.lang.Object x = null; } } lombok-1.16.18/test/transform/resource/after-delombok/WithInnerAnnotation.java000066400000000000000000000001151312655740700275030ustar00rootroot00000000000000class WithInnerAnnotation { @interface Inner { int bar() default 42; } } lombok-1.16.18/test/transform/resource/after-delombok/WitherAccessLevel.java000066400000000000000000000033221312655740700271200ustar00rootroot00000000000000class WitherAccessLevel { boolean isNone; boolean isPrivate; boolean isPackage; boolean isProtected; boolean isPublic; boolean value; WitherAccessLevel(boolean isNone, boolean isPrivate, boolean isPackage, boolean isProtected, boolean isPublic, boolean value) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private WitherAccessLevel withPrivate(final boolean isPrivate) { return this.isPrivate == isPrivate ? this : new WitherAccessLevel(this.isNone, isPrivate, this.isPackage, this.isProtected, this.isPublic, this.value); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherAccessLevel withPackage(final boolean isPackage) { return this.isPackage == isPackage ? this : new WitherAccessLevel(this.isNone, this.isPrivate, isPackage, this.isProtected, this.isPublic, this.value); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected WitherAccessLevel withProtected(final boolean isProtected) { return this.isProtected == isProtected ? this : new WitherAccessLevel(this.isNone, this.isPrivate, this.isPackage, isProtected, this.isPublic, this.value); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherAccessLevel withPublic(final boolean isPublic) { return this.isPublic == isPublic ? this : new WitherAccessLevel(this.isNone, this.isPrivate, this.isPackage, this.isProtected, isPublic, this.value); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherAccessLevel withValue(final boolean value) { return this.value == value ? this : new WitherAccessLevel(this.isNone, this.isPrivate, this.isPackage, this.isProtected, this.isPublic, value); } } lombok-1.16.18/test/transform/resource/after-delombok/WitherAlreadyExists.java000066400000000000000000000022201312655740700275040ustar00rootroot00000000000000class Wither1 { boolean foo; void withFoo(boolean foo) { } Wither1(boolean foo) { } } class Wither2 { boolean foo; void withFoo(String foo) { } Wither2(boolean foo) { } } class Wither3 { String foo; void withFoo(boolean foo) { } Wither3(String foo) { } } class Wither4 { String foo; void withFoo(String foo) { } Wither4(String foo) { } } class Wither5 { String foo; void withFoo() { } Wither5(String foo) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Wither5 withFoo(final String foo) { return this.foo == foo ? this : new Wither5(foo); } } class Wither6 { String foo; void withFoo(String foo, int x) { } Wither6(String foo) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public Wither6 withFoo(final String foo) { return this.foo == foo ? this : new Wither6(foo); } } class Wither7 { String foo; void withFoo(String foo, Object... x) { } Wither7(String foo) { } } class Wither8 { boolean isFoo; void withIsFoo(boolean foo) { } Wither8(boolean foo) { } } class Wither9 { boolean isFoo; void withFoo(boolean foo) { } Wither9(boolean foo) { } } lombok-1.16.18/test/transform/resource/after-delombok/WitherAndAllArgsConstructor.java000066400000000000000000000020001312655740700311350ustar00rootroot00000000000000class WitherAndAllArgsConstructor { J test; java.util.List test2; final int x = 10; int y = 20; final int z; @java.beans.ConstructorProperties({"test", "test2", "y", "z"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherAndAllArgsConstructor(final J test, final java.util.List test2, final int y, final int z) { this.test = test; this.test2 = test2; this.y = y; this.z = z; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherAndAllArgsConstructor withTest(final J test) { return this.test == test ? this : new WitherAndAllArgsConstructor(test, this.test2, this.y, this.z); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherAndAllArgsConstructor withTest2(final java.util.List test2) { return this.test2 == test2 ? this : new WitherAndAllArgsConstructor(this.test, test2, this.y, this.z); } } lombok-1.16.18/test/transform/resource/after-delombok/WitherDeprecated.java000066400000000000000000000012551312655740700267720ustar00rootroot00000000000000class WitherDeprecated { @Deprecated int annotation; /** * @deprecated */ int javadoc; WitherDeprecated(int annotation, int javadoc) { } @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherDeprecated withAnnotation(final int annotation) { return this.annotation == annotation ? this : new WitherDeprecated(annotation, this.javadoc); } /** * @deprecated */ @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherDeprecated withJavadoc(final int javadoc) { return this.javadoc == javadoc ? this : new WitherDeprecated(this.annotation, javadoc); } } lombok-1.16.18/test/transform/resource/after-delombok/WitherOnClass.java000066400000000000000000000037061312655740700262770ustar00rootroot00000000000000class WitherOnClass1 { boolean isNone; boolean isPublic; WitherOnClass1(boolean isNone, boolean isPublic) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherOnClass1 withPublic(final boolean isPublic) { return this.isPublic == isPublic ? this : new WitherOnClass1(this.isNone, isPublic); } } class WitherOnClass2 { boolean isNone; boolean isProtected; boolean isPackage; WitherOnClass2(boolean isNone, boolean isProtected, boolean isPackage) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") protected WitherOnClass2 withProtected(final boolean isProtected) { return this.isProtected == isProtected ? this : new WitherOnClass2(this.isNone, isProtected, this.isPackage); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherOnClass2 withPackage(final boolean isPackage) { return this.isPackage == isPackage ? this : new WitherOnClass2(this.isNone, this.isProtected, isPackage); } } class WitherOnClass3 { String couldBeNull; @lombok.NonNull String nonNull; WitherOnClass3(String couldBeNull, String nonNull) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherOnClass3 withCouldBeNull(final String couldBeNull) { return this.couldBeNull == couldBeNull ? this : new WitherOnClass3(couldBeNull, this.nonNull); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherOnClass3 withNonNull(@lombok.NonNull final String nonNull) { if (nonNull == null) { throw new java.lang.NullPointerException("nonNull"); } return this.nonNull == nonNull ? this : new WitherOnClass3(this.couldBeNull, nonNull); } } class WitherOnClass4 { final int fX = 10; final int fY; WitherOnClass4(int y) { this.fY = y; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherOnClass4 withY(final int fY) { return this.fY == fY ? this : new WitherOnClass4(fY); } } lombok-1.16.18/test/transform/resource/after-delombok/WitherOnStatic.java000066400000000000000000000000771312655740700264570ustar00rootroot00000000000000class WitherOnStatic { static boolean foo; static int bar; } lombok-1.16.18/test/transform/resource/after-delombok/WitherPlain.java000066400000000000000000000007361312655740700260000ustar00rootroot00000000000000class WitherPlain { int i; final int foo; WitherPlain(int i, int foo) { this.i = i; this.foo = foo; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherPlain withI(final int i) { return this.i == i ? this : new WitherPlain(i, this.foo); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherPlain withFoo(final int foo) { return this.foo == foo ? this : new WitherPlain(this.i, foo); } } lombok-1.16.18/test/transform/resource/after-delombok/WitherWithAbstract.java000066400000000000000000000002751312655740700273320ustar00rootroot00000000000000abstract class WitherWithAbstract { String foo; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public abstract WitherWithAbstract withFoo(final String foo); } lombok-1.16.18/test/transform/resource/after-delombok/WitherWithDollar.java000066400000000000000000000000441312655740700267760ustar00rootroot00000000000000class WitherWithDollar { int $i; } lombok-1.16.18/test/transform/resource/after-delombok/WitherWithGenerics.java000066400000000000000000000017711312655740700273300ustar00rootroot00000000000000class WitherWithGenerics { J test; java.util.List test2; java.util.List test3; int $i; public WitherWithGenerics(J test, java.util.List test2, java.util.List test3) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherWithGenerics withTest(final J test) { return this.test == test ? this : new WitherWithGenerics(test, this.test2, this.test3); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherWithGenerics withTest2(final java.util.List test2) { return this.test2 == test2 ? this : new WitherWithGenerics(this.test, test2, this.test3); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public WitherWithGenerics withTest3(final java.util.List test3) { return this.test3 == test3 ? this : new WitherWithGenerics(this.test, this.test2, test3); } } lombok-1.16.18/test/transform/resource/after-ecj/000077500000000000000000000000001312655740700216465ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/after-ecj/Accessors.java000066400000000000000000000120101312655740700244300ustar00rootroot00000000000000class AccessorsFluent { private @lombok.Getter @lombok.Setter @lombok.experimental.Accessors(fluent = true) String fieldName = ""; AccessorsFluent() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String fieldName() { return this.fieldName; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") AccessorsFluent fieldName(final String fieldName) { this.fieldName = fieldName; return this; } } @lombok.experimental.Accessors(fluent = true) @lombok.Getter class AccessorsFluentOnClass { private @lombok.Setter String fieldName = ""; private @lombok.experimental.Accessors String otherFieldWithOverride = ""; AccessorsFluentOnClass() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") AccessorsFluentOnClass fieldName(final String fieldName) { this.fieldName = fieldName; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String fieldName() { return this.fieldName; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getOtherFieldWithOverride() { return this.otherFieldWithOverride; } } class AccessorsChain { private @lombok.Setter @lombok.experimental.Accessors(chain = true) boolean isRunning; AccessorsChain() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") AccessorsChain setRunning(final boolean isRunning) { this.isRunning = isRunning; return this; } } @lombok.experimental.Accessors(prefix = "f") class AccessorsPrefix { private @lombok.Setter String fieldName; private @lombok.Setter String fActualField; AccessorsPrefix() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setActualField(final String fActualField) { this.fActualField = fActualField; } } @lombok.experimental.Accessors(prefix = {"f", ""}) class AccessorsPrefix2 { private @lombok.Setter String fieldName; private @lombok.Setter String fActualField; AccessorsPrefix2() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setFieldName(final String fieldName) { this.fieldName = fieldName; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setActualField(final String fActualField) { this.fActualField = fActualField; } } @lombok.experimental.Accessors(prefix = "f") @lombok.ToString @lombok.EqualsAndHashCode class AccessorsPrefix3 { private String fName; AccessorsPrefix3() { super(); } private String getName() { return fName; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("AccessorsPrefix3(fName=" + this.getName()) + ")"); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof AccessorsPrefix3))) return false; final AccessorsPrefix3 other = (AccessorsPrefix3) o; if ((! other.canEqual((java.lang.Object) this))) return false; final java.lang.Object this$fName = this.getName(); final java.lang.Object other$fName = other.getName(); if (((this$fName == null) ? (other$fName != null) : (! this$fName.equals(other$fName)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof AccessorsPrefix3); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $fName = this.getName(); result = ((result * PRIME) + (($fName == null) ? 43 : $fName.hashCode())); return result; } } class AccessorsFluentGenerics { private @lombok.Setter @lombok.experimental.Accessors(fluent = true) String name; AccessorsFluentGenerics() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") AccessorsFluentGenerics name(final String name) { this.name = name; return this; } } class AccessorsFluentNoChaining { private @lombok.Setter @lombok.experimental.Accessors(fluent = true,chain = false) String name; AccessorsFluentNoChaining() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void name(final String name) { this.name = name; } } class AccessorsFluentStatic { private static @lombok.Setter @lombok.experimental.Accessors(fluent = true) String name; () { } AccessorsFluentStatic() { super(); } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void name(final String name) { AccessorsFluentStatic.name = name; } } lombok-1.16.18/test/transform/resource/after-ecj/AccessorsConfiguration.java000066400000000000000000000022741312655740700271730ustar00rootroot00000000000000class AccessorsConfiguration { private @lombok.Getter @lombok.Setter @lombok.experimental.Accessors(fluent = true) String m_FieldName = ""; AccessorsConfiguration() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String fieldName() { return this.m_FieldName; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void fieldName(final String m_FieldName) { this.m_FieldName = m_FieldName; } } @lombok.experimental.Accessors(prefix = {}) class AccessorsConfiguration2 { private @lombok.Setter String m_FieldName = ""; AccessorsConfiguration2() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setM_FieldName(final String m_FieldName) { this.m_FieldName = m_FieldName; } } @lombok.experimental.Accessors(chain = true) class AccessorsConfiguration3 { private @lombok.Setter String fFieldName = ""; AccessorsConfiguration3() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") AccessorsConfiguration3 setFieldName(final String fFieldName) { this.fFieldName = fFieldName; return this; } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderChainAndFluent.java000066400000000000000000000025531312655740700266500ustar00rootroot00000000000000@lombok.experimental.Builder(fluent = false,chain = false) class BuilderChainAndFluent { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderChainAndFluentBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int yes; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderChainAndFluentBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setYes(final int yes) { this.yes = yes; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderChainAndFluent build() { return new BuilderChainAndFluent(yes); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("BuilderChainAndFluent.BuilderChainAndFluentBuilder(yes=" + this.yes) + ")"); } } private final int yes; @java.beans.ConstructorProperties({"yes"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderChainAndFluent(final int yes) { super(); this.yes = yes; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderChainAndFluentBuilder builder() { return new BuilderChainAndFluentBuilder(); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderComplex.java000066400000000000000000000043741312655740700254370ustar00rootroot00000000000000import java.util.List; import lombok.experimental.Builder; class BuilderComplex { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class VoidBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") T number; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int arg2; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String arg3; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderComplex selfRef; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") VoidBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") VoidBuilder number(final T number) { this.number = number; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") VoidBuilder arg2(final int arg2) { this.arg2 = arg2; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") VoidBuilder arg3(final String arg3) { this.arg3 = arg3; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") VoidBuilder selfRef(final BuilderComplex selfRef) { this.selfRef = selfRef; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void execute() { BuilderComplex.testVoidWithGenerics(number, arg2, arg3, selfRef); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((((("BuilderComplex.VoidBuilder(number=" + this.number) + ", arg2=") + this.arg2) + ", arg3=") + this.arg3) + ", selfRef=") + this.selfRef) + ")"); } } BuilderComplex() { super(); } private static @Builder(buildMethodName = "execute") void testVoidWithGenerics(T number, int arg2, String arg3, BuilderComplex selfRef) { } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") VoidBuilder builder() { return new VoidBuilder(); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderDefaults.java000066400000000000000000000105661312655740700255770ustar00rootroot00000000000000import lombok.Builder; import lombok.Value; public final @Value @Builder class BuilderDefaults { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderDefaultsBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int x; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean x$set; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String name; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") long z; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean z$set; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsBuilder x(final int x) { this.x = x; x$set = true; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsBuilder name(final String name) { this.name = name; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsBuilder z(final long z) { this.z = z; z$set = true; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaults build() { return new BuilderDefaults((x$set ? x : BuilderDefaults.$default$x()), name, (z$set ? z : BuilderDefaults.$default$z())); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("BuilderDefaults.BuilderDefaultsBuilder(x=" + this.x) + ", name=") + this.name) + ", z=") + this.z) + ")"); } } private final @Builder.Default int x; private final String name; private final @Builder.Default long z; private static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int $default$x() { return 10; } private static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") long $default$z() { return System.currentTimeMillis(); } @java.beans.ConstructorProperties({"x", "name", "z"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaults(final int x, final String name, final long z) { super(); this.x = x; this.name = name; this.z = z; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsBuilder builder() { return new BuilderDefaultsBuilder(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getName() { return this.name; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") long getZ() { return this.z; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof BuilderDefaults))) return false; final BuilderDefaults other = (BuilderDefaults) o; if ((this.getX() != other.getX())) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name)))) return false; if ((this.getZ() != other.getZ())) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); final java.lang.Object $name = this.getName(); result = ((result * PRIME) + (($name == null) ? 43 : $name.hashCode())); final long $z = this.getZ(); result = ((result * PRIME) + (int) ($z ^ ($z >>> 32))); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("BuilderDefaults(x=" + this.getX()) + ", name=") + this.getName()) + ", z=") + this.getZ()) + ")"); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderDefaultsWarnings.java000066400000000000000000000103171312655740700273020ustar00rootroot00000000000000import lombok.Builder; import lombok.Singular; public @Builder class BuilderDefaultsWarnings { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderDefaultsWarningsBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") long x; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int z; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList items; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarningsBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarningsBuilder x(final long x) { this.x = x; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarningsBuilder z(final int z) { this.z = z; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarningsBuilder item(String item) { if ((this.items == null)) this.items = new java.util.ArrayList(); this.items.add(item); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarningsBuilder items(java.util.Collection items) { if ((this.items == null)) this.items = new java.util.ArrayList(); this.items.addAll(items); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarningsBuilder clearItems() { if ((this.items != null)) this.items.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarnings build() { java.util.List items; switch (((this.items == null) ? 0 : this.items.size())) { case 0 : items = java.util.Collections.emptyList(); break; case 1 : items = java.util.Collections.singletonList(this.items.get(0)); break; default : items = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.items)); } return new BuilderDefaultsWarnings(x, z, items); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("BuilderDefaultsWarnings.BuilderDefaultsWarningsBuilder(x=" + this.x) + ", z=") + this.z) + ", items=") + this.items) + ")"); } } long x = System.currentTimeMillis(); final int y = 5; @Builder.Default int z; @Builder.Default @Singular java.util.List items; @java.beans.ConstructorProperties({"x", "z", "items"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarnings(final long x, final int z, final java.util.List items) { super(); this.x = x; this.z = z; this.items = items; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderDefaultsWarningsBuilder builder() { return new BuilderDefaultsWarningsBuilder(); } } class NoBuilderButHasDefaults { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class NoBuilderButHasDefaultsBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") NoBuilderButHasDefaultsBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") NoBuilderButHasDefaults build() { return new NoBuilderButHasDefaults(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "NoBuilderButHasDefaults.NoBuilderButHasDefaultsBuilder()"; } } private final @Builder.Default long z = 5; public @Builder NoBuilderButHasDefaults() { super(); } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") NoBuilderButHasDefaultsBuilder builder() { return new NoBuilderButHasDefaultsBuilder(); } }lombok-1.16.18/test/transform/resource/after-ecj/BuilderInstanceMethod.java000066400000000000000000000042021312655740700267230ustar00rootroot00000000000000import java.util.List; class BuilderInstanceMethod { public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class StringBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int show; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int yes; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") List also; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int $andMe; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StringBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StringBuilder show(final int show) { this.show = show; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StringBuilder yes(final int yes) { this.yes = yes; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StringBuilder also(final List also) { this.also = also; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StringBuilder $andMe(final int $andMe) { this.$andMe = $andMe; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String build() { return BuilderInstanceMethod.this.create(show, yes, also, $andMe); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((((("BuilderInstanceMethod.StringBuilder(show=" + this.show) + ", yes=") + this.yes) + ", also=") + this.also) + ", $andMe=") + this.$andMe) + ")"); } } BuilderInstanceMethod() { super(); } public @lombok.Builder String create(int show, final int yes, List also, int $andMe) { return (((("" + show) + yes) + also) + $andMe); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StringBuilder builder() { return new StringBuilder(); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderSimple.java000066400000000000000000000033771312655740700252630ustar00rootroot00000000000000import java.util.List; @lombok.Builder class BuilderSimple { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderSimpleBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int yes; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") List also; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSimpleBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSimpleBuilder yes(final int yes) { this.yes = yes; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSimpleBuilder also(final List also) { this.also = also; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSimple build() { return new BuilderSimple(yes, also); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("BuilderSimple.BuilderSimpleBuilder(yes=" + this.yes) + ", also=") + this.also) + ")"); } } private final int noshow = 0; private final int yes; private List also; private int $butNotMe; @java.beans.ConstructorProperties({"yes", "also"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSimple(final int yes, final List also) { super(); this.yes = yes; this.also = also; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSimpleBuilder builder() { return new BuilderSimpleBuilder(); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderSingularGuavaListsSets.java000066400000000000000000000200451312655740700304470ustar00rootroot00000000000000import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableTable; import lombok.Singular; @lombok.Builder class BuilderSingularGuavaListsSets { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderSingularGuavaListsSetsBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableList.Builder cards; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableList.Builder frogs; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableSet.Builder rawSet; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableSortedSet.Builder passes; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableTable.Builder users; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder card(T card) { if ((this.cards == null)) this.cards = com.google.common.collect.ImmutableList.builder(); this.cards.add(card); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder cards(java.lang.Iterable cards) { if ((this.cards == null)) this.cards = com.google.common.collect.ImmutableList.builder(); this.cards.addAll(cards); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder clearCards() { this.cards = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder frog(Number frog) { if ((this.frogs == null)) this.frogs = com.google.common.collect.ImmutableList.builder(); this.frogs.add(frog); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder frogs(java.lang.Iterable frogs) { if ((this.frogs == null)) this.frogs = com.google.common.collect.ImmutableList.builder(); this.frogs.addAll(frogs); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder clearFrogs() { this.frogs = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder rawSet(java.lang.Object rawSet) { if ((this.rawSet == null)) this.rawSet = com.google.common.collect.ImmutableSet.builder(); this.rawSet.add(rawSet); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder rawSet(java.lang.Iterable rawSet) { if ((this.rawSet == null)) this.rawSet = com.google.common.collect.ImmutableSet.builder(); this.rawSet.addAll(rawSet); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder clearRawSet() { this.rawSet = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder pass(String pass) { if ((this.passes == null)) this.passes = com.google.common.collect.ImmutableSortedSet.naturalOrder(); this.passes.add(pass); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder passes(java.lang.Iterable passes) { if ((this.passes == null)) this.passes = com.google.common.collect.ImmutableSortedSet.naturalOrder(); this.passes.addAll(passes); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder clearPasses() { this.passes = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder user(Number rowKey, Number columnKey, String value) { if ((this.users == null)) this.users = com.google.common.collect.ImmutableTable.builder(); this.users.put(rowKey, columnKey, value); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder users(com.google.common.collect.Table users) { if ((this.users == null)) this.users = com.google.common.collect.ImmutableTable.builder(); this.users.putAll(users); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder clearUsers() { this.users = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSets build() { com.google.common.collect.ImmutableList cards = ((this.cards == null) ? com.google.common.collect.ImmutableList.of() : this.cards.build()); com.google.common.collect.ImmutableCollection frogs = ((this.frogs == null) ? com.google.common.collect.ImmutableList.of() : this.frogs.build()); com.google.common.collect.ImmutableSet rawSet = ((this.rawSet == null) ? com.google.common.collect.ImmutableSet.of() : this.rawSet.build()); com.google.common.collect.ImmutableSortedSet passes = ((this.passes == null) ? com.google.common.collect.ImmutableSortedSet.of() : this.passes.build()); com.google.common.collect.ImmutableTable users = ((this.users == null) ? com.google.common.collect.ImmutableTable.of() : this.users.build()); return new BuilderSingularGuavaListsSets(cards, frogs, rawSet, passes, users); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((((((("BuilderSingularGuavaListsSets.BuilderSingularGuavaListsSetsBuilder(cards=" + this.cards) + ", frogs=") + this.frogs) + ", rawSet=") + this.rawSet) + ", passes=") + this.passes) + ", users=") + this.users) + ")"); } } private @Singular ImmutableList cards; private @Singular ImmutableCollection frogs; private @SuppressWarnings("all") @Singular("rawSet") ImmutableSet rawSet; private @Singular ImmutableSortedSet passes; private @Singular ImmutableTable users; @java.beans.ConstructorProperties({"cards", "frogs", "rawSet", "passes", "users"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSets(final ImmutableList cards, final ImmutableCollection frogs, final ImmutableSet rawSet, final ImmutableSortedSet passes, final ImmutableTable users) { super(); this.cards = cards; this.frogs = frogs; this.rawSet = rawSet; this.passes = passes; this.users = users; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaListsSetsBuilder builder() { return new BuilderSingularGuavaListsSetsBuilder(); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderSingularGuavaMaps.java000066400000000000000000000127071312655740700274200ustar00rootroot00000000000000import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableSortedMap; import lombok.Singular; @lombok.Builder class BuilderSingularGuavaMaps { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderSingularGuavaMapsBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableMap.Builder battleaxes; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableSortedMap.Builder vertices; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableBiMap.Builder rawMap; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder battleaxe(K key, V value) { if ((this.battleaxes == null)) this.battleaxes = com.google.common.collect.ImmutableMap.builder(); this.battleaxes.put(key, value); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder battleaxes(java.util.Map battleaxes) { if ((this.battleaxes == null)) this.battleaxes = com.google.common.collect.ImmutableMap.builder(); this.battleaxes.putAll(battleaxes); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder clearBattleaxes() { this.battleaxes = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder vertex(Integer key, V value) { if ((this.vertices == null)) this.vertices = com.google.common.collect.ImmutableSortedMap.naturalOrder(); this.vertices.put(key, value); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder vertices(java.util.Map vertices) { if ((this.vertices == null)) this.vertices = com.google.common.collect.ImmutableSortedMap.naturalOrder(); this.vertices.putAll(vertices); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder clearVertices() { this.vertices = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder rawMap(java.lang.Object key, java.lang.Object value) { if ((this.rawMap == null)) this.rawMap = com.google.common.collect.ImmutableBiMap.builder(); this.rawMap.put(key, value); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder rawMap(java.util.Map rawMap) { if ((this.rawMap == null)) this.rawMap = com.google.common.collect.ImmutableBiMap.builder(); this.rawMap.putAll(rawMap); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder clearRawMap() { this.rawMap = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMaps build() { com.google.common.collect.ImmutableMap battleaxes = ((this.battleaxes == null) ? com.google.common.collect.ImmutableMap.of() : this.battleaxes.build()); com.google.common.collect.ImmutableSortedMap vertices = ((this.vertices == null) ? com.google.common.collect.ImmutableSortedMap.of() : this.vertices.build()); com.google.common.collect.ImmutableBiMap rawMap = ((this.rawMap == null) ? com.google.common.collect.ImmutableBiMap.of() : this.rawMap.build()); return new BuilderSingularGuavaMaps(battleaxes, vertices, rawMap); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("BuilderSingularGuavaMaps.BuilderSingularGuavaMapsBuilder(battleaxes=" + this.battleaxes) + ", vertices=") + this.vertices) + ", rawMap=") + this.rawMap) + ")"); } } private @Singular ImmutableMap battleaxes; private @Singular ImmutableSortedMap vertices; private @SuppressWarnings("all") @Singular("rawMap") ImmutableBiMap rawMap; @java.beans.ConstructorProperties({"battleaxes", "vertices", "rawMap"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMaps(final ImmutableMap battleaxes, final ImmutableSortedMap vertices, final ImmutableBiMap rawMap) { super(); this.battleaxes = battleaxes; this.vertices = vertices; this.rawMap = rawMap; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularGuavaMapsBuilder builder() { return new BuilderSingularGuavaMapsBuilder(); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderSingularLists.java000066400000000000000000000133051312655740700266250ustar00rootroot00000000000000import java.util.List; import java.util.Collection; import lombok.Singular; @lombok.Builder class BuilderSingularLists { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderSingularListsBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList children; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList scarves; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList rawList; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder child(T child) { if ((this.children == null)) this.children = new java.util.ArrayList(); this.children.add(child); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder children(java.util.Collection children) { if ((this.children == null)) this.children = new java.util.ArrayList(); this.children.addAll(children); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder clearChildren() { if ((this.children != null)) this.children.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder scarf(Number scarf) { if ((this.scarves == null)) this.scarves = new java.util.ArrayList(); this.scarves.add(scarf); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder scarves(java.util.Collection scarves) { if ((this.scarves == null)) this.scarves = new java.util.ArrayList(); this.scarves.addAll(scarves); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder clearScarves() { if ((this.scarves != null)) this.scarves.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder rawList(java.lang.Object rawList) { if ((this.rawList == null)) this.rawList = new java.util.ArrayList(); this.rawList.add(rawList); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder rawList(java.util.Collection rawList) { if ((this.rawList == null)) this.rawList = new java.util.ArrayList(); this.rawList.addAll(rawList); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder clearRawList() { if ((this.rawList != null)) this.rawList.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularLists build() { java.util.List children; switch (((this.children == null) ? 0 : this.children.size())) { case 0 : children = java.util.Collections.emptyList(); break; case 1 : children = java.util.Collections.singletonList(this.children.get(0)); break; default : children = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.children)); } java.util.Collection scarves; switch (((this.scarves == null) ? 0 : this.scarves.size())) { case 0 : scarves = java.util.Collections.emptyList(); break; case 1 : scarves = java.util.Collections.singletonList(this.scarves.get(0)); break; default : scarves = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.scarves)); } java.util.List rawList; switch (((this.rawList == null) ? 0 : this.rawList.size())) { case 0 : rawList = java.util.Collections.emptyList(); break; case 1 : rawList = java.util.Collections.singletonList(this.rawList.get(0)); break; default : rawList = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.rawList)); } return new BuilderSingularLists(children, scarves, rawList); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("BuilderSingularLists.BuilderSingularListsBuilder(children=" + this.children) + ", scarves=") + this.scarves) + ", rawList=") + this.rawList) + ")"); } } private @Singular List children; private @Singular Collection scarves; private @SuppressWarnings("all") @Singular("rawList") List rawList; @java.beans.ConstructorProperties({"children", "scarves", "rawList"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularLists(final List children, final Collection scarves, final List rawList) { super(); this.children = children; this.scarves = scarves; this.rawList = rawList; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularListsBuilder builder() { return new BuilderSingularListsBuilder(); } }lombok-1.16.18/test/transform/resource/after-ecj/BuilderSingularMaps.java000066400000000000000000000255531312655740700264370ustar00rootroot00000000000000import java.util.Map; import java.util.SortedMap; import lombok.Singular; @lombok.Builder class BuilderSingularMaps { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderSingularMapsBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList women$key; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList women$value; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList men$key; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList men$value; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList rawMap$key; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList rawMap$value; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList stringMap$key; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList stringMap$value; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder woman(K womanKey, V womanValue) { if ((this.women$key == null)) { this.women$key = new java.util.ArrayList(); this.women$value = new java.util.ArrayList(); } this.women$key.add(womanKey); this.women$value.add(womanValue); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder women(java.util.Map women) { if ((this.women$key == null)) { this.women$key = new java.util.ArrayList(); this.women$value = new java.util.ArrayList(); } for (java.util.Map.Entry $lombokEntry : women.entrySet()) { this.women$key.add($lombokEntry.getKey()); this.women$value.add($lombokEntry.getValue()); } return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder clearWomen() { if ((this.women$key != null)) { this.women$key.clear(); this.women$value.clear(); } return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder man(K manKey, Number manValue) { if ((this.men$key == null)) { this.men$key = new java.util.ArrayList(); this.men$value = new java.util.ArrayList(); } this.men$key.add(manKey); this.men$value.add(manValue); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder men(java.util.Map men) { if ((this.men$key == null)) { this.men$key = new java.util.ArrayList(); this.men$value = new java.util.ArrayList(); } for (java.util.Map.Entry $lombokEntry : men.entrySet()) { this.men$key.add($lombokEntry.getKey()); this.men$value.add($lombokEntry.getValue()); } return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder clearMen() { if ((this.men$key != null)) { this.men$key.clear(); this.men$value.clear(); } return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder rawMap(java.lang.Object rawMapKey, java.lang.Object rawMapValue) { if ((this.rawMap$key == null)) { this.rawMap$key = new java.util.ArrayList(); this.rawMap$value = new java.util.ArrayList(); } this.rawMap$key.add(rawMapKey); this.rawMap$value.add(rawMapValue); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder rawMap(java.util.Map rawMap) { if ((this.rawMap$key == null)) { this.rawMap$key = new java.util.ArrayList(); this.rawMap$value = new java.util.ArrayList(); } for (java.util.Map.Entry $lombokEntry : rawMap.entrySet()) { this.rawMap$key.add($lombokEntry.getKey()); this.rawMap$value.add($lombokEntry.getValue()); } return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder clearRawMap() { if ((this.rawMap$key != null)) { this.rawMap$key.clear(); this.rawMap$value.clear(); } return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder stringMap(String stringMapKey, V stringMapValue) { if ((this.stringMap$key == null)) { this.stringMap$key = new java.util.ArrayList(); this.stringMap$value = new java.util.ArrayList(); } this.stringMap$key.add(stringMapKey); this.stringMap$value.add(stringMapValue); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder stringMap(java.util.Map stringMap) { if ((this.stringMap$key == null)) { this.stringMap$key = new java.util.ArrayList(); this.stringMap$value = new java.util.ArrayList(); } for (java.util.Map.Entry $lombokEntry : stringMap.entrySet()) { this.stringMap$key.add($lombokEntry.getKey()); this.stringMap$value.add($lombokEntry.getValue()); } return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder clearStringMap() { if ((this.stringMap$key != null)) { this.stringMap$key.clear(); this.stringMap$value.clear(); } return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMaps build() { java.util.Map women; switch (((this.women$key == null) ? 0 : this.women$key.size())) { case 0 : women = java.util.Collections.emptyMap(); break; case 1 : women = java.util.Collections.singletonMap(this.women$key.get(0), this.women$value.get(0)); break; default : women = new java.util.LinkedHashMap(((this.women$key.size() < 0x40000000) ? ((1 + this.women$key.size()) + ((this.women$key.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE)); for (int $i = 0;; ($i < this.women$key.size()); $i ++) women.put(this.women$key.get($i), this.women$value.get($i)); women = java.util.Collections.unmodifiableMap(women); } java.util.SortedMap men = new java.util.TreeMap(); if ((this.men$key != null)) for (int $i = 0;; ($i < ((this.men$key == null) ? 0 : this.men$key.size())); $i ++) men.put(this.men$key.get($i), this.men$value.get($i)); men = java.util.Collections.unmodifiableSortedMap(men); java.util.Map rawMap; switch (((this.rawMap$key == null) ? 0 : this.rawMap$key.size())) { case 0 : rawMap = java.util.Collections.emptyMap(); break; case 1 : rawMap = java.util.Collections.singletonMap(this.rawMap$key.get(0), this.rawMap$value.get(0)); break; default : rawMap = new java.util.LinkedHashMap(((this.rawMap$key.size() < 0x40000000) ? ((1 + this.rawMap$key.size()) + ((this.rawMap$key.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE)); for (int $i = 0;; ($i < this.rawMap$key.size()); $i ++) rawMap.put(this.rawMap$key.get($i), this.rawMap$value.get($i)); rawMap = java.util.Collections.unmodifiableMap(rawMap); } java.util.Map stringMap; switch (((this.stringMap$key == null) ? 0 : this.stringMap$key.size())) { case 0 : stringMap = java.util.Collections.emptyMap(); break; case 1 : stringMap = java.util.Collections.singletonMap(this.stringMap$key.get(0), this.stringMap$value.get(0)); break; default : stringMap = new java.util.LinkedHashMap(((this.stringMap$key.size() < 0x40000000) ? ((1 + this.stringMap$key.size()) + ((this.stringMap$key.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE)); for (int $i = 0;; ($i < this.stringMap$key.size()); $i ++) stringMap.put(this.stringMap$key.get($i), this.stringMap$value.get($i)); stringMap = java.util.Collections.unmodifiableMap(stringMap); } return new BuilderSingularMaps(women, men, rawMap, stringMap); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((((((((((((("BuilderSingularMaps.BuilderSingularMapsBuilder(women$key=" + this.women$key) + ", women$value=") + this.women$value) + ", men$key=") + this.men$key) + ", men$value=") + this.men$value) + ", rawMap$key=") + this.rawMap$key) + ", rawMap$value=") + this.rawMap$value) + ", stringMap$key=") + this.stringMap$key) + ", stringMap$value=") + this.stringMap$value) + ")"); } } private @Singular Map women; private @Singular SortedMap men; private @SuppressWarnings("all") @Singular("rawMap") Map rawMap; private @Singular("stringMap") Map stringMap; @java.beans.ConstructorProperties({"women", "men", "rawMap", "stringMap"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMaps(final Map women, final SortedMap men, final Map rawMap, final Map stringMap) { super(); this.women = women; this.men = men; this.rawMap = rawMap; this.stringMap = stringMap; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularMapsBuilder builder() { return new BuilderSingularMapsBuilder(); } }lombok-1.16.18/test/transform/resource/after-ecj/BuilderSingularNoAuto.java000066400000000000000000000127471312655740700267450ustar00rootroot00000000000000import java.util.List; import lombok.Singular; @lombok.Builder class BuilderSingularNoAuto { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderSingularNoAutoBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList things; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList widgets; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList items; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder things(String things) { if ((this.things == null)) this.things = new java.util.ArrayList(); this.things.add(things); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder things(java.util.Collection things) { if ((this.things == null)) this.things = new java.util.ArrayList(); this.things.addAll(things); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder clearThings() { if ((this.things != null)) this.things.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder widget(String widget) { if ((this.widgets == null)) this.widgets = new java.util.ArrayList(); this.widgets.add(widget); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder widgets(java.util.Collection widgets) { if ((this.widgets == null)) this.widgets = new java.util.ArrayList(); this.widgets.addAll(widgets); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder clearWidgets() { if ((this.widgets != null)) this.widgets.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder items(String items) { if ((this.items == null)) this.items = new java.util.ArrayList(); this.items.add(items); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder items(java.util.Collection items) { if ((this.items == null)) this.items = new java.util.ArrayList(); this.items.addAll(items); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder clearItems() { if ((this.items != null)) this.items.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAuto build() { java.util.List things; switch (((this.things == null) ? 0 : this.things.size())) { case 0 : things = java.util.Collections.emptyList(); break; case 1 : things = java.util.Collections.singletonList(this.things.get(0)); break; default : things = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.things)); } java.util.List widgets; switch (((this.widgets == null) ? 0 : this.widgets.size())) { case 0 : widgets = java.util.Collections.emptyList(); break; case 1 : widgets = java.util.Collections.singletonList(this.widgets.get(0)); break; default : widgets = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.widgets)); } java.util.List items; switch (((this.items == null) ? 0 : this.items.size())) { case 0 : items = java.util.Collections.emptyList(); break; case 1 : items = java.util.Collections.singletonList(this.items.get(0)); break; default : items = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.items)); } return new BuilderSingularNoAuto(things, widgets, items); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("BuilderSingularNoAuto.BuilderSingularNoAutoBuilder(things=" + this.things) + ", widgets=") + this.widgets) + ", items=") + this.items) + ")"); } } private @Singular List things; private @Singular("widget") List widgets; private @Singular List items; @java.beans.ConstructorProperties({"things", "widgets", "items"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAuto(final List things, final List widgets, final List items) { super(); this.things = things; this.widgets = widgets; this.items = items; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder builder() { return new BuilderSingularNoAutoBuilder(); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderSingularRedirectToGuava.java000066400000000000000000000124201312655740700305540ustar00rootroot00000000000000import java.util.Set; import java.util.NavigableMap; import java.util.Collection; import lombok.Singular; @lombok.Builder class BuilderSingularRedirectToGuava { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderSingularRedirectToGuavaBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableSet.Builder dangerMice; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableSortedMap.Builder things; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableList.Builder> doohickeys; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder dangerMouse(String dangerMouse) { if ((this.dangerMice == null)) this.dangerMice = com.google.common.collect.ImmutableSet.builder(); this.dangerMice.add(dangerMouse); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder dangerMice(java.lang.Iterable dangerMice) { if ((this.dangerMice == null)) this.dangerMice = com.google.common.collect.ImmutableSet.builder(); this.dangerMice.addAll(dangerMice); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder clearDangerMice() { this.dangerMice = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder thing(Integer key, Number value) { if ((this.things == null)) this.things = com.google.common.collect.ImmutableSortedMap.naturalOrder(); this.things.put(key, value); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder things(java.util.Map things) { if ((this.things == null)) this.things = com.google.common.collect.ImmutableSortedMap.naturalOrder(); this.things.putAll(things); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder clearThings() { this.things = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder doohickey(Class doohickey) { if ((this.doohickeys == null)) this.doohickeys = com.google.common.collect.ImmutableList.builder(); this.doohickeys.add(doohickey); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder doohickeys(java.lang.Iterable> doohickeys) { if ((this.doohickeys == null)) this.doohickeys = com.google.common.collect.ImmutableList.builder(); this.doohickeys.addAll(doohickeys); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder clearDoohickeys() { this.doohickeys = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuava build() { java.util.Set dangerMice = ((this.dangerMice == null) ? com.google.common.collect.ImmutableSet.of() : this.dangerMice.build()); java.util.NavigableMap things = ((this.things == null) ? com.google.common.collect.ImmutableSortedMap.of() : this.things.build()); java.util.Collection> doohickeys = ((this.doohickeys == null) ? com.google.common.collect.ImmutableList.>of() : this.doohickeys.build()); return new BuilderSingularRedirectToGuava(dangerMice, things, doohickeys); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("BuilderSingularRedirectToGuava.BuilderSingularRedirectToGuavaBuilder(dangerMice=" + this.dangerMice) + ", things=") + this.things) + ", doohickeys=") + this.doohickeys) + ")"); } } private @Singular Set dangerMice; private @Singular NavigableMap things; private @Singular Collection> doohickeys; @java.beans.ConstructorProperties({"dangerMice", "things", "doohickeys"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuava(final Set dangerMice, final NavigableMap things, final Collection> doohickeys) { super(); this.dangerMice = dangerMice; this.things = things; this.doohickeys = doohickeys; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularRedirectToGuavaBuilder builder() { return new BuilderSingularRedirectToGuavaBuilder(); } }lombok-1.16.18/test/transform/resource/after-ecj/BuilderSingularSets.java000066400000000000000000000173151312655740700264520ustar00rootroot00000000000000import java.util.Set; import java.util.SortedSet; import lombok.Singular; @lombok.Builder class BuilderSingularSets { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderSingularSetsBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList dangerMice; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList octopodes; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList rawSet; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList stringSet; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder dangerMouse(T dangerMouse) { if ((this.dangerMice == null)) this.dangerMice = new java.util.ArrayList(); this.dangerMice.add(dangerMouse); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder dangerMice(java.util.Collection dangerMice) { if ((this.dangerMice == null)) this.dangerMice = new java.util.ArrayList(); this.dangerMice.addAll(dangerMice); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder clearDangerMice() { if ((this.dangerMice != null)) this.dangerMice.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder octopus(Number octopus) { if ((this.octopodes == null)) this.octopodes = new java.util.ArrayList(); this.octopodes.add(octopus); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder octopodes(java.util.Collection octopodes) { if ((this.octopodes == null)) this.octopodes = new java.util.ArrayList(); this.octopodes.addAll(octopodes); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder clearOctopodes() { if ((this.octopodes != null)) this.octopodes.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder rawSet(java.lang.Object rawSet) { if ((this.rawSet == null)) this.rawSet = new java.util.ArrayList(); this.rawSet.add(rawSet); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder rawSet(java.util.Collection rawSet) { if ((this.rawSet == null)) this.rawSet = new java.util.ArrayList(); this.rawSet.addAll(rawSet); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder clearRawSet() { if ((this.rawSet != null)) this.rawSet.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder stringSet(String stringSet) { if ((this.stringSet == null)) this.stringSet = new java.util.ArrayList(); this.stringSet.add(stringSet); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder stringSet(java.util.Collection stringSet) { if ((this.stringSet == null)) this.stringSet = new java.util.ArrayList(); this.stringSet.addAll(stringSet); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder clearStringSet() { if ((this.stringSet != null)) this.stringSet.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSets build() { java.util.Set dangerMice; switch (((this.dangerMice == null) ? 0 : this.dangerMice.size())) { case 0 : dangerMice = java.util.Collections.emptySet(); break; case 1 : dangerMice = java.util.Collections.singleton(this.dangerMice.get(0)); break; default : dangerMice = new java.util.LinkedHashSet(((this.dangerMice.size() < 0x40000000) ? ((1 + this.dangerMice.size()) + ((this.dangerMice.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE)); dangerMice.addAll(this.dangerMice); dangerMice = java.util.Collections.unmodifiableSet(dangerMice); } java.util.SortedSet octopodes = new java.util.TreeSet(); if ((this.octopodes != null)) octopodes.addAll(this.octopodes); octopodes = java.util.Collections.unmodifiableSortedSet(octopodes); java.util.Set rawSet; switch (((this.rawSet == null) ? 0 : this.rawSet.size())) { case 0 : rawSet = java.util.Collections.emptySet(); break; case 1 : rawSet = java.util.Collections.singleton(this.rawSet.get(0)); break; default : rawSet = new java.util.LinkedHashSet(((this.rawSet.size() < 0x40000000) ? ((1 + this.rawSet.size()) + ((this.rawSet.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE)); rawSet.addAll(this.rawSet); rawSet = java.util.Collections.unmodifiableSet(rawSet); } java.util.Set stringSet; switch (((this.stringSet == null) ? 0 : this.stringSet.size())) { case 0 : stringSet = java.util.Collections.emptySet(); break; case 1 : stringSet = java.util.Collections.singleton(this.stringSet.get(0)); break; default : stringSet = new java.util.LinkedHashSet(((this.stringSet.size() < 0x40000000) ? ((1 + this.stringSet.size()) + ((this.stringSet.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE)); stringSet.addAll(this.stringSet); stringSet = java.util.Collections.unmodifiableSet(stringSet); } return new BuilderSingularSets(dangerMice, octopodes, rawSet, stringSet); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((((("BuilderSingularSets.BuilderSingularSetsBuilder(dangerMice=" + this.dangerMice) + ", octopodes=") + this.octopodes) + ", rawSet=") + this.rawSet) + ", stringSet=") + this.stringSet) + ")"); } } private @Singular Set dangerMice; private @Singular SortedSet octopodes; private @SuppressWarnings("all") @Singular("rawSet") Set rawSet; private @Singular("stringSet") Set stringSet; @java.beans.ConstructorProperties({"dangerMice", "octopodes", "rawSet", "stringSet"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSets(final Set dangerMice, final SortedSet octopodes, final Set rawSet, final Set stringSet) { super(); this.dangerMice = dangerMice; this.octopodes = octopodes; this.rawSet = rawSet; this.stringSet = stringSet; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularSetsBuilder builder() { return new BuilderSingularSetsBuilder(); } }lombok-1.16.18/test/transform/resource/after-ecj/BuilderSingularWithPrefixes.java000066400000000000000000000051421312655740700301500ustar00rootroot00000000000000import lombok.Singular; @lombok.Builder @lombok.experimental.Accessors(prefix = "_") class BuilderSingularWithPrefixes { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderSingularWithPrefixesBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList elems; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularWithPrefixesBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularWithPrefixesBuilder elem(String elem) { if ((this.elems == null)) this.elems = new java.util.ArrayList(); this.elems.add(elem); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularWithPrefixesBuilder elems(java.util.Collection elems) { if ((this.elems == null)) this.elems = new java.util.ArrayList(); this.elems.addAll(elems); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularWithPrefixesBuilder clearElems() { if ((this.elems != null)) this.elems.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularWithPrefixes build() { java.util.List elems; switch (((this.elems == null) ? 0 : this.elems.size())) { case 0 : elems = java.util.Collections.emptyList(); break; case 1 : elems = java.util.Collections.singletonList(this.elems.get(0)); break; default : elems = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.elems)); } return new BuilderSingularWithPrefixes(elems); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("BuilderSingularWithPrefixes.BuilderSingularWithPrefixesBuilder(elems=" + this.elems) + ")"); } } private @Singular java.util.List _elems; @java.beans.ConstructorProperties({"elems"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularWithPrefixes(final java.util.List elems) { super(); this._elems = elems; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularWithPrefixesBuilder builder() { return new BuilderSingularWithPrefixesBuilder(); } }lombok-1.16.18/test/transform/resource/after-ecj/BuilderValueData.java000066400000000000000000000100241312655740700256630ustar00rootroot00000000000000import java.util.List; final @lombok.Builder @lombok.Value class BuilderAndValue { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderAndValueBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndValueBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndValue build() { return new BuilderAndValue(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "BuilderAndValue.BuilderAndValueBuilder()"; } } private final int zero = 0; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndValue() { super(); } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndValueBuilder builder() { return new BuilderAndValueBuilder(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getZero() { return this.zero; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof BuilderAndValue))) return false; final BuilderAndValue other = (BuilderAndValue) o; if ((this.getZero() != other.getZero())) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getZero()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("BuilderAndValue(zero=" + this.getZero()) + ")"); } } @lombok.Builder @lombok.Data class BuilderAndData { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderAndDataBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndDataBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndData build() { return new BuilderAndData(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "BuilderAndData.BuilderAndDataBuilder()"; } } private final int zero = 0; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndData() { super(); } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderAndDataBuilder builder() { return new BuilderAndDataBuilder(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getZero() { return this.zero; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof BuilderAndData))) return false; final BuilderAndData other = (BuilderAndData) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getZero() != other.getZero())) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof BuilderAndData); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getZero()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("BuilderAndData(zero=" + this.getZero()) + ")"); } }lombok-1.16.18/test/transform/resource/after-ecj/BuilderWithAccessors.java000066400000000000000000000050651312655740700266070ustar00rootroot00000000000000@lombok.Builder @lombok.experimental.Accessors(prefix = {"p", "_"}) class BuilderWithAccessors { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderWithAccessorsBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int plower; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int upper; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int foo; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int _bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessorsBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessorsBuilder plower(final int plower) { this.plower = plower; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessorsBuilder upper(final int upper) { this.upper = upper; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessorsBuilder foo(final int foo) { this.foo = foo; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessorsBuilder _bar(final int _bar) { this._bar = _bar; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessors build() { return new BuilderWithAccessors(plower, upper, foo, _bar); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((((("BuilderWithAccessors.BuilderWithAccessorsBuilder(plower=" + this.plower) + ", upper=") + this.upper) + ", foo=") + this.foo) + ", _bar=") + this._bar) + ")"); } } private final int plower; private final int pUpper; private int _foo; private int __bar; @java.beans.ConstructorProperties({"plower", "upper", "foo", "_bar"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessors(final int plower, final int upper, final int foo, final int _bar) { super(); this.plower = plower; this.pUpper = upper; this._foo = foo; this.__bar = _bar; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithAccessorsBuilder builder() { return new BuilderWithAccessorsBuilder(); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderWithDeprecated.java000066400000000000000000000115151312655740700267170ustar00rootroot00000000000000import com.google.common.collect.ImmutableList; import lombok.Builder; import lombok.Singular; public @Builder class BuilderWithDeprecated { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderWithDeprecatedBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String dep1; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int dep2; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList strings; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") com.google.common.collect.ImmutableList.Builder numbers; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder() { super(); } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder dep1(final String dep1) { this.dep1 = dep1; return this; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder dep2(final int dep2) { this.dep2 = dep2; return this; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder string(String string) { if ((this.strings == null)) this.strings = new java.util.ArrayList(); this.strings.add(string); return this; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder strings(java.util.Collection strings) { if ((this.strings == null)) this.strings = new java.util.ArrayList(); this.strings.addAll(strings); return this; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder clearStrings() { if ((this.strings != null)) this.strings.clear(); return this; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder number(Integer number) { if ((this.numbers == null)) this.numbers = com.google.common.collect.ImmutableList.builder(); this.numbers.add(number); return this; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder numbers(java.lang.Iterable numbers) { if ((this.numbers == null)) this.numbers = com.google.common.collect.ImmutableList.builder(); this.numbers.addAll(numbers); return this; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder clearNumbers() { this.numbers = null; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecated build() { java.util.List strings; switch (((this.strings == null) ? 0 : this.strings.size())) { case 0 : strings = java.util.Collections.emptyList(); break; case 1 : strings = java.util.Collections.singletonList(this.strings.get(0)); break; default : strings = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.strings)); } com.google.common.collect.ImmutableList numbers = ((this.numbers == null) ? com.google.common.collect.ImmutableList.of() : this.numbers.build()); return new BuilderWithDeprecated(dep1, dep2, strings, numbers); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((((("BuilderWithDeprecated.BuilderWithDeprecatedBuilder(dep1=" + this.dep1) + ", dep2=") + this.dep2) + ", strings=") + this.strings) + ", numbers=") + this.numbers) + ")"); } } String dep1; @Deprecated int dep2; @Singular @Deprecated java.util.List strings; @Singular @Deprecated ImmutableList numbers; @java.beans.ConstructorProperties({"dep1", "dep2", "strings", "numbers"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecated(final String dep1, final int dep2, final java.util.List strings, final ImmutableList numbers) { super(); this.dep1 = dep1; this.dep2 = dep2; this.strings = strings; this.numbers = numbers; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithDeprecatedBuilder builder() { return new BuilderWithDeprecatedBuilder(); } }lombok-1.16.18/test/transform/resource/after-ecj/BuilderWithExistingBuilderClass.java000066400000000000000000000036221312655740700307460ustar00rootroot00000000000000import lombok.Builder; class BuilderWithExistingBuilderClass { public static class BuilderWithExistingBuilderClassBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean arg2; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String arg3; private Z arg1; public void arg2(boolean arg) { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithExistingBuilderClassBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithExistingBuilderClassBuilder arg1(final Z arg1) { this.arg1 = arg1; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithExistingBuilderClassBuilder arg3(final String arg3) { this.arg3 = arg3; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithExistingBuilderClass build() { return BuilderWithExistingBuilderClass.staticMethod(arg1, arg2, arg3); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("BuilderWithExistingBuilderClass.BuilderWithExistingBuilderClassBuilder(arg1=" + this.arg1) + ", arg2=") + this.arg2) + ", arg3=") + this.arg3) + ")"); } } BuilderWithExistingBuilderClass() { super(); } public static @Builder BuilderWithExistingBuilderClass staticMethod(Z arg1, boolean arg2, String arg3) { return null; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithExistingBuilderClassBuilder builder() { return new BuilderWithExistingBuilderClassBuilder(); } }lombok-1.16.18/test/transform/resource/after-ecj/BuilderWithRecursiveGenerics.java000066400000000000000000000076051312655740700303130ustar00rootroot00000000000000import java.util.Set; import lombok.Builder; import lombok.Value; public class BuilderWithRecursiveGenerics { interface Inter> { } public static final @Builder @Value class Test, Quz extends Inter> { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class TestBuilder, Quz extends Inter> { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Foo foo; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Bar bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") TestBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") TestBuilder foo(final Foo foo) { this.foo = foo; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") TestBuilder bar(final Bar bar) { this.bar = bar; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Test build() { return new Test(foo, bar); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("BuilderWithRecursiveGenerics.Test.TestBuilder(foo=" + this.foo) + ", bar=") + this.bar) + ")"); } } private final Foo foo; private final Bar bar; @java.beans.ConstructorProperties({"foo", "bar"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Test(final Foo foo, final Bar bar) { super(); this.foo = foo; this.bar = bar; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") , Quz extends Inter>TestBuilder builder() { return new TestBuilder(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Foo getFoo() { return this.foo; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Bar getBar() { return this.bar; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof BuilderWithRecursiveGenerics.Test))) return false; final BuilderWithRecursiveGenerics.Test other = (BuilderWithRecursiveGenerics.Test) o; final java.lang.Object this$foo = this.getFoo(); final java.lang.Object other$foo = other.getFoo(); if (((this$foo == null) ? (other$foo != null) : (! this$foo.equals(other$foo)))) return false; final java.lang.Object this$bar = this.getBar(); final java.lang.Object other$bar = other.getBar(); if (((this$bar == null) ? (other$bar != null) : (! this$bar.equals(other$bar)))) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $foo = this.getFoo(); result = ((result * PRIME) + (($foo == null) ? 43 : $foo.hashCode())); final java.lang.Object $bar = this.getBar(); result = ((result * PRIME) + (($bar == null) ? 43 : $bar.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("BuilderWithRecursiveGenerics.Test(foo=" + this.getFoo()) + ", bar=") + this.getBar()) + ")"); } } public BuilderWithRecursiveGenerics() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderWithToBuilder.java000066400000000000000000000177531312655740700265620ustar00rootroot00000000000000import java.util.List; import lombok.Builder; @Builder(toBuilder = true) @lombok.experimental.Accessors(prefix = "m") class BuilderWithToBuilder { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class BuilderWithToBuilderBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String one; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String two; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") T foo; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.util.ArrayList bars; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder one(final String one) { this.one = one; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder two(final String two) { this.two = two; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder foo(final T foo) { this.foo = foo; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder bar(T bar) { if ((this.bars == null)) this.bars = new java.util.ArrayList(); this.bars.add(bar); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder bars(java.util.Collection bars) { if ((this.bars == null)) this.bars = new java.util.ArrayList(); this.bars.addAll(bars); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder clearBars() { if ((this.bars != null)) this.bars.clear(); return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilder build() { java.util.List bars; switch (((this.bars == null) ? 0 : this.bars.size())) { case 0 : bars = java.util.Collections.emptyList(); break; case 1 : bars = java.util.Collections.singletonList(this.bars.get(0)); break; default : bars = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.bars)); } return new BuilderWithToBuilder(one, two, foo, bars); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((((("BuilderWithToBuilder.BuilderWithToBuilderBuilder(one=" + this.one) + ", two=") + this.two) + ", foo=") + this.foo) + ", bars=") + this.bars) + ")"); } } private String mOne; private String mTwo; private @Builder.ObtainVia(method = "rrr",isStatic = true) T foo; private @lombok.Singular List bars; public static K rrr(BuilderWithToBuilder x) { return x.foo; } @java.beans.ConstructorProperties({"one", "two", "foo", "bars"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilder(final String one, final String two, final T foo, final List bars) { super(); this.mOne = one; this.mTwo = two; this.foo = foo; this.bars = bars; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder builder() { return new BuilderWithToBuilderBuilder(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithToBuilderBuilder toBuilder() { return new BuilderWithToBuilderBuilder().one(this.mOne).two(this.mTwo).foo(BuilderWithToBuilder.rrr(this)).bars(this.bars); } } @lombok.experimental.Accessors(prefix = "m") class ConstructorWithToBuilder { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class ConstructorWithToBuilderBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String mOne; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") T bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConstructorWithToBuilderBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConstructorWithToBuilderBuilder mOne(final String mOne) { this.mOne = mOne; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConstructorWithToBuilderBuilder bar(final T bar) { this.bar = bar; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConstructorWithToBuilder build() { return new ConstructorWithToBuilder(mOne, bar); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("ConstructorWithToBuilder.ConstructorWithToBuilderBuilder(mOne=" + this.mOne) + ", bar=") + this.bar) + ")"); } } private String mOne; private String mTwo; private T foo; private @lombok.Singular List bars; public @Builder(toBuilder = true) ConstructorWithToBuilder(String mOne, @Builder.ObtainVia(field = "foo") T bar) { super(); } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConstructorWithToBuilderBuilder builder() { return new ConstructorWithToBuilderBuilder(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConstructorWithToBuilderBuilder toBuilder() { return new ConstructorWithToBuilderBuilder().mOne(this.mOne).bar(this.foo); } } @lombok.experimental.Accessors(prefix = "m") class StaticWithToBuilder { public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") class StaticWithToBuilderBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String mOne; private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Z bar; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StaticWithToBuilderBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StaticWithToBuilderBuilder mOne(final String mOne) { this.mOne = mOne; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StaticWithToBuilderBuilder bar(final Z bar) { this.bar = bar; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StaticWithToBuilder build() { return StaticWithToBuilder.test(mOne, bar); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("StaticWithToBuilder.StaticWithToBuilderBuilder(mOne=" + this.mOne) + ", bar=") + this.bar) + ")"); } } private String mOne; private String mTwo; private T foo; private K bar; private @lombok.Singular List bars; StaticWithToBuilder() { super(); } public static @Builder(toBuilder = true) StaticWithToBuilder test(String mOne, @Builder.ObtainVia(field = "foo") Z bar) { return new StaticWithToBuilder(); } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StaticWithToBuilderBuilder builder() { return new StaticWithToBuilderBuilder(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") StaticWithToBuilderBuilder toBuilder() { return new StaticWithToBuilderBuilder().mOne(this.mOne).bar(this.foo); } } lombok-1.16.18/test/transform/resource/after-ecj/BuilderWithTolerate.java000066400000000000000000000030721312655740700264350ustar00rootroot00000000000000import lombok.Builder; import lombok.experimental.Tolerate; public @Builder class BuilderWithTolerate { public static class BuilderWithTolerateBuilder { private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int value; public @Tolerate BuilderWithTolerateBuilder value(String s) { return this.value(Integer.parseInt(s)); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithTolerateBuilder() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithTolerateBuilder value(final int value) { this.value = value; return this; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithTolerate build() { return new BuilderWithTolerate(value); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("BuilderWithTolerate.BuilderWithTolerateBuilder(value=" + this.value) + ")"); } } private final int value; public static void main(String[] args) { BuilderWithTolerate.builder().value("42").build(); } @java.beans.ConstructorProperties({"value"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithTolerate(final int value) { super(); this.value = value; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderWithTolerateBuilder builder() { return new BuilderWithTolerateBuilder(); } }lombok-1.16.18/test/transform/resource/after-ecj/ClassNamedAfterGetter.java000066400000000000000000000003131312655740700266550ustar00rootroot00000000000000class GetFoo { private @lombok.Getter int foo; GetFoo() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getFoo() { return this.foo; } } lombok-1.16.18/test/transform/resource/after-ecj/CleanupName.java000066400000000000000000000012051312655740700246770ustar00rootroot00000000000000class CleanupName { CleanupName() { super(); } void test() { @lombok.Cleanup("toString") Object o = "Hello World!"; try { System.out.println(o); } finally { if ((java.util.Collections.singletonList(o).get(0) != null)) { o.toString(); } } } void test2() { @lombok.Cleanup(value = "toString") Object o = "Hello World too!"; try { System.out.println(o); } finally { if ((java.util.Collections.singletonList(o).get(0) != null)) { o.toString(); } } } }lombok-1.16.18/test/transform/resource/after-ecj/CleanupPlain.java000066400000000000000000000013741312655740700250710ustar00rootroot00000000000000import lombok.Cleanup; import java.io.*; class CleanupPlain { CleanupPlain() { super(); } void test() throws Exception { @lombok.Cleanup InputStream in = new FileInputStream("in"); try { @Cleanup OutputStream out = new FileOutputStream("out"); try { if (in.markSupported()) { out.flush(); } } finally { if ((java.util.Collections.singletonList(out).get(0) != null)) { out.close(); } } } finally { if ((java.util.Collections.singletonList(in).get(0) != null)) { in.close(); } } } }lombok-1.16.18/test/transform/resource/after-ecj/CommentsInterspersed.java000066400000000000000000000005061312655740700266670ustar00rootroot00000000000000import lombok.Getter; public class CommentsInterspersed { private int x; private @Getter String test = "foo"; public CommentsInterspersed() { super(); } public native void gwtTest(); public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getTest() { return this.test; } } lombok-1.16.18/test/transform/resource/after-ecj/ConflictingStaticConstructorNames.java000066400000000000000000000023461312655740700313570ustar00rootroot00000000000000@lombok.Data(staticConstructor = "of") @lombok.NoArgsConstructor class ConflictingStaticConstructorNames { public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof ConflictingStaticConstructorNames))) return false; final ConflictingStaticConstructorNames other = (ConflictingStaticConstructorNames) o; if ((! other.canEqual((java.lang.Object) this))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof ConflictingStaticConstructorNames); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "ConflictingStaticConstructorNames()"; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConflictingStaticConstructorNames() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/Constructors.java000066400000000000000000000076371312655740700252360ustar00rootroot00000000000000@lombok.RequiredArgsConstructor class RequiredArgsConstructor1 { final int x; String name; public @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") RequiredArgsConstructor1(final int x) { super(); this.x = x; } } @lombok.RequiredArgsConstructor(access = lombok.AccessLevel.PROTECTED) class RequiredArgsConstructorAccess { final int x; String name; protected @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") RequiredArgsConstructorAccess(final int x) { super(); this.x = x; } } @lombok.RequiredArgsConstructor(staticName = "staticname") class RequiredArgsConstructorStaticName { final int x; String name; private @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") RequiredArgsConstructorStaticName(final int x) { super(); this.x = x; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") RequiredArgsConstructorStaticName staticname(final int x) { return new RequiredArgsConstructorStaticName(x); } } @lombok.RequiredArgsConstructor() class RequiredArgsConstructorWithAnnotations { final int x; String name; public @Deprecated @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") RequiredArgsConstructorWithAnnotations(final int x) { super(); this.x = x; } } @lombok.AllArgsConstructor class AllArgsConstructor1 { final int x; String name; public @java.beans.ConstructorProperties({"x", "name"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") AllArgsConstructor1(final int x, final String name) { super(); this.x = x; this.name = name; } } @lombok.NoArgsConstructor class NoArgsConstructor1 { int x; String name; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") NoArgsConstructor1() { super(); } } @lombok.RequiredArgsConstructor(staticName = "of") class RequiredArgsConstructorStaticNameGenerics { final T x; String name; private @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") RequiredArgsConstructorStaticNameGenerics(final T x) { super(); this.x = x; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") RequiredArgsConstructorStaticNameGenerics of(final T x) { return new RequiredArgsConstructorStaticNameGenerics(x); } } @lombok.RequiredArgsConstructor(staticName = "of") class RequiredArgsConstructorStaticNameGenerics2 { final Class x; String name; private @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") RequiredArgsConstructorStaticNameGenerics2(final Class x) { super(); this.x = x; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") RequiredArgsConstructorStaticNameGenerics2 of(final Class x) { return new RequiredArgsConstructorStaticNameGenerics2(x); } } @lombok.AllArgsConstructor(access = lombok.AccessLevel.PACKAGE) class AllArgsConstructorPackageAccess { final String x; @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") AllArgsConstructorPackageAccess(final String x) { super(); this.x = x; } } @lombok.NoArgsConstructor(force = true) class NoArgsConstructor2 { final int x; final double y; final char c; final boolean b; final float f; final String s; byte z; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") NoArgsConstructor2() { super(); this.x = 0; this.y = 0D; this.c = '\0'; this.b = false; this.f = 0F; this.s = null; } }lombok-1.16.18/test/transform/resource/after-ecj/ConstructorsConfiguration.java000066400000000000000000000003441312655740700277520ustar00rootroot00000000000000@lombok.AllArgsConstructor class ConstructorsConfiguration { int x; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConstructorsConfiguration(final int x) { super(); this.x = x; } } lombok-1.16.18/test/transform/resource/after-ecj/ConstructorsWithAccessors.java000066400000000000000000000010231312655740700277170ustar00rootroot00000000000000@lombok.AllArgsConstructor @lombok.experimental.Accessors(prefix = {"p", "_"}) class ConstructorsWithAccessors { int plower; int pUpper; int _huh; int __huh2; public @java.beans.ConstructorProperties({"plower", "upper", "huh", "_huh2"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ConstructorsWithAccessors(final int plower, final int upper, final int huh, final int _huh2) { super(); this.plower = plower; this.pUpper = upper; this._huh = huh; this.__huh2 = _huh2; } } lombok-1.16.18/test/transform/resource/after-ecj/DataConfiguration.java000066400000000000000000000025561312655740700261220ustar00rootroot00000000000000@lombok.Data class DataConfiguration { final int x; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof DataConfiguration))) return false; final DataConfiguration other = (DataConfiguration) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.x != other.x)) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof DataConfiguration); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("DataConfiguration(x=" + this.x) + ")"); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") DataConfiguration(final int x) { super(); this.x = x; } } lombok-1.16.18/test/transform/resource/after-ecj/DataExtended.java000066400000000000000000000027411312655740700250470ustar00rootroot00000000000000@lombok.Data @lombok.ToString(doNotUseGetters = true) class DataExtended { int x; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setX(final int x) { this.x = x; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof DataExtended))) return false; final DataExtended other = (DataExtended) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getX() != other.getX())) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof DataExtended); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); return result; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") DataExtended() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("DataExtended(x=" + this.x) + ")"); } } lombok-1.16.18/test/transform/resource/after-ecj/DataIgnore.java000066400000000000000000000026121312655740700245270ustar00rootroot00000000000000@lombok.Data class DataIgnore { final int x; String $name; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof DataIgnore))) return false; final DataIgnore other = (DataIgnore) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getX() != other.getX())) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof DataIgnore); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("DataIgnore(x=" + this.getX()) + ")"); } public @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") DataIgnore(final int x) { super(); this.x = x; } } lombok-1.16.18/test/transform/resource/after-ecj/DataOnEnum.java000066400000000000000000000013151312655740700245040ustar00rootroot00000000000000public @lombok.Getter @lombok.ToString @lombok.RequiredArgsConstructor enum DataOnEnum { A("hello"), private final String someField; () { } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getSomeField() { return this.someField; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("DataOnEnum(someField=" + this.getSomeField()) + ")"); } private @java.beans.ConstructorProperties({"someField"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") DataOnEnum(final String someField) { super(); this.someField = someField; } } lombok-1.16.18/test/transform/resource/after-ecj/DataOnLocalClass.java000066400000000000000000000140671312655740700256300ustar00rootroot00000000000000import lombok.Data; class DataOnLocalClass1 { DataOnLocalClass1() { super(); } public static void main(String[] args) { @Data class Local { final int x; String name; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getName() { return this.name; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setName(final String name) { this.name = name; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Local))) return false; final Local other = (Local) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getX() != other.getX())) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof Local); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); final java.lang.Object $name = this.getName(); result = ((result * PRIME) + (($name == null) ? 43 : $name.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("Local(x=" + this.getX()) + ", name=") + this.getName()) + ")"); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Local(final int x) { super(); this.x = x; } } } } class DataOnLocalClass2 { { @Data class Local { @Data class InnerLocal { @lombok.NonNull String name; public @lombok.NonNull @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getName() { return this.name; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setName(final @lombok.NonNull String name) { if ((name == null)) { throw new java.lang.NullPointerException("name"); } this.name = name; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Local.InnerLocal))) return false; final Local.InnerLocal other = (Local.InnerLocal) o; if ((! other.canEqual((java.lang.Object) this))) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof Local.InnerLocal); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $name = this.getName(); result = ((result * PRIME) + (($name == null) ? 43 : $name.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("Local.InnerLocal(name=" + this.getName()) + ")"); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") InnerLocal(final @lombok.NonNull String name) { super(); if ((name == null)) { throw new java.lang.NullPointerException("name"); } this.name = name; } } final int x; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Local))) return false; final Local other = (Local) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getX() != other.getX())) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof Local); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("Local(x=" + this.getX()) + ")"); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Local(final int x) { super(); this.x = x; } } } DataOnLocalClass2() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/DataPlain.java000066400000000000000000000216121312655740700243500ustar00rootroot00000000000000import lombok.Data; @lombok.Data class Data1 { final int x; String name; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getName() { return this.name; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setName(final String name) { this.name = name; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Data1))) return false; final Data1 other = (Data1) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getX() != other.getX())) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof Data1); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); final java.lang.Object $name = this.getName(); result = ((result * PRIME) + (($name == null) ? 43 : $name.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("Data1(x=" + this.getX()) + ", name=") + this.getName()) + ")"); } public @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Data1(final int x) { super(); this.x = x; } } @Data class Data2 { final int x; String name; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getName() { return this.name; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setName(final String name) { this.name = name; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Data2))) return false; final Data2 other = (Data2) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getX() != other.getX())) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof Data2); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); final java.lang.Object $name = this.getName(); result = ((result * PRIME) + (($name == null) ? 43 : $name.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("Data2(x=" + this.getX()) + ", name=") + this.getName()) + ")"); } public @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Data2(final int x) { super(); this.x = x; } } final @Data class Data3 { final int x; String name; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getName() { return this.name; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setName(final String name) { this.name = name; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Data3))) return false; final Data3 other = (Data3) o; if ((this.getX() != other.getX())) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name)))) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); final java.lang.Object $name = this.getName(); result = ((result * PRIME) + (($name == null) ? 43 : $name.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("Data3(x=" + this.getX()) + ", name=") + this.getName()) + ")"); } public @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Data3(final int x) { super(); this.x = x; } } final @Data @lombok.EqualsAndHashCode(callSuper = true) class Data4 extends java.util.Timer { int x; Data4() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setX(final int x) { this.x = x; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("Data4(x=" + this.getX()) + ")"); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Data4))) return false; final Data4 other = (Data4) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((! super.equals(o))) return false; if ((this.getX() != other.getX())) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof Data4); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + super.hashCode()); result = ((result * PRIME) + this.getX()); return result; } } @Data class Data5 { public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Data5))) return false; final Data5 other = (Data5) o; if ((! other.canEqual((java.lang.Object) this))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof Data5); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "Data5()"; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Data5() { super(); } } final @Data class Data6 { public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Data6))) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "Data6()"; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Data6() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/DataWithGetter.java000066400000000000000000000046371312655740700254030ustar00rootroot00000000000000@lombok.Data @lombok.Getter class DataWithGetter { private int x; private int y; private final String z; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setX(final int x) { this.x = x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setY(final int y) { this.y = y; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof DataWithGetter))) return false; final DataWithGetter other = (DataWithGetter) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getX() != other.getX())) return false; if ((this.getY() != other.getY())) return false; final java.lang.Object this$z = this.getZ(); final java.lang.Object other$z = other.getZ(); if (((this$z == null) ? (other$z != null) : (! this$z.equals(other$z)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof DataWithGetter); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); result = ((result * PRIME) + this.getY()); final java.lang.Object $z = this.getZ(); result = ((result * PRIME) + (($z == null) ? 43 : $z.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("DataWithGetter(x=" + this.getX()) + ", y=") + this.getY()) + ", z=") + this.getZ()) + ")"); } public @java.beans.ConstructorProperties({"z"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") DataWithGetter(final String z) { super(); this.z = z; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getY() { return this.y; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getZ() { return this.z; } } lombok-1.16.18/test/transform/resource/after-ecj/DataWithGetterNone.java000066400000000000000000000040631312655740700262140ustar00rootroot00000000000000@lombok.Data @lombok.Getter(lombok.AccessLevel.NONE) class DataWithGetterNone { private int x; private int y; private final String z; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setX(final int x) { this.x = x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setY(final int y) { this.y = y; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof DataWithGetterNone))) return false; final DataWithGetterNone other = (DataWithGetterNone) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.x != other.x)) return false; if ((this.y != other.y)) return false; final java.lang.Object this$z = this.z; final java.lang.Object other$z = other.z; if (((this$z == null) ? (other$z != null) : (! this$z.equals(other$z)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof DataWithGetterNone); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); result = ((result * PRIME) + this.y); final java.lang.Object $z = this.z; result = ((result * PRIME) + (($z == null) ? 43 : $z.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((((("DataWithGetterNone(x=" + this.x) + ", y=") + this.y) + ", z=") + this.z) + ")"); } public @java.beans.ConstructorProperties({"z"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") DataWithGetterNone(final String z) { super(); this.z = z; } } lombok-1.16.18/test/transform/resource/after-ecj/DelegateOnGetter.java000066400000000000000000000031561312655740700257000ustar00rootroot00000000000000import lombok.Delegate; import lombok.Getter; class DelegateOnGetter { private interface Bar { void setList(java.util.ArrayList list); int getInt(); } private final @Delegate @Getter(lazy = true) java.util.concurrent.atomic.AtomicReference bar = new java.util.concurrent.atomic.AtomicReference(); DelegateOnGetter() { super(); } public @Delegate @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Bar getBar() { java.lang.Object value = this.bar.get(); if ((value == null)) { synchronized (this.bar) { value = this.bar.get(); if ((value == null)) { final Bar actualValue = new Bar() { x() { super(); } public void setList(java.util.ArrayList list) { } public int getInt() { return 42; } }; value = ((actualValue == null) ? this.bar : actualValue); this.bar.set(value); } } } return (Bar) ((value == this.bar) ? null : value); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getInt() { return this.getBar().getInt(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setList(final java.util.ArrayList list) { this.getBar().setList(list); } } lombok-1.16.18/test/transform/resource/after-ecj/DelegateOnGetterNone.java000066400000000000000000000012211312655740700265070ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.experimental.Delegate; import lombok.Getter; @Getter class DelegateOnGetterNone { private interface Bar { void setList(java.util.ArrayList list); int getInt(); } private final @Delegate @Getter(AccessLevel.NONE) Bar bar = null; DelegateOnGetterNone() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getInt() { return this.bar.getInt(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setList(final java.util.ArrayList list) { this.bar.setList(list); } } lombok-1.16.18/test/transform/resource/after-ecj/DelegateOnMethods.java000066400000000000000000000006531312655740700260500ustar00rootroot00000000000000import lombok.experimental.Delegate; abstract class DelegateOnMethods { public static interface Bar { void bar(java.util.ArrayList list); } DelegateOnMethods() { super(); } public abstract @Delegate Bar getBar(); public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void bar(final java.util.ArrayList list) { this.getBar().bar(list); } } lombok-1.16.18/test/transform/resource/after-ecj/DelegateTypesAndExcludes.java000066400000000000000000000020751312655740700273740ustar00rootroot00000000000000import lombok.experimental.Delegate; class DelegatePlain { private static class FooImpl implements Foo { private FooImpl() { super(); } public void foo() { } public void bar(java.util.ArrayList list) { } } private static class BarImpl implements Bar { private BarImpl() { super(); } public void bar(java.util.ArrayList list) { } } private static interface Foo extends Bar { void foo(); } private static interface Bar { void bar(java.util.ArrayList list); } private final @Delegate(types = Bar.class) BarImpl bar = new BarImpl(); private final @Delegate(types = Foo.class,excludes = Bar.class) FooImpl foo = new FooImpl(); DelegatePlain() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void bar(final java.util.ArrayList list) { this.bar.bar(list); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void foo() { this.foo.foo(); } } lombok-1.16.18/test/transform/resource/after-ecj/DelegateWithDeprecated.java000066400000000000000000000013671312655740700270470ustar00rootroot00000000000000import lombok.experimental.Delegate; class DelegateWithDeprecated { private interface Bar { @Deprecated void deprecatedAnnotation(); void deprecatedComment(); void notDeprecated(); } private @Delegate Bar bar; DelegateWithDeprecated() { super(); } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void deprecatedAnnotation() { this.bar.deprecatedAnnotation(); } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void deprecatedComment() { this.bar.deprecatedComment(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void notDeprecated() { this.bar.notDeprecated(); } } lombok-1.16.18/test/transform/resource/after-ecj/DelegateWithVarargs.java000066400000000000000000000020341312655740700264040ustar00rootroot00000000000000import lombok.experimental.Delegate; class DelegateWithVarargs { private interface Bar { void justOneParameter(int... varargs); void multipleParameters(String first, int... varargs); void array(int[] array); void arrayVarargs(int[]... arrayVarargs); } private @Delegate Bar bar; DelegateWithVarargs() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void array(final int[] array) { this.bar.array(array); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void arrayVarargs(final int[]... arrayVarargs) { this.bar.arrayVarargs(arrayVarargs); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void justOneParameter(final int... varargs) { this.bar.justOneParameter(varargs); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void multipleParameters(final java.lang.String first, final int... varargs) { this.bar.multipleParameters(first, varargs); } } lombok-1.16.18/test/transform/resource/after-ecj/EncodingUsAscii.java000066400000000000000000000002001312655740700255100ustar00rootroot00000000000000//ignore: This test serves to check what happens with 'weird' characters when you use delombok. It's just not relevant for ecj. lombok-1.16.18/test/transform/resource/after-ecj/EncodingUtf8.java000066400000000000000000000002001312655740700247760ustar00rootroot00000000000000//ignore: This test serves to check what happens with 'weird' characters when you use delombok. It's just not relevant for ecj. lombok-1.16.18/test/transform/resource/after-ecj/EqualsAndHashCode.java000066400000000000000000000122061312655740700257660ustar00rootroot00000000000000@lombok.EqualsAndHashCode class EqualsAndHashCode { int x; boolean[] y; Object[] z; String a; String b; EqualsAndHashCode() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCode))) return false; final EqualsAndHashCode other = (EqualsAndHashCode) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.x != other.x)) return false; if ((! java.util.Arrays.equals(this.y, other.y))) return false; if ((! java.util.Arrays.deepEquals(this.z, other.z))) return false; final java.lang.Object this$a = this.a; final java.lang.Object other$a = other.a; if (((this$a == null) ? (other$a != null) : (! this$a.equals(other$a)))) return false; final java.lang.Object this$b = this.b; final java.lang.Object other$b = other.b; if (((this$b == null) ? (other$b != null) : (! this$b.equals(other$b)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCode); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); result = ((result * PRIME) + java.util.Arrays.hashCode(this.y)); result = ((result * PRIME) + java.util.Arrays.deepHashCode(this.z)); final java.lang.Object $a = this.a; result = ((result * PRIME) + (($a == null) ? 43 : $a.hashCode())); final java.lang.Object $b = this.b; result = ((result * PRIME) + (($b == null) ? 43 : $b.hashCode())); return result; } } final @lombok.EqualsAndHashCode class EqualsAndHashCode2 { int x; long y; float f; double d; boolean b; EqualsAndHashCode2() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCode2))) return false; final EqualsAndHashCode2 other = (EqualsAndHashCode2) o; if ((this.x != other.x)) return false; if ((this.y != other.y)) return false; if ((java.lang.Float.compare(this.f, other.f) != 0)) return false; if ((java.lang.Double.compare(this.d, other.d) != 0)) return false; if ((this.b != other.b)) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); final long $y = this.y; result = ((result * PRIME) + (int) ($y ^ ($y >>> 32))); result = ((result * PRIME) + java.lang.Float.floatToIntBits(this.f)); final long $d = java.lang.Double.doubleToLongBits(this.d); result = ((result * PRIME) + (int) ($d ^ ($d >>> 32))); result = ((result * PRIME) + (this.b ? 79 : 97)); return result; } } final @lombok.EqualsAndHashCode(callSuper = false) class EqualsAndHashCode3 extends EqualsAndHashCode { EqualsAndHashCode3() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCode3))) return false; final EqualsAndHashCode3 other = (EqualsAndHashCode3) o; if ((! other.canEqual((java.lang.Object) this))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCode3); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } } @lombok.EqualsAndHashCode(callSuper = true) class EqualsAndHashCode4 extends EqualsAndHashCode { EqualsAndHashCode4() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCode4))) return false; final EqualsAndHashCode4 other = (EqualsAndHashCode4) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((! super.equals(o))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCode4); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + super.hashCode()); return result; } } lombok-1.16.18/test/transform/resource/after-ecj/EqualsAndHashCodeConfigKeys1.java000066400000000000000000000037761312655740700300450ustar00rootroot00000000000000@lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys1Parent { EqualsAndHashCodeConfigKeys1Parent() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeConfigKeys1Parent))) return false; final EqualsAndHashCodeConfigKeys1Parent other = (EqualsAndHashCodeConfigKeys1Parent) o; if ((! other.canEqual((java.lang.Object) this))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCodeConfigKeys1Parent); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } } @lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys1 extends EqualsAndHashCodeConfigKeys1Parent { int x; EqualsAndHashCodeConfigKeys1() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeConfigKeys1))) return false; final EqualsAndHashCodeConfigKeys1 other = (EqualsAndHashCodeConfigKeys1) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.x != other.x)) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCodeConfigKeys1); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); return result; } }lombok-1.16.18/test/transform/resource/after-ecj/EqualsAndHashCodeConfigKeys2.java000066400000000000000000000060601312655740700300330ustar00rootroot00000000000000@lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys2Object extends Object { EqualsAndHashCodeConfigKeys2Object() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeConfigKeys2Object))) return false; final EqualsAndHashCodeConfigKeys2Object other = (EqualsAndHashCodeConfigKeys2Object) o; if ((! other.canEqual((java.lang.Object) this))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCodeConfigKeys2Object); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } } @lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys2Parent { EqualsAndHashCodeConfigKeys2Parent() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeConfigKeys2Parent))) return false; final EqualsAndHashCodeConfigKeys2Parent other = (EqualsAndHashCodeConfigKeys2Parent) o; if ((! other.canEqual((java.lang.Object) this))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCodeConfigKeys2Parent); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } } @lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys2 extends EqualsAndHashCodeConfigKeys2Parent { int x; EqualsAndHashCodeConfigKeys2() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeConfigKeys2))) return false; final EqualsAndHashCodeConfigKeys2 other = (EqualsAndHashCodeConfigKeys2) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((! super.equals(o))) return false; if ((this.x != other.x)) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCodeConfigKeys2); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + super.hashCode()); result = ((result * PRIME) + this.x); return result; } }lombok-1.16.18/test/transform/resource/after-ecj/EqualsAndHashCodeNestedShadow.java000066400000000000000000000044661312655740700303100ustar00rootroot00000000000000interface EqualsAndHashCodeNestedShadow { interface Foo { } class Bar { public static @lombok.EqualsAndHashCode(callSuper = false) class Foo extends Bar implements EqualsAndHashCodeNestedShadow.Foo { public Foo() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeNestedShadow.Bar.Foo))) return false; final EqualsAndHashCodeNestedShadow.Bar.Foo other = (EqualsAndHashCodeNestedShadow.Bar.Foo) o; if ((! other.canEqual((java.lang.Object) this))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCodeNestedShadow.Bar.Foo); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } } Bar() { super(); } } class Baz { public static @lombok.EqualsAndHashCode(callSuper = false) class Foo extends Bar implements EqualsAndHashCodeNestedShadow.Foo { public Foo() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeNestedShadow.Baz.Foo))) return false; final EqualsAndHashCodeNestedShadow.Baz.Foo other = (EqualsAndHashCodeNestedShadow.Baz.Foo) o; if ((! other.canEqual((java.lang.Object) this))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCodeNestedShadow.Baz.Foo); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } } Baz() { super(); } } }lombok-1.16.18/test/transform/resource/after-ecj/EqualsAndHashCodeWithExistingMethods.java000066400000000000000000000027711312655740700316670ustar00rootroot00000000000000@lombok.EqualsAndHashCode class EqualsAndHashCodeWithExistingMethods { int x; EqualsAndHashCodeWithExistingMethods() { super(); } public int hashCode() { return 42; } } final @lombok.EqualsAndHashCode class EqualsAndHashCodeWithExistingMethods2 { int x; EqualsAndHashCodeWithExistingMethods2() { super(); } public boolean equals(Object other) { return false; } } final @lombok.EqualsAndHashCode(callSuper = true) class EqualsAndHashCodeWithExistingMethods3 extends EqualsAndHashCodeWithExistingMethods { int x; EqualsAndHashCodeWithExistingMethods3() { super(); } private boolean canEqual(Object other) { return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeWithExistingMethods3))) return false; final EqualsAndHashCodeWithExistingMethods3 other = (EqualsAndHashCodeWithExistingMethods3) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((! super.equals(o))) return false; if ((this.x != other.x)) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + super.hashCode()); result = ((result * PRIME) + this.x); return result; } }lombok-1.16.18/test/transform/resource/after-ecj/EqualsAndHashCodeWithOnParam.java000066400000000000000000000037751312655740700301130ustar00rootroot00000000000000@interface Nullable { } @lombok.EqualsAndHashCode() class EqualsAndHashCodeWithOnParam { int x; boolean[] y; Object[] z; String a; String b; EqualsAndHashCodeWithOnParam() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final @Nullable java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeWithOnParam))) return false; final EqualsAndHashCodeWithOnParam other = (EqualsAndHashCodeWithOnParam) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.x != other.x)) return false; if ((! java.util.Arrays.equals(this.y, other.y))) return false; if ((! java.util.Arrays.deepEquals(this.z, other.z))) return false; final java.lang.Object this$a = this.a; final java.lang.Object other$a = other.a; if (((this$a == null) ? (other$a != null) : (! this$a.equals(other$a)))) return false; final java.lang.Object this$b = this.b; final java.lang.Object other$b = other.b; if (((this$b == null) ? (other$b != null) : (! this$b.equals(other$b)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final @Nullable java.lang.Object other) { return (other instanceof EqualsAndHashCodeWithOnParam); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); result = ((result * PRIME) + java.util.Arrays.hashCode(this.y)); result = ((result * PRIME) + java.util.Arrays.deepHashCode(this.z)); final java.lang.Object $a = this.a; result = ((result * PRIME) + (($a == null) ? 43 : $a.hashCode())); final java.lang.Object $b = this.b; result = ((result * PRIME) + (($b == null) ? 43 : $b.hashCode())); return result; } }lombok-1.16.18/test/transform/resource/after-ecj/EqualsAndHashCodeWithSomeExistingMethods.java000066400000000000000000000064071312655740700325130ustar00rootroot00000000000000import lombok.*; import static lombok.AccessLevel.NONE; @Data @Getter(NONE) @Setter(NONE) class EqualsAndHashCodeWithSomeExistingMethods { int x; public int hashCode() { return 42; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (("EqualsAndHashCodeWithSomeExistingMethods(x=" + this.x) + ")"); } public @java.lang.SuppressWarnings("all") EqualsAndHashCodeWithSomeExistingMethods() { super(); } } @Data @Getter(NONE) @Setter(NONE) class EqualsAndHashCodeWithSomeExistingMethods2 { int x; protected boolean canEqual(Object other) { return false; } public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeWithSomeExistingMethods2))) return false; final EqualsAndHashCodeWithSomeExistingMethods2 other = (EqualsAndHashCodeWithSomeExistingMethods2) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.x != other.x)) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (("EqualsAndHashCodeWithSomeExistingMethods2(x=" + this.x) + ")"); } public @java.lang.SuppressWarnings("all") EqualsAndHashCodeWithSomeExistingMethods2() { super(); } } @Data @Getter(NONE) @Setter(NONE) class EqualsAndHashCodeWithAllExistingMethods { int x; public int hashCode() { return 42; } public boolean equals(Object other) { return false; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (("EqualsAndHashCodeWithAllExistingMethods(x=" + this.x) + ")"); } public @java.lang.SuppressWarnings("all") EqualsAndHashCodeWithAllExistingMethods() { super(); } } @Data @Getter(AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) class EqualsAndHashCodeWithNoExistingMethods { int x; public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeWithNoExistingMethods))) return false; final EqualsAndHashCodeWithNoExistingMethods other = (EqualsAndHashCodeWithNoExistingMethods) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.x != other.x)) return false; return true; } protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) { return (other instanceof EqualsAndHashCodeWithNoExistingMethods); } public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (("EqualsAndHashCodeWithNoExistingMethods(x=" + this.x) + ")"); } public @java.lang.SuppressWarnings("all") EqualsAndHashCodeWithNoExistingMethods() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/EqualsAndHashcodeOfExclude.java000066400000000000000000000030071312655740700276240ustar00rootroot00000000000000final @lombok.EqualsAndHashCode(of = {"x"}) class EqualsAndHashCodeOf { int x; int y; EqualsAndHashCodeOf() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeOf))) return false; final EqualsAndHashCodeOf other = (EqualsAndHashCodeOf) o; if ((this.x != other.x)) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); return result; } } final @lombok.EqualsAndHashCode(exclude = {"y"}) class EqualsAndHashCodeExclude { int x; int y; EqualsAndHashCodeExclude() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof EqualsAndHashCodeExclude))) return false; final EqualsAndHashCodeExclude other = (EqualsAndHashCodeExclude) o; if ((this.x != other.x)) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.x); return result; } }lombok-1.16.18/test/transform/resource/after-ecj/ExtensionMethodPlain.java000066400000000000000000000014461312655740700266170ustar00rootroot00000000000000import lombok.experimental.ExtensionMethod; @ExtensionMethod({java.util.Arrays.class, ExtensionMethodPlain.Extensions.class}) class ExtensionMethodPlain { static class Extensions { Extensions() { super(); } public static T or(T obj, T ifNull) { return ((obj != null) ? obj : ifNull); } public static String toTitleCase(String in) { if (in.isEmpty()) return in; return (("" + Character.toTitleCase(in.charAt(0))) + in.substring(1).toLowerCase()); } } ExtensionMethodPlain() { super(); } public String test() { int[] intArray = {5, 3, 8, 2}; java.util.Arrays.sort(intArray); String iAmNull = null; return ExtensionMethodPlain.Extensions.or(iAmNull, ExtensionMethodPlain.Extensions.toTitleCase("hELlO, WORlD!")); } }lombok-1.16.18/test/transform/resource/after-ecj/FieldDefaults.java000066400000000000000000000007321312655740700252260ustar00rootroot00000000000000@lombok.experimental.FieldDefaults(makeFinal = true) class FieldDefaults1 { static int STATIC = 3; final int x; @lombok.experimental.NonFinal int y; () { } FieldDefaults1(int x) { super(); this.x = x; } } @lombok.experimental.FieldDefaults(level = lombok.AccessLevel.PRIVATE) class FieldDefaults2 { static int STATIC = 3; @lombok.experimental.PackagePrivate int x; private int y; () { } FieldDefaults2() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/FieldDefaultsNoop.java000066400000000000000000000001471312655740700260620ustar00rootroot00000000000000@lombok.experimental.FieldDefaults class FieldDefaultsNoop { FieldDefaultsNoop() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/FieldDefaultsViaConfig.java000066400000000000000000000006321312655740700270130ustar00rootroot00000000000000class FieldDefaultsViaConfig1 { private final int x; private @lombok.experimental.NonFinal int y; FieldDefaultsViaConfig1(int x) { super(); this.x = x; } } @lombok.experimental.FieldDefaults(level = lombok.AccessLevel.PROTECTED) class FieldDefaultsViaConfig2 { final @lombok.experimental.PackagePrivate int x = 2; protected final int y = 0; FieldDefaultsViaConfig2() { super(); } } FieldDefaultsViaConfigAndRequiredArgsConstructor.java000066400000000000000000000005061312655740700341430ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/after-ecj@lombok.RequiredArgsConstructor class FieldDefaultsViaConfigAndRequiredArgsConstructor { final int x; public @java.beans.ConstructorProperties({"x"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") FieldDefaultsViaConfigAndRequiredArgsConstructor(final int x) { super(); this.x = x; } } lombok-1.16.18/test/transform/resource/after-ecj/GenerateSuppressFBWarnings.java000066400000000000000000000004721312655740700277340ustar00rootroot00000000000000class GenerateSuppressFBWarnings { @lombok.Getter int y; GenerateSuppressFBWarnings() { super(); } public @java.lang.SuppressWarnings("all") @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(justification = "generated code") @javax.annotation.Generated("lombok") int getY() { return this.y; } }lombok-1.16.18/test/transform/resource/after-ecj/GeneratedJavaxOff.java000066400000000000000000000002551312655740700260360ustar00rootroot00000000000000class GeneratedJavaxOff { @lombok.Getter int x; GeneratedJavaxOff() { super(); } public @java.lang.SuppressWarnings("all") int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-ecj/GeneratedJavaxOnLombokOn.java000066400000000000000000000003631312655740700273410ustar00rootroot00000000000000class GeneratedJavaxOnLombokOn { @lombok.Getter int x; GeneratedJavaxOnLombokOn() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") @lombok.Generated int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-ecj/GeneratedOff.java000066400000000000000000000002431312655740700250410ustar00rootroot00000000000000class GeneratedOff { @lombok.Getter int x; GeneratedOff() { super(); } public @java.lang.SuppressWarnings("all") int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-ecj/GeneratedOffJavaxOn.java000066400000000000000000000003271312655740700263330ustar00rootroot00000000000000class GeneratedOffJavaxOn { @lombok.Getter int x; GeneratedOffJavaxOn() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-ecj/GeneratedOffLombokOn.java000066400000000000000000000003051312655740700265010ustar00rootroot00000000000000class GeneratedOffLombokOn { @lombok.Getter int x; GeneratedOffLombokOn() { super(); } public @java.lang.SuppressWarnings("all") @lombok.Generated int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterAccessLevel.java000066400000000000000000000037551312655740700260670ustar00rootroot00000000000000class GetterAccessLevel { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; @lombok.Getter(lombok.AccessLevel.PRIVATE) boolean isPrivate; @lombok.Getter(lombok.AccessLevel.PACKAGE) boolean isPackage; @lombok.Getter(lombok.AccessLevel.PROTECTED) boolean isProtected; @lombok.Getter(lombok.AccessLevel.PUBLIC) boolean isPublic; @lombok.Getter(lombok.AccessLevel.NONE) String noneString; @lombok.Getter(lombok.AccessLevel.PRIVATE) String privateString; @lombok.Getter(lombok.AccessLevel.PACKAGE) String packageString; @lombok.Getter(lombok.AccessLevel.PROTECTED) String protectedString; @lombok.Getter(lombok.AccessLevel.PUBLIC) String publicString; @lombok.Getter(value = lombok.AccessLevel.PUBLIC) String value; GetterAccessLevel() { super(); } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPrivate() { return this.isPrivate; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPackage() { return this.isPackage; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isProtected() { return this.isProtected; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPublic() { return this.isPublic; } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getPrivateString() { return this.privateString; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getPackageString() { return this.packageString; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getProtectedString() { return this.protectedString; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getPublicString() { return this.publicString; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getValue() { return this.value; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterAlreadyExists.java000066400000000000000000000066401312655740700264530ustar00rootroot00000000000000class Getter1 { @lombok.Getter boolean foo; Getter1() { super(); } boolean hasFoo() { return true; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isFoo() { return this.foo; } } class Getter2 { @lombok.Getter boolean foo; Getter2() { super(); } boolean isFoo() { return true; } } class Getter3 { @lombok.Getter boolean foo; Getter3() { super(); } boolean getFoo() { return true; } } class Getter4 { @lombok.Getter String foo; Getter4() { super(); } String hasFoo() { return null; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getFoo() { return this.foo; } } class Getter5 { @lombok.Getter String foo; Getter5() { super(); } String isFoo() { return null; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getFoo() { return this.foo; } } class Getter6 { @lombok.Getter String foo; Getter6() { super(); } String getFoo() { return null; } } class Getter7 { @lombok.Getter String foo; Getter7() { super(); } boolean hasFoo() { return false; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getFoo() { return this.foo; } } class Getter8 { @lombok.Getter String foo; Getter8() { super(); } boolean isFoo() { return false; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getFoo() { return this.foo; } } class Getter9 { @lombok.Getter String foo; Getter9() { super(); } boolean getFoo() { return false; } } class Getter10 { @lombok.Getter boolean foo; Getter10() { super(); } static boolean hasFoo() { return false; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isFoo() { return this.foo; } } class Getter11 { @lombok.Getter boolean foo; Getter11() { super(); } static boolean isFoo() { return false; } } class Getter12 { @lombok.Getter boolean foo; Getter12() { super(); } static boolean getFoo() { return false; } } class Getter13 { @lombok.Getter String foo; Getter13() { super(); } static boolean hasFoo() { return false; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getFoo() { return this.foo; } } class Getter14 { @lombok.Getter String foo; Getter14() { super(); } static boolean isFoo() { return false; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getFoo() { return this.foo; } } class Getter15 { @lombok.Getter String foo; Getter15() { super(); } static boolean getFoo() { return false; } } class Getter16 { @lombok.Getter String foo; Getter16() { super(); } static String hasFoo() { return ""; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getFoo() { return this.foo; } } class Getter17 { @lombok.Getter String foo; Getter17() { super(); } static String isFoo() { return ""; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getFoo() { return this.foo; } } class Getter18 { @lombok.Getter String foo; Getter18() { super(); } static String getFoo() { return ""; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterBoolean.java000066400000000000000000000016161312655740700252470ustar00rootroot00000000000000class Getter { @lombok.Getter boolean foo; @lombok.Getter boolean isBar; @lombok.Getter boolean hasBaz; Getter() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isFoo() { return this.foo; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isBar() { return this.isBar; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isHasBaz() { return this.hasBaz; } } class MoreGetter { @lombok.Getter boolean foo; MoreGetter() { super(); } boolean hasFoo() { return true; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isFoo() { return this.foo; } } class YetMoreGetter { @lombok.Getter boolean foo; YetMoreGetter() { super(); } boolean getFoo() { return true; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterDeprecated.java000066400000000000000000000007141312655740700257260ustar00rootroot00000000000000import lombok.Getter; class GetterDeprecated { @Deprecated @Getter int annotation; @Getter int javadoc; GetterDeprecated() { super(); } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getAnnotation() { return this.annotation; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getJavadoc() { return this.javadoc; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterEnum.java000066400000000000000000000013571312655740700245760ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(access = AccessLevel.PRIVATE) enum GetterEnum { ONE(1, "One"), private final @Getter int id; private final @Getter String name; () { } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getId() { return this.id; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getName() { return this.name; } private @java.beans.ConstructorProperties({"id", "name"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") GetterEnum(final int id, final String name) { super(); this.id = id; this.name = name; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterLazy.java000066400000000000000000000017151312655740700246070ustar00rootroot00000000000000class GetterLazy { static class ValueType { ValueType() { super(); } } private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference fieldName = new java.util.concurrent.atomic.AtomicReference(); GetterLazy() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ValueType getFieldName() { java.lang.Object value = this.fieldName.get(); if ((value == null)) { synchronized (this.fieldName) { value = this.fieldName.get(); if ((value == null)) { final ValueType actualValue = new ValueType(); value = ((actualValue == null) ? this.fieldName : actualValue); this.fieldName.set(value); } } } return (ValueType) ((value == this.fieldName) ? null : value); } } lombok-1.16.18/test/transform/resource/after-ecj/GetterLazyBoolean.java000066400000000000000000000056561312655740700261170ustar00rootroot00000000000000@lombok.EqualsAndHashCode(of = "booleanValue") @lombok.ToString(of = "booleanValue") class GetterLazyBoolean { private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference booleanValue = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference otherBooleanValue = new java.util.concurrent.atomic.AtomicReference(); GetterLazyBoolean() { super(); } private static boolean calculateBoolean() { return true; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isBooleanValue() { java.lang.Object value = this.booleanValue.get(); if ((value == null)) { synchronized (this.booleanValue) { value = this.booleanValue.get(); if ((value == null)) { final boolean actualValue = calculateBoolean(); value = actualValue; this.booleanValue.set(value); } } } return (java.lang.Boolean) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isOtherBooleanValue() { java.lang.Object value = this.otherBooleanValue.get(); if ((value == null)) { synchronized (this.otherBooleanValue) { value = this.otherBooleanValue.get(); if ((value == null)) { final boolean actualValue = (! calculateBoolean()); value = actualValue; this.otherBooleanValue.set(value); } } } return (java.lang.Boolean) value; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof GetterLazyBoolean))) return false; final GetterLazyBoolean other = (GetterLazyBoolean) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.isBooleanValue() != other.isBooleanValue())) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof GetterLazyBoolean); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + (this.isBooleanValue() ? 79 : 97)); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("GetterLazyBoolean(booleanValue=" + this.isBooleanValue()) + ")"); } } lombok-1.16.18/test/transform/resource/after-ecj/GetterLazyEahcToString.java000066400000000000000000000055421312655740700270640ustar00rootroot00000000000000@lombok.EqualsAndHashCode(doNotUseGetters = true) @lombok.ToString(doNotUseGetters = true) class GetterLazyEahcToString { private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference value = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter String value2 = ""; GetterLazyEahcToString() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getValue() { java.lang.Object value = this.value.get(); if ((value == null)) { synchronized (this.value) { value = this.value.get(); if ((value == null)) { final String actualValue = ""; value = ((actualValue == null) ? this.value : actualValue); this.value.set(value); } } } return (String) ((value == this.value) ? null : value); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getValue2() { return this.value2; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof GetterLazyEahcToString))) return false; final GetterLazyEahcToString other = (GetterLazyEahcToString) o; if ((! other.canEqual((java.lang.Object) this))) return false; final java.lang.Object this$value = this.getValue(); final java.lang.Object other$value = other.getValue(); if (((this$value == null) ? (other$value != null) : (! this$value.equals(other$value)))) return false; final java.lang.Object this$value2 = this.value2; final java.lang.Object other$value2 = other.value2; if (((this$value2 == null) ? (other$value2 != null) : (! this$value2.equals(other$value2)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof GetterLazyEahcToString); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $value = this.getValue(); result = ((result * PRIME) + (($value == null) ? 43 : $value.hashCode())); final java.lang.Object $value2 = this.value2; result = ((result * PRIME) + (($value2 == null) ? 43 : $value2.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("GetterLazyEahcToString(value=" + this.getValue()) + ", value2=") + this.value2) + ")"); } } lombok-1.16.18/test/transform/resource/after-ecj/GetterLazyInvalid.java000066400000000000000000000020641312655740700261140ustar00rootroot00000000000000class GetterLazyInvalidNotFinal { private @lombok.Getter(lazy = true) String fieldName = ""; GetterLazyInvalidNotFinal() { super(); } } class GetterLazyInvalidNotPrivate { final @lombok.Getter(lazy = true) String fieldName = ""; GetterLazyInvalidNotPrivate() { super(); } } class GetterLazyInvalidNotPrivateFinal { @lombok.Getter(lazy = true) String fieldName = ""; GetterLazyInvalidNotPrivateFinal() { super(); } } class GetterLazyInvalidNone { private final @lombok.Getter(lazy = true,value = lombok.AccessLevel.NONE) String fieldName = ""; GetterLazyInvalidNone() { super(); } } @lombok.Getter(lazy = true) class GetterLazyInvalidClass { private final String fieldName = ""; GetterLazyInvalidClass() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getFieldName() { return this.fieldName; } } class GetterLazyInvalidNoInit { private final @lombok.Getter(lazy = true) String fieldName; GetterLazyInvalidNoInit() { super(); this.fieldName = "foo"; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterLazyNative.java000066400000000000000000000155241312655740700257610ustar00rootroot00000000000000class GetterLazyNative { private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference booleanField = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference byteField = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference shortField = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference intField = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference longField = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference floatField = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference doubleField = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference charField = new java.util.concurrent.atomic.AtomicReference(); private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference intArrayField = new java.util.concurrent.atomic.AtomicReference(); GetterLazyNative() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isBooleanField() { java.lang.Object value = this.booleanField.get(); if ((value == null)) { synchronized (this.booleanField) { value = this.booleanField.get(); if ((value == null)) { final boolean actualValue = true; value = actualValue; this.booleanField.set(value); } } } return (java.lang.Boolean) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") byte getByteField() { java.lang.Object value = this.byteField.get(); if ((value == null)) { synchronized (this.byteField) { value = this.byteField.get(); if ((value == null)) { final byte actualValue = 1; value = actualValue; this.byteField.set(value); } } } return (java.lang.Byte) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") short getShortField() { java.lang.Object value = this.shortField.get(); if ((value == null)) { synchronized (this.shortField) { value = this.shortField.get(); if ((value == null)) { final short actualValue = 1; value = actualValue; this.shortField.set(value); } } } return (java.lang.Short) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getIntField() { java.lang.Object value = this.intField.get(); if ((value == null)) { synchronized (this.intField) { value = this.intField.get(); if ((value == null)) { final int actualValue = 1; value = actualValue; this.intField.set(value); } } } return (java.lang.Integer) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") long getLongField() { java.lang.Object value = this.longField.get(); if ((value == null)) { synchronized (this.longField) { value = this.longField.get(); if ((value == null)) { final long actualValue = 1; value = actualValue; this.longField.set(value); } } } return (java.lang.Long) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") float getFloatField() { java.lang.Object value = this.floatField.get(); if ((value == null)) { synchronized (this.floatField) { value = this.floatField.get(); if ((value == null)) { final float actualValue = 1.0f; value = actualValue; this.floatField.set(value); } } } return (java.lang.Float) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") double getDoubleField() { java.lang.Object value = this.doubleField.get(); if ((value == null)) { synchronized (this.doubleField) { value = this.doubleField.get(); if ((value == null)) { final double actualValue = 1.0; value = actualValue; this.doubleField.set(value); } } } return (java.lang.Double) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") char getCharField() { java.lang.Object value = this.charField.get(); if ((value == null)) { synchronized (this.charField) { value = this.charField.get(); if ((value == null)) { final char actualValue = '1'; value = actualValue; this.charField.set(value); } } } return (java.lang.Character) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int[] getIntArrayField() { java.lang.Object value = this.intArrayField.get(); if ((value == null)) { synchronized (this.intArrayField) { value = this.intArrayField.get(); if ((value == null)) { final int[] actualValue = new int[]{1}; value = ((actualValue == null) ? this.intArrayField : actualValue); this.intArrayField.set(value); } } } return (int[]) ((value == this.intArrayField) ? null : value); } } lombok-1.16.18/test/transform/resource/after-ecj/GetterLazyTransient.java000066400000000000000000000022321312655740700264720ustar00rootroot00000000000000class GetterLazyTransient { private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference nonTransientField = new java.util.concurrent.atomic.AtomicReference(); private final transient @lombok.Getter(lazy = true) int transientField = 2; private final transient @lombok.Getter int nonLazyTransientField = 3; GetterLazyTransient() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getNonTransientField() { java.lang.Object value = this.nonTransientField.get(); if ((value == null)) { synchronized (this.nonTransientField) { value = this.nonTransientField.get(); if ((value == null)) { final int actualValue = 1; value = actualValue; this.nonTransientField.set(value); } } } return (java.lang.Integer) value; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getNonLazyTransientField() { return this.nonLazyTransientField; } }lombok-1.16.18/test/transform/resource/after-ecj/GetterNone.java000066400000000000000000000004241312655740700245630ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.Getter; @Getter class GetterNone { int i; @Getter(AccessLevel.NONE) int foo; GetterNone() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getI() { return this.i; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterOnClass.java000066400000000000000000000042121312655740700252250ustar00rootroot00000000000000@lombok.Getter class GetterOnClass1 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; GetterOnClass1() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPublic() { return this.isPublic; } } @lombok.Getter(lombok.AccessLevel.PROTECTED) class GetterOnClass2 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isProtected; @lombok.Getter(lombok.AccessLevel.PACKAGE) boolean isPackage; GetterOnClass2() { super(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPackage() { return this.isPackage; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isProtected() { return this.isProtected; } } @lombok.Getter(lombok.AccessLevel.PACKAGE) class GetterOnClass3 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isPackage; GetterOnClass3() { super(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPackage() { return this.isPackage; } } @lombok.Getter(lombok.AccessLevel.PRIVATE) class GetterOnClass4 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isPrivate; GetterOnClass4() { super(); } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPrivate() { return this.isPrivate; } } @lombok.Getter(lombok.AccessLevel.PUBLIC) class GetterOnClass5 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; GetterOnClass5() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isPublic() { return this.isPublic; } } @lombok.Getter class GetterOnClass6 { String couldBeNull; @lombok.NonNull String nonNull; GetterOnClass6() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getCouldBeNull() { return this.couldBeNull; } public @lombok.NonNull @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getNonNull() { return this.nonNull; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterOnMethod.java000066400000000000000000000011221312655740700253750ustar00rootroot00000000000000class GetterOnMethod { public @interface Test { } @lombok.Getter() int i; @lombok.Getter() int j; @lombok.Getter() int k; GetterOnMethod() { super(); } public @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getI() { return this.i; } public @java.lang.Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getJ() { return this.j; } public @java.lang.Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getK() { return this.k; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterOnMethodErrors.java000066400000000000000000000005341312655740700266000ustar00rootroot00000000000000class PlaceFillerToMakeSurePositionIsRelevant { PlaceFillerToMakeSurePositionIsRelevant() { super(); } } @lombok.Getter() class GetterOnMethodErrors { private int test; GetterOnMethodErrors() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getTest() { return this.test; } }lombok-1.16.18/test/transform/resource/after-ecj/GetterOnMethodErrors2.java000066400000000000000000000026351312655740700266660ustar00rootroot00000000000000class GetterOnMethodErrors2 { public @interface Test { } private @lombok.Getter() int bad1; private @lombok.Getter() int bad2; private @lombok.Getter() int bad3; private @lombok.Getter() int bad4; private @lombok.Getter() int good1; private @lombok.Getter() int good2; private @lombok.Getter() int good3; private @lombok.Getter() int good4; GetterOnMethodErrors2() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getBad1() { return this.bad1; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getBad2() { return this.bad2; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getBad3() { return this.bad3; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getBad4() { return this.bad4; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getGood1() { return this.good1; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getGood2() { return this.good2; } public @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getGood3() { return this.good3; } public @Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getGood4() { return this.good4; } }lombok-1.16.18/test/transform/resource/after-ecj/GetterOnStatic.java000066400000000000000000000006211312655740700254070ustar00rootroot00000000000000class Getter { static @lombok.Getter boolean foo; static @lombok.Getter int bar; () { } Getter() { super(); } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean isFoo() { return Getter.foo; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getBar() { return Getter.bar; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterPlain.java000066400000000000000000000005521312655740700247310ustar00rootroot00000000000000import lombok.Getter; class GetterPlain { @lombok.Getter int i; @Getter int foo; GetterPlain() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getI() { return this.i; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getFoo() { return this.foo; } } lombok-1.16.18/test/transform/resource/after-ecj/GetterSetterJavadoc.java000066400000000000000000000066441312655740700264340ustar00rootroot00000000000000@lombok.Data class GetterSetterJavadoc1 { private int fieldName; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getFieldName() { return this.fieldName; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setFieldName(final int fieldName) { this.fieldName = fieldName; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof GetterSetterJavadoc1))) return false; final GetterSetterJavadoc1 other = (GetterSetterJavadoc1) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getFieldName() != other.getFieldName())) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof GetterSetterJavadoc1); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getFieldName()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("GetterSetterJavadoc1(fieldName=" + this.getFieldName()) + ")"); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") GetterSetterJavadoc1() { super(); } } class GetterSetterJavadoc2 { private @lombok.Getter @lombok.Setter int fieldName; GetterSetterJavadoc2() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getFieldName() { return this.fieldName; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setFieldName(final int fieldName) { this.fieldName = fieldName; } } class GetterSetterJavadoc3 { private @lombok.Getter @lombok.Setter int fieldName; GetterSetterJavadoc3() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getFieldName() { return this.fieldName; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setFieldName(final int fieldName) { this.fieldName = fieldName; } } @lombok.experimental.Accessors(chain = true,fluent = true) class GetterSetterJavadoc4 { private @lombok.Getter @lombok.Setter int fieldName; GetterSetterJavadoc4() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int fieldName() { return this.fieldName; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") GetterSetterJavadoc4 fieldName(final int fieldName) { this.fieldName = fieldName; return this; } } @lombok.experimental.Accessors(chain = true,fluent = true) class GetterSetterJavadoc5 { private @lombok.Getter @lombok.Setter int fieldName; GetterSetterJavadoc5() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int fieldName() { return this.fieldName; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") GetterSetterJavadoc5 fieldName(final int fieldName) { this.fieldName = fieldName; return this; } }lombok-1.16.18/test/transform/resource/after-ecj/GetterWithDollar.java000066400000000000000000000010721312655740700257350ustar00rootroot00000000000000class GetterWithDollar1 { @lombok.Getter int $i; GetterWithDollar1() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int get$i() { return this.$i; } } class GetterWithDollar2 { @lombok.Getter int $i; @lombok.Getter int i; GetterWithDollar2() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int get$i() { return this.$i; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getI() { return this.i; } } lombok-1.16.18/test/transform/resource/after-ecj/Helper.java000066400000000000000000000011041312655740700237240ustar00rootroot00000000000000import lombok.experimental.Helper; class HelperTest { { final int z = 5; if (Boolean.TRUE) { @Helper class H1 { H1() { super(); } void foo(int x) { System.out.println(("Hello, " + (x + z))); } } final H1 $H1 = new H1(); $H1.foo(10); @Helper class H2 { H2() { super(); } void bar() { $H1.foo(12); } } } } HelperTest() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/InjectField.java000066400000000000000000000032451312655740700246750ustar00rootroot00000000000000import java.util.logging.Level; import lombok.extern.java.Log; import lombok.Synchronized; @Log enum InjectField1 { A(), B(), private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(InjectField1.class.getName()); private final java.lang.Object $lock = new java.lang.Object[0]; private static final java.lang.Object $LOCK = new java.lang.Object[0]; private static final String LOG_MESSAGE = "static initializer"; private String fieldA; static { log.log(Level.FINE, LOG_MESSAGE); } private String fieldB; () { } InjectField1() { super(); } @Synchronized void generateLockField() { synchronized (this.$lock) { System.out.println("lock field"); } } static @Synchronized void generateStaticLockField() { synchronized (InjectField1.$LOCK) { System.out.println("static lock field"); } } } @Log class InjectField2 { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(InjectField2.class.getName()); private final java.lang.Object $lock = new java.lang.Object[0]; private static final String LOG_MESSAGE = "static initializer"; static { log.log(Level.FINE, LOG_MESSAGE); } () { } InjectField2() { super(); } @Synchronized void generateLockField() { synchronized (this.$lock) { System.out.println("lock field"); } } } @Log class InjectField3 { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(InjectField3.class.getName()); static { log.log(Level.FINE, "static initializer"); } () { } InjectField3() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/JavadocGenerally.java000066400000000000000000000002611312655740700257220ustar00rootroot00000000000000package testPackage; class JavadocGenerally { public interface TestingInner { } private int someField; JavadocGenerally() { super(); } public void test() { } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerCommons.java000066400000000000000000000014601312655740700252650ustar00rootroot00000000000000import lombok.extern.apachecommons.CommonsLog; @lombok.extern.apachecommons.CommonsLog class LoggerCommons { private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LoggerCommons.class); () { } LoggerCommons() { super(); } } @CommonsLog class LoggerCommonsWithImport { private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LoggerCommonsWithImport.class); () { } LoggerCommonsWithImport() { super(); } } @CommonsLog(topic = "DifferentName") class LoggerCommonsWithDifferentName { private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("DifferentName"); () { } LoggerCommonsWithDifferentName() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerConfig.java000066400000000000000000000003041312655740700250530ustar00rootroot00000000000000@lombok.extern.slf4j.Slf4j class LoggerWithConfig { private final org.slf4j.Logger myLogger = org.slf4j.LoggerFactory.getLogger(LoggerWithConfig.class); LoggerWithConfig() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerJBossLog.java000066400000000000000000000020561312655740700253360ustar00rootroot00000000000000import lombok.extern.jbosslog.JBossLog; @lombok.extern.jbosslog.JBossLog class LoggerJBossLog { private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(LoggerJBossLog.class); () { } LoggerJBossLog() { super(); } } @JBossLog class LoggerJBossLogWithImport { private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(LoggerJBossLogWithImport.class); () { } LoggerJBossLogWithImport() { super(); } } class LoggerJBossLogOuter { static @lombok.extern.jbosslog.JBossLog class Inner { private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(Inner.class); () { } Inner() { super(); } } LoggerJBossLogOuter() { super(); } } @JBossLog(topic = "DifferentLogger") class LoggerJBossLogWithDifferentLoggerName { private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger("DifferentLogger"); () { } LoggerJBossLogWithDifferentLoggerName() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerJul.java000066400000000000000000000013061312655740700244030ustar00rootroot00000000000000import lombok.extern.java.Log; @lombok.extern.java.Log class LoggerJul { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LoggerJul.class.getName()); () { } LoggerJul() { super(); } } @Log class LoggerJulWithImport { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LoggerJulWithImport.class.getName()); () { } LoggerJulWithImport() { super(); } } @Log(topic = "DifferentName") class LoggerJulWithDifferentName { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger("DifferentName"); () { } LoggerJulWithDifferentName() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerLog4j.java000066400000000000000000000013061312655740700246300ustar00rootroot00000000000000import lombok.extern.log4j.Log4j; @lombok.extern.log4j.Log4j class LoggerLog4j { private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LoggerLog4j.class); () { } LoggerLog4j() { super(); } } @Log4j class LoggerLog4jWithImport { private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LoggerLog4jWithImport.class); () { } LoggerLog4jWithImport() { super(); } } @Log4j(topic = "DifferentName") class LoggerLog4jWithDifferentName { private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("DifferentName"); () { } LoggerLog4jWithDifferentName() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerLog4j2.java000066400000000000000000000014161312655740700247140ustar00rootroot00000000000000import lombok.extern.log4j.Log4j2; @lombok.extern.log4j.Log4j2 class LoggerLog4j2 { private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LoggerLog4j2.class); () { } LoggerLog4j2() { super(); } } @Log4j2 class LoggerLog4j2WithImport { private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LoggerLog4j2WithImport.class); () { } LoggerLog4j2WithImport() { super(); } } @Log4j2(topic = "DifferentName") class LoggerLog4j2WithDifferentName { private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger("DifferentName"); () { } LoggerLog4j2WithDifferentName() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerSlf4j.java000066400000000000000000000017251312655740700246400ustar00rootroot00000000000000import lombok.extern.slf4j.Slf4j; @lombok.extern.slf4j.Slf4j class LoggerSlf4j { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4j.class); () { } LoggerSlf4j() { super(); } } @Slf4j class LoggerSlf4jWithImport { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4jWithImport.class); () { } LoggerSlf4jWithImport() { super(); } } class LoggerSlf4jOuter { static @lombok.extern.slf4j.Slf4j class Inner { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Inner.class); () { } Inner() { super(); } } LoggerSlf4jOuter() { super(); } } @Slf4j(topic = "DifferentLogger") class LoggerSlf4jWithDifferentLoggerName { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("DifferentLogger"); () { } LoggerSlf4jWithDifferentLoggerName() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerSlf4jAlreadyExists.java000066400000000000000000000001701312655740700273330ustar00rootroot00000000000000@lombok.extern.slf4j.Slf4j class LoggerSlf4jAlreadyExists { int log; LoggerSlf4jAlreadyExists() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerSlf4jTypes.java000066400000000000000000000015611312655740700256630ustar00rootroot00000000000000@lombok.extern.slf4j.Slf4j interface LoggerSlf4jTypesInterface { } @lombok.extern.slf4j.Slf4j @interface LoggerSlf4jTypesAnnotation { } @lombok.extern.slf4j.Slf4j enum LoggerSlf4jTypesEnum { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4jTypesEnum.class); () { } LoggerSlf4jTypesEnum() { super(); } } @lombok.extern.slf4j.Slf4j enum LoggerSlf4jTypesEnumWithElement { FOO(), private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4jTypesEnumWithElement.class); () { } LoggerSlf4jTypesEnumWithElement() { super(); } } interface LoggerSlf4jTypesInterfaceOuter { @lombok.extern.slf4j.Slf4j class Inner { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Inner.class); () { } Inner() { super(); } } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerSlf4jWithPackage.java000066400000000000000000000010441312655740700267420ustar00rootroot00000000000000package before; @lombok.extern.slf4j.Slf4j class LoggerSlf4jWithPackage { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggerSlf4jWithPackage.class); () { } LoggerSlf4jWithPackage() { super(); } } class LoggerSlf4jWithPackageOuter { static @lombok.extern.slf4j.Slf4j class Inner { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Inner.class); () { } Inner() { super(); } } LoggerSlf4jWithPackageOuter() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/LoggerXSlf4j.java000066400000000000000000000013361312655740700247660ustar00rootroot00000000000000import lombok.extern.slf4j.XSlf4j; @lombok.extern.slf4j.XSlf4j class LoggerXSlf4j { private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LoggerXSlf4j.class); () { } LoggerXSlf4j() { super(); } } @XSlf4j class LoggerXSlf4jWithImport { private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LoggerXSlf4jWithImport.class); () { } LoggerXSlf4jWithImport() { super(); } } @XSlf4j(topic = "DifferentName") class LoggerXSlf4jWithDifferentName { private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger("DifferentName"); () { } LoggerXSlf4jWithDifferentName() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/MixGetterVal.java000066400000000000000000000005671312655740700250740ustar00rootroot00000000000000import lombok.Getter; import lombok.val; class MixGetterVal { private @Getter int x; MixGetterVal() { super(); } public void m(int z) { } public void test() { final @val int y = x; m(y); final @val int a = getX(); m(a); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } }lombok-1.16.18/test/transform/resource/after-ecj/MultiFieldGetter.java000066400000000000000000000014551312655740700257270ustar00rootroot00000000000000import lombok.Getter; import lombok.AccessLevel; class MultiFieldGetter { @Getter(AccessLevel.PROTECTED) int x; @Getter(AccessLevel.PROTECTED) int y; MultiFieldGetter() { super(); } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getY() { return this.y; } } @Getter class MultiFieldGetter2 { @Getter(AccessLevel.PACKAGE) int x; @Getter(AccessLevel.PACKAGE) int y; MultiFieldGetter2() { super(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getY() { return this.y; } } lombok-1.16.18/test/transform/resource/after-ecj/NoArgsConstructorForce.java000066400000000000000000000006341312655740700271320ustar00rootroot00000000000000import lombok.NoArgsConstructor; public @NoArgsConstructor(force = true) class NoArgsConstructorForce { private final int[] i; private final Object[] o; private final java.util.List[] fullQualifiedList; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") NoArgsConstructorForce() { super(); this.i = null; this.o = null; this.fullQualifiedList = null; } }lombok-1.16.18/test/transform/resource/after-ecj/NonNullOnParameter.java000066400000000000000000000033551312655740700262420ustar00rootroot00000000000000class NonNullOnParameter extends Thread { NonNullOnParameter(@lombok.NonNull String arg) { this(arg, ""); if ((arg == null)) { throw new java.lang.NullPointerException("arg"); } } NonNullOnParameter(@lombok.NonNull String arg, @lombok.NonNull String arg2) { super(arg); if ((arg2 == null)) { throw new java.lang.NullPointerException("arg2"); } if ((arg == null)) throw new NullPointerException(); } public void test2(@lombok.NonNull String arg, @lombok.NonNull String arg2, @lombok.NonNull String arg3) { if ((arg == null)) { throw new java.lang.NullPointerException("arg"); } if ((arg3 == null)) { throw new java.lang.NullPointerException("arg3"); } if ((arg2 == null)) { throw new NullPointerException("arg2"); } if ((arg == null)) System.out.println("Hello"); } public void test3(@lombok.NonNull String arg) { if ((arg == null)) { throw new java.lang.NullPointerException("arg"); } if ((arg != null)) throw new IllegalStateException(); } public void test(@lombok.NonNull String stringArg, @lombok.NonNull String arg2, @lombok.NonNull int primitiveArg) { if ((stringArg == null)) { throw new java.lang.NullPointerException("stringArg"); } if ((arg2 == null)) { throw new java.lang.NullPointerException("arg2"); } } public void test(@lombok.NonNull String arg) { if ((arg == null)) { throw new java.lang.NullPointerException("arg"); } System.out.println("Hey"); if ((arg == null)) throw new NullPointerException(); } }lombok-1.16.18/test/transform/resource/after-ecj/NonNullOnParameterAbstract.java000066400000000000000000000005231312655740700277200ustar00rootroot00000000000000abstract class NonNullOnParameterAbstract { NonNullOnParameterAbstract() { super(); } public void test(@lombok.NonNull String arg) { if ((arg == null)) { throw new java.lang.NullPointerException("arg"); } System.out.println("Hey"); } public abstract void test2(@lombok.NonNull String arg); }lombok-1.16.18/test/transform/resource/after-ecj/NonNullOnParameterOfDefaultMethod.java000066400000000000000000000004231312655740700311660ustar00rootroot00000000000000interface NonNullOnParameterOfDefaultMethod { void test(@lombok.NonNull String arg); default void test2(@lombok.NonNull String arg) { if ((arg == null)) { throw new java.lang.NullPointerException("arg"); } System.out.println(arg); } } lombok-1.16.18/test/transform/resource/after-ecj/NonNullPlain.java000066400000000000000000000031211312655740700250570ustar00rootroot00000000000000import java.lang.annotation.*; @lombok.RequiredArgsConstructor @lombok.Getter @lombok.Setter class NonNullPlain { public @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) @Retention(RetentionPolicy.CLASS) @interface NotNull { } @lombok.NonNull int i; @lombok.NonNull String s; @NotNull Object o; public @java.beans.ConstructorProperties({"i", "s"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") NonNullPlain(final @lombok.NonNull int i, final @lombok.NonNull String s) { super(); if ((s == null)) { throw new java.lang.NullPointerException("s"); } this.i = i; this.s = s; } public @lombok.NonNull @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getI() { return this.i; } public @lombok.NonNull @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getS() { return this.s; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Object getO() { return this.o; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final @lombok.NonNull int i) { this.i = i; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setS(final @lombok.NonNull String s) { if ((s == null)) { throw new java.lang.NullPointerException("s"); } this.s = s; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setO(final Object o) { this.o = o; } }lombok-1.16.18/test/transform/resource/after-ecj/NonNullWithAlternateException.java000066400000000000000000000011741312655740700304540ustar00rootroot00000000000000public class NonNullWithAlternateException { private @lombok.NonNull @lombok.Setter String test; public NonNullWithAlternateException() { super(); } public void testMethod(@lombok.NonNull String arg) { if ((arg == null)) { throw new java.lang.IllegalArgumentException("arg is null"); } System.out.println(arg); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setTest(final @lombok.NonNull String test) { if ((test == null)) { throw new java.lang.IllegalArgumentException("test is null"); } this.test = test; } }lombok-1.16.18/test/transform/resource/after-ecj/NonNullWithSneakyThrows.java000066400000000000000000000006471312655740700273230ustar00rootroot00000000000000class NonNullWithSneakyThrows { NonNullWithSneakyThrows() { super(); } @lombok.SneakyThrows void test(@lombok.NonNull String in) { try { if ((in == null)) { throw new java.lang.NullPointerException("in"); } System.out.println(in); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } }lombok-1.16.18/test/transform/resource/after-ecj/OnXJava7Style.java000066400000000000000000000020141312655740700251240ustar00rootroot00000000000000public class OnXJava7Style { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } @lombok.Getter() String a; @lombok.Setter() String b; @lombok.Setter() String c; @lombok.Setter() String d; @lombok.Getter() String e; public OnXJava7Style() { super(); } public @Foo @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getA() { return this.a; } public @Foo() @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setB(final String b) { this.b = b; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setC(final @Foo("a") String c) { this.c = c; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setD(final @Bar(stuff = "b") String d) { this.d = d; } public @Foo(value = "c") @Bar(stuff = "d") @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getE() { return this.e; } } lombok-1.16.18/test/transform/resource/after-ecj/OnXJava7StyleOn8.java000066400000000000000000000020221312655740700255100ustar00rootroot00000000000000public class OnXJava7StyleOn8 { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } @lombok.Getter() String a; @lombok.Setter() String b; @lombok.Setter() String c; @lombok.Setter() String d; @lombok.Getter() String e; public OnXJava7StyleOn8() { super(); } public @Foo @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getA() { return this.a; } public @Foo() @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setB(final String b) { this.b = b; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setC(final @Foo("a") String c) { this.c = c; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setD(final @Bar(stuff = "b") String d) { this.d = d; } public @Foo(value = "c") @Bar(stuff = "d") @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getE() { return this.e; } } lombok-1.16.18/test/transform/resource/after-ecj/OnXJava8Style.java000066400000000000000000000020141312655740700251250ustar00rootroot00000000000000public class OnXJava8Style { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } @lombok.Getter() String a; @lombok.Setter() String b; @lombok.Setter() String c; @lombok.Setter() String d; @lombok.Getter() String e; public OnXJava8Style() { super(); } public @Foo @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getA() { return this.a; } public @Foo() @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setB(final String b) { this.b = b; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setC(final @Foo("a") String c) { this.c = c; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setD(final @Bar(stuff = "b") String d) { this.d = d; } public @Foo(value = "c") @Bar(stuff = "d") @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getE() { return this.e; } } lombok-1.16.18/test/transform/resource/after-ecj/OnXJava8StyleOn7.java000066400000000000000000000020221312655740700255100ustar00rootroot00000000000000public class OnXJava8StyleOn7 { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } @lombok.Getter() String a; @lombok.Setter() String b; @lombok.Setter() String c; @lombok.Setter() String d; @lombok.Getter() String e; public OnXJava8StyleOn7() { super(); } public @Foo @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getA() { return this.a; } public @Foo() @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setB(final String b) { this.b = b; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setC(final @Foo("a") String c) { this.c = c; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setD(final @Bar(stuff = "b") String d) { this.d = d; } public @Foo(value = "c") @Bar(stuff = "d") @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getE() { return this.e; } } lombok-1.16.18/test/transform/resource/after-ecj/SetterAccessLevel.java000066400000000000000000000023341312655740700260730ustar00rootroot00000000000000class SetterAccessLevel { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; @lombok.Setter(lombok.AccessLevel.PRIVATE) boolean isPrivate; @lombok.Setter(lombok.AccessLevel.PACKAGE) boolean isPackage; @lombok.Setter(lombok.AccessLevel.PROTECTED) boolean isProtected; @lombok.Setter(lombok.AccessLevel.PUBLIC) boolean isPublic; @lombok.Setter(value = lombok.AccessLevel.PUBLIC) boolean value; SetterAccessLevel() { super(); } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPrivate(final boolean isPrivate) { this.isPrivate = isPrivate; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPackage(final boolean isPackage) { this.isPackage = isPackage; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setProtected(final boolean isProtected) { this.isProtected = isProtected; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPublic(final boolean isPublic) { this.isPublic = isPublic; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setValue(final boolean value) { this.value = value; } } lombok-1.16.18/test/transform/resource/after-ecj/SetterAlreadyExists.java000066400000000000000000000024121312655740700264600ustar00rootroot00000000000000class Setter1 { @lombok.Setter boolean foo; Setter1() { super(); } void setFoo(boolean foo) { } } class Setter2 { @lombok.Setter boolean foo; Setter2() { super(); } void setFoo(String foo) { } } class Setter3 { @lombok.Setter String foo; Setter3() { super(); } void setFoo(boolean foo) { } } class Setter4 { @lombok.Setter String foo; Setter4() { super(); } void setFoo(String foo) { } } class Setter5 { @lombok.Setter String foo; Setter5() { super(); } void setFoo() { } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setFoo(final String foo) { this.foo = foo; } } class Setter6 { @lombok.Setter String foo; Setter6() { super(); } void setFoo(String foo, int x) { } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setFoo(final String foo) { this.foo = foo; } } class Setter7 { @lombok.Setter String foo; Setter7() { super(); } void setFoo(String foo, Object... x) { } } class Setter8 { @lombok.Setter boolean isFoo; Setter8() { super(); } void setIsFoo(boolean foo) { } } class Setter9 { @lombok.Setter boolean isFoo; Setter9() { super(); } void setFoo(boolean foo) { } } lombok-1.16.18/test/transform/resource/after-ecj/SetterDeprecated.java000066400000000000000000000007741312655740700257500ustar00rootroot00000000000000import lombok.Setter; class SetterDeprecated { @Deprecated @Setter int annotation; @Setter int javadoc; SetterDeprecated() { super(); } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setAnnotation(final int annotation) { this.annotation = annotation; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setJavadoc(final int javadoc) { this.javadoc = javadoc; } } lombok-1.16.18/test/transform/resource/after-ecj/SetterOnClass.java000066400000000000000000000047061312655740700252510ustar00rootroot00000000000000@lombok.Setter class SetterOnClass1 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; SetterOnClass1() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPublic(final boolean isPublic) { this.isPublic = isPublic; } } @lombok.Setter(lombok.AccessLevel.PROTECTED) class SetterOnClass2 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isProtected; @lombok.Setter(lombok.AccessLevel.PACKAGE) boolean isPackage; SetterOnClass2() { super(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPackage(final boolean isPackage) { this.isPackage = isPackage; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setProtected(final boolean isProtected) { this.isProtected = isProtected; } } @lombok.Setter(lombok.AccessLevel.PACKAGE) class SetterOnClass3 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isPackage; SetterOnClass3() { super(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPackage(final boolean isPackage) { this.isPackage = isPackage; } } @lombok.Setter(lombok.AccessLevel.PRIVATE) class SetterOnClass4 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isPrivate; SetterOnClass4() { super(); } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPrivate(final boolean isPrivate) { this.isPrivate = isPrivate; } } @lombok.Setter(lombok.AccessLevel.PUBLIC) class SetterOnClass5 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; SetterOnClass5() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPublic(final boolean isPublic) { this.isPublic = isPublic; } } @lombok.Setter class SetterOnClass6 { String couldBeNull; @lombok.NonNull String nonNull; SetterOnClass6() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setCouldBeNull(final String couldBeNull) { this.couldBeNull = couldBeNull; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setNonNull(final @lombok.NonNull String nonNull) { if ((nonNull == null)) { throw new java.lang.NullPointerException("nonNull"); } this.nonNull = nonNull; } } lombok-1.16.18/test/transform/resource/after-ecj/SetterOnMethod.java000066400000000000000000000022611312655740700254160ustar00rootroot00000000000000import lombok.Setter; class SetterOnMethod { @lombok.Setter() int i; @lombok.Setter() int j; public @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final int i) { this.i = i; } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setJ(final int j) { this.j = j; } SetterOnMethod() { super(); } } @lombok.Setter() class SetterOnClassOnMethod { int i; int j; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final int i) { this.i = i; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setJ(final int j) { this.j = j; } SetterOnClassOnMethod() { super(); } } @lombok.Setter() class SetterOnClassAndOnAField { int i; @lombok.Setter() int j; public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setJ(final int j) { this.j = j; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final int i) { this.i = i; } SetterOnClassAndOnAField() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/SetterOnMethodOnParam.java000066400000000000000000000012061312655740700266720ustar00rootroot00000000000000class SetterOnMethodOnParam { public @interface Test { } @lombok.Setter() int i; @lombok.Setter() int j; @lombok.Setter() int k; SetterOnMethodOnParam() { super(); } public @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final int i) { this.i = i; } public @java.lang.Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setJ(final @Test int j) { this.j = j; } public @java.lang.Deprecated @Test @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setK(final @Test int k) { this.k = k; } }lombok-1.16.18/test/transform/resource/after-ecj/SetterOnParam.java000066400000000000000000000024521312655740700252400ustar00rootroot00000000000000import lombok.Setter; class SetterOnParam { @lombok.Setter() int i; @lombok.Setter() int j; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final @SuppressWarnings("all") int i) { this.i = i; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setJ(final @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int j) { this.j = j; } SetterOnParam() { super(); } } @lombok.Setter() class SetterOnClassOnParam { int i; int j; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final int i) { this.i = i; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setJ(final int j) { this.j = j; } SetterOnClassOnParam() { super(); } } @lombok.Setter() class SetterOnClassAndOnAFieldParam { int i; @lombok.Setter() int j; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setJ(final @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int j) { this.j = j; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final int i) { this.i = i; } SetterOnClassAndOnAFieldParam() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/SetterOnParamAndOnMethod.java000066400000000000000000000004201312655740700273120ustar00rootroot00000000000000class SetterOnParamAndOnMethod { @lombok.Setter() int i; public @Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final @SuppressWarnings("all") int i) { this.i = i; } SetterOnParamAndOnMethod() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/SetterOnStatic.java000066400000000000000000000006541312655740700254310ustar00rootroot00000000000000class Setter { static @lombok.Setter boolean foo; static @lombok.Setter int bar; () { } Setter() { super(); } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setFoo(final boolean foo) { Setter.foo = foo; } public static @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setBar(final int bar) { Setter.bar = bar; } } lombok-1.16.18/test/transform/resource/after-ecj/SetterPlain.java000066400000000000000000000006001312655740700247370ustar00rootroot00000000000000import lombok.Setter; class SetterPlain { @lombok.Setter int i; @Setter int foo; SetterPlain() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final int i) { this.i = i; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setFoo(final int foo) { this.foo = foo; } } lombok-1.16.18/test/transform/resource/after-ecj/SetterWithDollar.java000066400000000000000000000011311312655740700257450ustar00rootroot00000000000000class SetterWithDollar1 { @lombok.Setter int $i; SetterWithDollar1() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void set$i(final int $i) { this.$i = $i; } } class SetterWithDollar2 { @lombok.Setter int $i; @lombok.Setter int i; SetterWithDollar2() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void set$i(final int $i) { this.$i = $i; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setI(final int i) { this.i = i; } } lombok-1.16.18/test/transform/resource/after-ecj/SimpleTypeResolution.java000066400000000000000000000005011312655740700266640ustar00rootroot00000000000000class SimpleTypeResolutionFail { private @Getter int x; SimpleTypeResolutionFail() { } } class SimpleTypeResolutionSuccess { private @lombok.Getter int x; SimpleTypeResolutionSuccess() { } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } } lombok-1.16.18/test/transform/resource/after-ecj/SneakyThrowsMultiple.java000066400000000000000000000031721312655740700266710ustar00rootroot00000000000000import java.awt.AWTException; import java.io.IOException; import java.util.Random; class SneakyThrowsMultiple { SneakyThrowsMultiple() { super(); } public @lombok.SneakyThrows({IOException.class, Throwable.class}) void test() { try { try { System.out.println("test1"); throw new IOException(); } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } catch (final Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public @lombok.SneakyThrows({AWTException.class, IOException.class}) void test2() { try { try { System.out.println("test2"); if (new Random().nextBoolean()) { throw new IOException(); } else { throw new AWTException("WHAT"); } } catch (final AWTException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public @lombok.SneakyThrows(value = {IOException.class, Throwable.class}) void test3() { try { try { System.out.println("test3"); throw new IOException(); } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } catch (final Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } }lombok-1.16.18/test/transform/resource/after-ecj/SneakyThrowsPlain.java000066400000000000000000000016671312655740700261500ustar00rootroot00000000000000import lombok.SneakyThrows; class SneakyThrowsPlain { @lombok.SneakyThrows SneakyThrowsPlain() { super(); try { System.out.println("constructor"); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } @lombok.SneakyThrows SneakyThrowsPlain(int x) { this(); try { System.out.println("constructor2"); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public @lombok.SneakyThrows void test() { try { System.out.println("test1"); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public @SneakyThrows void test2() { try { System.out.println("test2"); } catch (final java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } } lombok-1.16.18/test/transform/resource/after-ecj/SneakyThrowsSingle.java000066400000000000000000000015161312655740700263170ustar00rootroot00000000000000import java.io.IOException; class SneakyThrowsSingle { SneakyThrowsSingle() { super(); } public @lombok.SneakyThrows(Throwable.class) void test() { try { System.out.println("test1"); } catch (final Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public @lombok.SneakyThrows(IOException.class) void test2() { try { System.out.println("test2"); throw new IOException(); } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } public @lombok.SneakyThrows(value = IOException.class) void test3() { try { System.out.println("test3"); throw new IOException(); } catch (final IOException $ex) { throw lombok.Lombok.sneakyThrow($ex); } } } lombok-1.16.18/test/transform/resource/after-ecj/SynchronizedName.java000066400000000000000000000010711312655740700257700ustar00rootroot00000000000000class SynchronizedName { private Object read = new Object(); private static Object READ = new Object(); () { } SynchronizedName() { super(); } @lombok.Synchronized("read") void test1() { synchronized (this.read) { System.out.println("one"); } } @lombok.Synchronized("READ") void test4() { synchronized (this.READ) { System.out.println("four"); } } @lombok.Synchronized(value = "read") void test5() { synchronized (this.read) { System.out.println("five"); } } } lombok-1.16.18/test/transform/resource/after-ecj/SynchronizedNameNoSuchField.java000066400000000000000000000004211312655740700300520ustar00rootroot00000000000000class SynchronizedNameNoSuchField { private Object read = new Object(); private static Object READ = new Object(); () { } SynchronizedNameNoSuchField() { super(); } @lombok.Synchronized("write") void test2() { System.out.println("two"); } } lombok-1.16.18/test/transform/resource/after-ecj/SynchronizedNameStaticToInstanceRef.java000066400000000000000000000005711312655740700315710ustar00rootroot00000000000000class SynchronizedNameStaticToInstanceRef { private Object read = new Object(); private static Object READ = new Object(); () { } SynchronizedNameStaticToInstanceRef() { super(); } static @lombok.Synchronized("read") void test3() { synchronized (SynchronizedNameStaticToInstanceRef.read) { System.out.println("three"); } } } lombok-1.16.18/test/transform/resource/after-ecj/SynchronizedPlain.java000066400000000000000000000015211312655740700261530ustar00rootroot00000000000000import lombok.Synchronized; class SynchronizedPlain1 { private final java.lang.Object $lock = new java.lang.Object[0]; SynchronizedPlain1() { super(); } @lombok.Synchronized void test() { synchronized (this.$lock) { System.out.println("one"); } } @Synchronized void test2() { synchronized (this.$lock) { System.out.println("two"); } } } class SynchronizedPlain2 { private static final java.lang.Object $LOCK = new java.lang.Object[0]; () { } SynchronizedPlain2() { super(); } static @lombok.Synchronized void test() { synchronized (SynchronizedPlain2.$LOCK) { System.out.println("three"); } } static @Synchronized void test2() { synchronized (SynchronizedPlain2.$LOCK) { System.out.println("four"); } } } lombok-1.16.18/test/transform/resource/after-ecj/TestOperators.java000066400000000000000000000014361312655740700253330ustar00rootroot00000000000000class TestOperators { int x = 10; TestOperators() { super(); } public void test() { x = 12; int a = (+ x); boolean d = true; boolean e = false; boolean b; a = (- x); b = (! d); a = (~ x); a = (++ x); a = (-- x); a = (x ++); a = (x --); b = (d || e); b = (d && e); a = (x | a); a = (x ^ a); a = (x & a); b = (a == x); b = (a != x); b = (a < x); b = (a > x); b = (a <= x); b = (a >= x); a = (a << x); a = (a >> x); a = (a >>> x); a = (a + x); a = (a - x); a = (a * x); a = (a / x); a = (a % x); a |= x; a ^= x; a &= x; a <<= x; a >>= x; a >>>= x; a += x; a -= x; a *= x; a /= x; a %= x; a = ((a > x) ? 1 : 0); } } lombok-1.16.18/test/transform/resource/after-ecj/ToStringConfiguration.java000066400000000000000000000023111312655740700270070ustar00rootroot00000000000000import lombok.ToString; import lombok.Getter; @ToString @Getter class ToStringConfiguration { int x; ToStringConfiguration() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("ToStringConfiguration(" + this.x) + ")"); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } } @ToString(includeFieldNames = true) class ToStringConfiguration2 { int x; ToStringConfiguration2() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("ToStringConfiguration2(x=" + this.x) + ")"); } } @ToString(doNotUseGetters = false) @Getter class ToStringConfiguration3 { int x; ToStringConfiguration3() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("ToStringConfiguration3(" + this.getX()) + ")"); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } }lombok-1.16.18/test/transform/resource/after-ecj/ToStringInner.java000066400000000000000000000025461312655740700252650ustar00rootroot00000000000000import lombok.ToString; @ToString class ToStringOuter { @ToString class ToStringInner { int y; ToStringInner() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("ToStringOuter.ToStringInner(y=" + this.y) + ")"); } } static @ToString class ToStringStaticInner { int y; ToStringStaticInner() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("ToStringOuter.ToStringStaticInner(y=" + this.y) + ")"); } } class ToStringMiddle { @ToString class ToStringMoreInner { String name; ToStringMoreInner() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (("ToStringOuter.ToStringMiddle.ToStringMoreInner(name=" + this.name) + ")"); } } ToStringMiddle() { super(); } } int x; String name; ToStringOuter() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("ToStringOuter(x=" + this.x) + ", name=") + this.name) + ")"); } } lombok-1.16.18/test/transform/resource/after-ecj/ToStringPlain.java000066400000000000000000000011611312655740700252450ustar00rootroot00000000000000import lombok.ToString; @lombok.ToString class ToString1 { int x; String name; ToString1() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("ToString1(x=" + this.x) + ", name=") + this.name) + ")"); } } @ToString class ToString2 { int x; String name; ToString2() { super(); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("ToString2(x=" + this.x) + ", name=") + this.name) + ")"); } } lombok-1.16.18/test/transform/resource/after-ecj/Tolerate.java000066400000000000000000000027701312655740700242760ustar00rootroot00000000000000import java.util.regex.Pattern; @lombok.Setter @lombok.Getter class Tolerate { private Pattern pattern; Tolerate() { super(); } public @lombok.experimental.Tolerate void setPattern(String pattern) { setPattern(Pattern.compile(pattern)); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") void setPattern(final Pattern pattern) { this.pattern = pattern; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Pattern getPattern() { return this.pattern; } } @lombok.Getter @lombok.experimental.Wither @lombok.AllArgsConstructor class Tolerate2 { private final Pattern pattern; public @lombok.experimental.Tolerate Tolerate2 withPattern(String pattern) { return withPattern(Pattern.compile(pattern)); } public Tolerate2 withPattern(String nameGlob, String extensionGlob) { return withPattern(((nameGlob.replace("*", ".*") + "\\.") + extensionGlob.replace("*", ".*"))); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Pattern getPattern() { return this.pattern; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Tolerate2 withPattern(final Pattern pattern) { return ((this.pattern == pattern) ? this : new Tolerate2(pattern)); } public @java.beans.ConstructorProperties({"pattern"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Tolerate2(final Pattern pattern) { super(); this.pattern = pattern; } } lombok-1.16.18/test/transform/resource/after-ecj/TrickyTypeResolution.java000066400000000000000000000025221312655740700267050ustar00rootroot00000000000000import lombok.*; class TrickyDoNothing { @interface Getter { } @Getter int x; TrickyDoNothing() { super(); } } class TrickyDoNothing2 { @interface Getter { } @Getter int x; TrickyDoNothing2() { super(); } } class TrickySuccess { @Getter int x; TrickySuccess() { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } } class TrickyDoNothing3 { TrickyDoNothing3() { super(); } void test() { class val { val() { super(); } } val x = null; } } class TrickyDoSomething { TrickyDoSomething() { super(); } void test() { final @val java.lang.Object x = null; class val { val() { super(); } } } } class DoubleTrickyDoNothing { DoubleTrickyDoNothing() { super(); } void test() { class val { val() { super(); } } for (int i = 10;; (i < 20); i ++) { val y = null; } } } class DoubleTrickyDoSomething { DoubleTrickyDoSomething() { super(); } void test() { for (int j = 10;; (j < 20); j ++) { class val { val() { super(); } } } for (int i = 10;; (i < 20); i ++) { final @val java.lang.Object y = null; } } } lombok-1.16.18/test/transform/resource/after-ecj/TrickyTypeResolution2.java000066400000000000000000000002561312655740700267710ustar00rootroot00000000000000import lombok.*; class DoNothingDueToTopLevel { DoNothingDueToTopLevel() { super(); } void test() { val x = null; } } class val { val() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/UtilityClass.java000066400000000000000000000036611312655740700251500ustar00rootroot00000000000000final @lombok.experimental.UtilityClass class UtilityClass { protected static class InnerClass { private String innerInnerMember; protected InnerClass() { super(); } } private static long someField = System.currentTimeMillis(); () { } static void someMethod() { System.out.println(); } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") UtilityClass() { super(); throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } } class UtilityInner { static class InnerInner { static final @lombok.experimental.UtilityClass class InnerInnerInner { static int member; () { } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") InnerInnerInner() { super(); throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } } InnerInner() { super(); } } enum UtilityInsideEnum { static final @lombok.experimental.UtilityClass class InsideEnum { static int member; () { } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") InsideEnum() { super(); throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } } FOO(), BAR(), () { } UtilityInsideEnum() { super(); } } interface UtilityInsideInterface { final @lombok.experimental.UtilityClass class InsideInterface { static int member; () { } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") InsideInterface() { super(); throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } } } UtilityInner() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/UtilityClassErrors.java000066400000000000000000000013501312655740700263360ustar00rootroot00000000000000final @lombok.experimental.UtilityClass class UtilityClassErrors1 { private static String someField; () { } protected UtilityClassErrors1() { super(); } static void method() { @lombok.experimental.UtilityClass class MethodLocalClass { MethodLocalClass() { super(); } } } } @lombok.experimental.UtilityClass enum UtilityClassErrors2 { () { } UtilityClassErrors2() { super(); } } class UtilityClassErrors3 { class NonStaticInner { @lombok.experimental.UtilityClass class ThisShouldFail { private String member; ThisShouldFail() { super(); } } NonStaticInner() { super(); } } UtilityClassErrors3() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/ValAnonymousSubclassWithGenerics.java000066400000000000000000000010661312655740700311630ustar00rootroot00000000000000import java.util.*; import lombok.val; public class ValAnonymousSubclassWithGenerics { Object object = new Object() { x() { super(); } void foo() { final @val int j = 1; } }; java.util.List names = new java.util.ArrayList() { x() { super(); } public String get(int i) { final @val java.lang.String result = super.get(i); return result; } }; public ValAnonymousSubclassWithGenerics() { super(); } void bar() { final @val int k = super.hashCode(); int x = k; } }lombok-1.16.18/test/transform/resource/after-ecj/ValComplex.java000066400000000000000000000013011312655740700245560ustar00rootroot00000000000000import lombok.val; public class ValComplex { private String field = ""; private static final int CONSTANT = 20; () { } public ValComplex() { super(); } public void testComplex() { final @val char[] shouldBeCharArray = field.toCharArray(); final @val int shouldBeInt = CONSTANT; final @val java.lang.Object lock = new Object(); synchronized (lock) { final @val int field = 20; final @val int inner = 10; switch (field) { case 5 : final @val char[] shouldBeCharArray2 = shouldBeCharArray; final @val int innerInner = inner; } } final @val java.lang.String shouldBeString = field; } }lombok-1.16.18/test/transform/resource/after-ecj/ValDefault.java000066400000000000000000000002161312655740700245370ustar00rootroot00000000000000interface ValDefault { int size(); default void method() { final @lombok.val int x = 1; final @lombok.val int size = size(); } }lombok-1.16.18/test/transform/resource/after-ecj/ValErrors.java000066400000000000000000000003241312655740700244270ustar00rootroot00000000000000import lombok.val; public class ValErrors { public ValErrors() { super(); } public void unresolvableExpression() { val c = d; } public void arrayInitializer() { val e = {"foo", "bar"}; } }lombok-1.16.18/test/transform/resource/after-ecj/ValFinal.java000066400000000000000000000002121312655740700242000ustar00rootroot00000000000000import lombok.val; public class ValFinal { public ValFinal() { super(); } public void test() { final @val int x = 10; } } lombok-1.16.18/test/transform/resource/after-ecj/ValInBasicFor.java000066400000000000000000000004751312655740700251410ustar00rootroot00000000000000import lombok.val; public class ValInBasicFor { public ValInBasicFor() { super(); } public void basicFor() { java.util.List list = java.util.Arrays.asList("Hello, World!"); for (val shouldBe = 1;, val marked = "";, val error = 1.0;; ; ) { System.out.println(""); } } }lombok-1.16.18/test/transform/resource/after-ecj/ValInFor.java000066400000000000000000000006161312655740700241740ustar00rootroot00000000000000import lombok.val; public class ValInFor { public ValInFor() { super(); } public void enhancedFor() { java.util.List list = java.util.Arrays.asList("Hello, World!"); for (final @val java.lang.String shouldBeString : list) { System.out.println(shouldBeString.toLowerCase()); final @val java.lang.String shouldBeString2 = shouldBeString; } } }lombok-1.16.18/test/transform/resource/after-ecj/ValInLambda.java000066400000000000000000000005521312655740700246250ustar00rootroot00000000000000// version 8: import lombok.val; class ValInLambda { Runnable foo = (Runnable) () -> { final @val int i = 1; }; ValInLambda() { super(); } public void easyLambda() { Runnable foo = (Runnable) () -> { final @val int i = 1; }; } public void easyIntersectionLambda() { Runnable foo = (Runnable) () -> { final @val int i = 1; }; } } lombok-1.16.18/test/transform/resource/after-ecj/ValInMultiDeclaration.java000066400000000000000000000003141312655740700267010ustar00rootroot00000000000000import lombok.val; public class ValInMultiDeclaration { public ValInMultiDeclaration() { super(); } public void test() { final @val int x = 10; final @val java.lang.String y = ""; } } lombok-1.16.18/test/transform/resource/after-ecj/ValInTryWithResources.java000066400000000000000000000006331312655740700267520ustar00rootroot00000000000000import lombok.val; import java.io.IOException; public class ValInTryWithResources { public ValInTryWithResources() { super(); } public void whyTryInsteadOfCleanup() throws IOException { try (final @val java.io.InputStream in = getClass().getResourceAsStream("ValInTryWithResources.class")) { final @val java.io.InputStream i = in; final @val int j = in.read(); } } } lombok-1.16.18/test/transform/resource/after-ecj/ValLambda.java000066400000000000000000000010521312655740700243320ustar00rootroot00000000000000class ValLambda { ValLambda() { super(); } public void easyLambda() { final @lombok.val java.lang.Runnable foo = (Runnable) () -> { }; } public void easyIntersectionLambda() { final @lombok.val java.lang.Object foo = (Runnable & java.io.Serializable) () -> { }; final @lombok.val java.lang.Object bar = (java.io.Serializable & Runnable) () -> { }; } public void easyLubLambda() { final @lombok.val java.lang.Runnable foo = ((System.currentTimeMillis() > 0) ? (Runnable) () -> { } : (Runnable) System.out::println); } }lombok-1.16.18/test/transform/resource/after-ecj/ValLessSimple.java000066400000000000000000000015431312655740700252370ustar00rootroot00000000000000import lombok.val; public class ValLessSimple { private short field2 = 5; { System.out.println("Hello"); final @val int z = 20; final @val int x = 10; final @val int a = z; final @val short y = field2; } private String field = "field"; public ValLessSimple() { super(); } private String method() { return "method"; } private double method2() { return 2.0; } private void testVal(String param) { final @val java.lang.String fieldV = field; final @val int a = 10; final @val int b = 20; { final @val java.lang.String methodV = method(); final @val java.lang.String foo = (fieldV + methodV); } } private void testValInCatchBlock() { try { final @val int x = (1 / 0); } catch (ArithmeticException e) { final @val int y = 0; } } } lombok-1.16.18/test/transform/resource/after-ecj/ValLub.java000066400000000000000000000016461312655740700237050ustar00rootroot00000000000000class ValLub { ValLub() { super(); } public void easyLub() { java.util.Map m = java.util.Collections.emptyMap(); final @lombok.val java.util.Map foo = ((System.currentTimeMillis() > 0) ? m : java.util.Collections.emptyMap()); } public void sillyLubWithUnboxingThatProducesErrorThatVarIsPrimitive() { Integer i = 20; Double d = 20.0; final @lombok.val double thisShouldBePrimitiveDouble = ((System.currentTimeMillis() > 0) ? i : d); } public void hardLub() { java.util.List list = new java.util.ArrayList(); java.util.Set set = new java.util.HashSet(); final @lombok.val java.util.Collection thisShouldBeCollection = ((System.currentTimeMillis() > 0) ? list : set); thisShouldBeCollection.add(""); String foo = thisShouldBeCollection.iterator().next(); } } lombok-1.16.18/test/transform/resource/after-ecj/ValNullInit.java000066400000000000000000000002141312655740700247070ustar00rootroot00000000000000import lombok.val; class ValNullInit { ValNullInit() { super(); } void method() { final @val java.lang.Object x = null; } }lombok-1.16.18/test/transform/resource/after-ecj/ValOutersWithGenerics.java000066400000000000000000000027001312655740700267500ustar00rootroot00000000000000import java.util.*; import lombok.val; public class ValOutersWithGenerics { class Inner { Inner() { super(); } } class InnerWithGenerics { InnerWithGenerics() { super(); } } static class SubClass extends ValOutersWithGenerics { SubClass() { super(); } public void testSubClassOfOutersWithGenerics() { List list = new ArrayList(); final @val ValOutersWithGenerics.Inner elem = list.get(0); } } public ValOutersWithGenerics() { super(); } public void testOutersWithGenerics() { final @val java.lang.String foo = ""; List list = new ArrayList(); final @val ValOutersWithGenerics.Inner elem = list.get(0); } public void testLocalClasses() { class Local { Local() { super(); } } final @val Local q = new Local(); } public static void test() { final @val ValOutersWithGenerics outer = new ValOutersWithGenerics(); final @val ValOutersWithGenerics.Inner inner1 = outer.new Inner(); final @val ValOutersWithGenerics.InnerWithGenerics inner2 = outer.new InnerWithGenerics(); } public static void loop(Map map) { for (final @val java.util.Map.Entry e : map.entrySet()) { } } } lombok-1.16.18/test/transform/resource/after-ecj/ValRawType.java000066400000000000000000000010241312655740700245440ustar00rootroot00000000000000import java.util.List; import lombok.val; public class ValRawType { static class Element { Element() { super(); } public List attributes() { return null; } } static class Attribute { Attribute() { super(); } } public ValRawType() { super(); } public void test() { Element propElement = new Element(); for (final @val java.lang.Object attribute : propElement.attributes()) { final @val ValRawType.Attribute attr = (Attribute) attribute; } } }lombok-1.16.18/test/transform/resource/after-ecj/ValSimple.java000066400000000000000000000013101312655740700244000ustar00rootroot00000000000000import lombok.val; public class ValSimple { private String field = "field"; private short field2 = 5; public ValSimple() { super(); } private String method() { return "method"; } private double method2() { return 2.0; } private void testVal(String param) { final @val java.lang.String fieldV = field; final @val java.lang.String methodV = method(); final @val java.lang.String paramV = param; final @val java.lang.String valOfVal = fieldV; final @val java.lang.String operatorV = (fieldV + valOfVal); final @val short fieldW = field2; final @val double methodW = method2(); byte localVar = 3; final @val int operatorW = (fieldW + localVar); } }lombok-1.16.18/test/transform/resource/after-ecj/ValWeirdTypes.java000066400000000000000000000046311312655740700252570ustar00rootroot00000000000000import java.util.*; import lombok.val; public class ValWeirdTypes { private List fieldList; public ValWeirdTypes() { super(); } public void testGenerics() { List list = new ArrayList(); list.add("Hello, World!"); final @val java.lang.String shouldBeString = list.get(0); final @val java.util.List shouldBeListOfString = list; final @val java.util.List shouldBeListOfStringToo = Arrays.asList("hello", "world"); final @val java.lang.String shouldBeString2 = shouldBeListOfString.get(0); } public void testGenericsInference() { final @val java.util.List huh = Collections.emptyList(); final @val java.util.List huh2 = Collections.emptyList(); } public void testPrimitives() { final @val int x = 10; final @val long y = (5 + 3L); } public void testAnonymousInnerClass() { final @val java.lang.Runnable y = new Runnable() { x() { super(); } public void run() { } }; } public void testTypeParams(List param) { final @val T t = param.get(0); final @val Z z = fieldList.get(0); final @val java.util.List k = param; final @val java.util.List y = fieldList; } public void testBounds(List lower, List upper) { final @val java.lang.Number a = lower.get(0); final @val java.lang.Object b = upper.get(0); final @val java.util.List c = lower; final @val java.util.List d = upper; List unbound = lower; final @val java.util.List e = unbound; } public void testCompound() { final @val java.util.ArrayList a = new ArrayList(); final @val java.util.Vector b = new Vector(); final @val boolean c = (1 < System.currentTimeMillis()); final @val java.util.AbstractList d = (c ? a : b); java.util.RandomAccess confirm = (c ? a : b); } public void nullType() { final @val java.lang.Object nully = null; } public void testArrays() { final @val int[] intArray = new int[]{1, 2, 3}; final @val java.lang.Object[][] multiDimArray = new Object[][]{{}}; final @val int[] copy = intArray; final @val java.lang.Object[] single = multiDimArray[0]; final @val int singleInt = copy[0]; } }lombok-1.16.18/test/transform/resource/after-ecj/ValWithLabel.java000066400000000000000000000003741312655740700250330ustar00rootroot00000000000000import lombok.val; public class ValWithLabel { { LABEL: for (final @val java.lang.String x : new String[0]) { if ((x.toLowerCase() == null)) { continue LABEL; } } } public ValWithLabel() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/ValWithLocalClasses.java000066400000000000000000000005011312655740700263540ustar00rootroot00000000000000class ValWithLocalClasses1 { { final @lombok.val ValWithLocalClasses2 f2 = new ValWithLocalClasses2() { x() { super(); } }; } ValWithLocalClasses1() { super(); } } class ValWithLocalClasses2 { { final @lombok.val int f3 = 0; } ValWithLocalClasses2() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/ValueCallSuper.java000066400000000000000000000024451312655740700254050ustar00rootroot00000000000000class ValueParent { ValueParent() { super(); } } final @lombok.Value class ValueCallSuper extends ValueParent { public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof ValueCallSuper))) return false; final ValueCallSuper other = (ValueCallSuper) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((! super.equals(o))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof ValueCallSuper); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + super.hashCode()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "ValueCallSuper()"; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ValueCallSuper() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/ValueExperimental.java000066400000000000000000000031011312655740700261360ustar00rootroot00000000000000import lombok.experimental.Value; final @Value class ValueExperimental1 { public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof ValueExperimental1))) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "ValueExperimental1()"; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ValueExperimental1() { super(); } } final @lombok.experimental.Value class ValueExperimental2 { public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof ValueExperimental2))) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "ValueExperimental2()"; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ValueExperimental2() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/ValueExperimentalStarImport.java000066400000000000000000000015101312655740700301650ustar00rootroot00000000000000import lombok.experimental.*; final @Value class ValueExperimentalStarImport { public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof ValueExperimentalStarImport))) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "ValueExperimentalStarImport()"; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ValueExperimentalStarImport() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/ValuePlain.java000066400000000000000000000121271312655740700245540ustar00rootroot00000000000000import lombok.Value; final @lombok.Value class Value1 { private final int x; private final String name; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getName() { return this.name; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Value1))) return false; final Value1 other = (Value1) o; if ((this.getX() != other.getX())) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name)))) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); final java.lang.Object $name = this.getName(); result = ((result * PRIME) + (($name == null) ? 43 : $name.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("Value1(x=" + this.getX()) + ", name=") + this.getName()) + ")"); } public @java.beans.ConstructorProperties({"x", "name"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Value1(final int x, final String name) { super(); this.x = x; this.name = name; } } @Value @lombok.experimental.NonFinal class Value2 { public final int x; private final String name; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") String getName() { return this.name; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Value2))) return false; final Value2 other = (Value2) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getX() != other.getX())) return false; final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name)))) return false; return true; } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean canEqual(final java.lang.Object other) { return (other instanceof Value2); } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); final java.lang.Object $name = this.getName(); result = ((result * PRIME) + (($name == null) ? 43 : $name.hashCode())); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("Value2(x=" + this.getX()) + ", name=") + this.getName()) + ")"); } public @java.beans.ConstructorProperties({"x", "name"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Value2(final int x, final String name) { super(); this.x = x; this.name = name; } } final @Value class Value3 { private @lombok.experimental.NonFinal int x; private final int y; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getX() { return this.x; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int getY() { return this.y; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof Value3))) return false; final Value3 other = (Value3) o; if ((this.getX() != other.getX())) return false; if ((this.getY() != other.getY())) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getX()); result = ((result * PRIME) + this.getY()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return (((("Value3(x=" + this.getX()) + ", y=") + this.getY()) + ")"); } public @java.beans.ConstructorProperties({"x", "y"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Value3(final int x, final int y) { super(); this.x = x; this.y = y; } } lombok-1.16.18/test/transform/resource/after-ecj/ValueStaticField.java000066400000000000000000000015371312655740700257070ustar00rootroot00000000000000import lombok.Value; final @Value class ValueStaticField { static int x; static String PASSWORD = "Ken sent me"; () { } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof ValueStaticField))) return false; return true; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") int hashCode() { int result = 1; return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") java.lang.String toString() { return "ValueStaticField()"; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") ValueStaticField() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/VarComplex.java000066400000000000000000000012361312655740700245730ustar00rootroot00000000000000import lombok.experimental.var; public class VarComplex { private String field = ""; private static final int CONSTANT = 20; () { } public VarComplex() { super(); } public void testComplex() { @var char[] shouldBeCharArray = field.toCharArray(); @var int shouldBeInt = CONSTANT; @var java.lang.Object lock = new Object(); synchronized (lock) { @var int field = 20; @var int inner = 10; switch (field) { case 5 : @var char[] shouldBeCharArray2 = shouldBeCharArray; @var int innerInner = inner; } } @var java.lang.String shouldBeString = field; } }lombok-1.16.18/test/transform/resource/after-ecj/VarInFor.java000066400000000000000000000004601312655740700241770ustar00rootroot00000000000000import lombok.experimental.var; public class VarInFor { public VarInFor() { super(); } public void enhancedFor() { int[] list = new int[]{1, 2}; for (@var int shouldBeInt : list) { System.out.println(shouldBeInt); @var int shouldBeInt2 = shouldBeInt; } } }lombok-1.16.18/test/transform/resource/after-ecj/VarInForOld.java000066400000000000000000000003351312655740700246370ustar00rootroot00000000000000import lombok.experimental.var; public class VarInForOld { public VarInForOld() { super(); } public void oldFor() { for (@var int i = 0;; (i < 100); ++ i) { System.out.println(i); } } }lombok-1.16.18/test/transform/resource/after-ecj/VarModifier.java000066400000000000000000000004431312655740700247210ustar00rootroot00000000000000import lombok.experimental.var; public class VarModifier { private String field = ""; public VarModifier() { super(); } public void testComplex() { final @var char[] shouldBeFinalCharArray = field.toCharArray(); @var char[] shouldBeCharArray = field.toCharArray(); } }lombok-1.16.18/test/transform/resource/after-ecj/VarNullInit.java000066400000000000000000000002401312655740700247140ustar00rootroot00000000000000import lombok.experimental.var; public class VarNullInit { public VarNullInit() { super(); } void method() { @var java.lang.Object x = null; } }lombok-1.16.18/test/transform/resource/after-ecj/WithInnerAnnotation.java000066400000000000000000000001731312655740700264540ustar00rootroot00000000000000class WithInnerAnnotation { @interface Inner { int bar() default 42; } WithInnerAnnotation() { super(); } }lombok-1.16.18/test/transform/resource/after-ecj/WitherAccessLevel.java000066400000000000000000000041471312655740700260730ustar00rootroot00000000000000import lombok.AccessLevel; class WitherAccessLevel { @lombok.experimental.Wither(lombok.AccessLevel.NONE) boolean isNone; @lombok.experimental.Wither(AccessLevel.PRIVATE) boolean isPrivate; @lombok.experimental.Wither(lombok.AccessLevel.PACKAGE) boolean isPackage; @lombok.experimental.Wither(AccessLevel.PROTECTED) boolean isProtected; @lombok.experimental.Wither(lombok.AccessLevel.PUBLIC) boolean isPublic; @lombok.experimental.Wither(value = lombok.AccessLevel.PUBLIC) boolean value; WitherAccessLevel(boolean isNone, boolean isPrivate, boolean isPackage, boolean isProtected, boolean isPublic, boolean value) { super(); } private @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherAccessLevel withPrivate(final boolean isPrivate) { return ((this.isPrivate == isPrivate) ? this : new WitherAccessLevel(this.isNone, isPrivate, this.isPackage, this.isProtected, this.isPublic, this.value)); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherAccessLevel withPackage(final boolean isPackage) { return ((this.isPackage == isPackage) ? this : new WitherAccessLevel(this.isNone, this.isPrivate, isPackage, this.isProtected, this.isPublic, this.value)); } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherAccessLevel withProtected(final boolean isProtected) { return ((this.isProtected == isProtected) ? this : new WitherAccessLevel(this.isNone, this.isPrivate, this.isPackage, isProtected, this.isPublic, this.value)); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherAccessLevel withPublic(final boolean isPublic) { return ((this.isPublic == isPublic) ? this : new WitherAccessLevel(this.isNone, this.isPrivate, this.isPackage, this.isProtected, isPublic, this.value)); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherAccessLevel withValue(final boolean value) { return ((this.value == value) ? this : new WitherAccessLevel(this.isNone, this.isPrivate, this.isPackage, this.isProtected, this.isPublic, value)); } } lombok-1.16.18/test/transform/resource/after-ecj/WitherAlreadyExists.java000066400000000000000000000030721312655740700264570ustar00rootroot00000000000000class Wither1 { @lombok.experimental.Wither boolean foo; void withFoo(boolean foo) { } Wither1(boolean foo) { super(); } } class Wither2 { @lombok.experimental.Wither boolean foo; void withFoo(String foo) { } Wither2(boolean foo) { super(); } } class Wither3 { @lombok.experimental.Wither String foo; void withFoo(boolean foo) { } Wither3(String foo) { super(); } } class Wither4 { @lombok.experimental.Wither String foo; void withFoo(String foo) { } Wither4(String foo) { super(); } } class Wither5 { @lombok.experimental.Wither String foo; void withFoo() { } Wither5(String foo) { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Wither5 withFoo(final String foo) { return ((this.foo == foo) ? this : new Wither5(foo)); } } class Wither6 { @lombok.experimental.Wither String foo; void withFoo(String foo, int x) { } Wither6(String foo) { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Wither6 withFoo(final String foo) { return ((this.foo == foo) ? this : new Wither6(foo)); } } class Wither7 { @lombok.experimental.Wither String foo; void withFoo(String foo, Object... x) { } Wither7(String foo) { super(); } } class Wither8 { @lombok.experimental.Wither boolean isFoo; void withIsFoo(boolean foo) { } Wither8(boolean foo) { super(); } } class Wither9 { @lombok.experimental.Wither boolean isFoo; void withFoo(boolean foo) { } Wither9(boolean foo) { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/WitherAndAllArgsConstructor.java000066400000000000000000000021701312655740700301120ustar00rootroot00000000000000@lombok.AllArgsConstructor class WitherAndAllArgsConstructor { @lombok.experimental.Wither J test; @lombok.experimental.Wither java.util.List test2; final int x = 10; int y = 20; final int z; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherAndAllArgsConstructor withTest(final J test) { return ((this.test == test) ? this : new WitherAndAllArgsConstructor(test, this.test2, this.y, this.z)); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherAndAllArgsConstructor withTest2(final java.util.List test2) { return ((this.test2 == test2) ? this : new WitherAndAllArgsConstructor(this.test, test2, this.y, this.z)); } public @java.beans.ConstructorProperties({"test", "test2", "y", "z"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherAndAllArgsConstructor(final J test, final java.util.List test2, final int y, final int z) { super(); this.test = test; this.test2 = test2; this.y = y; this.z = z; } } lombok-1.16.18/test/transform/resource/after-ecj/WitherDeprecated.java000066400000000000000000000013061312655740700257340ustar00rootroot00000000000000import lombok.experimental.Wither; class WitherDeprecated { @Deprecated @Wither int annotation; @Wither int javadoc; WitherDeprecated(int annotation, int javadoc) { super(); } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherDeprecated withAnnotation(final int annotation) { return ((this.annotation == annotation) ? this : new WitherDeprecated(annotation, this.javadoc)); } public @java.lang.Deprecated @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherDeprecated withJavadoc(final int javadoc) { return ((this.javadoc == javadoc) ? this : new WitherDeprecated(this.annotation, javadoc)); } } lombok-1.16.18/test/transform/resource/after-ecj/WitherOnClass.java000066400000000000000000000046461312655740700252500ustar00rootroot00000000000000@lombok.experimental.Wither class WitherOnClass1 { @lombok.experimental.Wither(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; WitherOnClass1(boolean isNone, boolean isPublic) { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherOnClass1 withPublic(final boolean isPublic) { return ((this.isPublic == isPublic) ? this : new WitherOnClass1(this.isNone, isPublic)); } } @lombok.experimental.Wither(lombok.AccessLevel.PROTECTED) class WitherOnClass2 { @lombok.experimental.Wither(lombok.AccessLevel.NONE) boolean isNone; boolean isProtected; @lombok.experimental.Wither(lombok.AccessLevel.PACKAGE) boolean isPackage; WitherOnClass2(boolean isNone, boolean isProtected, boolean isPackage) { super(); } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherOnClass2 withPackage(final boolean isPackage) { return ((this.isPackage == isPackage) ? this : new WitherOnClass2(this.isNone, this.isProtected, isPackage)); } protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherOnClass2 withProtected(final boolean isProtected) { return ((this.isProtected == isProtected) ? this : new WitherOnClass2(this.isNone, isProtected, this.isPackage)); } } @lombok.experimental.Wither class WitherOnClass3 { String couldBeNull; @lombok.NonNull String nonNull; WitherOnClass3(String couldBeNull, String nonNull) { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherOnClass3 withCouldBeNull(final String couldBeNull) { return ((this.couldBeNull == couldBeNull) ? this : new WitherOnClass3(couldBeNull, this.nonNull)); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherOnClass3 withNonNull(final @lombok.NonNull String nonNull) { if ((nonNull == null)) { throw new java.lang.NullPointerException("nonNull"); } return ((this.nonNull == nonNull) ? this : new WitherOnClass3(this.couldBeNull, nonNull)); } } @lombok.experimental.Wither @lombok.experimental.Accessors(prefix = "f") class WitherOnClass4 { final int fX = 10; final int fY; WitherOnClass4(int y) { super(); this.fY = y; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherOnClass4 withY(final int fY) { return ((this.fY == fY) ? this : new WitherOnClass4(fY)); } } lombok-1.16.18/test/transform/resource/after-ecj/WitherOnStatic.java000066400000000000000000000002621312655740700254200ustar00rootroot00000000000000class WitherOnStatic { static @lombok.experimental.Wither boolean foo; static @lombok.experimental.Wither int bar; () { } WitherOnStatic() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/WitherPlain.java000066400000000000000000000011061312655740700247350ustar00rootroot00000000000000import lombok.experimental.Wither; class WitherPlain { @lombok.experimental.Wither int i; final @Wither int foo; WitherPlain(int i, int foo) { super(); this.i = i; this.foo = foo; } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherPlain withI(final int i) { return ((this.i == i) ? this : new WitherPlain(i, this.foo)); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherPlain withFoo(final int foo) { return ((this.foo == foo) ? this : new WitherPlain(this.i, foo)); } } lombok-1.16.18/test/transform/resource/after-ecj/WitherWithAbstract.java000066400000000000000000000004031312655740700262700ustar00rootroot00000000000000abstract class WitherWithAbstract { @lombok.experimental.Wither String foo; WitherWithAbstract() { super(); } public abstract @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherWithAbstract withFoo(final String foo); } lombok-1.16.18/test/transform/resource/after-ecj/WitherWithDollar.java000066400000000000000000000001511312655740700257420ustar00rootroot00000000000000class WitherWithDollar { @lombok.experimental.Wither int $i; WitherWithDollar() { super(); } } lombok-1.16.18/test/transform/resource/after-ecj/WitherWithGenerics.java000066400000000000000000000021621312655740700262700ustar00rootroot00000000000000class WitherWithGenerics { @lombok.experimental.Wither J test; @lombok.experimental.Wither java.util.List test2; @lombok.experimental.Wither java.util.List test3; int $i; public WitherWithGenerics(J test, java.util.List test2, java.util.List test3) { super(); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherWithGenerics withTest(final J test) { return ((this.test == test) ? this : new WitherWithGenerics(test, this.test2, this.test3)); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherWithGenerics withTest2(final java.util.List test2) { return ((this.test2 == test2) ? this : new WitherWithGenerics(this.test, test2, this.test3)); } public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WitherWithGenerics withTest3(final java.util.List test3) { return ((this.test3 == test3) ? this : new WitherWithGenerics(this.test, this.test2, test3)); } } lombok-1.16.18/test/transform/resource/before/000077500000000000000000000000001312655740700212505ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/before/Accessors.java000066400000000000000000000025321312655740700240420ustar00rootroot00000000000000class AccessorsFluent { @lombok.Getter @lombok.Setter @lombok.experimental.Accessors(fluent=true) private String fieldName = ""; } @lombok.experimental.Accessors(fluent=true) @lombok.Getter class AccessorsFluentOnClass { @lombok.Setter private String fieldName = ""; @lombok.experimental.Accessors private String otherFieldWithOverride = ""; } class AccessorsChain { @lombok.Setter @lombok.experimental.Accessors(chain=true) private boolean isRunning; } @lombok.experimental.Accessors(prefix="f") class AccessorsPrefix { @lombok.Setter private String fieldName; @lombok.Setter private String fActualField; } @lombok.experimental.Accessors(prefix={"f", ""}) class AccessorsPrefix2 { @lombok.Setter private String fieldName; @lombok.Setter private String fActualField; } @lombok.experimental.Accessors(prefix="f") @lombok.ToString @lombok.EqualsAndHashCode class AccessorsPrefix3 { private String fName; private String getName() { return fName; } } class AccessorsFluentGenerics { @lombok.Setter @lombok.experimental.Accessors(fluent=true) private String name; } class AccessorsFluentNoChaining { @lombok.Setter @lombok.experimental.Accessors(fluent=true,chain=false) private String name; } class AccessorsFluentStatic { @lombok.Setter @lombok.experimental.Accessors(fluent=true) private static String name; }lombok-1.16.18/test/transform/resource/before/AccessorsConfiguration.java000066400000000000000000000010031312655740700265620ustar00rootroot00000000000000//CONF: lombok.Accessors.prefix += m_ //CONF: lombok.Accessors.prefix += f //CONF: lombok.Accessors.chain = false class AccessorsConfiguration { @lombok.Getter @lombok.Setter @lombok.experimental.Accessors(fluent=true) private String m_FieldName = ""; } @lombok.experimental.Accessors(prefix = {}) class AccessorsConfiguration2 { @lombok.Setter private String m_FieldName = ""; } @lombok.experimental.Accessors(chain = true) class AccessorsConfiguration3 { @lombok.Setter private String fFieldName = ""; } lombok-1.16.18/test/transform/resource/before/BuilderChainAndFluent.java000066400000000000000000000001641312655740700262460ustar00rootroot00000000000000@lombok.experimental.Builder(fluent = false, chain = false) class BuilderChainAndFluent { private final int yes; } lombok-1.16.18/test/transform/resource/before/BuilderComplex.java000066400000000000000000000003651312655740700250350ustar00rootroot00000000000000import java.util.List; import lombok.experimental.Builder; class BuilderComplex { @Builder(buildMethodName = "execute") private static void testVoidWithGenerics(T number, int arg2, String arg3, BuilderComplex selfRef) {} } lombok-1.16.18/test/transform/resource/before/BuilderDefaults.java000066400000000000000000000003011312655740700251630ustar00rootroot00000000000000import lombok.Builder; import lombok.Value; @Value @Builder public class BuilderDefaults { @Builder.Default int x = 10; String name; @Builder.Default long z = System.currentTimeMillis(); } lombok-1.16.18/test/transform/resource/before/BuilderDefaultsWarnings.java000066400000000000000000000005571312655740700267110ustar00rootroot00000000000000import lombok.Builder; import lombok.Singular; @Builder public class BuilderDefaultsWarnings { long x = System.currentTimeMillis(); final int y = 5; @Builder.Default int z; @Builder.Default @Singular java.util.List items; } class NoBuilderButHasDefaults { @Builder.Default private final long z = 5; @Builder public NoBuilderButHasDefaults() { } } lombok-1.16.18/test/transform/resource/before/BuilderInstanceMethod.java000066400000000000000000000003041312655740700263240ustar00rootroot00000000000000import java.util.List; class BuilderInstanceMethod { @lombok.Builder public String create(int show, final int yes, List also, int $andMe) { return "" + show + yes + also + $andMe; } } lombok-1.16.18/test/transform/resource/before/BuilderInvalidUse.java000066400000000000000000000006671312655740700254760ustar00rootroot00000000000000//skip compare content @lombok.Builder class BuilderInvalidUse { private int something; @lombok.Getter @lombok.Setter @lombok.experimental.FieldDefaults(makeFinal = true) @lombok.experimental.Wither @lombok.Data @lombok.ToString @lombok.EqualsAndHashCode @lombok.AllArgsConstructor public static class BuilderInvalidUseBuilder { } } @lombok.Builder class AlsoInvalid { @lombok.Value public static class AlsoInvalidBuilder { } }lombok-1.16.18/test/transform/resource/before/BuilderSimple.java000066400000000000000000000002511312655740700246510ustar00rootroot00000000000000import java.util.List; @lombok.Builder class BuilderSimple { private final int noshow = 0; private final int yes; private List also; private int $butNotMe; } lombok-1.16.18/test/transform/resource/before/BuilderSingularGuavaListsSets.java000066400000000000000000000012211312655740700300440ustar00rootroot00000000000000import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableTable; import lombok.Singular; @lombok.Builder class BuilderSingularGuavaListsSets { @Singular private ImmutableList cards; @Singular private ImmutableCollection frogs; @SuppressWarnings("all") @Singular("rawSet") private ImmutableSet rawSet; @Singular private ImmutableSortedSet passes; @Singular private ImmutableTable users; } lombok-1.16.18/test/transform/resource/before/BuilderSingularGuavaMaps.java000066400000000000000000000006551312655740700270210ustar00rootroot00000000000000import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableSortedMap; import lombok.Singular; @lombok.Builder class BuilderSingularGuavaMaps { @Singular private ImmutableMap battleaxes; @Singular private ImmutableSortedMap vertices; @SuppressWarnings("all") @Singular("rawMap") private ImmutableBiMap rawMap; } lombok-1.16.18/test/transform/resource/before/BuilderSingularLists.java000066400000000000000000000004431312655740700262260ustar00rootroot00000000000000import java.util.List; import java.util.Collection; import lombok.Singular; @lombok.Builder class BuilderSingularLists { @Singular private List children; @Singular private Collection scarves; @SuppressWarnings("all") @Singular("rawList") private List rawList; } lombok-1.16.18/test/transform/resource/before/BuilderSingularMaps.java000066400000000000000000000006561312655740700260360ustar00rootroot00000000000000//FORMAT: javaLangAsFQN = skip //FORMAT: generated = skip //FORMAT: finalParams = skip import java.util.Map; import java.util.SortedMap; import lombok.Singular; @lombok.Builder class BuilderSingularMaps { @Singular private Map women; @Singular private SortedMap men; @SuppressWarnings("all") @Singular("rawMap") private Map rawMap; @Singular("stringMap") private Map stringMap; } lombok-1.16.18/test/transform/resource/before/BuilderSingularNoAuto.java000066400000000000000000000004101312655740700263270ustar00rootroot00000000000000//CONF: lombok.singular.auto = false import java.util.List; import lombok.Singular; @lombok.Builder class BuilderSingularNoAuto { @Singular private List things; @Singular("widget") private List widgets; @Singular private List items; } lombok-1.16.18/test/transform/resource/before/BuilderSingularRedirectToGuava.java000066400000000000000000000005451312655740700301630ustar00rootroot00000000000000//CONF: lombok.singular.useGuava = true import java.util.Set; import java.util.NavigableMap; import java.util.Collection; import lombok.Singular; @lombok.Builder class BuilderSingularRedirectToGuava { @Singular private Set dangerMice; @Singular private NavigableMap things; @Singular private Collection> doohickeys; } lombok-1.16.18/test/transform/resource/before/BuilderSingularSets.java000066400000000000000000000005261312655740700260500ustar00rootroot00000000000000import java.util.Set; import java.util.SortedSet; import lombok.Singular; @lombok.Builder class BuilderSingularSets { @Singular private Set dangerMice; @Singular private SortedSet octopodes; @SuppressWarnings("all") @Singular("rawSet") private Set rawSet; @Singular("stringSet") private Set stringSet; } lombok-1.16.18/test/transform/resource/before/BuilderSingularWithPrefixes.java000066400000000000000000000002561312655740700275530ustar00rootroot00000000000000import lombok.Singular; @lombok.Builder @lombok.experimental.Accessors(prefix = "_") class BuilderSingularWithPrefixes { @Singular private java.util.List _elems; } lombok-1.16.18/test/transform/resource/before/BuilderValueData.java000066400000000000000000000003011312655740700252620ustar00rootroot00000000000000import java.util.List; @lombok.Builder @lombok.Value class BuilderAndValue { private final int zero = 0; } @lombok.Builder @lombok.Data class BuilderAndData { private final int zero = 0; } lombok-1.16.18/test/transform/resource/before/BuilderWithAccessors.java000066400000000000000000000002761312655740700262100ustar00rootroot00000000000000@lombok.Builder @lombok.experimental.Accessors(prefix={"p", "_"}) class BuilderWithAccessors { private final int plower; private final int pUpper; private int _foo; private int __bar; } lombok-1.16.18/test/transform/resource/before/BuilderWithDeprecated.java000066400000000000000000000004661312655740700263240ustar00rootroot00000000000000import com.google.common.collect.ImmutableList; import lombok.Builder; import lombok.Singular; @Builder public class BuilderWithDeprecated { /** @deprecated */ String dep1; @Deprecated int dep2; @Singular @Deprecated java.util.List strings; @Singular @Deprecated ImmutableList numbers; } lombok-1.16.18/test/transform/resource/before/BuilderWithExistingBuilderClass.java000066400000000000000000000006011312655740700303420ustar00rootroot00000000000000import lombok.Builder; class BuilderWithExistingBuilderClass { @Builder public static BuilderWithExistingBuilderClass staticMethod(Z arg1, boolean arg2, String arg3) { return null; } public static class BuilderWithExistingBuilderClassBuilder { private Z arg1; public void arg2(boolean arg) { } } }lombok-1.16.18/test/transform/resource/before/BuilderWithRecursiveGenerics.java000066400000000000000000000004531312655740700277070ustar00rootroot00000000000000//issue #1298 import java.util.Set; import lombok.Builder; import lombok.Value; public class BuilderWithRecursiveGenerics { interface Inter> {} @Builder @Value public static class Test, Quz extends Inter> { Foo foo; Bar bar; } } lombok-1.16.18/test/transform/resource/before/BuilderWithToBuilder.java000066400000000000000000000017721312655740700261560ustar00rootroot00000000000000import java.util.List; import lombok.Builder; @Builder(toBuilder = true) @lombok.experimental.Accessors(prefix = "m") class BuilderWithToBuilder { private String mOne, mTwo; @Builder.ObtainVia(method = "rrr", isStatic = true) private T foo; @lombok.Singular private List bars; public static K rrr(BuilderWithToBuilder x) { return x.foo; } } @lombok.experimental.Accessors(prefix = "m") class ConstructorWithToBuilder { private String mOne, mTwo; private T foo; @lombok.Singular private List bars; @Builder(toBuilder = true) public ConstructorWithToBuilder(String mOne, @Builder.ObtainVia(field = "foo") T bar) { } } @lombok.experimental.Accessors(prefix = "m") class StaticWithToBuilder { private String mOne, mTwo; private T foo; private K bar; @lombok.Singular private List bars; @Builder(toBuilder = true) public static StaticWithToBuilder test(String mOne, @Builder.ObtainVia(field = "foo") Z bar) { return new StaticWithToBuilder(); } } lombok-1.16.18/test/transform/resource/before/BuilderWithTolerate.java000066400000000000000000000006221312655740700260350ustar00rootroot00000000000000import lombok.Builder; import lombok.experimental.Tolerate; @Builder public class BuilderWithTolerate { private final int value; public static void main(String[] args) { BuilderWithTolerate.builder().value("42").build(); } public static class BuilderWithTolerateBuilder { @Tolerate public BuilderWithTolerateBuilder value(String s) { return this.value(Integer.parseInt(s)); } } }lombok-1.16.18/test/transform/resource/before/ClassNamedAfterGetter.java000066400000000000000000000000621312655740700262600ustar00rootroot00000000000000class GetFoo { @lombok.Getter private int foo; } lombok-1.16.18/test/transform/resource/before/CleanupName.java000066400000000000000000000003501312655740700243010ustar00rootroot00000000000000class CleanupName { void test() { @lombok.Cleanup("toString") Object o = "Hello World!"; System.out.println(o); } void test2() { @lombok.Cleanup(value="toString") Object o = "Hello World too!"; System.out.println(o); } }lombok-1.16.18/test/transform/resource/before/CleanupPlain.java000066400000000000000000000004131312655740700244640ustar00rootroot00000000000000import lombok.Cleanup; import java.io.*; class CleanupPlain { void test() throws Exception { @lombok.Cleanup InputStream in = new FileInputStream("in"); @Cleanup OutputStream out = new FileOutputStream("out"); if (in.markSupported()) { out.flush(); } } }lombok-1.16.18/test/transform/resource/before/CommentsInterspersed.java000066400000000000000000000005301312655740700262660ustar00rootroot00000000000000import /* cmt */ lombok./* cmt2 */Getter /* cmt3 */ ; public /*bla */ class CommentsInterspersed { /** * javadoc for field */ private int x; private /* bla2 */ @Getter String test = "foo"; //$NON-NLS-1$ /** * Javadoc on method */ public native void gwtTest(); /*-{ javascript; }-*/ } //haha! //hahaha! //hahahaha! lombok-1.16.18/test/transform/resource/before/ConflictingStaticConstructorNames.java000066400000000000000000000001521312655740700307520ustar00rootroot00000000000000@lombok.Data(staticConstructor="of") @lombok.NoArgsConstructor class ConflictingStaticConstructorNames { }lombok-1.16.18/test/transform/resource/before/Constructors.java000066400000000000000000000023521312655740700246250ustar00rootroot00000000000000@lombok.RequiredArgsConstructor class RequiredArgsConstructor1 { final int x; String name; } @lombok.RequiredArgsConstructor(access=lombok.AccessLevel.PROTECTED) class RequiredArgsConstructorAccess { final int x; String name; } @lombok.RequiredArgsConstructor(staticName="staticname") class RequiredArgsConstructorStaticName { final int x; String name; } @lombok.RequiredArgsConstructor(onConstructor=@__(@Deprecated)) class RequiredArgsConstructorWithAnnotations { final int x; String name; } @lombok.AllArgsConstructor class AllArgsConstructor1 { final int x; String name; } @lombok.NoArgsConstructor class NoArgsConstructor1 { int x; String name; } @lombok.RequiredArgsConstructor(staticName="of") class RequiredArgsConstructorStaticNameGenerics { final T x; String name; } @lombok.RequiredArgsConstructor(staticName="of") class RequiredArgsConstructorStaticNameGenerics2 { final Class x; String name; } @lombok.AllArgsConstructor(access=lombok.AccessLevel.PACKAGE) class AllArgsConstructorPackageAccess { final String x; } @lombok.NoArgsConstructor(force = true) class NoArgsConstructor2 { final int x; final double y; final char c; final boolean b; final float f; final String s; byte z; } lombok-1.16.18/test/transform/resource/before/ConstructorsConfiguration.java000066400000000000000000000002121312655740700273460ustar00rootroot00000000000000//CONF: lombok.anyConstructor.suppressConstructorProperties = true @lombok.AllArgsConstructor class ConstructorsConfiguration { int x; } lombok-1.16.18/test/transform/resource/before/ConstructorsWithAccessors.java000066400000000000000000000002431312655740700273240ustar00rootroot00000000000000@lombok.AllArgsConstructor @lombok.experimental.Accessors(prefix={"p", "_"}) class ConstructorsWithAccessors { int plower; int pUpper; int _huh; int __huh2; } lombok-1.16.18/test/transform/resource/before/DataConfiguration.java000066400000000000000000000003411312655740700255120ustar00rootroot00000000000000//CONF: lombok.anyConstructor.suppressConstructorProperties = true //CONF: lombok.toString.doNotUseGetters = true //CONF: lombok.equalsAndHashCode.doNotUseGetters = true @lombok.Data class DataConfiguration { final int x; } lombok-1.16.18/test/transform/resource/before/DataExtended.java000066400000000000000000000001241312655740700244420ustar00rootroot00000000000000@lombok.Data @lombok.ToString(doNotUseGetters = true) class DataExtended { int x; }lombok-1.16.18/test/transform/resource/before/DataIgnore.java000066400000000000000000000000771312655740700241340ustar00rootroot00000000000000@lombok.Data class DataIgnore { final int x; String $name; } lombok-1.16.18/test/transform/resource/before/DataOnEnum.java000066400000000000000000000002101312655740700240770ustar00rootroot00000000000000@lombok.Getter @lombok.ToString @lombok.RequiredArgsConstructor public enum DataOnEnum { A("hello"); private final String someField; }lombok-1.16.18/test/transform/resource/before/DataOnLocalClass.java000066400000000000000000000004441312655740700252240ustar00rootroot00000000000000import lombok.Data; class DataOnLocalClass1 { public static void main(String[] args) { @Data class Local { final int x; String name; } } } class DataOnLocalClass2 { { @Data class Local { final int x; @Data class InnerLocal { @lombok.NonNull String name; } } } }lombok-1.16.18/test/transform/resource/before/DataPlain.java000066400000000000000000000005511312655740700237510ustar00rootroot00000000000000import lombok.Data; @lombok.Data class Data1 { final int x; String name; } @Data class Data2 { final int x; String name; } final @Data class Data3 { final int x; String name; } @Data @lombok.EqualsAndHashCode(callSuper=true) final class Data4 extends java.util.Timer { int x; Data4() { super(); } } @Data class Data5 { } @Data final class Data6 { } lombok-1.16.18/test/transform/resource/before/DataWithGetter.java000066400000000000000000000001401312655740700247660ustar00rootroot00000000000000@lombok.Data @lombok.Getter class DataWithGetter { private int x, y; private final String z; }lombok-1.16.18/test/transform/resource/before/DataWithGetterNone.java000066400000000000000000000001751312655740700256160ustar00rootroot00000000000000@lombok.Data @lombok.Getter(lombok.AccessLevel.NONE) class DataWithGetterNone { private int x, y; private final String z; }lombok-1.16.18/test/transform/resource/before/DelegateFlagUsage.java000066400000000000000000000003101312655740700253760ustar00rootroot00000000000000//conf: lombok.delegate.flagUsage = warning //skip compare content: We're just checking if the flagUsage key works. public class DelegateFlagUsage { @lombok.experimental.Delegate Runnable r = null; }lombok-1.16.18/test/transform/resource/before/DelegateOnGetter.java000066400000000000000000000005421312655740700252760ustar00rootroot00000000000000import lombok.Delegate; import lombok.Getter; class DelegateOnGetter { @Delegate @Getter(lazy=true) private final Bar bar = new Bar() { public void setList(java.util.ArrayList list) { } public int getInt() { return 42; } }; private interface Bar { void setList(java.util.ArrayList list); int getInt(); } }lombok-1.16.18/test/transform/resource/before/DelegateOnGetterNone.java000066400000000000000000000004531312655740700261170ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.experimental.Delegate; import lombok.Getter; @Getter class DelegateOnGetterNone { @Delegate @Getter(AccessLevel.NONE) private final Bar bar = null; private interface Bar { void setList(java.util.ArrayList list); int getInt(); } } lombok-1.16.18/test/transform/resource/before/DelegateOnMethods.java000066400000000000000000000003201312655740700254410ustar00rootroot00000000000000import lombok.experimental.Delegate; abstract class DelegateOnMethods { @Delegate public abstract Bar getBar(); public static interface Bar { void bar(java.util.ArrayList list); } }lombok-1.16.18/test/transform/resource/before/DelegateOnStatic.java000066400000000000000000000004561312655740700252770ustar00rootroot00000000000000//skip compare content import lombok.experimental.Delegate; import lombok.Getter; class DelegateOnStatic { @Delegate private static final java.lang.Runnable staticField = null; } class DelegateOnStaticMethod { @Delegate private static final java.lang.Runnable staticMethod() { return null; }; }lombok-1.16.18/test/transform/resource/before/DelegateRecursion.java000066400000000000000000000007301312655740700255170ustar00rootroot00000000000000//skip compare content: This test is to see if the 'delegate recursion is not supported' error pops up. import lombok.experimental.Delegate; class DelegateRecursionOuterMost { @Delegate private final DelegateRecursionCenter center = new DelegateRecursionCenter(); } class DelegateRecursionCenter { @Delegate private final DelegateRecursionInnerMost inner = new DelegateRecursionInnerMost(); } class DelegateRecursionInnerMost { public void innerMostMethod() { } } lombok-1.16.18/test/transform/resource/before/DelegateTypesAndExcludes.java000066400000000000000000000012111312655740700267650ustar00rootroot00000000000000import lombok.experimental.Delegate; class DelegatePlain { @Delegate(types = Bar.class) private final BarImpl bar = new BarImpl(); @Delegate(types = Foo.class, excludes = Bar.class) private final FooImpl foo = new FooImpl(); private static class FooImpl implements Foo { public void foo() { } public void bar(java.util.ArrayList list) { } } private static class BarImpl implements Bar { public void bar(java.util.ArrayList list) { } } private static interface Foo extends Bar { void foo(); } private static interface Bar { void bar(java.util.ArrayList list); } }lombok-1.16.18/test/transform/resource/before/DelegateWithDeprecated.java000066400000000000000000000003751312655740700264470ustar00rootroot00000000000000import lombok.experimental.Delegate; class DelegateWithDeprecated { @Delegate private Bar bar; private interface Bar { @Deprecated void deprecatedAnnotation(); /** * @deprecated */ void deprecatedComment(); void notDeprecated(); } }lombok-1.16.18/test/transform/resource/before/DelegateWithVarargs.java000066400000000000000000000004451312655740700260120ustar00rootroot00000000000000import lombok.experimental.Delegate; class DelegateWithVarargs { @Delegate private Bar bar; private interface Bar { void justOneParameter(int... varargs); void multipleParameters(String first, int... varargs); void array(int[] array); void arrayVarargs(int[]... arrayVarargs); } }lombok-1.16.18/test/transform/resource/before/EncodingUsAscii.java000066400000000000000000000001501312655740700251160ustar00rootroot00000000000000//ENCODING: US-ASCII @lombok.ToString class EncodingUsAscii { String foo\u0e51\u0e51 = "\u000e \10 "; }lombok-1.16.18/test/transform/resource/before/EncodingUtf8.java000066400000000000000000000001371312655740700244110ustar00rootroot00000000000000//ENCODING: UTF-8 @lombok.ToString class EncodingUtf8 { String foo\u0e51๑ = "\u000e \10 "; }lombok-1.16.18/test/transform/resource/before/EqualsAndHashCode.java000066400000000000000000000006511312655740700253710ustar00rootroot00000000000000@lombok.EqualsAndHashCode class EqualsAndHashCode { int x; boolean[] y; Object[] z; String a; String b; } @lombok.EqualsAndHashCode final class EqualsAndHashCode2 { int x; long y; float f; double d; boolean b; } @lombok.EqualsAndHashCode(callSuper=false) final class EqualsAndHashCode3 extends EqualsAndHashCode { } @lombok.EqualsAndHashCode(callSuper=true) class EqualsAndHashCode4 extends EqualsAndHashCode { }lombok-1.16.18/test/transform/resource/before/EqualsAndHashCodeConfigKeys1.java000066400000000000000000000003561312655740700274360ustar00rootroot00000000000000//CONF: lombok.equalsAndHashCode.callSuper = skip @lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys1Parent { } @lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys1 extends EqualsAndHashCodeConfigKeys1Parent { int x; } lombok-1.16.18/test/transform/resource/before/EqualsAndHashCodeConfigKeys2.java000066400000000000000000000005031312655740700274310ustar00rootroot00000000000000//CONF: lombok.equalsAndHashCode.callSuper = call @lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys2Object extends Object { } @lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys2Parent { } @lombok.EqualsAndHashCode class EqualsAndHashCodeConfigKeys2 extends EqualsAndHashCodeConfigKeys2Parent { int x; } lombok-1.16.18/test/transform/resource/before/EqualsAndHashCodeNestedShadow.java000066400000000000000000000005601312655740700277010ustar00rootroot00000000000000interface EqualsAndHashCodeNestedShadow { interface Foo { } class Bar { @lombok.EqualsAndHashCode(callSuper=false) public static class Foo extends Bar implements EqualsAndHashCodeNestedShadow.Foo { } } class Baz { @lombok.EqualsAndHashCode(callSuper=false) public static class Foo extends Bar implements EqualsAndHashCodeNestedShadow.Foo { } } }lombok-1.16.18/test/transform/resource/before/EqualsAndHashCodeOfExclude.java000066400000000000000000000002721312655740700271670ustar00rootroot00000000000000@lombok.EqualsAndHashCode(of={"x"}) final class EqualsAndHashCodeOf { int x; int y; } @lombok.EqualsAndHashCode(exclude={"y"}) final class EqualsAndHashCodeExclude { int x; int y; }lombok-1.16.18/test/transform/resource/before/EqualsAndHashCodeWithExistingMethods.java000066400000000000000000000007441312655740700312670ustar00rootroot00000000000000@lombok.EqualsAndHashCode class EqualsAndHashCodeWithExistingMethods { int x; public int hashCode() { return 42; } } @lombok.EqualsAndHashCode final class EqualsAndHashCodeWithExistingMethods2 { int x; public boolean equals(Object other) { return false; } } @lombok.EqualsAndHashCode(callSuper=true) final class EqualsAndHashCodeWithExistingMethods3 extends EqualsAndHashCodeWithExistingMethods { int x; private boolean canEqual(Object other) { return true; } }lombok-1.16.18/test/transform/resource/before/EqualsAndHashCodeWithOnParam.java000066400000000000000000000002541312655740700275020ustar00rootroot00000000000000@interface Nullable { } @lombok.EqualsAndHashCode(onParam=@__({@Nullable})) class EqualsAndHashCodeWithOnParam { int x; boolean[] y; Object[] z; String a; String b; }lombok-1.16.18/test/transform/resource/before/EqualsAndHashCodeWithSomeExistingMethods.java000066400000000000000000000013171312655740700321100ustar00rootroot00000000000000//CONF: lombok.addGeneratedAnnotation = false import lombok.*; import static lombok.AccessLevel.NONE; @Data @Getter(NONE) @Setter(NONE) class EqualsAndHashCodeWithSomeExistingMethods { int x; public int hashCode() { return 42; } } @Data @Getter(NONE) @Setter(NONE) class EqualsAndHashCodeWithSomeExistingMethods2 { int x; protected boolean canEqual(Object other) { return false; } } @Data @Getter(NONE) @Setter(NONE) class EqualsAndHashCodeWithAllExistingMethods { int x; public int hashCode() { return 42; } public boolean equals(Object other) { return false; } } @Data @Getter(AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) class EqualsAndHashCodeWithNoExistingMethods { int x; } lombok-1.16.18/test/transform/resource/before/ExtensionMethodPlain.java000066400000000000000000000011361312655740700262150ustar00rootroot00000000000000import lombok.experimental.ExtensionMethod; @ExtensionMethod({java.util.Arrays.class, ExtensionMethodPlain.Extensions.class}) class ExtensionMethodPlain { public String test() { int[] intArray = {5, 3, 8, 2}; intArray.sort(); String iAmNull = null; return iAmNull.or("hELlO, WORlD!".toTitleCase()); } static class Extensions { public static T or(T obj, T ifNull) { return obj != null ? obj : ifNull; } public static String toTitleCase(String in) { if (in.isEmpty()) return in; return "" + Character.toTitleCase(in.charAt(0)) + in.substring(1).toLowerCase(); } } } lombok-1.16.18/test/transform/resource/before/FieldDefaults.java000066400000000000000000000005541312655740700246320ustar00rootroot00000000000000@lombok.experimental.FieldDefaults(makeFinal = true) class FieldDefaults1 { static int STATIC = 3; int x; @lombok.experimental.NonFinal int y; FieldDefaults1(int x) { this.x = x; } } @lombok.experimental.FieldDefaults(level = lombok.AccessLevel.PRIVATE) class FieldDefaults2 { static int STATIC = 3; @lombok.experimental.PackagePrivate int x; int y; }lombok-1.16.18/test/transform/resource/before/FieldDefaultsNoop.java000066400000000000000000000000761312655740700254650ustar00rootroot00000000000000@lombok.experimental.FieldDefaults class FieldDefaultsNoop { }lombok-1.16.18/test/transform/resource/before/FieldDefaultsViaConfig.java000066400000000000000000000006211312655740700264130ustar00rootroot00000000000000//CONF: lombok.fieldDefaults.defaultFinal = true //CONF: lombok.fieldDefaults.defaultPrivate = true class FieldDefaultsViaConfig1 { int x; @lombok.experimental.NonFinal int y; FieldDefaultsViaConfig1(int x) { this.x = x; } } @lombok.experimental.FieldDefaults(level = lombok.AccessLevel.PROTECTED) class FieldDefaultsViaConfig2 { @lombok.experimental.PackagePrivate int x = 2; int y = 0; } lombok-1.16.18/test/transform/resource/before/FieldDefaultsViaConfigAndRequiredArgsConstructor.java000066400000000000000000000002241312655740700336210ustar00rootroot00000000000000//CONF: lombok.fieldDefaults.defaultFinal = true @lombok.RequiredArgsConstructor class FieldDefaultsViaConfigAndRequiredArgsConstructor { int x; } lombok-1.16.18/test/transform/resource/before/FlagUsages.java000066400000000000000000000003721312655740700241360ustar00rootroot00000000000000//skip compare content //CONF: lombok.Getter.flagUsage = WARNING //CONF: lombok.experimental.flagUsage = ERROR public class FlagUsages { @lombok.Getter String x; @lombok.experimental.Wither String z; public FlagUsages(String x, String y) { } } lombok-1.16.18/test/transform/resource/before/GenerateSuppressFBWarnings.java000066400000000000000000000002051312655740700273300ustar00rootroot00000000000000//VERSION 7: //CONF: lombok.extern.findbugs.addSuppressFBWarnings = true class GenerateSuppressFBWarnings { @lombok.Getter int y; } lombok-1.16.18/test/transform/resource/before/GeneratedJavaxOff.java000066400000000000000000000001471312655740700254400ustar00rootroot00000000000000//CONF: lombok.addJavaxGeneratedAnnotation = false class GeneratedJavaxOff { @lombok.Getter int x; } lombok-1.16.18/test/transform/resource/before/GeneratedJavaxOnLombokOn.java000066400000000000000000000002401312655740700267350ustar00rootroot00000000000000//CONF: lombok.addJavaxGeneratedAnnotation = true //CONF: lombok.addLombokGeneratedAnnotation = true class GeneratedJavaxOnLombokOn { @lombok.Getter int x; } lombok-1.16.18/test/transform/resource/before/GeneratedOff.java000066400000000000000000000001351312655740700244430ustar00rootroot00000000000000//CONF: lombok.addGeneratedAnnotation = false class GeneratedOff { @lombok.Getter int x; } lombok-1.16.18/test/transform/resource/before/GeneratedOffJavaxOn.java000066400000000000000000000002261312655740700257330ustar00rootroot00000000000000//CONF: lombok.addGeneratedAnnotation = false //CONF: lombok.addJavaxGeneratedAnnotation = true class GeneratedOffJavaxOn { @lombok.Getter int x; } lombok-1.16.18/test/transform/resource/before/GeneratedOffLombokOn.java000066400000000000000000000002301312655740700261000ustar00rootroot00000000000000//CONF: lombok.addGeneratedAnnotation = false //CONF: lombok.addLombokGeneratedAnnotation = true class GeneratedOffLombokOn { @lombok.Getter int x; } lombok-1.16.18/test/transform/resource/before/GetterAccessLevel.java000066400000000000000000000013431312655740700254600ustar00rootroot00000000000000class GetterAccessLevel { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; @lombok.Getter(lombok.AccessLevel.PRIVATE) boolean isPrivate; @lombok.Getter(lombok.AccessLevel.PACKAGE) boolean isPackage; @lombok.Getter(lombok.AccessLevel.PROTECTED) boolean isProtected; @lombok.Getter(lombok.AccessLevel.PUBLIC) boolean isPublic; @lombok.Getter(lombok.AccessLevel.NONE) String noneString; @lombok.Getter(lombok.AccessLevel.PRIVATE) String privateString; @lombok.Getter(lombok.AccessLevel.PACKAGE) String packageString; @lombok.Getter(lombok.AccessLevel.PROTECTED) String protectedString; @lombok.Getter(lombok.AccessLevel.PUBLIC) String publicString; @lombok.Getter(value=lombok.AccessLevel.PUBLIC) String value; } lombok-1.16.18/test/transform/resource/before/GetterAlreadyExists.java000066400000000000000000000030541312655740700260510ustar00rootroot00000000000000class Getter1 { @lombok.Getter boolean foo; boolean hasFoo() { return true; } } class Getter2 { @lombok.Getter boolean foo; boolean isFoo() { return true; } } class Getter3 { @lombok.Getter boolean foo; boolean getFoo() { return true; } } class Getter4 { @lombok.Getter String foo; String hasFoo() { return null; } } class Getter5 { @lombok.Getter String foo; String isFoo() { return null; } } class Getter6 { @lombok.Getter String foo; String getFoo() { return null; } } class Getter7 { @lombok.Getter String foo; boolean hasFoo() { return false; } } class Getter8 { @lombok.Getter String foo; boolean isFoo() { return false; } } class Getter9 { @lombok.Getter String foo; boolean getFoo() { return false; } } class Getter10 { @lombok.Getter boolean foo; static boolean hasFoo() { return false; } } class Getter11 { @lombok.Getter boolean foo; static boolean isFoo() { return false; } } class Getter12 { @lombok.Getter boolean foo; static boolean getFoo() { return false; } } class Getter13 { @lombok.Getter String foo; static boolean hasFoo() { return false; } } class Getter14 { @lombok.Getter String foo; static boolean isFoo() { return false; } } class Getter15 { @lombok.Getter String foo; static boolean getFoo() { return false; } } class Getter16 { @lombok.Getter String foo; static String hasFoo() { return ""; } } class Getter17 { @lombok.Getter String foo; static String isFoo() { return ""; } } class Getter18 { @lombok.Getter String foo; static String getFoo() { return ""; } }lombok-1.16.18/test/transform/resource/before/GetterBoolean.java000066400000000000000000000004371312655740700246510ustar00rootroot00000000000000class Getter { @lombok.Getter boolean foo; @lombok.Getter boolean isBar; @lombok.Getter boolean hasBaz; } class MoreGetter { @lombok.Getter boolean foo; boolean hasFoo() { return true; } } class YetMoreGetter { @lombok.Getter boolean foo; boolean getFoo() { return true; } }lombok-1.16.18/test/transform/resource/before/GetterDeprecated.java000066400000000000000000000002121312655740700253210ustar00rootroot00000000000000import lombok.Getter; class GetterDeprecated { @Deprecated @Getter int annotation; /** * @deprecated */ @Getter int javadoc; }lombok-1.16.18/test/transform/resource/before/GetterEnum.java000066400000000000000000000003671312655740700242000ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(access=AccessLevel.PRIVATE) enum GetterEnum { ONE(1, "One") ; @Getter private final int id; @Getter private final String name; } lombok-1.16.18/test/transform/resource/before/GetterLazy.java000066400000000000000000000002051312655740700242020ustar00rootroot00000000000000class GetterLazy { static class ValueType { } @lombok.Getter(lazy=true) private final ValueType fieldName = new ValueType(); } lombok-1.16.18/test/transform/resource/before/GetterLazyBoolean.java000066400000000000000000000005371312655740700255120ustar00rootroot00000000000000@lombok.EqualsAndHashCode(of="booleanValue") @lombok.ToString(of="booleanValue") class GetterLazyBoolean { @lombok.Getter(lazy=true) private final boolean booleanValue = calculateBoolean(); @lombok.Getter(lazy=true) private final boolean otherBooleanValue = !calculateBoolean(); private static boolean calculateBoolean() { return true; } } lombok-1.16.18/test/transform/resource/before/GetterLazyEahcToString.java000066400000000000000000000003541312655740700264620ustar00rootroot00000000000000@lombok.EqualsAndHashCode(doNotUseGetters = true) @lombok.ToString(doNotUseGetters = true) class GetterLazyEahcToString { @lombok.Getter(lazy=true) private final String value = ""; @lombok.Getter private final String value2 = ""; } lombok-1.16.18/test/transform/resource/before/GetterLazyInvalid.java000066400000000000000000000012301312655740700255100ustar00rootroot00000000000000class GetterLazyInvalidNotFinal { @lombok.Getter(lazy=true) private String fieldName = ""; } class GetterLazyInvalidNotPrivate { @lombok.Getter(lazy=true) final String fieldName = ""; } class GetterLazyInvalidNotPrivateFinal { @lombok.Getter(lazy=true) String fieldName = ""; } class GetterLazyInvalidNone { @lombok.Getter(lazy=true, value=lombok.AccessLevel.NONE) private final String fieldName = ""; } @lombok.Getter(lazy = true) class GetterLazyInvalidClass { private final String fieldName = ""; } class GetterLazyInvalidNoInit { @lombok.Getter(lazy = true) private final String fieldName; GetterLazyInvalidNoInit() { this.fieldName = "foo"; } }lombok-1.16.18/test/transform/resource/before/GetterLazyNative.java000066400000000000000000000012001312655740700253450ustar00rootroot00000000000000class GetterLazyNative { @lombok.Getter(lazy=true) private final boolean booleanField = true; @lombok.Getter(lazy=true) private final byte byteField = 1; @lombok.Getter(lazy=true) private final short shortField = 1; @lombok.Getter(lazy=true) private final int intField = 1; @lombok.Getter(lazy=true) private final long longField = 1; @lombok.Getter(lazy=true) private final float floatField = 1.0f; @lombok.Getter(lazy=true) private final double doubleField = 1.0; @lombok.Getter(lazy=true) private final char charField = '1'; @lombok.Getter(lazy=true) private final int[] intArrayField = new int[] {1}; } lombok-1.16.18/test/transform/resource/before/GetterLazyTransient.java000066400000000000000000000003731312655740700261000ustar00rootroot00000000000000class GetterLazyTransient { @lombok.Getter(lazy=true) private final int nonTransientField = 1; @lombok.Getter(lazy=true) private final transient int transientField = 2; @lombok.Getter private final transient int nonLazyTransientField = 3; } lombok-1.16.18/test/transform/resource/before/GetterNone.java000066400000000000000000000001721312655740700241650ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.Getter; @Getter class GetterNone { int i; @Getter(AccessLevel.NONE) int foo; }lombok-1.16.18/test/transform/resource/before/GetterOnClass.java000066400000000000000000000015341312655740700246330ustar00rootroot00000000000000@lombok.Getter class GetterOnClass1 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; } @lombok.Getter(lombok.AccessLevel.PROTECTED) class GetterOnClass2 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isProtected; @lombok.Getter(lombok.AccessLevel.PACKAGE) boolean isPackage; } @lombok.Getter(lombok.AccessLevel.PACKAGE) class GetterOnClass3 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isPackage; } @lombok.Getter(lombok.AccessLevel.PRIVATE) class GetterOnClass4 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isPrivate; } @lombok.Getter(lombok.AccessLevel.PUBLIC) class GetterOnClass5 { @lombok.Getter(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; } @lombok.Getter class GetterOnClass6 { String couldBeNull; @lombok.NonNull String nonNull; }lombok-1.16.18/test/transform/resource/before/GetterOnMethod.java000066400000000000000000000002611312655740700250020ustar00rootroot00000000000000class GetterOnMethod { @lombok.Getter(onMethod=@__(@Deprecated)) int i; @lombok.Getter(onMethod=@__({@java.lang.Deprecated, @Test})) int j, k; public @interface Test { } } lombok-1.16.18/test/transform/resource/before/GetterOnMethodErrors.java000066400000000000000000000002161312655740700261770ustar00rootroot00000000000000class PlaceFillerToMakeSurePositionIsRelevant { } @lombok.Getter(onMethod=@__(@Deprecated)) class GetterOnMethodErrors { private int test; } lombok-1.16.18/test/transform/resource/before/GetterOnMethodErrors2.java000066400000000000000000000010641312655740700262630ustar00rootroot00000000000000//version 8: class GetterOnMethodErrors2 { @lombok.Getter(onMethod=@_A_(@Deprecated)) private int bad1; @lombok.Getter(onMethod=@__(5)) private int bad2; @lombok.Getter(onMethod=@__({@Deprecated, 5})) private int bad3; @lombok.Getter(onMethod=@$(bar=@Deprecated)) private int bad4; @lombok.Getter(onMethod=@__) private int good1; @lombok.Getter(onMethod=@X()) private int good2; @lombok.Getter(onMethod=@__(value=@Deprecated)) private int good3; @lombok.Getter(onMethod=@xXx$$(value={@Deprecated, @Test})) private int good4; public @interface Test { } } lombok-1.16.18/test/transform/resource/before/GetterOnStatic.java000066400000000000000000000001251312655740700250100ustar00rootroot00000000000000class Getter { @lombok.Getter static boolean foo; @lombok.Getter static int bar; } lombok-1.16.18/test/transform/resource/before/GetterPlain.java000066400000000000000000000001241312655740700243260ustar00rootroot00000000000000import lombok.Getter; class GetterPlain { @lombok.Getter int i; @Getter int foo; }lombok-1.16.18/test/transform/resource/before/GetterSetterJavadoc.java000066400000000000000000000022271312655740700260270ustar00rootroot00000000000000@lombok.Data class GetterSetterJavadoc1 { /** * Some text * * @param fieldName Hello, World1 * --- GETTER --- * Getter section * * @return Sky is blue1 */ private int fieldName; } class GetterSetterJavadoc2 { /** * Some text * * @param fieldName Hello, World2 * @return Sky is blue2 */ @lombok.Getter @lombok.Setter private int fieldName; } class GetterSetterJavadoc3 { /** * Some text * * **SETTER** * Setter section * @param fieldName Hello, World3 * **GETTER** * Getter section * @return Sky is blue3 */ @lombok.Getter @lombok.Setter private int fieldName; } @lombok.experimental.Accessors(chain = true, fluent = true) class GetterSetterJavadoc4 { /** * Some text * * @param fieldName Hello, World4 * @return Sky is blue4 */ @lombok.Getter @lombok.Setter private int fieldName; } @lombok.experimental.Accessors(chain = true, fluent = true) class GetterSetterJavadoc5 { /** * Some text * * **SETTER** * Setter section * @param fieldName Hello, World5 * @return Sky is blue5 * **GETTER** * Getter section * @return Sky is blue5 */ @lombok.Getter @lombok.Setter private int fieldName; } lombok-1.16.18/test/transform/resource/before/GetterWithDollar.java000066400000000000000000000002001312655740700253270ustar00rootroot00000000000000class GetterWithDollar1 { @lombok.Getter int $i; } class GetterWithDollar2 { @lombok.Getter int $i; @lombok.Getter int i; } lombok-1.16.18/test/transform/resource/before/Helper.java000066400000000000000000000004441312655740700233340ustar00rootroot00000000000000import lombok.experimental.Helper; class HelperTest { { final int z = 5; if (Boolean.TRUE) { @Helper class H1 { void foo(int x) { System.out.println("Hello, " + (x + z)); } } foo(10); @Helper class H2 { void bar() { foo(12); } } } } }lombok-1.16.18/test/transform/resource/before/InjectField.java000066400000000000000000000014301312655740700242710ustar00rootroot00000000000000import java.util.logging.Level; import lombok.extern.java.Log; import lombok.Synchronized; @Log enum InjectField1 { A, B; private static final String LOG_MESSAGE = "static initializer"; private String fieldA; static { log.log(Level.FINE, LOG_MESSAGE); } private String fieldB; @Synchronized void generateLockField() { System.out.println("lock field"); } @Synchronized static void generateStaticLockField() { System.out.println("static lock field"); } } @Log class InjectField2 { private static final String LOG_MESSAGE = "static initializer"; static { log.log(Level.FINE, LOG_MESSAGE); } @Synchronized void generateLockField() { System.out.println("lock field"); } } @Log class InjectField3 { static { log.log(Level.FINE, "static initializer"); } }lombok-1.16.18/test/transform/resource/before/JavadocGenerally.java000066400000000000000000000004521312655740700253260ustar00rootroot00000000000000// unchanged /** * Doc on package */ package testPackage; /** Weird doc */ /** * Doc on class */ class JavadocGenerally { /** * Doc on field */ private int someField; /** * Doc on method */ public void test() { } /** * Doc on inner */ public interface TestingInner { } } lombok-1.16.18/test/transform/resource/before/LoggerCommons.java000066400000000000000000000003541312655740700246700ustar00rootroot00000000000000import lombok.extern.apachecommons.CommonsLog; @lombok.extern.apachecommons.CommonsLog class LoggerCommons { } @CommonsLog class LoggerCommonsWithImport { } @CommonsLog(topic="DifferentName") class LoggerCommonsWithDifferentName { } lombok-1.16.18/test/transform/resource/before/LoggerConfig.java000066400000000000000000000002071312655740700244570ustar00rootroot00000000000000//CONF: lombok.log.fieldName = myLogger //CONF: lombok.log.fieldIsStatic = false @lombok.extern.slf4j.Slf4j class LoggerWithConfig { } lombok-1.16.18/test/transform/resource/before/LoggerJBossLog.java000066400000000000000000000005011312655740700247310ustar00rootroot00000000000000import lombok.extern.jbosslog.JBossLog; @lombok.extern.jbosslog.JBossLog class LoggerJBossLog { } @JBossLog class LoggerJBossLogWithImport { } class LoggerJBossLogOuter { @lombok.extern.jbosslog.JBossLog static class Inner { } } @JBossLog(topic="DifferentLogger") class LoggerJBossLogWithDifferentLoggerName { }lombok-1.16.18/test/transform/resource/before/LoggerJul.java000066400000000000000000000002611312655740700240040ustar00rootroot00000000000000import lombok.extern.java.Log; @lombok.extern.java.Log class LoggerJul { } @Log class LoggerJulWithImport { } @Log(topic="DifferentName") class LoggerJulWithDifferentName { }lombok-1.16.18/test/transform/resource/before/LoggerLog4j.java000066400000000000000000000003011312655740700242240ustar00rootroot00000000000000import lombok.extern.log4j.Log4j; @lombok.extern.log4j.Log4j class LoggerLog4j { } @Log4j class LoggerLog4jWithImport { } @Log4j(topic="DifferentName") class LoggerLog4jWithDifferentName { }lombok-1.16.18/test/transform/resource/before/LoggerLog4j2.java000066400000000000000000000003101312655740700243060ustar00rootroot00000000000000import lombok.extern.log4j.Log4j2; @lombok.extern.log4j.Log4j2 class LoggerLog4j2 { } @Log4j2 class LoggerLog4j2WithImport { } @Log4j2(topic="DifferentName") class LoggerLog4j2WithDifferentName { }lombok-1.16.18/test/transform/resource/before/LoggerSlf4j.java000066400000000000000000000004351312655740700242370ustar00rootroot00000000000000import lombok.extern.slf4j.Slf4j; @lombok.extern.slf4j.Slf4j class LoggerSlf4j { } @Slf4j class LoggerSlf4jWithImport { } class LoggerSlf4jOuter { @lombok.extern.slf4j.Slf4j static class Inner { } } @Slf4j(topic="DifferentLogger") class LoggerSlf4jWithDifferentLoggerName { }lombok-1.16.18/test/transform/resource/before/LoggerSlf4jAlreadyExists.java000066400000000000000000000001071312655740700267350ustar00rootroot00000000000000@lombok.extern.slf4j.Slf4j class LoggerSlf4jAlreadyExists { int log; }lombok-1.16.18/test/transform/resource/before/LoggerSlf4jOnNonType.java000066400000000000000000000001431312655740700260450ustar00rootroot00000000000000// skip-compare-content class LoggerSlf4jOnNonType { @lombok.extern.slf4j.Slf4j void foo() { } }lombok-1.16.18/test/transform/resource/before/LoggerSlf4jTypes.java000066400000000000000000000005451312655740700252660ustar00rootroot00000000000000@lombok.extern.slf4j.Slf4j interface LoggerSlf4jTypesInterface { } @lombok.extern.slf4j.Slf4j @interface LoggerSlf4jTypesAnnotation { } @lombok.extern.slf4j.Slf4j enum LoggerSlf4jTypesEnum { } @lombok.extern.slf4j.Slf4j enum LoggerSlf4jTypesEnumWithElement { FOO; } interface LoggerSlf4jTypesInterfaceOuter { @lombok.extern.slf4j.Slf4j class Inner { } }lombok-1.16.18/test/transform/resource/before/LoggerSlf4jWithPackage.java000066400000000000000000000002461312655740700263470ustar00rootroot00000000000000package before; @lombok.extern.slf4j.Slf4j class LoggerSlf4jWithPackage { } class LoggerSlf4jWithPackageOuter { @lombok.extern.slf4j.Slf4j static class Inner { } }lombok-1.16.18/test/transform/resource/before/LoggerXSlf4j.java000066400000000000000000000003101312655740700243570ustar00rootroot00000000000000import lombok.extern.slf4j.XSlf4j; @lombok.extern.slf4j.XSlf4j class LoggerXSlf4j { } @XSlf4j class LoggerXSlf4jWithImport { } @XSlf4j(topic="DifferentName") class LoggerXSlf4jWithDifferentName { }lombok-1.16.18/test/transform/resource/before/MixGetterVal.java000066400000000000000000000002741312655740700244710ustar00rootroot00000000000000import lombok.Getter; import lombok.val; class MixGetterVal { @Getter private int x; public void m(int z) {} public void test() { val y = x; m(y); val a = getX(); m(a); } } lombok-1.16.18/test/transform/resource/before/MultiFieldGetter.java000066400000000000000000000003031312655740700253200ustar00rootroot00000000000000import lombok.Getter; import lombok.AccessLevel; class MultiFieldGetter { @Getter(AccessLevel.PROTECTED) int x, y; } @Getter class MultiFieldGetter2 { @Getter(AccessLevel.PACKAGE) int x, y; }lombok-1.16.18/test/transform/resource/before/NoArgsConstructorForce.java000066400000000000000000000003231312655740700265270ustar00rootroot00000000000000import lombok.NoArgsConstructor; @NoArgsConstructor(force = true) public class NoArgsConstructorForce { private final int[] i; private final Object[] o; private final java.util.List[] fullQualifiedList; }lombok-1.16.18/test/transform/resource/before/NonNullOnParameter.java000066400000000000000000000015351312655740700256420ustar00rootroot00000000000000class NonNullOnParameter extends Thread { NonNullOnParameter(@lombok.NonNull String arg) { this(arg, ""); } NonNullOnParameter(@lombok.NonNull String arg, @lombok.NonNull String arg2) { super(arg); if (arg == null) throw new NullPointerException(); } public void test2(@lombok.NonNull String arg, @lombok.NonNull String arg2, @lombok.NonNull String arg3) { if (arg2 == null) { throw new NullPointerException("arg2"); } if (arg == null) System.out.println("Hello"); } public void test3(@lombok.NonNull String arg) { if (arg != null) throw new IllegalStateException(); } public void test(@lombok.NonNull String stringArg, @lombok.NonNull String arg2, @lombok.NonNull int primitiveArg) { } public void test(@lombok.NonNull String arg) { System.out.println("Hey"); if (arg == null) throw new NullPointerException(); } }lombok-1.16.18/test/transform/resource/before/NonNullOnParameterAbstract.java000066400000000000000000000002701312655740700273210ustar00rootroot00000000000000abstract class NonNullOnParameterAbstract { public void test(@lombok.NonNull String arg) { System.out.println("Hey"); } public abstract void test2(@lombok.NonNull String arg); }lombok-1.16.18/test/transform/resource/before/NonNullOnParameterOfDefaultMethod.java000066400000000000000000000002661312655740700305750ustar00rootroot00000000000000// version 8: interface NonNullOnParameterOfDefaultMethod { void test(@lombok.NonNull String arg); default void test2(@lombok.NonNull String arg) { System.out.println(arg); } } lombok-1.16.18/test/transform/resource/before/NonNullPlain.java000066400000000000000000000005461312655740700244710ustar00rootroot00000000000000import java.lang.annotation.*; @lombok.RequiredArgsConstructor @lombok.Getter @lombok.Setter class NonNullPlain { @lombok.NonNull int i; @lombok.NonNull String s; @NotNull Object o; @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) @Retention(RetentionPolicy.CLASS) public @interface NotNull {} }lombok-1.16.18/test/transform/resource/before/NonNullWithAlternateException.java000066400000000000000000000003721312655740700300550ustar00rootroot00000000000000//CONF: lombok.nonNull.exceptionType = IllegalArgumentException public class NonNullWithAlternateException { @lombok.NonNull @lombok.Setter private String test; public void testMethod(@lombok.NonNull String arg) { System.out.println(arg); } } lombok-1.16.18/test/transform/resource/before/NonNullWithSneakyThrows.java000066400000000000000000000001741312655740700267200ustar00rootroot00000000000000class NonNullWithSneakyThrows { @lombok.SneakyThrows void test(@lombok.NonNull String in) { System.out.println(in); } } lombok-1.16.18/test/transform/resource/before/OnXJava7Style.java000066400000000000000000000006461312655740700245370ustar00rootroot00000000000000//version :7 public class OnXJava7Style { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } @lombok.Getter(onMethod=@__(@Foo)) String a; @lombok.Setter(onMethod=@__(@Foo())) String b; @lombok.Setter(onParam=@__(@Foo("a"))) String c; @lombok.Setter(onParam=@__(@Bar(stuff="b"))) String d; @lombok.Getter(onMethod=@__({@Foo(value="c"), @Bar(stuff="d")})) String e; } lombok-1.16.18/test/transform/resource/before/OnXJava7StyleOn8.java000066400000000000000000000006711312655740700251220ustar00rootroot00000000000000//platform ecj //version 8: public class OnXJava7StyleOn8 { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } @lombok.Getter(onMethod=@__(@Foo)) String a; @lombok.Setter(onMethod=@__(@Foo())) String b; @lombok.Setter(onParam=@__(@Foo("a"))) String c; @lombok.Setter(onParam=@__(@Bar(stuff="b"))) String d; @lombok.Getter(onMethod=@__({@Foo(value="c"), @Bar(stuff="d")})) String e; } lombok-1.16.18/test/transform/resource/before/OnXJava8Style.java000066400000000000000000000006221312655740700245320ustar00rootroot00000000000000//version 8: public class OnXJava8Style { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } @lombok.Getter(onMethod_=@Foo) String a; @lombok.Setter(onMethod_=@Foo()) String b; @lombok.Setter(onParam_=@Foo("a")) String c; @lombok.Setter(onParam_=@Bar(stuff="b")) String d; @lombok.Getter(onMethod_={@Foo(value="c"), @Bar(stuff="d")}) String e; } lombok-1.16.18/test/transform/resource/before/OnXJava8StyleOn7.java000066400000000000000000000006451312655740700251230ustar00rootroot00000000000000//platform ecj //version :7 public class OnXJava8StyleOn7 { @interface Foo { String value() default ""; } @interface Bar { String stuff() default ""; } @lombok.Getter(onMethod_=@Foo) String a; @lombok.Setter(onMethod_=@Foo()) String b; @lombok.Setter(onParam_=@Foo("a")) String c; @lombok.Setter(onParam_=@Bar(stuff="b")) String d; @lombok.Getter(onMethod_={@Foo(value="c"), @Bar(stuff="d")}) String e; } lombok-1.16.18/test/transform/resource/before/SetterAccessLevel.java000066400000000000000000000006431312655740700254760ustar00rootroot00000000000000class SetterAccessLevel { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; @lombok.Setter(lombok.AccessLevel.PRIVATE) boolean isPrivate; @lombok.Setter(lombok.AccessLevel.PACKAGE) boolean isPackage; @lombok.Setter(lombok.AccessLevel.PROTECTED) boolean isProtected; @lombok.Setter(lombok.AccessLevel.PUBLIC) boolean isPublic; @lombok.Setter(value=lombok.AccessLevel.PUBLIC) boolean value; } lombok-1.16.18/test/transform/resource/before/SetterAlreadyExists.java000066400000000000000000000013141312655740700260620ustar00rootroot00000000000000class Setter1 { @lombok.Setter boolean foo; void setFoo(boolean foo) { } } class Setter2 { @lombok.Setter boolean foo; void setFoo(String foo) { } } class Setter3 { @lombok.Setter String foo; void setFoo(boolean foo) { } } class Setter4 { @lombok.Setter String foo; void setFoo(String foo) { } } class Setter5 { @lombok.Setter String foo; void setFoo() { } } class Setter6 { @lombok.Setter String foo; void setFoo(String foo, int x) { } } class Setter7 { @lombok.Setter String foo; void setFoo(String foo, Object... x) { } } class Setter8 { @lombok.Setter boolean isFoo; void setIsFoo(boolean foo) { } } class Setter9 { @lombok.Setter boolean isFoo; void setFoo(boolean foo) { } } lombok-1.16.18/test/transform/resource/before/SetterDeprecated.java000066400000000000000000000002121312655740700253350ustar00rootroot00000000000000import lombok.Setter; class SetterDeprecated { @Deprecated @Setter int annotation; /** * @deprecated */ @Setter int javadoc; }lombok-1.16.18/test/transform/resource/before/SetterOnClass.java000066400000000000000000000015411312655740700246450ustar00rootroot00000000000000@lombok.Setter class SetterOnClass1 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; } @lombok.Setter(lombok.AccessLevel.PROTECTED) class SetterOnClass2 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isProtected; @lombok.Setter(lombok.AccessLevel.PACKAGE) boolean isPackage; } @lombok.Setter(lombok.AccessLevel.PACKAGE) class SetterOnClass3 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isPackage; } @lombok.Setter(lombok.AccessLevel.PRIVATE) class SetterOnClass4 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isPrivate; } @lombok.Setter(lombok.AccessLevel.PUBLIC) class SetterOnClass5 { @lombok.Setter(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; } @lombok.Setter class SetterOnClass6 { String couldBeNull; @lombok.NonNull String nonNull; }lombok-1.16.18/test/transform/resource/before/SetterOnMethodOnParam.java000066400000000000000000000003141312655740700262730ustar00rootroot00000000000000class SetterOnMethodOnParam { @lombok.Setter(onMethod=@__(@Deprecated)) int i; @lombok.Setter(onMethod=@__({@java.lang.Deprecated, @Test}), onParam=@__(@Test)) int j, k; public @interface Test { } } lombok-1.16.18/test/transform/resource/before/SetterOnStatic.java000066400000000000000000000001251312655740700250240ustar00rootroot00000000000000class Setter { @lombok.Setter static boolean foo; @lombok.Setter static int bar; } lombok-1.16.18/test/transform/resource/before/SetterPlain.java000066400000000000000000000001241312655740700243420ustar00rootroot00000000000000import lombok.Setter; class SetterPlain { @lombok.Setter int i; @Setter int foo; }lombok-1.16.18/test/transform/resource/before/SetterWithDollar.java000066400000000000000000000002001312655740700253430ustar00rootroot00000000000000class SetterWithDollar1 { @lombok.Setter int $i; } class SetterWithDollar2 { @lombok.Setter int $i; @lombok.Setter int i; } lombok-1.16.18/test/transform/resource/before/SimpleTypeResolution.java000066400000000000000000000002011312655740700262630ustar00rootroot00000000000000class SimpleTypeResolutionFail { @Getter private int x; } class SimpleTypeResolutionSuccess { @lombok.Getter private int x; } lombok-1.16.18/test/transform/resource/before/SneakyThrowsMultiple.java000066400000000000000000000012041312655740700262650ustar00rootroot00000000000000import java.awt.AWTException; import java.io.IOException; import java.util.Random; class SneakyThrowsMultiple { @lombok.SneakyThrows({IOException.class,Throwable.class}) public void test() { System.out.println("test1"); throw new IOException(); } @lombok.SneakyThrows({AWTException.class,IOException.class}) public void test2() { System.out.println("test2"); if (new Random().nextBoolean()) { throw new IOException(); } else { throw new AWTException("WHAT"); } } @lombok.SneakyThrows(value={IOException.class,Throwable.class}) public void test3() { System.out.println("test3"); throw new IOException(); } }lombok-1.16.18/test/transform/resource/before/SneakyThrowsPlain.java000066400000000000000000000006241312655740700255420ustar00rootroot00000000000000import lombok.SneakyThrows; class SneakyThrowsPlain { @lombok.SneakyThrows SneakyThrowsPlain() { super(); System.out.println("constructor"); } @lombok.SneakyThrows SneakyThrowsPlain(int x) { this(); System.out.println("constructor2"); } @lombok.SneakyThrows public void test() { System.out.println("test1"); } @SneakyThrows public void test2() { System.out.println("test2"); } }lombok-1.16.18/test/transform/resource/before/SneakyThrowsSingle.java000066400000000000000000000006361312655740700257230ustar00rootroot00000000000000import java.io.IOException; class SneakyThrowsSingle { @lombok.SneakyThrows(Throwable.class) public void test() { System.out.println("test1"); } @lombok.SneakyThrows(IOException.class) public void test2() { System.out.println("test2"); throw new IOException(); } @lombok.SneakyThrows(value=IOException.class) public void test3() { System.out.println("test3"); throw new IOException(); } }lombok-1.16.18/test/transform/resource/before/SynchronizedName.java000066400000000000000000000005361312655740700253770ustar00rootroot00000000000000class SynchronizedName { private Object read = new Object(); private static Object READ = new Object(); @lombok.Synchronized("read") void test1() { System.out.println("one"); } @lombok.Synchronized("READ") void test4() { System.out.println("four"); } @lombok.Synchronized(value="read") void test5() { System.out.println("five"); } } lombok-1.16.18/test/transform/resource/before/SynchronizedNameNoSuchField.java000066400000000000000000000003071312655740700274570ustar00rootroot00000000000000class SynchronizedNameNoSuchField { private Object read = new Object(); private static Object READ = new Object(); @lombok.Synchronized("write") void test2() { System.out.println("two"); } } lombok-1.16.18/test/transform/resource/before/SynchronizedNameStaticToInstanceRef.java000066400000000000000000000003301312655740700311640ustar00rootroot00000000000000class SynchronizedNameStaticToInstanceRef { private Object read = new Object(); private static Object READ = new Object(); @lombok.Synchronized("read") static void test3() { System.out.println("three"); } } lombok-1.16.18/test/transform/resource/before/SynchronizedPlain.java000066400000000000000000000005521312655740700255600ustar00rootroot00000000000000import lombok.Synchronized; class SynchronizedPlain1 { @lombok.Synchronized void test() { System.out.println("one"); } @Synchronized void test2() { System.out.println("two"); } } class SynchronizedPlain2 { @lombok.Synchronized static void test() { System.out.println("three"); } @Synchronized static void test2() { System.out.println("four"); } }lombok-1.16.18/test/transform/resource/before/TestOperators.java000066400000000000000000000011531312655740700247310ustar00rootroot00000000000000// unchanged class TestOperators { int x = 10; public void test() { x = 12; int a = +x; boolean d = true; boolean e = false; boolean b; a = -x; b = !d; a = ~x; a = ++x; a = --x; a = x++; a = x--; b = d || e; b = d && e; a = x | a; a = x ^ a; a = x & a; b = a == x; b = a != x; b = a < x; b = a > x; b = a <= x; b = a >= x; a = a << x; a = a >> x; a = a >>> x; a = a + x; a = a - x; a = a * x; a = a / x; a = a % x; a |= x; a ^= x; a &= x; a <<= x; a >>= x; a >>>= x; a += x; a -= x; a *= x; a /= x; a %= x; a = a > x ? 1 : 0; } } lombok-1.16.18/test/transform/resource/before/ToStringConfiguration.java000066400000000000000000000005461312655740700264210ustar00rootroot00000000000000//CONF: lombok.ToString.includeFieldNames = false //CONF: lombok.ToString.doNotUseGetters = true import lombok.ToString; import lombok.Getter; @ToString @Getter class ToStringConfiguration { int x; } @ToString(includeFieldNames=true) class ToStringConfiguration2 { int x; } @ToString(doNotUseGetters=false) @Getter class ToStringConfiguration3 { int x; } lombok-1.16.18/test/transform/resource/before/ToStringInner.java000066400000000000000000000004141312655740700246570ustar00rootroot00000000000000import lombok.ToString; @ToString class ToStringOuter { int x; String name; @ToString class ToStringInner { int y; } @ToString static class ToStringStaticInner { int y; } class ToStringMiddle { @ToString class ToStringMoreInner { String name; } } }lombok-1.16.18/test/transform/resource/before/ToStringPlain.java000066400000000000000000000002061312655740700246460ustar00rootroot00000000000000import lombok.ToString; @lombok.ToString class ToString1 { int x; String name; } @ToString class ToString2 { int x; String name; }lombok-1.16.18/test/transform/resource/before/Tolerate.java000066400000000000000000000012101312655740700236640ustar00rootroot00000000000000import java.util.regex.Pattern; @lombok.Setter @lombok.Getter class Tolerate { private Pattern pattern; @lombok.experimental.Tolerate public void setPattern(String pattern) { setPattern(Pattern.compile(pattern)); } } @lombok.Getter @lombok.experimental.Wither @lombok.AllArgsConstructor class Tolerate2 { private final Pattern pattern; @lombok.experimental.Tolerate public Tolerate2 withPattern(String pattern) { return withPattern(Pattern.compile(pattern)); } public Tolerate2 withPattern(String nameGlob, String extensionGlob) { return withPattern(nameGlob.replace("*", ".*") + "\\." + extensionGlob.replace("*", ".*")); } } lombok-1.16.18/test/transform/resource/before/TrickyTypeResolution.java000066400000000000000000000011651312655740700263110ustar00rootroot00000000000000import lombok.*; class TrickyDoNothing { @interface Getter {} @Getter int x; } class TrickyDoNothing2 { @Getter int x; @interface Getter {} } class TrickySuccess { @Getter int x; } class TrickyDoNothing3 { void test() { class val {} val x = null; } } class TrickyDoSomething { void test() { val x = null; class val {} } } class DoubleTrickyDoNothing { void test() { class val {} for (int i = 10; i < 20; i++) { val y = null; } } } class DoubleTrickyDoSomething { void test() { for (int j = 10; j < 20; j++) { class val {} } for (int i = 10; i < 20; i++) { val y = null; } } } lombok-1.16.18/test/transform/resource/before/TrickyTypeResolution2.java000066400000000000000000000001571312655740700263730ustar00rootroot00000000000000// unchanged import lombok.*; class DoNothingDueToTopLevel { void test() { val x = null; } } class val {} lombok-1.16.18/test/transform/resource/before/UtilityClass.java000066400000000000000000000011421312655740700245420ustar00rootroot00000000000000@lombok.experimental.UtilityClass class UtilityClass { private long someField = System.currentTimeMillis(); void someMethod() { System.out.println(); } protected class InnerClass { private String innerInnerMember; } } class UtilityInner { static class InnerInner { @lombok.experimental.UtilityClass class InnerInnerInner { int member; } } enum UtilityInsideEnum { FOO, BAR; @lombok.experimental.UtilityClass class InsideEnum { int member; } } interface UtilityInsideInterface { @lombok.experimental.UtilityClass class InsideInterface { int member; } } } lombok-1.16.18/test/transform/resource/before/UtilityClassErrors.java000066400000000000000000000006521312655740700257440ustar00rootroot00000000000000@lombok.experimental.UtilityClass class UtilityClassErrors1 { private String someField; protected UtilityClassErrors1() { } void method() { @lombok.experimental.UtilityClass class MethodLocalClass { } } } @lombok.experimental.UtilityClass enum UtilityClassErrors2 { } class UtilityClassErrors3 { class NonStaticInner { @lombok.experimental.UtilityClass class ThisShouldFail { private String member; } } }lombok-1.16.18/test/transform/resource/before/ValAnonymousSubclassWithGenerics.java000066400000000000000000000007451312655740700305700ustar00rootroot00000000000000// issue 205: val inside anonymous inner classes is a bit tricky in javac, this test ensures we don't break it. import java.util.*; import lombok.val; public class ValAnonymousSubclassWithGenerics { Object object = new Object(){ void foo() { val j = 1; } }; void bar() { val k = super.hashCode(); int x = k; } java.util.List names = new java.util.ArrayList() { public String get(int i) { val result = super.get(i); return result; } }; } lombok-1.16.18/test/transform/resource/before/ValComplex.java000066400000000000000000000007531312655740700241720ustar00rootroot00000000000000import lombok.val; public class ValComplex { private String field = ""; private static final int CONSTANT = 20; public void testComplex() { val shouldBeCharArray = field.toCharArray(); val shouldBeInt = CONSTANT; val lock = new Object(); synchronized (lock) { val field = 20; //Shadowing val inner = 10; switch (field) { case 5: val shouldBeCharArray2 = shouldBeCharArray; val innerInner = inner; } } val shouldBeString = field; //Unshadowing } }lombok-1.16.18/test/transform/resource/before/ValDefault.java000066400000000000000000000002011312655740700241330ustar00rootroot00000000000000// version 8: interface ValDefault { int size(); default void method() { lombok.val x = 1; lombok.val size = size(); } }lombok-1.16.18/test/transform/resource/before/ValErrors.java000066400000000000000000000002651312655740700240350ustar00rootroot00000000000000// unchanged import lombok.val; public class ValErrors { public void unresolvableExpression() { val c = d; } public void arrayInitializer() { val e = { "foo", "bar"}; } }lombok-1.16.18/test/transform/resource/before/ValFinal.java000066400000000000000000000001311312655740700236020ustar00rootroot00000000000000import lombok.val; public class ValFinal { public void test() { final val x = 10; } }lombok-1.16.18/test/transform/resource/before/ValInBasicFor.java000066400000000000000000000003761312655740700245430ustar00rootroot00000000000000// unchanged import lombok.val; public class ValInBasicFor { public void basicFor() { java.util.List list = java.util.Arrays.asList("Hello, World!"); for (val shouldBe = 1, marked = "", error = 1.0; ; ) { System.out.println(""); } } }lombok-1.16.18/test/transform/resource/before/ValInFor.java000066400000000000000000000004351312655740700235750ustar00rootroot00000000000000import lombok.val; public class ValInFor { public void enhancedFor() { java.util.List list = java.util.Arrays.asList("Hello, World!"); for (val shouldBeString : list) { System.out.println(shouldBeString.toLowerCase()); val shouldBeString2 = shouldBeString; } } }lombok-1.16.18/test/transform/resource/before/ValInLambda.java000066400000000000000000000005511312655740700242260ustar00rootroot00000000000000// version 8: import lombok.val; class ValInLambda { Runnable foo = (Runnable) () -> { val i = 1; }; public void easyLambda() { Runnable foo = (Runnable) () -> { val i = 1; }; } public void easyIntersectionLambda() { Runnable foo = (Runnable) () -> { val i = 1; }; } } lombok-1.16.18/test/transform/resource/before/ValInMultiDeclaration.java000066400000000000000000000001501312655740700263010ustar00rootroot00000000000000import lombok.val; public class ValInMultiDeclaration { public void test() { val x = 10, y = ""; } }lombok-1.16.18/test/transform/resource/before/ValInTryWithResources.java000066400000000000000000000004341312655740700263530ustar00rootroot00000000000000//version 7: import lombok.val; import java.io.IOException; public class ValInTryWithResources { public void whyTryInsteadOfCleanup() throws IOException { try (val in = getClass().getResourceAsStream("ValInTryWithResources.class")) { val i = in; val j = in.read(); } } }lombok-1.16.18/test/transform/resource/before/ValLambda.java000066400000000000000000000012131312655740700237330ustar00rootroot00000000000000// version 8: class ValLambda { public void easyLambda() { lombok.val foo = (Runnable)()-> {}; } public void easyIntersectionLambda() { lombok.val foo = (Runnable & java.io.Serializable)()-> {}; lombok.val bar = (java.io.Serializable & Runnable)()-> {}; } public void easyLubLambda() { lombok.val foo = (System.currentTimeMillis() > 0) ? (Runnable)()-> {} : (Runnable)System.out::println; } // public void castLubLambda() { // Runnable foo = (Runnable) ((System.currentTimeMillis() > 0) ? () -> {} : System.out::println); // lombok.val foo = (Runnable) ((System.currentTimeMillis() > 0) ? () -> {} : System.out::println); // } } lombok-1.16.18/test/transform/resource/before/ValLessSimple.java000066400000000000000000000011171312655740700246360ustar00rootroot00000000000000import lombok.val; public class ValLessSimple { private short field2 = 5; private String method() { return "method"; } private double method2() { return 2.0; } { System.out.println("Hello"); val z = 20; val x = 10; val a = z; val y = field2; } private void testVal(String param) { val fieldV = field; val a = 10; val b = 20; { val methodV = method(); val foo = fieldV + methodV; } } private void testValInCatchBlock() { try { val x = 1 / 0; } catch (ArithmeticException e) { val y = 0; } } private String field = "field"; } lombok-1.16.18/test/transform/resource/before/ValLub.java000066400000000000000000000013701312655740700233010ustar00rootroot00000000000000class ValLub { public void easyLub() { java.util.Map m = java.util.Collections.emptyMap(); lombok.val foo = (System.currentTimeMillis() > 0) ? m : java.util.Collections.emptyMap(); } public void sillyLubWithUnboxingThatProducesErrorThatVarIsPrimitive() { Integer i = 20; Double d = 20.0; lombok.val thisShouldBePrimitiveDouble = (System.currentTimeMillis() > 0) ? i : d; } public void hardLub() { java.util.List list = new java.util.ArrayList(); java.util.Set set = new java.util.HashSet(); lombok.val thisShouldBeCollection = (System.currentTimeMillis() > 0) ? list : set; thisShouldBeCollection.add(""); String foo = thisShouldBeCollection.iterator().next(); } } lombok-1.16.18/test/transform/resource/before/ValNullInit.java000066400000000000000000000001151312655740700243110ustar00rootroot00000000000000import lombok.val; class ValNullInit { void method() { val x = null; } }lombok-1.16.18/test/transform/resource/before/ValOutersWithGenerics.java000066400000000000000000000014721312655740700263570ustar00rootroot00000000000000import java.util.*; import lombok.val; public class ValOutersWithGenerics { class Inner { } class InnerWithGenerics { } public void testOutersWithGenerics() { val foo = ""; List list = new ArrayList(); val elem = list.get(0); } public void testLocalClasses() { class Local {} val q = new Local(); } public static void test() { val outer = new ValOutersWithGenerics(); val inner1 = outer.new Inner(); val inner2 = outer.new InnerWithGenerics(); } static class SubClass extends ValOutersWithGenerics { public void testSubClassOfOutersWithGenerics() { List list = new ArrayList(); val elem = list.get(0); } } public static void loop(Map map) { for (val e : map.entrySet()) { } } } lombok-1.16.18/test/transform/resource/before/ValRawType.java000066400000000000000000000005171312655740700241540ustar00rootroot00000000000000import java.util.List; import lombok.val; public class ValRawType { public void test() { Element propElement = new Element(); for (val attribute : propElement.attributes()) { val attr = (Attribute) attribute; } } static class Element { public List attributes() { return null; } } static class Attribute { } }lombok-1.16.18/test/transform/resource/before/ValSimple.java000066400000000000000000000007561312655740700240170ustar00rootroot00000000000000import lombok.val; public class ValSimple { private String field = "field"; private short field2 = 5; private String method() { return "method"; } private double method2() { return 2.0; } private void testVal(String param) { val fieldV = field; val methodV = method(); val paramV = param; val valOfVal = fieldV; val operatorV = fieldV + valOfVal; val fieldW = field2; val methodW = method2(); byte localVar = 3; val operatorW = fieldW + localVar; } } lombok-1.16.18/test/transform/resource/before/ValWeirdTypes.java000066400000000000000000000027771312655740700246720ustar00rootroot00000000000000import java.util.*; import lombok.val; public class ValWeirdTypes { private List fieldList; public void testGenerics() { List list = new ArrayList(); list.add("Hello, World!"); val shouldBeString = list.get(0); val shouldBeListOfString = list; val shouldBeListOfStringToo = Arrays.asList("hello", "world"); val shouldBeString2 = shouldBeListOfString.get(0); } public void testGenericsInference() { val huh = Collections.emptyList(); val huh2 = Collections.emptyList(); } public void testPrimitives() { val x = 10; val y = 5 + 3L; } public void testAnonymousInnerClass() { val y = new Runnable() { public void run() {} }; } public void testTypeParams(List param) { val t = param.get(0); val z = fieldList.get(0); val k = param; val y = fieldList; } public void testBounds(List lower, List upper) { val a = lower.get(0); val b = upper.get(0); val c = lower; val d = upper; List unbound = lower; val e = unbound; } public void testCompound() { val a = new ArrayList(); val b = new Vector(); val c = 1 < System.currentTimeMillis(); val d = c ? a : b; java.util.RandomAccess confirm = c ? a : b; } public void nullType() { val nully = null; } public void testArrays() { val intArray = new int[] {1, 2, 3}; val multiDimArray = new Object[][] {{}}; val copy = intArray; val single = multiDimArray[0]; val singleInt = copy[0]; } }lombok-1.16.18/test/transform/resource/before/ValWithLabel.java000066400000000000000000000002351312655740700244310ustar00rootroot00000000000000import lombok.val; public class ValWithLabel { { LABEL: for (val x : new String[0]) { if (x.toLowerCase() == null) { continue LABEL; } } } }lombok-1.16.18/test/transform/resource/before/ValWithLocalClasses.java000066400000000000000000000005201312655740700257570ustar00rootroot00000000000000//issue 694: In javac, resolving the RHS (which is what val does) can cause an entire class to be resolved, breaking all usage of val inside that class. This tests that we handle that better. class ValWithLocalClasses1 { { lombok.val f2 = new ValWithLocalClasses2() {}; } } class ValWithLocalClasses2 { { lombok.val f3 = 0; } }lombok-1.16.18/test/transform/resource/before/ValueCallSuper.java000066400000000000000000000002131312655740700247760ustar00rootroot00000000000000//CONF: lombok.equalsAndHashCode.callSuper = call class ValueParent { } @lombok.Value class ValueCallSuper extends ValueParent { } lombok-1.16.18/test/transform/resource/before/ValueExperimental.java000066400000000000000000000001771312655740700255520ustar00rootroot00000000000000import lombok.experimental.Value; @Value class ValueExperimental1 { } @lombok.experimental.Value class ValueExperimental2 { }lombok-1.16.18/test/transform/resource/before/ValueExperimentalStarImport.java000066400000000000000000000001131312655740700275650ustar00rootroot00000000000000import lombok.experimental.*; @Value class ValueExperimentalStarImport { }lombok-1.16.18/test/transform/resource/before/ValuePlain.java000066400000000000000000000003501312655740700241510ustar00rootroot00000000000000import lombok.Value; @lombok.Value class Value1 { final int x; String name; } @Value @lombok.experimental.NonFinal class Value2 { public int x; String name; } @Value class Value3 { @lombok.experimental.NonFinal int x; int y; }lombok-1.16.18/test/transform/resource/before/ValueStaticField.java000066400000000000000000000001571312655740700253060ustar00rootroot00000000000000import lombok.Value; @Value class ValueStaticField { static int x; static String PASSWORD = "Ken sent me"; } lombok-1.16.18/test/transform/resource/before/VarComplex.java000066400000000000000000000010341312655740700241710ustar00rootroot00000000000000//CONF: lombok.var.flagUsage = ALLOW import lombok.experimental.var; public class VarComplex { private String field = ""; private static final int CONSTANT = 20; public void testComplex() { var shouldBeCharArray = field.toCharArray(); var shouldBeInt = CONSTANT; var lock = new Object(); synchronized (lock) { var field = 20; //Shadowing var inner = 10; switch (field) { case 5: var shouldBeCharArray2 = shouldBeCharArray; var innerInner = inner; } } var shouldBeString = field; //Unshadowing } }lombok-1.16.18/test/transform/resource/before/VarInFor.java000066400000000000000000000004141312655740700236000ustar00rootroot00000000000000//CONF: lombok.var.flagUsage = ALLOW import lombok.experimental.var; public class VarInFor { public void enhancedFor() { int[] list = new int[] {1, 2}; for (var shouldBeInt : list) { System.out.println(shouldBeInt); var shouldBeInt2 = shouldBeInt; } } }lombok-1.16.18/test/transform/resource/before/VarInForOld.java000066400000000000000000000002751312655740700242440ustar00rootroot00000000000000//CONF: lombok.var.flagUsage = ALLOW import lombok.experimental.var; public class VarInForOld { public void oldFor() { for (var i = 0; i < 100; ++i) { System.out.println(i); } } }lombok-1.16.18/test/transform/resource/before/VarModifier.java000066400000000000000000000004101312655740700243150ustar00rootroot00000000000000//CONF: lombok.var.flagUsage = ALLOW import lombok.experimental.var; public class VarModifier { private String field = ""; public void testComplex() { final var shouldBeFinalCharArray = field.toCharArray(); var shouldBeCharArray = field.toCharArray(); } }lombok-1.16.18/test/transform/resource/before/VarNullInit.java000066400000000000000000000002061312655740700243200ustar00rootroot00000000000000//CONF: lombok.var.flagUsage = ALLOW import lombok.experimental.var; public class VarNullInit { void method() { var x = null; } }lombok-1.16.18/test/transform/resource/before/VarWarning.java000066400000000000000000000002761312655740700241760ustar00rootroot00000000000000//CONF: lombok.var.flagUsage = WARNING //skip compare contents import lombok.experimental.var; public class VarWarning { public void isOkay() { var x = "Warning"; x.toLowerCase(); } }lombok-1.16.18/test/transform/resource/before/WithInnerAnnotation.java000066400000000000000000000001311312655740700260500ustar00rootroot00000000000000// unchanged class WithInnerAnnotation { @interface Inner { int bar() default 42; } }lombok-1.16.18/test/transform/resource/before/WitherAccessLevel.java000066400000000000000000000012051312655740700254650ustar00rootroot00000000000000import lombok.AccessLevel; class WitherAccessLevel { @lombok.experimental.Wither(lombok.AccessLevel.NONE) boolean isNone; @lombok.experimental.Wither(AccessLevel.PRIVATE) boolean isPrivate; @lombok.experimental.Wither(lombok.AccessLevel.PACKAGE) boolean isPackage; @lombok.experimental.Wither(AccessLevel.PROTECTED) boolean isProtected; @lombok.experimental.Wither(lombok.AccessLevel.PUBLIC) boolean isPublic; @lombok.experimental.Wither(value=lombok.AccessLevel.PUBLIC) boolean value; WitherAccessLevel(boolean isNone, boolean isPrivate, boolean isPackage, boolean isProtected, boolean isPublic, boolean value) { } } lombok-1.16.18/test/transform/resource/before/WitherAlreadyExists.java000066400000000000000000000021341312655740700260570ustar00rootroot00000000000000class Wither1 { @lombok.experimental.Wither boolean foo; void withFoo(boolean foo) { } Wither1(boolean foo) { } } class Wither2 { @lombok.experimental.Wither boolean foo; void withFoo(String foo) { } Wither2(boolean foo) { } } class Wither3 { @lombok.experimental.Wither String foo; void withFoo(boolean foo) { } Wither3(String foo) { } } class Wither4 { @lombok.experimental.Wither String foo; void withFoo(String foo) { } Wither4(String foo) { } } class Wither5 { @lombok.experimental.Wither String foo; void withFoo() { } Wither5(String foo) { } } class Wither6 { @lombok.experimental.Wither String foo; void withFoo(String foo, int x) { } Wither6(String foo) { } } class Wither7 { @lombok.experimental.Wither String foo; void withFoo(String foo, Object... x) { } Wither7(String foo) { } } class Wither8 { @lombok.experimental.Wither boolean isFoo; void withIsFoo(boolean foo) { } Wither8(boolean foo) { } } class Wither9 { @lombok.experimental.Wither boolean isFoo; void withFoo(boolean foo) { } Wither9(boolean foo) { } } lombok-1.16.18/test/transform/resource/before/WitherAndAllArgsConstructor.java000066400000000000000000000003751312655740700275210ustar00rootroot00000000000000@lombok.AllArgsConstructor class WitherAndAllArgsConstructor { @lombok.experimental.Wither J test; @lombok.experimental.Wither java.util.List test2; final int x = 10; int y = 20; final int z; }lombok-1.16.18/test/transform/resource/before/WitherDeprecated.java000066400000000000000000000003161312655740700253360ustar00rootroot00000000000000import lombok.experimental.Wither; class WitherDeprecated { @Deprecated @Wither int annotation; /** * @deprecated */ @Wither int javadoc; WitherDeprecated(int annotation, int javadoc) { } }lombok-1.16.18/test/transform/resource/before/WitherOnClass.java000066400000000000000000000015671312655740700246510ustar00rootroot00000000000000@lombok.experimental.Wither class WitherOnClass1 { @lombok.experimental.Wither(lombok.AccessLevel.NONE) boolean isNone; boolean isPublic; WitherOnClass1(boolean isNone, boolean isPublic) { } } @lombok.experimental.Wither(lombok.AccessLevel.PROTECTED) class WitherOnClass2 { @lombok.experimental.Wither(lombok.AccessLevel.NONE) boolean isNone; boolean isProtected; @lombok.experimental.Wither(lombok.AccessLevel.PACKAGE) boolean isPackage; WitherOnClass2(boolean isNone, boolean isProtected, boolean isPackage) { } } @lombok.experimental.Wither class WitherOnClass3 { String couldBeNull; @lombok.NonNull String nonNull; WitherOnClass3(String couldBeNull, String nonNull) { } } @lombok.experimental.Wither @lombok.experimental.Accessors(prefix="f") class WitherOnClass4 { final int fX = 10; final int fY; WitherOnClass4(int y) { this.fY = y; } } lombok-1.16.18/test/transform/resource/before/WitherOnStatic.java000066400000000000000000000001671312655740700250260ustar00rootroot00000000000000class WitherOnStatic { @lombok.experimental.Wither static boolean foo; @lombok.experimental.Wither static int bar; } lombok-1.16.18/test/transform/resource/before/WitherPlain.java000066400000000000000000000002711312655740700243410ustar00rootroot00000000000000import lombok.experimental.Wither; class WitherPlain { @lombok.experimental.Wither int i; @Wither final int foo; WitherPlain(int i, int foo) { this.i = i; this.foo = foo; } } lombok-1.16.18/test/transform/resource/before/WitherWithAbstract.java000066400000000000000000000001161312655740700256730ustar00rootroot00000000000000abstract class WitherWithAbstract { @lombok.experimental.Wither String foo; }lombok-1.16.18/test/transform/resource/before/WitherWithDollar.java000066400000000000000000000001001312655740700253360ustar00rootroot00000000000000class WitherWithDollar { @lombok.experimental.Wither int $i; } lombok-1.16.18/test/transform/resource/before/WitherWithGenerics.java000066400000000000000000000005221312655740700256700ustar00rootroot00000000000000class WitherWithGenerics { @lombok.experimental.Wither J test; @lombok.experimental.Wither java.util.List test2; @lombok.experimental.Wither java.util.List test3; int $i; public WitherWithGenerics(J test, java.util.List test2, java.util.List test3) { } }lombok-1.16.18/test/transform/resource/messages-delombok/000077500000000000000000000000001312655740700234075ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-delombok/Accessors.java.messages000066400000000000000000000001251312655740700300030ustar00rootroot0000000000000019 Not generating setter for this field: It does not fit your @Accessors prefix list.lombok-1.16.18/test/transform/resource/messages-delombok/BuilderDefaultsWarnings.java.messages000066400000000000000000000006441312655740700326530ustar00rootroot0000000000000013 @Builder.Default requires @Builder on the class for it to mean anything. 6 @Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final. 8 @Builder.Default requires an initializing expression (' = something;'). 9 @Builder.Default and @Singular cannot be mixed. lombok-1.16.18/test/transform/resource/messages-delombok/BuilderInvalidUse.java.messages000066400000000000000000000002471312655740700314350ustar00rootroot000000000000002 @Getter, @Setter, @Wither, @Data, @ToString, @EqualsAndHashCode, @AllArgsConstructor are not allowed on builder classes. 13 @Value is not allowed on builder classes.lombok-1.16.18/test/transform/resource/messages-delombok/BuilderSingularNoAuto.java.messages000066400000000000000000000003371312655740700323040ustar00rootroot000000000000008 The singular must be specified explicitly (e.g. @Singular("task")) because auto singularization is disabled. 10 The singular must be specified explicitly (e.g. @Singular("task")) because auto singularization is disabled. ConflictingStaticConstructorNames.java.messages000066400000000000000000000001761312655740700346460ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-delombok1 Ignoring static constructor name: explicit @XxxArgsConstructor annotation present; its `staticName` parameter will be used. lombok-1.16.18/test/transform/resource/messages-delombok/DelegateFlagUsage.java.messages000066400000000000000000000001001312655740700313400ustar00rootroot000000000000004 Use of @Delegate is flagged according to lombok configuration.lombok-1.16.18/test/transform/resource/messages-delombok/DelegateOnStatic.java.messages000066400000000000000000000002341312655740700312360ustar00rootroot000000000000006 @Delegate is legal only on instance fields or no-argument instance methods. 10 @Delegate is legal only on instance fields or no-argument instance methods.lombok-1.16.18/test/transform/resource/messages-delombok/DelegateRecursion.java.messages000066400000000000000000000002371312655740700314660ustar00rootroot000000000000004 @Delegate does not support recursion (delegating to a type that itself has @Delegate members). Member "inner" is @Delegate in type "DelegateRecursionCenter" EqualsAndHashCodeWithExistingMethods.java.messages000066400000000000000000000004431312655740700351510ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-delombok1 Not generating equals and hashCode: A method with one of those names already exists. (Either both or none of these methods will be generated). 10 Not generating equals and hashCode: A method with one of those names already exists. (Either both or none of these methods will be generated). EqualsAndHashCodeWithSomeExistingMethods.java.messages000066400000000000000000000002371312655740700357760ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-delombok5 Not generating equals: One of equals or hashCode exists. You should either write both of these or none of these (in the latter case, lombok generates them). lombok-1.16.18/test/transform/resource/messages-delombok/FieldDefaultsNoop.java.messages000066400000000000000000000000771312655740700314330ustar00rootroot000000000000001 This does nothing; provide either level or makeFinal or both.lombok-1.16.18/test/transform/resource/messages-delombok/FlagUsages.java.messages000066400000000000000000000002261312655740700301010ustar00rootroot000000000000005 Use of @Getter is flagged according to lombok configuration. 7 Use of any lombok.experimental feature is flagged according to lombok configuration. lombok-1.16.18/test/transform/resource/messages-delombok/GetterAlreadyExists.java.messages000066400000000000000000000010461312655740700320150ustar00rootroot000000000000008 Not generating isFoo(): A method with that name already exists 14 Not generating isFoo(): A method with that name already exists (getFoo) 32 Not generating getFoo(): A method with that name already exists 50 Not generating getFoo(): A method with that name already exists 62 Not generating isFoo(): A method with that name already exists 68 Not generating isFoo(): A method with that name already exists (getFoo) 86 Not generating getFoo(): A method with that name already exists 104 Not generating getFoo(): A method with that name already exists lombok-1.16.18/test/transform/resource/messages-delombok/GetterBoolean.java.messages000066400000000000000000000001121312655740700306040ustar00rootroot0000000000000013 Not generating isFoo(): A method with that name already exists (getFoo)lombok-1.16.18/test/transform/resource/messages-delombok/GetterLazyInvalid.java.messages000066400000000000000000000004511312655740700314610ustar00rootroot000000000000002 'lazy' requires the field to be private and final. 6 'lazy' requires the field to be private and final. 10 'lazy' requires the field to be private and final. 14 'lazy' does not work with AccessLevel.NONE. 17 'lazy' is not supported for @Getter on a type. 22 'lazy' requires field initialization.lombok-1.16.18/test/transform/resource/messages-delombok/GetterLazyTransient.java.messages000066400000000000000000000000561312655740700320430ustar00rootroot000000000000005 'lazy' is not supported on transient fields.lombok-1.16.18/test/transform/resource/messages-delombok/GetterOnMethodErrors.java.messages000066400000000000000000000000641312655740700321450ustar00rootroot000000000000003 'onMethod' is not supported for @Getter on a type.lombok-1.16.18/test/transform/resource/messages-delombok/GetterOnMethodErrors2.java.messages000066400000000000000000000001401312655740700322220ustar00rootroot000000000000003 The correct format is 4 The correct format is 5 The correct format is 6 The correct format is lombok-1.16.18/test/transform/resource/messages-delombok/Helper.java.messages000066400000000000000000000000611312655740700272740ustar00rootroot0000000000000015 No methods of this helper class are ever used.lombok-1.16.18/test/transform/resource/messages-delombok/LoggerSlf4jAlreadyExists.java.messages000066400000000000000000000000361312655740700327030ustar00rootroot000000000000001 Field 'log' already exists. LoggerSlf4jOnNonStaticInnerClass.java.messages000066400000000000000000000000601312655740700342210ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-delombok2 @Log is not legal on non-static inner classes.lombok-1.16.18/test/transform/resource/messages-delombok/LoggerSlf4jOnNonType.java.messages000066400000000000000000000001401312655740700320070ustar00rootroot000000000000003 @Log is legal only on types. |||| 3 annotation type not applicable to this kind of declarationlombok-1.16.18/test/transform/resource/messages-delombok/LoggerSlf4jTypes.java.messages000066400000000000000000000001251312655740700312250ustar00rootroot000000000000001 @Log is legal only on classes and enums. 4 @Log is legal only on classes and enums.lombok-1.16.18/test/transform/resource/messages-delombok/NonNullOnParameter.java.messages000066400000000000000000000000531312655740700316010ustar00rootroot0000000000000022 @NonNull is meaningless on a primitive. lombok-1.16.18/test/transform/resource/messages-delombok/NonNullPlain.java.messages000066400000000000000000000000511312655740700304250ustar00rootroot000000000000005 @NonNull is meaningless on a primitive.lombok-1.16.18/test/transform/resource/messages-delombok/SetterAlreadyExists.java.messages000066400000000000000000000007361312655740700320360ustar00rootroot000000000000002 Not generating setFoo(): A method with that name already exists 8 Not generating setFoo(): A method with that name already exists 14 Not generating setFoo(): A method with that name already exists 20 Not generating setFoo(): A method with that name already exists 38 Not generating setFoo(): A method with that name already exists 44 Not generating setFoo(): A method with that name already exists (setIsFoo) 50 Not generating setFoo(): A method with that name already exists lombok-1.16.18/test/transform/resource/messages-delombok/SetterOnMethod.java.messages000066400000000000000000000003261312655740700307650ustar00rootroot000000000000003 incompatible types 4 incompatible types 6 incompatible types 11 incompatible types 14 incompatible types 6 'onMethod' is not supported for @Setter on a type. 11 'onMethod' is not supported for @Setter on a type. lombok-1.16.18/test/transform/resource/messages-delombok/SetterOnParam.java.messages000066400000000000000000000003241312655740700306030ustar00rootroot000000000000003 incompatible types 4 incompatible types 6 incompatible types 11 incompatible types 14 incompatible types 6 'onParam' is not supported for @Setter on a type. 11 'onParam' is not supported for @Setter on a type. lombok-1.16.18/test/transform/resource/messages-delombok/SetterOnParamAndOnMethod.java.messages000066400000000000000000000000521312655740700326620ustar00rootroot000000000000002 incompatible types 2 incompatible types lombok-1.16.18/test/transform/resource/messages-delombok/SimpleTypeResolution.java.messages000066400000000000000000000000251312655740700322340ustar00rootroot000000000000002 cannot find symbol lombok-1.16.18/test/transform/resource/messages-delombok/SynchronizedNameNoSuchField.java.messages000066400000000000000000000000421312655740700334200ustar00rootroot000000000000005 The field write does not exist. SynchronizedNameStaticToInstanceRef.java.messages000066400000000000000000000001051312655740700350520ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-delombok5 non-static variable read cannot be referenced from a static contextlombok-1.16.18/test/transform/resource/messages-delombok/UtilityClassErrors.java.messages000066400000000000000000000005441312655740700317110ustar00rootroot000000000000004 @UtilityClasses cannot have declared constructors. 7 @UtilityClass cannot be placed on a method local or anonymous inner class, or any class nested in such a class. 12 @UtilityClass is only supported on a class (can't be an interface, enum, or annotation). 17 @UtilityClass automatically makes the class static, however, this class cannot be made static.lombok-1.16.18/test/transform/resource/messages-delombok/ValErrors.java.messages000066400000000000000000000003601312655740700277760ustar00rootroot000000000000006 Cannot use 'val' here because initializer expression does not have a representable type: Type cannot be resolved 10 'val' is not compatible with array initializer expressions. Use the full form (new int[] { ... } instead of just { ... }) lombok-1.16.18/test/transform/resource/messages-delombok/ValInBasicFor.java.messages000066400000000000000000000000561312655740700305030ustar00rootroot000000000000007 'val' is not allowed in old-style for loops lombok-1.16.18/test/transform/resource/messages-delombok/VarNullInit.java.messages000066400000000000000000000000401312655740700302610ustar00rootroot000000000000006 variable initializer is 'null'lombok-1.16.18/test/transform/resource/messages-delombok/VarWarning.java.messages000066400000000000000000000000711312655740700301340ustar00rootroot000000000000007 Use of var is flagged according to lombok configurationlombok-1.16.18/test/transform/resource/messages-delombok/WitherAlreadyExists.java.messages000066400000000000000000000007471312655740700320340ustar00rootroot000000000000002 Not generating withFoo(): A method with that name already exists 12 Not generating withFoo(): A method with that name already exists 22 Not generating withFoo(): A method with that name already exists 32 Not generating withFoo(): A method with that name already exists 62 Not generating withFoo(): A method with that name already exists 72 Not generating withFoo(): A method with that name already exists (withIsFoo) 82 Not generating withFoo(): A method with that name already exists lombok-1.16.18/test/transform/resource/messages-delombok/WitherOnStatic.java.messages000066400000000000000000000002561312655740700307720ustar00rootroot000000000000002 Not generating wither for this field: Withers cannot be generated for static fields. 3 Not generating wither for this field: Withers cannot be generated for static fields. lombok-1.16.18/test/transform/resource/messages-delombok/WitherWithDollar.java.messages000066400000000000000000000001401312655740700313070ustar00rootroot000000000000002 Not generating wither for this field: Withers cannot be generated for fields starting with $. lombok-1.16.18/test/transform/resource/messages-ecj/000077500000000000000000000000001312655740700223545ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-ecj/Accessors.java.messages000066400000000000000000000001261312655740700267510ustar00rootroot0000000000000019 Not generating setter for this field: It does not fit your @Accessors prefix list. lombok-1.16.18/test/transform/resource/messages-ecj/BuilderComplex.java.messages000066400000000000000000000000411312655740700277360ustar00rootroot000000000000002 The type Builder is deprecated lombok-1.16.18/test/transform/resource/messages-ecj/BuilderDefaultsWarnings.java.messages000066400000000000000000000006451312655740700316210ustar00rootroot000000000000006 @Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final. 8 @Builder.Default requires an initializing expression (' = something;'). 9 @Builder.Default and @Singular cannot be mixed. 13 @Builder.Default requires @Builder on the class for it to mean anything. lombok-1.16.18/test/transform/resource/messages-ecj/BuilderInvalidUse.java.messages000066400000000000000000000002671312655740700304040ustar00rootroot000000000000002 @Getter, @Setter, @FieldDefaults, @Wither, @Data, @ToString, @EqualsAndHashCode, @AllArgsConstructor are not allowed on builder classes. 13 @Value is not allowed on builder classes.lombok-1.16.18/test/transform/resource/messages-ecj/BuilderSingularNoAuto.java.messages000066400000000000000000000003371312655740700312510ustar00rootroot000000000000008 The singular must be specified explicitly (e.g. @Singular("task")) because auto singularization is disabled. 10 The singular must be specified explicitly (e.g. @Singular("task")) because auto singularization is disabled. lombok-1.16.18/test/transform/resource/messages-ecj/ConflictingStaticConstructorNames.java.messages000066400000000000000000000001761312655740700336720ustar00rootroot000000000000001 Ignoring static constructor name: explicit @XxxArgsConstructor annotation present; its `staticName` parameter will be used. lombok-1.16.18/test/transform/resource/messages-ecj/DelegateFlagUsage.java.messages000066400000000000000000000001011312655740700303060ustar00rootroot000000000000004 Use of @Delegate is flagged according to lombok configuration. lombok-1.16.18/test/transform/resource/messages-ecj/DelegateOnGetter.java.messages000066400000000000000000000001041312655740700302020ustar00rootroot000000000000001 The type Delegate is deprecated 6 The type Delegate is deprecated lombok-1.16.18/test/transform/resource/messages-ecj/DelegateOnStatic.java.messages000066400000000000000000000002341312655740700302030ustar00rootroot000000000000006 @Delegate is legal only on instance fields or no-argument instance methods. 10 @Delegate is legal only on instance fields or no-argument instance methods.lombok-1.16.18/test/transform/resource/messages-ecj/DelegateRecursion.java.messages000066400000000000000000000002371312655740700304330ustar00rootroot000000000000004 @Delegate does not support recursion (delegating to a type that itself has @Delegate members). Member "inner" is @Delegate in type "DelegateRecursionCenter" EqualsAndHashCodeWithExistingMethods.java.messages000066400000000000000000000004431312655740700341160ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-ecj1 Not generating equals and hashCode: A method with one of those names already exists. (Either both or none of these methods will be generated). 10 Not generating equals and hashCode: A method with one of those names already exists. (Either both or none of these methods will be generated). EqualsAndHashCodeWithSomeExistingMethods.java.messages000066400000000000000000000002371312655740700347430ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-ecj5 Not generating equals: One of equals or hashCode exists. You should either write both of these or none of these (in the latter case, lombok generates them). lombok-1.16.18/test/transform/resource/messages-ecj/FieldDefaultsNoop.java.messages000066400000000000000000000000771312655740700304000ustar00rootroot000000000000001 This does nothing; provide either level or makeFinal or both.lombok-1.16.18/test/transform/resource/messages-ecj/FlagUsages.java.messages000066400000000000000000000002261312655740700270460ustar00rootroot000000000000005 Use of @Getter is flagged according to lombok configuration. 7 Use of any lombok.experimental feature is flagged according to lombok configuration. lombok-1.16.18/test/transform/resource/messages-ecj/GetterAlreadyExists.java.messages000066400000000000000000000010461312655740700307620ustar00rootroot000000000000008 Not generating isFoo(): A method with that name already exists 14 Not generating isFoo(): A method with that name already exists (getFoo) 32 Not generating getFoo(): A method with that name already exists 50 Not generating getFoo(): A method with that name already exists 62 Not generating isFoo(): A method with that name already exists 68 Not generating isFoo(): A method with that name already exists (getFoo) 86 Not generating getFoo(): A method with that name already exists 104 Not generating getFoo(): A method with that name already exists lombok-1.16.18/test/transform/resource/messages-ecj/GetterBoolean.java.messages000066400000000000000000000001131312655740700275520ustar00rootroot0000000000000013 Not generating isFoo(): A method with that name already exists (getFoo) lombok-1.16.18/test/transform/resource/messages-ecj/GetterLazyInvalid.java.messages000066400000000000000000000004521312655740700304270ustar00rootroot000000000000002 'lazy' requires the field to be private and final. 6 'lazy' requires the field to be private and final. 10 'lazy' requires the field to be private and final. 14 'lazy' does not work with AccessLevel.NONE. 17 'lazy' is not supported for @Getter on a type. 22 'lazy' requires field initialization. lombok-1.16.18/test/transform/resource/messages-ecj/GetterLazyTransient.java.messages000066400000000000000000000000561312655740700310100ustar00rootroot000000000000005 'lazy' is not supported on transient fields.lombok-1.16.18/test/transform/resource/messages-ecj/GetterOnMethodErrors.java.messages000066400000000000000000000000641312655740700311120ustar00rootroot000000000000003 'onMethod' is not supported for @Getter on a type.lombok-1.16.18/test/transform/resource/messages-ecj/GetterOnMethodErrors2.java.messages000066400000000000000000000001401312655740700311670ustar00rootroot000000000000003 The correct format is 4 The correct format is 5 The correct format is 6 The correct format is lombok-1.16.18/test/transform/resource/messages-ecj/Helper.java.messages000066400000000000000000000000621312655740700262420ustar00rootroot0000000000000015 No methods of this helper class are ever used. lombok-1.16.18/test/transform/resource/messages-ecj/LoggerSlf4jAlreadyExists.java.messages000066400000000000000000000000361312655740700316500ustar00rootroot000000000000001 Field 'log' already exists. lombok-1.16.18/test/transform/resource/messages-ecj/LoggerSlf4jOnNonStaticInnerClass.java.messages000066400000000000000000000000601312655740700332450ustar00rootroot000000000000002 @Log is not legal on non-static inner classes.lombok-1.16.18/test/transform/resource/messages-ecj/LoggerSlf4jOnNonType.java.messages000066400000000000000000000000701312655740700307560ustar00rootroot000000000000003 The annotation @Slf4j is disallowed for this location lombok-1.16.18/test/transform/resource/messages-ecj/LoggerSlf4jTypes.java.messages000066400000000000000000000001321312655740700301700ustar00rootroot000000000000001 @Slf4j is legal only on classes and enums. 4 @Slf4j is legal only on classes and enums. lombok-1.16.18/test/transform/resource/messages-ecj/NonNullOnParameter.java.messages000066400000000000000000000001041312655740700305430ustar00rootroot0000000000000015 Dead code 22 @NonNull is meaningless on a primitive. 28 Dead codelombok-1.16.18/test/transform/resource/messages-ecj/NonNullPlain.java.messages000066400000000000000000000000511312655740700273720ustar00rootroot000000000000007 @NonNull is meaningless on a primitive.lombok-1.16.18/test/transform/resource/messages-ecj/SetterAlreadyExists.java.messages000066400000000000000000000007361312655740700310030ustar00rootroot000000000000002 Not generating setFoo(): A method with that name already exists 8 Not generating setFoo(): A method with that name already exists 14 Not generating setFoo(): A method with that name already exists 20 Not generating setFoo(): A method with that name already exists 38 Not generating setFoo(): A method with that name already exists 44 Not generating setFoo(): A method with that name already exists (setIsFoo) 50 Not generating setFoo(): A method with that name already exists lombok-1.16.18/test/transform/resource/messages-ecj/SetterOnMethod.java.messages000066400000000000000000000001521312655740700277270ustar00rootroot000000000000006 'onMethod' is not supported for @Setter on a type. 11 'onMethod' is not supported for @Setter on a type.lombok-1.16.18/test/transform/resource/messages-ecj/SetterOnParam.java.messages000066400000000000000000000001501312655740700275450ustar00rootroot000000000000006 'onParam' is not supported for @Setter on a type. 11 'onParam' is not supported for @Setter on a type.lombok-1.16.18/test/transform/resource/messages-ecj/SimpleTypeResolution.java.messages000066400000000000000000000000461312655740700312040ustar00rootroot000000000000002 Getter cannot be resolved to a type lombok-1.16.18/test/transform/resource/messages-ecj/SynchronizedName.java.messages000066400000000000000000000001141312655740700303010ustar00rootroot000000000000008 The static field SynchronizedName.READ should be accessed in a static way lombok-1.16.18/test/transform/resource/messages-ecj/SynchronizedNameNoSuchField.java.messages000066400000000000000000000000421312655740700323650ustar00rootroot000000000000005 The field write does not exist. SynchronizedNameStaticToInstanceRef.java.messages000066400000000000000000000001421312655740700340200ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-ecj5 Cannot make a static reference to the non-static field SynchronizedNameStaticToInstanceRef.read lombok-1.16.18/test/transform/resource/messages-ecj/UtilityClassErrors.java.messages000066400000000000000000000005431312655740700306550ustar00rootroot000000000000004 @UtilityClasses cannot have declared constructors. 7 @UtilityClass cannot be placed on a method local or anonymous inner class, or any class nested in such a class. 12 @UtilityClass is only supported on a class (can't be an interface, enum, or annotation) 17 @UtilityClass automatically makes the class static, however, this class cannot be made static.lombok-1.16.18/test/transform/resource/messages-ecj/ValAnonymousSubclassWithGenerics.java.messages000066400000000000000000000001361312655740700334740ustar00rootroot0000000000000017 The serializable class does not declare a static final serialVersionUID field of type longlombok-1.16.18/test/transform/resource/messages-ecj/ValErrors.java.messages000066400000000000000000000002421312655740700267420ustar00rootroot000000000000006 d cannot be resolved to a variable 10 'val' is not compatible with array initializer expressions. Use the full form (new int[] { ... } instead of just { ... }) lombok-1.16.18/test/transform/resource/messages-ecj/ValInBasicFor.java.messages000066400000000000000000000001361312655740700274470ustar00rootroot000000000000007 'val' is not allowed in old-style for loops 7 Type mismatch: cannot convert from int to val lombok-1.16.18/test/transform/resource/messages-ecj/ValRawType.java.messages000066400000000000000000000001221312655740700270560ustar00rootroot0000000000000013 List is a raw type. References to generic type List should be parameterized lombok-1.16.18/test/transform/resource/messages-ecj/ValueExperimental.java.messages000066400000000000000000000000361312655740700304560ustar00rootroot000000000000001 The type Value is deprecatedlombok-1.16.18/test/transform/resource/messages-ecj/VarNullInit.java.messages000066400000000000000000000000401312655740700272260ustar00rootroot000000000000006 variable initializer is 'null'lombok-1.16.18/test/transform/resource/messages-ecj/VarWarning.java.messages000066400000000000000000000000711312655740700271010ustar00rootroot000000000000007 Use of var is flagged according to lombok configurationlombok-1.16.18/test/transform/resource/messages-ecj/WitherAlreadyExists.java.messages000066400000000000000000000007471312655740700310010ustar00rootroot000000000000002 Not generating withFoo(): A method with that name already exists 12 Not generating withFoo(): A method with that name already exists 22 Not generating withFoo(): A method with that name already exists 32 Not generating withFoo(): A method with that name already exists 62 Not generating withFoo(): A method with that name already exists 72 Not generating withFoo(): A method with that name already exists (withIsFoo) 82 Not generating withFoo(): A method with that name already exists lombok-1.16.18/test/transform/resource/messages-ecj/WitherOnStatic.java.messages000066400000000000000000000002561312655740700277370ustar00rootroot000000000000002 Not generating wither for this field: Withers cannot be generated for static fields. 3 Not generating wither for this field: Withers cannot be generated for static fields. lombok-1.16.18/test/transform/resource/messages-ecj/WitherWithDollar.java.messages000066400000000000000000000001401312655740700302540ustar00rootroot000000000000002 Not generating wither for this field: Withers cannot be generated for fields starting with $. lombok-1.16.18/test/transform/resource/messages-idempotent/000077500000000000000000000000001312655740700237635ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-idempotent/NonNullOnParameter.java.messages000066400000000000000000000000521312655740700321540ustar00rootroot0000000000000033 @NonNull is meaningless on a primitive.lombok-1.16.18/test/transform/resource/messages-idempotent/NonNullPlain.java.messages000066400000000000000000000001771312655740700310120ustar00rootroot000000000000003 @NonNull is meaningless on a primitive. 16 @NonNull is meaningless on a primitive. 42 @NonNull is meaningless on a primitive.lombok-1.16.18/test/transform/resource/messages-idempotent/SimpleTypeResolution.java.messages000066400000000000000000000000251312655740700326100ustar00rootroot000000000000002 cannot find symbol SynchronizedNameStaticToInstanceRef.java.messages000066400000000000000000000001061312655740700354270ustar00rootroot00000000000000lombok-1.16.18/test/transform/resource/messages-idempotent5 non-static variable read cannot be referenced from a static context lombok-1.16.18/test/transform/resource/messages-idempotent/ValErrors.java.messages000066400000000000000000000001241312655740700303500ustar00rootroot000000000000003 cannot find symbol 6 cannot find symbol OPTIONAL 6 illegal initializer for lombok-1.16.18/test/transform/resource/messages-idempotent/ValInBasicFor.java.messages000066400000000000000000000000561312655740700310570ustar00rootroot000000000000005 'val' is not allowed in old-style for loops lombok-1.16.18/test/transform/src/000077500000000000000000000000001312655740700167465ustar00rootroot00000000000000lombok-1.16.18/test/transform/src/lombok/000077500000000000000000000000001312655740700202315ustar00rootroot00000000000000lombok-1.16.18/test/transform/src/lombok/transform/000077500000000000000000000000001312655740700222445ustar00rootroot00000000000000lombok-1.16.18/test/transform/src/lombok/transform/RunTransformTests.java000066400000000000000000000026521312655740700265770ustar00rootroot00000000000000/* * Copyright (C) 2011-2012 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.transform; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({TestLombokFilesIdempotent.class, TestSourceFiles.class, TestWithDelombok.class, TestWithEcj.class}) public class RunTransformTests { } lombok-1.16.18/test/transform/src/lombok/transform/TestLombokFilesIdempotent.java000066400000000000000000000035731312655740700302160ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.transform; import java.io.File; import lombok.DirectoryRunner; import org.junit.runner.RunWith; @RunWith(DirectoryRunner.class) public class TestLombokFilesIdempotent extends DirectoryRunner.TestParams { @Override public File getBeforeDirectory() { return getAfterDirectory(); } @Override public File getAfterDirectory() { return new File("test/transform/resource/after-delombok"); } @Override public File getMessagesDirectory() { return new File("test/transform/resource/messages-idempotent"); } @Override public DirectoryRunner.Compiler getCompiler() { return DirectoryRunner.Compiler.DELOMBOK; } @Override public boolean printErrors() { return true; } @Override public boolean expectChanges() { return false; } } lombok-1.16.18/test/transform/src/lombok/transform/TestSourceFiles.java000066400000000000000000000035061312655740700261760ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.transform; import java.io.File; import lombok.DirectoryRunner; import org.junit.runner.RunWith; @RunWith(DirectoryRunner.class) public class TestSourceFiles extends DirectoryRunner.TestParams { @Override public DirectoryRunner.Compiler getCompiler() { return DirectoryRunner.Compiler.DELOMBOK; } @Override public boolean printErrors() { return true; } @Override public File getBeforeDirectory() { return new File("test/pretty/resource/before"); } @Override public File getAfterDirectory() { return new File("test/pretty/resource/after"); } @Override public File getMessagesDirectory() { return null; } @Override public boolean expectChanges() { return false; } } lombok-1.16.18/test/transform/src/lombok/transform/TestWithDelombok.java000066400000000000000000000036061312655740700263440ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.transform; import java.io.File; import lombok.DirectoryRunner; import org.junit.runner.RunWith; @RunWith(DirectoryRunner.class) public class TestWithDelombok extends DirectoryRunner.TestParams { @Override public DirectoryRunner.Compiler getCompiler() { return DirectoryRunner.Compiler.DELOMBOK; } @Override public boolean printErrors() { return true; } @Override public File getBeforeDirectory() { return new File("test/transform/resource/before"); } @Override public File getAfterDirectory() { return new File("test/transform/resource/after-delombok"); } @Override public File getMessagesDirectory() { return new File("test/transform/resource/messages-delombok"); } @Override public boolean expectChanges() { return true; } } lombok-1.16.18/test/transform/src/lombok/transform/TestWithEcj.java000066400000000000000000000041341312655740700253060ustar00rootroot00000000000000/* * Copyright (C) 2009-2015 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.transform; import java.io.File; import lombok.DirectoryRunner; import org.junit.runner.RunWith; // You need to add the following vm-parameter to run the test: // -javaagent:${project_loc:lombok}/dist/lombok.jar // When running inside eclipse's junit tester, you don't actually need to run 'ant dist' after updating code, though. @RunWith(DirectoryRunner.class) public class TestWithEcj extends DirectoryRunner.TestParams { @Override public DirectoryRunner.Compiler getCompiler() { return DirectoryRunner.Compiler.ECJ; } @Override public boolean printErrors() { return true; } @Override public File getBeforeDirectory() { return new File("test/transform/resource/before"); } @Override public File getAfterDirectory() { return new File("test/transform/resource/after-ecj"); } @Override public File getMessagesDirectory() { return new File("test/transform/resource/messages-ecj"); } @Override public boolean expectChanges() { return true; } } lombok-1.16.18/usage_examples/000077500000000000000000000000001312655740700161675ustar00rootroot00000000000000lombok-1.16.18/usage_examples/BuilderExample_post.jpage000066400000000000000000000042701312655740700231510ustar00rootroot00000000000000import java.util.Set; public class BuilderExample { private long created; private String name; private int age; private Set occupations; BuilderExample(String name, int age, Set occupations) { this.name = name; this.age = age; this.occupations = occupations; } private static long $default$created() { return System.currentTimeMillis(); } public static BuilderExampleBuilder builder() { return new BuilderExampleBuilder(); } public static class BuilderExampleBuilder { private long created; private boolean created$set; private String name; private int age; private java.util.ArrayList occupations; BuilderExampleBuilder() { } public BuilderExampleBuilder created(long created) { this.created = created; this.created$set = true; return this; } public BuilderExampleBuilder name(String name) { this.name = name; return this; } public BuilderExampleBuilder age(int age) { this.age = age; return this; } public BuilderExampleBuilder occupation(String occupation) { if (this.occupations == null) { this.occupations = new java.util.ArrayList(); } this.occupations.add(occupation); return this; } public BuilderExampleBuilder occupations(Collection occupations) { if (this.occupations == null) { this.occupations = new java.util.ArrayList(); } this.occupations.addAll(occupations); return this; } public BuilderExampleBuilder clearOccupations() { if (this.occupations != null) { this.occupations.clear(); } return this; } public BuilderExample build() { // complicated switch statement to produce a compact properly sized immutable set omitted. // go to https://projectlombok.org/features/Singular-snippet.html to see it. Set occupations = ...; return new BuilderExample(created$set ? created : BuilderExample.$default$created(), name, age, occupations); } @java.lang.Override public String toString() { return "BuilderExample.BuilderExampleBuilder(created = " + this.created + ", name = " + this.name + ", age = " + this.age + ", occupations = " + this.occupations + ")"; } } }lombok-1.16.18/usage_examples/BuilderExample_pre.jpage000066400000000000000000000004101312655740700227420ustar00rootroot00000000000000import lombok.Builder; import lombok.Singular; import java.util.Set; @Builder public class BuilderExample { @Builder.Default private long created = System.currentTimeMillis(); private String name; private int age; @Singular private Set occupations; } lombok-1.16.18/usage_examples/CleanupExample_post.jpage000066400000000000000000000007551312655740700231560ustar00rootroot00000000000000import java.io.*; public class CleanupExample { public static void main(String[] args) throws IOException { InputStream in = new FileInputStream(args[0]); try { OutputStream out = new FileOutputStream(args[1]); try { byte[] b = new byte[10000]; while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } } finally { if (out != null) { out.close(); } } } finally { if (in != null) { in.close(); } } } } lombok-1.16.18/usage_examples/CleanupExample_pre.jpage000066400000000000000000000005711312655740700227530ustar00rootroot00000000000000import lombok.Cleanup; import java.io.*; public class CleanupExample { public static void main(String[] args) throws IOException { @Cleanup InputStream in = new FileInputStream(args[0]); @Cleanup OutputStream out = new FileOutputStream(args[1]); byte[] b = new byte[10000]; while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } } } lombok-1.16.18/usage_examples/ConstructorExample_post.jpage000066400000000000000000000013411312655740700241040ustar00rootroot00000000000000public class ConstructorExample { private int x, y; @NonNull private T description; private ConstructorExample(T description) { if (description == null) throw new NullPointerException("description"); this.description = description; } public static ConstructorExample of(T description) { return new ConstructorExample(description); } @java.beans.ConstructorProperties({"x", "y", "description"}) protected ConstructorExample(int x, int y, T description) { if (description == null) throw new NullPointerException("description"); this.x = x; this.y = y; this.description = description; } public static class NoArgsExample { @NonNull private String field; public NoArgsExample() { } } } lombok-1.16.18/usage_examples/ConstructorExample_pre.jpage000066400000000000000000000006261312655740700237120ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.AllArgsConstructor; import lombok.NonNull; @RequiredArgsConstructor(staticName = "of") @AllArgsConstructor(access = AccessLevel.PROTECTED) public class ConstructorExample { private int x, y; @NonNull private T description; @NoArgsConstructor public static class NoArgsExample { @NonNull private String field; } } lombok-1.16.18/usage_examples/DataExample_post.jpage000066400000000000000000000061771312655740700224440ustar00rootroot00000000000000import java.util.Arrays; public class DataExample { private final String name; private int age; private double score; private String[] tags; public DataExample(String name) { this.name = name; } public String getName() { return this.name; } void setAge(int age) { this.age = age; } public int getAge() { return this.age; } public void setScore(double score) { this.score = score; } public double getScore() { return this.score; } public String[] getTags() { return this.tags; } public void setTags(String[] tags) { this.tags = tags; } @Override public String toString() { return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")"; } protected boolean canEqual(Object other) { return other instanceof DataExample; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof DataExample)) return false; DataExample other = (DataExample) o; if (!other.canEqual((Object)this)) return false; if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false; if (this.getAge() != other.getAge()) return false; if (Double.compare(this.getScore(), other.getScore()) != 0) return false; if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false; return true; } @Override public int hashCode() { final int PRIME = 59; int result = 1; final long temp1 = Double.doubleToLongBits(this.getScore()); result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode()); result = (result*PRIME) + this.getAge(); result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32)); result = (result*PRIME) + Arrays.deepHashCode(this.getTags()); return result; } public static class Exercise { private final String name; private final T value; private Exercise(String name, T value) { this.name = name; this.value = value; } public static Exercise of(String name, T value) { return new Exercise(name, value); } public String getName() { return this.name; } public T getValue() { return this.value; } @Override public String toString() { return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")"; } protected boolean canEqual(Object other) { return other instanceof Exercise; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Exercise)) return false; Exercise other = (Exercise) o; if (!other.canEqual((Object)this)) return false; if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false; if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false; return true; } @Override public int hashCode() { final int PRIME = 59; int result = 1; result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode()); result = (result*PRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode()); return result; } } } lombok-1.16.18/usage_examples/DataExample_pre.jpage000066400000000000000000000006331312655740700222340ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.Setter; import lombok.Data; import lombok.ToString; @Data public class DataExample { private final String name; @Setter(AccessLevel.PACKAGE) private int age; private double score; private String[] tags; @ToString(includeFieldNames=true) @Data(staticConstructor="of") public static class Exercise { private final String name; private final T value; } } lombok-1.16.18/usage_examples/EqualsAndHashCodeExample_post.jpage000066400000000000000000000041141312655740700250340ustar00rootroot00000000000000import java.util.Arrays; public class EqualsAndHashCodeExample { private transient int transientVar = 10; private String name; private double score; private Shape shape = new Square(5, 10); private String[] tags; private int id; public String getName() { return this.name; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeExample)) return false; EqualsAndHashCodeExample other = (EqualsAndHashCodeExample) o; if (!other.canEqual((Object)this)) return false; if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false; if (Double.compare(this.score, other.score) != 0) return false; if (!Arrays.deepEquals(this.tags, other.tags)) return false; return true; } @Override public int hashCode() { final int PRIME = 59; int result = 1; final long temp1 = Double.doubleToLongBits(this.score); result = (result*PRIME) + (this.name == null ? 43 : this.name.hashCode()); result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32)); result = (result*PRIME) + Arrays.deepHashCode(this.tags); return result; } protected boolean canEqual(Object other) { return other instanceof EqualsAndHashCodeExample; } public static class Square extends Shape { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Square)) return false; Square other = (Square) o; if (!other.canEqual((Object)this)) return false; if (!super.equals(o)) return false; if (this.width != other.width) return false; if (this.height != other.height) return false; return true; } @Override public int hashCode() { final int PRIME = 59; int result = 1; result = (result*PRIME) + super.hashCode(); result = (result*PRIME) + this.width; result = (result*PRIME) + this.height; return result; } protected boolean canEqual(Object other) { return other instanceof Square; } } } lombok-1.16.18/usage_examples/EqualsAndHashCodeExample_pre.jpage000066400000000000000000000010561312655740700246370ustar00rootroot00000000000000import lombok.EqualsAndHashCode; @EqualsAndHashCode(exclude={"id", "shape"}) public class EqualsAndHashCodeExample { private transient int transientVar = 10; private String name; private double score; private Shape shape = new Square(5, 10); private String[] tags; private int id; public String getName() { return this.name; } @EqualsAndHashCode(callSuper=true) public static class Square extends Shape { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } } } lombok-1.16.18/usage_examples/GetterLazyExample_post.jpage000066400000000000000000000013571312655740700236600ustar00rootroot00000000000000public class GetterLazyExample { private final java.util.concurrent.AtomicReference cached = new java.util.concurrent.AtomicReference(); public double[] getCached() { java.lang.Object value = this.cached.get(); if (value == null) { synchronized(this.cached) { value = this.cached.get(); if (value == null) { final double[] actualValue = expensive(); value = actualValue == null ? this.cached : actualValue; this.cached.set(value); } } } return (double[])(value == this.cached ? null : value); } private double[] expensive() { double[] result = new double[1000000]; for (int i = 0; i < result.length; i++) { result[i] = Math.asin(i); } return result; } } lombok-1.16.18/usage_examples/GetterLazyExample_pre.jpage000066400000000000000000000004471312655740700234600ustar00rootroot00000000000000import lombok.Getter; public class GetterLazyExample { @Getter(lazy=true) private final double[] cached = expensive(); private double[] expensive() { double[] result = new double[1000000]; for (int i = 0; i < result.length; i++) { result[i] = Math.asin(i); } return result; } } lombok-1.16.18/usage_examples/GetterSetterExample_post.jpage000066400000000000000000000013361312655740700242040ustar00rootroot00000000000000public class GetterSetterExample { /** * Age of the person. Water is wet. */ private int age = 10; /** * Name of the person. */ private String name; @Override public String toString() { return String.format("%s (age: %d)", name, age); } /** * Age of the person. Water is wet. * * @return The current value of this person's age. Circles are round. */ public int getAge() { return age; } /** * Age of the person. Water is wet. * * @param age New value for this person's age. Sky is blue. */ public void setAge(int age) { this.age = age; } /** * Changes the name of this person. * * @param name The new value. */ protected void setName(String name) { this.name = name; } } lombok-1.16.18/usage_examples/GetterSetterExample_pre.jpage000066400000000000000000000011351312655740700240020ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; public class GetterSetterExample { /** * Age of the person. Water is wet. * * @param age New value for this person's age. Sky is blue. * @return The current value of this person's age. Circles are round. */ @Getter @Setter private int age = 10; /** * Name of the person. * -- SETTER -- * Changes the name of this person. * * @param name The new value. */ @Setter(AccessLevel.PROTECTED) private String name; @Override public String toString() { return String.format("%s (age: %d)", name, age); } } lombok-1.16.18/usage_examples/LogExample_post.jpage000066400000000000000000000013211312655740700222760ustar00rootroot00000000000000public class LogExample { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName()); public static void main(String... args) { log.error("Something's wrong here"); } } public class LogExampleOther { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class); public static void main(String... args) { log.error("Something else is wrong here"); } } public class LogExampleCategory { private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog"); public static void main(String... args) { log.error("Calling the 'CounterLog' with a message"); } } lombok-1.16.18/usage_examples/LogExample_pre.jpage000066400000000000000000000007541312655740700221100ustar00rootroot00000000000000import lombok.extern.java.Log; import lombok.extern.slf4j.Slf4j; @Log public class LogExample { public static void main(String... args) { log.error("Something's wrong here"); } } @Slf4j public class LogExampleOther { public static void main(String... args) { log.error("Something else is wrong here"); } } @CommonsLog(topic="CounterLog") public class LogExampleCategory { public static void main(String... args) { log.error("Calling the 'CounterLog' with a message"); } } lombok-1.16.18/usage_examples/NonNullExample_post.jpage000066400000000000000000000004211312655740700231420ustar00rootroot00000000000000import lombok.NonNull; public class NonNullExample extends Something { private String name; public NonNullExample(@NonNull Person person) { super("Hello"); if (person == null) { throw new NullPointerException("person"); } this.name = person.getName(); } } lombok-1.16.18/usage_examples/NonNullExample_pre.jpage000066400000000000000000000003101312655740700227400ustar00rootroot00000000000000import lombok.NonNull; public class NonNullExample extends Something { private String name; public NonNullExample(@NonNull Person person) { super("Hello"); this.name = person.getName(); } } lombok-1.16.18/usage_examples/Singular-snippetExample_post.jpage000066400000000000000000000122021312655740700250210ustar00rootroot00000000000000import java.util.Collection; import java.util.Set; import java.util.SortedMap; import com.google.common.collect.ImmutableList; public class SingularExample { private Set occupations; private ImmutableList axes; private SortedMap elves; private Collection minutiae; SingularExample(Set occupations, ImmutableList axes, SortedMap elves, Collection minutiae) { this.occupations = occupations; this.axes = axes; this.elves = elves; this.minutiae = minutiae; } public static class SingularExampleBuilder { private java.util.ArrayList occupations; private com.google.common.collect.ImmutableList.Builder axes; private java.util.ArrayList elves$key; private java.util.ArrayList elves$value; private java.util.ArrayList minutiae; SingularExampleBuilder() { } public SingularExampleBuilder occupation(String occupation) { if (this.occupations == null) { this.occupations = new java.util.ArrayList(); } this.occupations.add(occupation); return this; } @java.lang.SuppressWarnings("all") public SingularExampleBuilder occupations(java.util.Collection occupations) { if (this.occupations == null) { this.occupations = new java.util.ArrayList(); } this.occupations.addAll(occupations); return this; } public SingularExampleBuilder axis(String axis) { if (this.axes == null) { this.axes = com.google.common.collect.ImmutableList.builder(); } this.axes.add(axis); return this; } public SingularExampleBuilder axes(java.lang.Iterable axes) { if (this.axes == null) { this.axes = com.google.common.collect.ImmutableList.builder(); } this.axes.addAll(axes); return this; } public SingularExampleBuilder elf(Integer elfKey, T elfValue) { if (this.elves$key == null) { this.elves$key = new java.util.ArrayList(); this.elves$value = new java.util.ArrayList(); } this.elves$key.add(elfKey); this.elves$value.add(elfValue); return this; } public SingularExampleBuilder elves(java.util.Map elves) { if (this.elves$key == null) { this.elves$key = new java.util.ArrayList(); this.elves$value = new java.util.ArrayList(); } for (java.util.Map.Entry $lombokEntry : elves.entrySet()) { this.elves$key.add($lombokEntry.getKey()); this.elves$value.add($lombokEntry.getValue()); } return this; } public SingularExampleBuilder minutia(java.lang.Object minutia) { if (this.minutiae == null) { this.minutiae = new java.util.ArrayList(); } this.minutiae.add(minutia); return this; } public SingularExampleBuilder minutiae(java.util.Collection minutiae) { if (this.minutiae == null) { this.minutiae = new java.util.ArrayList(); } this.minutiae.addAll(minutiae); return this; } public SingularExample build() { java.util.Set occupations; switch (this.occupations == null ? 0 : this.occupations.size()) { case 0: occupations = java.util.Collections.emptySet(); break; case 1: occupations = java.util.Collections.singleton(this.occupations.get(0)); break; default: occupations = new java.util.LinkedHashSet(this.occupations.size() < 1073741824 ? 1 + this.occupations.size() + (this.occupations.size() - 3) / 3 : java.lang.Integer.MAX_VALUE); occupations.addAll(this.occupations); occupations = java.util.Collections.unmodifiableSet(occupations); } com.google.common.collect.ImmutableList axes = this.axes == null ? com.google.common.collect.ImmutableList.of() : this.axes.build(); java.util.SortedMap elves = new java.util.TreeMap(); if (this.elves$key != null) for (int $i = 0; $i < (this.elves$key == null ? 0 : this.elves$key.size()); $i++) elves.put(this.elves$key.get($i), this.elves$value.get($i)); elves = java.util.Collections.unmodifiableSortedMap(elves); java.util.Collection minutiae; switch (this.minutiae == null ? 0 : this.minutiae.size()) { case 0: minutiae = java.util.Collections.emptyList(); break; case 1: minutiae = java.util.Collections.singletonList(this.minutiae.get(0)); break; default: minutiae = java.util.Collections.unmodifiableList(new java.util.ArrayList(this.minutiae)); } return new SingularExample(occupations, axes, elves, minutiae); } @java.lang.Override public java.lang.String toString() { return "SingularExample.SingularExampleBuilder(occupations=" + this.occupations + ", axes=" + this.axes + ", elves$key=" + this.elves$key + ", elves$value=" + this.elves$value + ", minutiae=" + this.minutiae + ")"; } } @java.lang.SuppressWarnings("all") public static SingularExampleBuilder builder() { return new SingularExampleBuilder(); } } lombok-1.16.18/usage_examples/Singular-snippetExample_pre.jpage000066400000000000000000000006511312655740700246270ustar00rootroot00000000000000import lombok.Builder; import lombok.Singular; import java.util.Collection; import java.util.Set; import java.util.SortedMap; import com.google.common.collect.ImmutableList; @Builder public class SingularExample { private @Singular Set occupations; private @Singular("axis") ImmutableList axes; private @Singular SortedMap elves; private @Singular Collection minutiae; } lombok-1.16.18/usage_examples/SneakyThrowsExample_post.jpage000066400000000000000000000005701312655740700242230ustar00rootroot00000000000000import lombok.Lombok; public class SneakyThrowsExample implements Runnable { public String utf8ToString(byte[] bytes) { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw Lombok.sneakyThrow(e); } } public void run() { try { throw new Throwable(); } catch (Throwable t) { throw Lombok.sneakyThrow(t); } } } lombok-1.16.18/usage_examples/SneakyThrowsExample_pre.jpage000066400000000000000000000004371312655740700240260ustar00rootroot00000000000000import lombok.SneakyThrows; public class SneakyThrowsExample implements Runnable { @SneakyThrows(UnsupportedEncodingException.class) public String utf8ToString(byte[] bytes) { return new String(bytes, "UTF-8"); } @SneakyThrows public void run() { throw new Throwable(); } } lombok-1.16.18/usage_examples/SynchronizedExample_post.jpage000066400000000000000000000006671312655740700242500ustar00rootroot00000000000000public class SynchronizedExample { private static final Object $LOCK = new Object[0]; private final Object $lock = new Object[0]; private final Object readLock = new Object(); public static void hello() { synchronized($LOCK) { System.out.println("world"); } } public int answerToLife() { synchronized($lock) { return 42; } } public void foo() { synchronized(readLock) { System.out.println("bar"); } } } lombok-1.16.18/usage_examples/SynchronizedExample_pre.jpage000066400000000000000000000005221312655740700240370ustar00rootroot00000000000000import lombok.Synchronized; public class SynchronizedExample { private final Object readLock = new Object(); @Synchronized public static void hello() { System.out.println("world"); } @Synchronized public int answerToLife() { return 42; } @Synchronized("readLock") public void foo() { System.out.println("bar"); } } lombok-1.16.18/usage_examples/ToStringExample_post.jpage000066400000000000000000000013571312655740700233370ustar00rootroot00000000000000import java.util.Arrays; public class ToStringExample { private static final int STATIC_VAR = 10; private String name; private Shape shape = new Square(5, 10); private String[] tags; private int id; public String getName() { return this.getName(); } public static class Square extends Shape { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } @Override public String toString() { return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")"; } } @Override public String toString() { return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")"; } } lombok-1.16.18/usage_examples/ToStringExample_pre.jpage000066400000000000000000000010061312655740700231270ustar00rootroot00000000000000import lombok.ToString; @ToString(exclude="id") public class ToStringExample { private static final int STATIC_VAR = 10; private String name; private Shape shape = new Square(5, 10); private String[] tags; private int id; public String getName() { return this.getName(); } @ToString(callSuper=true, includeFieldNames=true) public static class Square extends Shape { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } } } lombok-1.16.18/usage_examples/ValueExample_post.jpage000066400000000000000000000065461312655740700226470ustar00rootroot00000000000000import java.util.Arrays; public final class ValueExample { private final String name; private int age; private final double score; protected final String[] tags; @java.beans.ConstructorProperties({"name", "age", "score", "tags"}) public ValueExample(String name, int age, double score, String[] tags) { this.name = name; this.age = age; this.score = score; this.tags = tags; } public String getName() { return this.name; } public int getAge() { return this.age; } public double getScore() { return this.score; } public String[] getTags() { return this.tags; } @java.lang.Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ValueExample)) return false; final ValueExample other = (ValueExample)o; final Object this$name = this.getName(); final Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; if (this.getAge() != other.getAge()) return false; if (Double.compare(this.getScore(), other.getScore()) != 0) return false; if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false; return true; } @java.lang.Override public int hashCode() { final int PRIME = 59; int result = 1; final Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); result = result * PRIME + this.getAge(); final long $score = Double.doubleToLongBits(this.getScore()); result = result * PRIME + (int)($score >>> 32 ^ $score); result = result * PRIME + Arrays.deepHashCode(this.getTags()); return result; } @java.lang.Override public String toString() { return "ValueExample(name=" + getName() + ", age=" + getAge() + ", score=" + getScore() + ", tags=" + Arrays.deepToString(getTags()) + ")"; } ValueExample withAge(int age) { return this.age == age ? this : new ValueExample(name, age, score, tags); } public static final class Exercise { private final String name; private final T value; private Exercise(String name, T value) { this.name = name; this.value = value; } public static Exercise of(String name, T value) { return new Exercise(name, value); } public String getName() { return this.name; } public T getValue() { return this.value; } @java.lang.Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ValueExample.Exercise)) return false; final Exercise other = (Exercise)o; final Object this$name = this.getName(); final Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false; final Object this$value = this.getValue(); final Object other$value = other.getValue(); if (this$value == null ? other$value != null : !this$value.equals(other$value)) return false; return true; } @java.lang.Override public int hashCode() { final int PRIME = 59; int result = 1; final Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); final Object $value = this.getValue(); result = result * PRIME + ($value == null ? 43 : $value.hashCode()); return result; } @java.lang.Override public String toString() { return "ValueExample.Exercise(name=" + getName() + ", value=" + getValue() + ")"; } } }lombok-1.16.18/usage_examples/ValueExample_pre.jpage000066400000000000000000000006601312655740700224370ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.experimental.NonFinal; import lombok.experimental.Value; import lombok.experimental.Wither; import lombok.ToString; @Value public class ValueExample { String name; @Wither(AccessLevel.PACKAGE) @NonFinal int age; double score; protected String[] tags; @ToString(includeFieldNames=true) @Value(staticConstructor="of") public static class Exercise { String name; T value; } } lombok-1.16.18/usage_examples/experimental/000077500000000000000000000000001312655740700206645ustar00rootroot00000000000000lombok-1.16.18/usage_examples/experimental/AccessorsExample_post.jpage000066400000000000000000000004601312655740700262020ustar00rootroot00000000000000public class AccessorsExample { private int age = 10; public int age() { return this.age; } public AccessorsExample age(final int age) { this.age = age; return this; } } class PrefixExample { private String fName = "Hello, World!"; public String getName() { return this.fName; } } lombok-1.16.18/usage_examples/experimental/AccessorsExample_pre.jpage000066400000000000000000000004331312655740700260030ustar00rootroot00000000000000import lombok.experimental.Accessors; import lombok.Getter; import lombok.Setter; @Accessors(fluent = true) public class AccessorsExample { @Getter @Setter private int age = 10; } class PrefixExample { @Accessors(prefix = "f") @Getter private String fName = "Hello, World!"; } lombok-1.16.18/usage_examples/experimental/DelegateExample_post.jpage000066400000000000000000000045141312655740700257730ustar00rootroot00000000000000import java.util.ArrayList; import java.util.Collection; public class DelegationExample { private interface SimpleCollection { boolean add(String item); boolean remove(Object item); } private final Collection collection = new ArrayList(); @java.lang.SuppressWarnings("all") public boolean add(final java.lang.String item) { return this.collection.add(item); } @java.lang.SuppressWarnings("all") public boolean remove(final java.lang.Object item) { return this.collection.remove(item); } } class ExcludesDelegateExample { long counter = 0L; private interface Add { boolean add(String x); boolean addAll(Collection x); } private final Collection collection = new ArrayList(); public boolean add(String item) { counter++; return collection.add(item); } public boolean addAll(Collection col) { counter += col.size(); return collection.addAll(col); } @java.lang.SuppressWarnings("all") public int size() { return this.collection.size(); } @java.lang.SuppressWarnings("all") public boolean isEmpty() { return this.collection.isEmpty(); } @java.lang.SuppressWarnings("all") public boolean contains(final java.lang.Object arg0) { return this.collection.contains(arg0); } @java.lang.SuppressWarnings("all") public java.util.Iterator iterator() { return this.collection.iterator(); } @java.lang.SuppressWarnings("all") public java.lang.Object[] toArray() { return this.collection.toArray(); } @java.lang.SuppressWarnings("all") public T[] toArray(final T[] arg0) { return this.collection.toArray(arg0); } @java.lang.SuppressWarnings("all") public boolean remove(final java.lang.Object arg0) { return this.collection.remove(arg0); } @java.lang.SuppressWarnings("all") public boolean containsAll(final java.util.Collection arg0) { return this.collection.containsAll(arg0); } @java.lang.SuppressWarnings("all") public boolean removeAll(final java.util.Collection arg0) { return this.collection.removeAll(arg0); } @java.lang.SuppressWarnings("all") public boolean retainAll(final java.util.Collection arg0) { return this.collection.retainAll(arg0); } @java.lang.SuppressWarnings("all") public void clear() { this.collection.clear(); } } lombok-1.16.18/usage_examples/experimental/DelegateExample_pre.jpage000066400000000000000000000014621312655740700255730ustar00rootroot00000000000000import java.util.ArrayList; import java.util.Collection; import lombok.experimental.Delegate; public class DelegationExample { private interface SimpleCollection { boolean add(String item); boolean remove(Object item); } @Delegate(types=SimpleCollection.class) private final Collection collection = new ArrayList(); } class ExcludesDelegateExample { long counter = 0L; private interface Add { boolean add(String x); boolean addAll(Collection x); } @Delegate(excludes=Add.class) private final Collection collection = new ArrayList(); public boolean add(String item) { counter++; return collection.add(item); } public boolean addAll(Collection col) { counter += col.size(); return collection.addAll(col); } } lombok-1.16.18/usage_examples/experimental/ExtensionMethodExample_post.jpage000066400000000000000000000010001312655740700273610ustar00rootroot00000000000000public class ExtensionMethodExample { public String test() { int[] intArray = {5, 3, 8, 2}; java.util.Arrays.sort(intArray); String iAmNull = null; return Extensions.or(iAmNull, Extensions.toTitleCase("hELlO, WORlD!")); } } class Extensions { public static T or(T obj, T ifNull) { return obj != null ? obj : ifNull; } public static String toTitleCase(String in) { if (in.isEmpty()) return in; return "" + Character.toTitleCase(in.charAt(0)) + in.substring(1).toLowerCase(); } } lombok-1.16.18/usage_examples/experimental/ExtensionMethodExample_pre.jpage000066400000000000000000000011041312655740700271670ustar00rootroot00000000000000import lombok.experimental.ExtensionMethod; @ExtensionMethod({java.util.Arrays.class, Extensions.class}) public class ExtensionMethodExample { public String test() { int[] intArray = {5, 3, 8, 2}; intArray.sort(); String iAmNull = null; return iAmNull.or("hELlO, WORlD!".toTitleCase()); } } class Extensions { public static T or(T obj, T ifNull) { return obj != null ? obj : ifNull; } public static String toTitleCase(String in) { if (in.isEmpty()) return in; return "" + Character.toTitleCase(in.charAt(0)) + in.substring(1).toLowerCase(); } } lombok-1.16.18/usage_examples/experimental/FieldDefaultsExample_post.jpage000066400000000000000000000002511312655740700267660ustar00rootroot00000000000000public class FieldDefaultsExample { public final int a; private final int b; private int c; final int d; FieldDefaultsExample() { a = 0; b = 0; d = 0; } } lombok-1.16.18/usage_examples/experimental/FieldDefaultsExample_pre.jpage000066400000000000000000000005671312655740700266010ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.experimental.FieldDefaults; import lombok.experimental.NonFinal; import lombok.experimental.PackagePrivate; @FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE) public class FieldDefaultsExample { public final int a; int b; @NonFinal int c; @PackagePrivate int d; FieldDefaultsExample() { a = 0; b = 0; d = 0; } } lombok-1.16.18/usage_examples/experimental/HelperExample_post.jpage000066400000000000000000000003611312655740700254740ustar00rootroot00000000000000public class HelperExample { int someMethod(int arg1) { int localVar = 5; class Helpers { int helperMethod(int arg) { return arg + localVar; } } Helpers $Helpers = new Helpers(); return $Helpers.helperMethod(10); } } lombok-1.16.18/usage_examples/experimental/HelperExample_pre.jpage000066400000000000000000000003601312655740700252740ustar00rootroot00000000000000import lombok.experimental.Helper; public class HelperExample { int someMethod(int arg1) { int localVar = 5; @Helper class Helpers { int helperMethod(int arg) { return arg + localVar; } } return helperMethod(10); } } lombok-1.16.18/usage_examples/experimental/UtilityClassExample_post.jpage000066400000000000000000000004521312655740700267070ustar00rootroot00000000000000public final class UtilityClassExample { private static final int CONSTANT = 5; private UtilityClassExample() { throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } public static void addSomething(int in) { return in + CONSTANT; } } lombok-1.16.18/usage_examples/experimental/UtilityClassExample_pre.jpage000066400000000000000000000002761312655740700265140ustar00rootroot00000000000000import lombok.experimental.UtilityClass; @UtilityClass public class UtilityClassExample { private final int CONSTANT = 5; public void addSomething(int in) { return in + CONSTANT; } } lombok-1.16.18/usage_examples/experimental/WitherExample_post.jpage000066400000000000000000000010671312655740700255230ustar00rootroot00000000000000import lombok.NonNull; public class WitherExample { private final int age; private @NonNull final String name; public WitherExample(String name, int age) { if (name == null) throw new NullPointerException(); this.name = name; this.age = age; } public WitherExample withAge(int age) { return this.age == age ? this : new WitherExample(age, name); } protected WitherExample withName(@NonNull String name) { if (name == null) throw new java.lang.NullPointerException("name"); return this.name == name ? this : new WitherExample(age, name); } }lombok-1.16.18/usage_examples/experimental/WitherExample_pre.jpage000066400000000000000000000005501312655740700253200ustar00rootroot00000000000000import lombok.AccessLevel; import lombok.NonNull; import lombok.experimental.Wither; public class WitherExample { @Wither private final int age; @Wither(AccessLevel.PROTECTED) @NonNull private final String name; public WitherExample(String name, int age) { if (name == null) throw new NullPointerException(); this.name = name; this.age = age; } } lombok-1.16.18/usage_examples/experimental/onXExample_post.jpage000066400000000000000000000006061312655740700250230ustar00rootroot00000000000000import javax.inject.Inject; import javax.persistence.Id; import javax.persistence.Column; import javax.validation.constraints.Max; public class OnXExample { private long unid; @Inject public OnXExample(long unid) { this.unid = unid; } @Id @Column(name="unique-id") public long getUnid() { return unid; } public void setUnid(@Max(10000) long unid) { this.unid = unid; } } lombok-1.16.18/usage_examples/experimental/onXExample_pre.jpage000066400000000000000000000010031312655740700246140ustar00rootroot00000000000000import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import javax.inject.Inject; import javax.persistence.Id; import javax.persistence.Column; import javax.validation.constraints.Max; @AllArgsConstructor(onConstructor=@__(@Inject)) public class OnXExample { // @Getter(onMethod=@__({@Id, @Column(name="unique-id")})) //JDK7 // @Setter(onParam=@__(@Max(10000))) //JDK7 @Getter(onMethod_={@Id, @Column(name="unique-id")}) //JDK8 @Setter(onParam_=@Max(10000)) //JDK8 private long unid; } lombok-1.16.18/usage_examples/experimental/varExample_post.jpage000066400000000000000000000007551312655740700250540ustar00rootroot00000000000000import java.util.ArrayList; import lombok.var; public class VarExample { public String example() { ArrayList example = new ArrayList(); example.add("Hello, World!"); final String foo = example.get(0); return foo.toLowerCase(); } public void example2() { ArrayList list = new ArrayList(); list.add("zero"); list.add("one"); list.add("two"); for(int i = 0; i < list.size(); ++i) { System.out.printf("%d: %s\n", i, list.get(i)); } } } lombok-1.16.18/usage_examples/experimental/varExample_pre.jpage000066400000000000000000000007161312655740700246520ustar00rootroot00000000000000import java.util.ArrayList; import lombok.var; public class VarExample { public String example() { var example = new ArrayList(); example.add("Hello, World!"); final var foo = example.get(0); return foo.toLowerCase(); } public void example2() { var list = new ArrayList(); list.add("zero"); list.add("one"); list.add("two"); for(var i = 0; i < list.size(); ++i) { System.out.printf("%d: %s\n", i, list.get(i)); } } } lombok-1.16.18/usage_examples/valExample_post.jpage000066400000000000000000000011011312655740700223330ustar00rootroot00000000000000import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class ValExample { public String example() { final ArrayList example = new ArrayList(); example.add("Hello, World!"); final String foo = example.get(0); return foo.toLowerCase(); } public void example2() { final HashMap map = new HashMap(); map.put(0, "zero"); map.put(5, "five"); for (final Map.Entry entry : map.entrySet()) { System.out.printf("%d: %s\n", entry.getKey(), entry.getValue()); } } } lombok-1.16.18/usage_examples/valExample_pre.jpage000066400000000000000000000007511312655740700221460ustar00rootroot00000000000000import java.util.ArrayList; import java.util.HashMap; import lombok.val; public class ValExample { public String example() { val example = new ArrayList(); example.add("Hello, World!"); val foo = example.get(0); return foo.toLowerCase(); } public void example2() { val map = new HashMap(); map.put(0, "zero"); map.put(5, "five"); for (val entry : map.entrySet()) { System.out.printf("%d: %s\n", entry.getKey(), entry.getValue()); } } } lombok-1.16.18/winsrc/000077500000000000000000000000001312655740700144725ustar00rootroot00000000000000lombok-1.16.18/winsrc/.gitignore000066400000000000000000000001571312655740700164650ustar00rootroot00000000000000lombok_installer_WindowsDriveInfo.o WindowsDriveInfo.dll WindowsDriveInfo-x86_64.dll WindowsDriveInfo-i386.dll lombok-1.16.18/winsrc/lombok_installer_WindowsDriveInfo.c000066400000000000000000000035611312655740700235230ustar00rootroot00000000000000/* * Copyright (C) 2009 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include #include #include #include #include "lombok_installer_WindowsDriveInfo.h" /* * Class: lombok_installer_WindowsDriveInfo * Method: getLogicalDrives0 * Signature: ()I */ JNIEXPORT jint JNICALL Java_lombok_installer_WindowsDriveInfo_getLogicalDrives0 (JNIEnv *env, jobject obj) { return GetLogicalDrives(); } /* * Class: lombok_installer_WindowsDriveInfo * Method: getDriveType * Signature: (Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_lombok_installer_WindowsDriveInfo_getDriveType (JNIEnv *env, jobject obj, jstring drive) { const char *str= (*env)->GetStringUTFChars(env, drive, 0); DWORD val = GetDriveTypeA(str); (*env)->ReleaseStringUTFChars(env, drive, str); return val; } lombok-1.16.18/winsrc/lombok_installer_WindowsDriveInfo.h000066400000000000000000000013461312655740700235270ustar00rootroot00000000000000/* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class lombok_installer_WindowsDriveInfo */ #ifndef _Included_lombok_installer_WindowsDriveInfo #define _Included_lombok_installer_WindowsDriveInfo #ifdef __cplusplus extern "C" { #endif /* * Class: lombok_installer_WindowsDriveInfo * Method: getLogicalDrives0 * Signature: ()I */ JNIEXPORT jint JNICALL Java_lombok_installer_WindowsDriveInfo_getLogicalDrives0 (JNIEnv *, jobject); /* * Class: lombok_installer_WindowsDriveInfo * Method: getDriveType * Signature: (Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_lombok_installer_WindowsDriveInfo_getDriveType (JNIEnv *, jobject, jstring); #ifdef __cplusplus } #endif #endif