diff options
author | Tor Norbye <tnorbye@google.com> | 2014-06-10 18:12:50 -0700 |
---|---|---|
committer | Tor Norbye <tnorbye@google.com> | 2014-06-10 18:12:57 -0700 |
commit | 9ea67227e8fdcf8ed37e65bb96e32767291d0f4f (patch) | |
tree | b9d56f49fde137a6098f7cec1aebeda51af705ef /java/java-impl/src/com | |
parent | c667c1f74abd96a2098520effdd5afdff7f0d34b (diff) | |
download | idea-9ea67227e8fdcf8ed37e65bb96e32767291d0f4f.tar.gz |
Snapshot idea/138.538 from git://git.jetbrains.org/idea/community.git
a18cb3f: fix CCE
d7d596e: Groovy: Remove extra spaces after deleted statements. So no extra line feed in Introduce Variable appears
25032fc: Groovy traits : abstract trait methods are not clashing
acf850e: IDEA-126013 fix SOE : maps and lists declared recursively should not fail type inference into recursion
75e06bf: clashing trait methods inspection
7ae9c94: TypesUtil.getQualifiedName(type) should return qname even if type is not resolved
beaa518: GrClassReferenceType.rawType() should return raw type even if type is not resolved
2e95615: Groovy: don't use type.getCanonicalText() to infer type qualified name since it can lead to inferring of type parameters and wasting time
08c6e63: Skipping Ant "After Compilation" task if compilation completed with errors (IDEA-125901)
1856d07: SoftWrapModelImpl refactoring. Mocking SoftWrapPainter to make tests platform-independent.
6246ee2: unlock under finally
9ab9a99: corrected 'contains' for library scopes for files from library sources
2e7fcc7: Merge remote-tracking branch 'origin/master'
5928bf7: Merge remote-tracking branch 'origin/master'
718a6a5: removed explicit virtual file inequality
08cab53: Fixed shebang formatting (PY-12775).
24be689: http://ea.jetbrains.com/browser/ea_problems/57321
bf4c84d: http://ea.jetbrains.com/browser/ea_problems/57321
65944db: Merge remote-tracking branch 'origin/master'
5106fdd: better name: reuseActivation -> reuseToolWindowActivation
e1c9f77: Merge pull request 191 from suman-ganta for IDEA-123890
b66574a: Karma auto-rerun tests shouldn't activate Run toolwindow
56409a9: Karma auto-rerun tests shouldn't activate Run toolwindow every time
880a4db: added test for SurroundWithQuotesAnnotationParameterValueFix that checks that char '\n' replaces by "\n" correctly
f6a393d: lambda: fix parameter types comparing order (IDEA-126056)
ccdc69a: method references: avoid double substitution (IDEA-126062)
e05cddc: JavaFx SceneBuilder b-14 fix
c4e8b2c: Merge remote-tracking branch 'origin/master'
879c23d: PY-13210 Unused star import in Django settings.py
a4351eb: platform: profiling actions overhauled
5ec97cf: IDEA-81568 (ignore FS events from /private unless asked explicitly)
236752e: unused library: use existing graph instead of custom dependency analysis
2a1a7c8: IDEA-126047 - Git Clouds: show commit dialog on deploy
d05243d: prefer junit/testng pattern configuration: detect multiple selection directly by context component (IDEA-126045)
27f10a6: check to prevent contradicted intersection type (IDEA-67600)
046b90c: IDEA-114252 WebStorm clipboard history conflicts with external clipboard manager (ClipMenu) Fix native hangup (steps: periodical "Paste action" update() for toolbar button during Drag&Drop in AppCode UI Designer)
885a24d: don't even schedule excluded files for update upon before contents changed events
122cd32: check for invaild file
de3bf99: optimisation: reduce instances of DirectoryScope created
e2efe2e: cleanup
000bd7a: cleanup
68a5b6e: performance
732238f: performance
2f08301: check for type param numbers in java 1.6 should not rise error if super methods have type params (IDEA-57338)
598f921: testdata for IDEA-61415
6deb5bb: testdata for IDEA-65473
9853fb6: suspicious removeAll: compare type arguments, not qualifiers
1dc83a9: Added ability to pass command-line args to Gradle on project sync/refresh.
e61c327: fix binary compatibility
ef92f2f: fix binary compatibility
40875a7: fix binary compatibility
79d53fd: IDEA-118400 Update Project dialog redesigned, IDEA-106435 ability to perform only update, IDEA-75768 checks saved for Update dialog
d218629: Remove 'zen coding' from emmet support configurable
150b674: HTML: ignore unknown filters
2fac634: @NotNull
99d5348: Emmet CSS completion
2989429: EA-57291 (severity reduced as the real reason is logged earlier)
491dc5f: contract inference initial
bc12a14: extract contract checking to a separatate inspection
75c4257: MethodContract.createConstraintArray
109906e: WEB-12316 PhpStorm performing awful when typing in HTML zones in PHP files
91b7c69: check file on updateExecutionPoint
1591844: WEB-11678 JavaScript debug: step into and step over do not change the line
ec43ad0: Merge remote-tracking branch 'origin/master'
e58ce76: try unnecessary module dependencies to support exported dependencies
a9c8a08: IDEA-125568 (possible NPE in some test setup paths fixed)
2fdb004: Merge remote-tracking branch 'origin/master'
39cc27d: suggest to restart IDEA if user accepted to enable/disable plugins from startup notification (IDEA-121369)
693bbf6: encapsulate fields: preserve comments inside (IDEA-124747)
fcaa3e2: add java specific debugger settings into common settings node
1a3c6c6: code cleanup optimization: run inspections over exactly one element
4c3bda0: Get rid of direct "dispose" call
539f90a: WI-23626 Breakpoint muting does not disable after run. Regression from 7.1.3 to EAP 8.
ffcf607: junit: accept custom matcher descriptions (IDEA-125942)
de7387f: provide remove assignment fix for silly assignment inspection (IDEA-125993)
54e38ee: IDEA-121664 Search Everywhere: results from different categories appear mixed
99adcfd: EA-55292 (NPE fixed)
a87bf9b: Unneeded exception dropped
128b05b: Merge remote-tracking branch 'origin/master'
abc4ba7: GWT builder: test added
f76fea5: test added
30fe2c4: invoke 'save' after 'mark root' action to update iml files immediately
9f6fa54: registering output-to-buildTarget mapping instead of output-to-source mapping to address cases when multiple sources compile into the same output (e.g. Kotlin)
f06f5a6: Handle '@' symbol in ssh username
c142a3c: OC-9609 [Refactoring: common approach for Non-DumbAware mode in folding] +review CR-OC-1561
e4dbc27: fix problem with extending sorted set by one and attempting to increase random access capacity in case of value removal
aa0e217: use more detailed path to file only when opened file name is not unique (IDEA-125958)
fe72975: Marking DuplicateIndex as PsiDependentIndex to attempt to avoid problems with unsaved document indexing being asynchronously committed (EA-36001)
22db3a8: get rid of RowSorters to fix a few exceptions. New Plugin UI has its own table header without swing's row sorters
e5541c8: deprecation inspection uses default serialization
24077b1: push 'change method return type' fix down when variable is checked
65ec59f: icon decoration for external annotations (IDEA-39633)
8f10d71: option to warn about members in deprecated classes (IDEA-112084)
27ec65a: optimize imports under progress (IDEA-125761)
14d3780: Cleanup (formatting)
e5fcad3: revert (java: minor optimization)
f8e2be2: do not recreate breakpoint highlighter if not requested implicitly, this fixes jumping breakpoints on several quick line insertions
44fc624: sql: better varchar and varchar2 completion
b5d09fe: getEqualityObject() fixed for JS debugger
dc3bd73: call applyInformation for all EditorBoundPass for each editor
47336a6: cleanup
67c4e4b: calculate default inspection name by trimming Inspection or InspectionBase
4a0d396: notnull
a3f3988: cleanup
c8337a2: cleanup
8ad9eb1: moved long-running tests into performance suite
395ae29: expand javadoc on PSI validity
48c2fc4: special PIEAE handling for NULL_PSI_ELEMENT (its getUserData throws exceptions)
f3fe82e: IDEA-114252 WebStorm clipboard history conflicts with external clipboard manager (ClipMenu)
3d7f7d2: IDEA-125820 DOM Generator: problem with XML element names matching default/generated imports CR-IC-5549
eadc889: build initial foldings in background (improvements as per CR-IC-5531)
350760c: rename: detect "field would hide local" conflict (IDEA-125934)
0de6aa9: move: do not convert classes to files before move
35005bc: IDEA-125947 not initialized final field should not be raised on any refs from inner classes
62f7acd: plugins: take into account already installed plugins during dependencies check (IDEA-123767)
a673a47: softReference to cache known plugin extensions
3995088: update info: link to the product home page (IDEA-124023)
aa9a7b1: move: filter out nested dirs/files on actionPerformed, update should be fast (IDEA-111413)
e887cc3: Merge remote-tracking branch 'origin/master'
24c1fab: fix thread crash in debug console after syntax error (PY-12600)
49b602b: java: minor optimization
f5f8124: java: helper method for Kotlin
e674dd1: fixed PY-13177 PyCharm hangs on adding incorrect interpreter (python3-pyinotify)
5c41c76: Maven: manifest generation fixes - use ApplicationNamesInfo#getFullProductName for "Created-By" attribute value, redundant code removed
d2752f1: invalidNames is a bit confusing, let's use existingNames; also small cleanup
7b282c4: lots of EA-57109 - PIEAE: LeafPsiElement.invalid. attempt 2.
cf78c48: External System + Gradle: support for running a task before launch of another configuration added. Related issue for Gradle: IDEA-113437 'Before Launch' should support running a Gradle task
6396cd8: IDEA-125900 (resolve of synthetic enum methods in class files fixed)
bb35b26: Cleanup (cached value manager instead of boilerplate)
6f417af: reuse LocalQuickFix because several instances can be handled badly
c44d318: IDEA-104484 Console ExceptionFilters are added twice for debugging java app
e67157d: IDEA-125470 While in editor, wild re-displaying occurs when soft wraps are enabled
2de7658: folding model implementation cleanup
c7a1fbb: fixed NPE in debuggers that do not use value markers
159a46b: JavaRearranger: fixed field caching in case of multiple classes in java file (IDEA-123733)
b3f67525: Added scope and file mask filter to reformat directory/project/module dialogs (IDEA-59850) [CR-IC-5534]
c3a1eb8: Merge remote-tracking branch 'origin/master'
9d5429e: remove variable: do not leave tailing loops/ifs (IDEA-124489)
d6c14fb: Delete LightLexerTestCase
83abbd0: fixing OOME in tests
fd0acc2: temp disable 6520348e0292c4bb47389cb12926dc83826796e7
22c687d: Merge remote-tracking branch 'origin/master'
9102909: use goto.nonProjectScopeDisabler EP to show/hide 'include non-project files' checkbox
0dca1c3: use goto.nonProjectScopeDisabler EP to show/hide non-project items checkbox
def9b6f: EP to disable using Non-project scope for IDEs where this doesn't make sence
6520348: lots of EA-57109 - PIEAE: LeafPsiElement.invalid
1ecc94f: don't set Darcula UI in search text field if it's already set
2357251: rollback NPE fix (found the real problem)
f52fccd: Cleanup (optimization; formatting)
5d85b2b: spped search by value in debugger trees
7e5f8a2: fixed VM leak in debugger tree listener
8771d61: fixed VM leak in object marks
b9abbfb: template ConstructorInsertHandler test (IDEA-101429)
6713978: start type template if at least object was inferred
8540bac: RefCountHolder: allow referenced files' ast to be gc-ed during highlighting
716aa5a: generate name for save scheme dialog
c86e3af: external annotation change should drop all psi cachedValues
ae0bd0f: cleanup
26af3f5: implement equals and hashCode to make two LocalQuickFix instances equal if they refer to one and the same IntentionAction
0ade045: IDEA-125645 On breakpoint hit, opens file in new tab in "active" split -- even if file is already open in tab in "inactive" split
1881ceb: test — auto expressions: filter out expression contained unresolved local variable
3677585: IDEA-103523 MethodMayBeStaticInspection replace qualified usages by class name (reused MakeMethodStaticProcessor)
89905f6: don't hold reference to PsiFile
83bc4af: move AddSpaceInsertHandler.java to lang-impl
769a599: WEB-12348 Quick fixes not always working in Inspection window
18b220c: IDEA-90008 (editor files are refreshed elsewhere, no need to watch)
894818e: Cleanup (deprecated code dropped)
aba3f2f: CreateSwitchIntention removed all operations with Document to exclude possible problems
4c6818a: removed from IdeaPlugin SurroundWithQoutesIntention
044671d: Merge remote-tracking branch 'origin/master'
a109c22: IDEA-121370 Failed Gradle task doesn't block the dependent run configurations
fbf4eb5: Merge remote-tracking branch 'origin/master'
89f5018: imports optimized
baa6389: SurroundWithQuotesAnnotationParameter: intention replaced by quick fix to the corresponding error
5f7a426: no later runnable for anonymous class creation template
05d13a3: Get rid of needless filtering
a8660f4: use "OS user" term
cb71334: fix NPE on linux
930235e: notnull and remove unused field
c7cd901: notnull
83d5484: Color & Fonts panel: generate new name when copy
6cc553f: cleanup
fa4e0deb: remove unused class
e291480: correct checking read-only status for CreateSwitchIntention
cdd07a4: CreateSwitchIntention checks language level and that file is witable
11adc57: Cleanup (warning; unneeded reflection)
b6b5bbd: start template when anonymous class is completed with Object params (need better heuristic)
f9a561c: enable change type signature for anonymous classes
d645cf9: optimize icon
b393a47: IDEA-125825 Surround with quotes annotation parameter value intention
f5f2f31: IDEA-99541 New run configuration type to run Ant Return back ProcessHandler.waitFor() for standard task execution (not Run Configuration)
4112da6: IDEA-125872 (avoid resetting mod. stamp)
4b93641: fix html parsing (big thanks to cdr)
0b6b37c: notnull
4ffddd7: IDEA-125829 ClassInheritorSearch should find traits
2fe5331: fix compilation
9ddfbc8: IDEA-125730 Declare explicit type: broken template should revert all its changes and move the caret back to the original position.
8f5e205: IDEA-125759 correct assert check
59aef31: IDEA-125781 ReadAction in GroovyTraitFieldSearcher
d946471: IDEA-125730 correct item order in ChooseTypeExpression
9c99488: JS debugger in Chrome: support breakpoint conditions, better support for 'log evaluated expression', non-strict column number comparison
6b9f4a4: goto related localizations for properties files
3c06c05: fixed truncated object id
ee5bba7: ResourceBundleEditor: subeditors without virtual spaces (part of IDEA-85572)
9e358f4: CR-IC-5505 (cleanup)
69b649e: Offer to launch vagrant on skeletons generation in popup balloon.
82b7f75: Merge remote-tracking branch 'origin/master'
86ada28: Don't show modal dialog about vagrant start from packages list (PY-12838).
af40fe8: DataPointHolderConversionIntention not supports fields without initializer for conflicts escapings
0455ae8: NPE
02ca2bd: PsiBundle: fix typo in bundle name, cleanup
cc8d259: don't cache language level in JavaDirectoryService
60cbfb0: allow to create java classes named pkg.Class (IDEA-125442, CR-IC-5537)
b673277: ensure canonical module order in CE modules.xml
1388cfb: BaseElementAtCaretIntentionAction extends BaseElementAtCaretIntentionAction
a777074: IDEA-125558 new debugger: double result in evaluate expression - updated fix
add5377: reverted fix for IDEA-125558
5ad334b: AddJavadocIntention moved to "Declaration" category
b4f899b: notnull
dd53334: allow com.intellij.openapi.roots.impl.ModuleRootManagerImpl#getFileIndex to work in upsource
a28c2f4: register ExternalResourceManagerExImpl
9aa5346: EA-53941 - assert: FileManagerImpl.getCachedPsiFile
3b946e3: Merge remote-tracking branch 'origin/master'
62eeced: show notification if power save mode is on on startup (IDEA-125847)
d13982b: most specific: do not start java 8 algorithm for provided type args (IDEA-125855)
12a99d8: virtual array by selection rule (IDEA-125862)
610b0ba: IDEA-125820 DOM Generator: problem with XML element names matching default/generated imports
80199b4: DBE-19 0xDBE: edit description at Settings / Passwords
85c5cf1: Merge remote-tracking branch 'origin/master'
3efe19e: added help id for evaluate dialog
8456e04: IDEA-123787 "No live templates selected" label in multiple selection
9ce90b8: IDEA-124362 No scrollbar in Settings | Code Style | General
c04939b: auto expressions: don't compute for nested values
56917b3: make it by default and look at the performance
f30498b: Merge remote-tracking branch 'origin/master'
adae926: Don't ask to start Vagrant in a modal dialog on skeleton generation (PY-12838).
1315295: watches in tasks
57f4bbf: IDEA-125462 Unable to execute simple platform test with IDEA Ultimate Plugin SDK
9a56986: do not evaluate values twice
b7b995b: IDEA-54137 All alarms in RBE deleted. Save to file on focus change
c3b697a: IDEA-39879 Background color and gutter stripe color for bookmarks should be configurable
b893466: close editors only
08d3b73: NPE fixed
37cb86b6: fixed Color object icon renderer
a1ecb55: fixed switching multiple suspended threads in java
0c7e893: correctly load old enabled state of debugger expressions
6847fc3: IDEA-119364 (not introduces case statements for enum)
673d730: wrong shortcut suggested in goto test popup (IDEA-125857)
6a73a71: IDEA-108141 reused code of FixDocCommentAction
d03289c: IDEA-85274 Tasks: the detached editors are not affected by context change
a375d1e: java: correct stub for enums compiled by Groovy
c4edd41: aware of debugger communication error on break event
fd6ccfc: IDEA-125678 ConvertInterfaceToClassIntention.moveExtendsToImplements improved
0b0873d: IDEA-58422 implemented in IPP
ef6b09a: more possible reasons for non-physical file invalidation
745c9b0: IDEA-68916 "Zoom" for Mac OS
5372371: cleanup
c1810c1: cleanup
24cc395: Merge remote-tracking branch 'origin/master'
fd72f3e: javac 6 workaround (from IDEA-16723)
19af1ec: refactoring (following CR-IC-5531)
784512b: enum constants access inside enum constant initializers fixed (IDEA-125816)
b1b3b1d: accept intersection types in foreach stmts (IDEA-125800)
f1d927b: Mac: add app-title if project-title is empty
08f4caf: fix sorting
4559c7f: IDEA-123189 Project wizard: tree entries text cutoff
90bd11d: javadoc
6a6fa53: cleanup
b8be4e2: IDEA-125805 (language level increase quickfix for switch on enum/string)
75a492a: Cleanup (less repeated checks; less parameter pinballing)
b159632: testdata for IDEA-57388
656ce72: testdata for IDEA-67578
88a9ace: old inference: take only EQUALS bounds from sibling param (IDEA-119757)
dc3b3a9: try 'generate missed tests' without names check (IDEA-125818)
1dfcabe: javadoc fix
9b09325: moved to psi, register more services
f3cc359: register find usage providers
a0f8840: moved to psi
25fe38e: javadoc fix
6f7574c: dfa: invalid type diagnostics (IDEA-125179)
c9dff24: don't advertise Quick Definition when completion doesn't contain psi items (IDEA-87208)
43c06cfc: always use forward slashes in copy reference (IDEA-125292)
3dd0451: IDEA-125442 Strip .java from classname when creating new class
571196f: IDEA-125749 Create New Class Dialog - Pressing 'e' in Kind selects 'Interface' instead of 'Enum'
7a71a4d: External system: code cleanup
a635296: fix popup width jumping
9ea2438: IDEA-125609 - Built-in Git SSH executable ignores IDEA http proxy settings
f894389: IDEA-122962 - Clouds: perform connection test in background - auto-reload in CloudFoundry run configuration
494fbfe: renamed and more factories
309e1b1: provide empty quick fix factories for upsource
b78b8d0: initialize and register stub serializers
da59ab8: IDEA-125498 Search Everywhere: sometimes after navigation the list of search results reappears in the left corner of the screen
6549903: External System: IDEA-123031 Import sources and docs for module level libraries
b8d02c9: isValid
c59fbba: Reimplement parameter info test
50e11e6: fixed PY-13150 Pyramid run configuration fails when specifing '--reload' in additional option
320ecac: IDEA-39879 Background color and gutter stripe color for bookmarks should be configurable
ab780e0: WEB-12346 Watches pane: Adding/removing variable not possible when dragged out
4cdca43: Merge remote-tracking branch 'origin/master'
347094c: Merge remote-tracking branch 'origin/master'
b75e6ed: fixed tests
ae2b6c6: testdata fixed
37b352f: changelist preselection for file fixed and refactored
982e039: fix rendering issues
4dbfccf: registry ui improvements
16ce85a: notnull
4568663: IDEA-114011 Github: work with HTTP, not only with HTTPS
8cb550e: ExternalResourceManagerImpl inlined, moved to psi
ecff152: moved to core
2ff189c: removed "new in" which are not that new anymore
8787917: toString
6afd4f4: build initial foldings in background
9a121b2: EA-57104 - assert: PsiFileImpl.navigate
1080da4: IDEA-77640 Warn if the current subscription license will not work with the new version in the Update Info dialog
478fc87: test fixes and code unification
fda1430: update inspection and quickfix
287c944: OC-9609 [Java doc only] +review CR-OC-1561
71594cc: OC-9609 broken based on AST-tree folding at project opening +review CR-OC-1561
80ea2b9: better name for static method newOne -> of
b97e528: suppress contract validation for wrong Logger.assertTrue
5d8ee45: IDEA-112222 Validate @Contract annotation is related to the code
b09762d: cache properties files by bundle name and module
f25f58e: fix invalid PsiTreeUtil contract
97e0bde: remove unused VfsUtil.virtualToIFile
1f4d0df: notify BuildManager only if file events affect opened and watched projects (second part of IDEA-122685)
c503439: quickfix for IDEA-125710 (Wrong selection behavior in file history window)
5318e0e: fix assertion / comments / better transformation policy of array of changes / sorted ints into bit set
edeb5d2: testdata for IDEA-57290
b1b3964: testdata for IDEA-58692
af3e413: testdata for IDEA-24496
ae57176: provide 'place' language level for convertible check to allow types from old libraries to be casted to primitives (IDEA-117684)
2f6d5c9: testdata for IDEA-118362
f55b7ff: equality asymmetry fixed (IDEA-118533)
fdcb20b: type distinct prover asymmetry fixed (IDEA-118533)
6b5c924: suspicious collections call: process removeAll (IDEA-108755)
e9e9523: IDEA-125414 DB keys/indices to columns navigation
756b77b: accumulate index changes into array and convert it into bitset as needed
29f2788: track index info when encountering duplicated inputId
5803a5f: to Peter: addAll for emptySet doesn't work
61dbfe9: Merge remote-tracking branch 'origin/master'
95bc1fb: some more @MagicConstant
c3c31bd: EA-57052 - assert: MasterKeyPasswordSafe.decryptPassword
e761dd8: @NotNull'ed for EA-56831 - NPE: RemoteProcessSupport.release
9463bb3: Merge remote-tracking branch 'origin/master'
ff49bd1: use VirtualFile.nameSequence for isProjectOrWorkspaceFile check
248d752: restore classes merge with fix of foreach processing
fedbba7: Merge remote-tracking branch 'origin/master'
a494959: WeakReference objects used for vfile->document mapping should not stay in memory forever
8110e0b: less allocations in FileBasedIndexImpl.getUnsavedDocuments
180df2c: completion: don't suggest true/false literals where boolean is not expected
76939c8: restore query mismatch inspection
fffde12: new inference: mark erased for type params/raw types compatibility (IDEA-122932)
a2615d0: new inference: accept raw equality
67daae0: leave capture during bound composition of unbounded wildcards (IDEA-125423)
01c9bba: old inference: ignore java 1.6 bug in new versions (IDEA-125744)
b7ab465: old inference: choose child type between types in subtypes constraint (IDEA-118536)
d311a4e: perform target.findUsages() if no psi found
98302cc: IDEA-125186 Shorten reference with an import even if there is a conflicting class from Groovy default packages
d47756d: show initial value only for strings and primitive types
13986db: IDEA-125693 Creating a project in dir '~/Desktop/test' creates the project in the dir '/Applications/IntelliJ IDEA 13 CE.app/bin/test'
ae7d190: NPE when using from UML
530189b: a little bit smarter methods matching
8150b8b: IDEA-125566 Start From Scratch: can't close Customize IDEA dialog
ab7b2a0: IDEA-122962 - Clouds: perform connection test in background - auto-reload in frameworks
1a7ab39: restore (wrong) Logger.assertTrue contracts
c12b68d: dumb-aware error dropping actions
ac9d1e8: get java language level from the root model when pushers haven't finished yet
bd93483: IDEA-125565 Start from Scratch: Customize IDEA dialog: UI Themes page looks bad on Linux
6ea44e9: Gradle: use module library level for local dependencies, update library name to contain groupId
7d4dae9: IDEA-125565 Start from Scratch: Customize IDEA dialog: UI Themes page looks bad on Linux
fb173cc: IDEA-124461 New Module (Maven, Gradle) created in Empty project don't get the specified jdk
be064c3: cleanup
89dc105: show mark for a stack frame executing a method from marked object
f48b9fa: Merge remote-tracking branch 'origin/master'
c4dc543: IDEA-125745 Controls on breakpoints dialog resize differently
a105b5b: IDEA-125736 new debugger: disabled all exceptions breakpoint stops at every exception even in mute mode
5fd6a23: IDEA-124082 default changelist for Commit dialog fixed when 'commit directory' called
3a9e539: IDEA-124347 Master Password prompt strategy changed for mercurial authentication
74d52dd: introduce CvsFilePath to prevent public api changes
a489967: fix typo
f2c14b5: Start plugins wizard #30 for Mac OS X should be "native" keymap by default
a16bfe6: External-system: IDEA-124927 Don't refresh projects on opening when auto-import is disabled
78ee0a2: IDEA-125551 Start From Scratch: Customize IDEA dialog: JBoss plugin should not appear in JavaFrameworks group
e276bfa: unregistering obsolete service components
fbb0f39: jasper validation tests: fixes and cleanup
0d5f295: clean up: - replaced 2 usages isAssociated method from ValueContainer with getValueAssociationPredicate() delegation - rewrote serialization of input ids to be independent from concrete input id set implementation via usage of int iterator - inlined saveInvalidateCommand in ValueContainermpl and added comments
7321069: ad text in 'go to' actions
b57a8ca: get python language level from the root model when pushers haven't finished yet
a30a74e8: fix dfa contract believing that nullable is always null
9c29b95: fix dfa contract IOOBE with varargs
31be027: relax time in MessageBusTest.testPostingPerformanceWithLowListenerDensityInHierarchy
4955009: remove mostly non-useful Integer.valueOf completion suggestions
41b974e: anonym -> lambda: disable if target SAM type is raw and methods are called on params with Object erasure (IDEA-125613)
032faad: EIAE
2f4d4fb: register container provider
ba6e884: initialize file types
2f3db6a: UOE
73bfc96: NPE
3a8647f: reverted changes blocking inner classes in libraries to work
b66623a: do not fail position manager if assert happened in one of the providers
6dc93a1: skip binary files earlier, no need to get psi for that
91f7c25: do not scan all files when trigram index is available
7d81587: register extension points
4489140: -contributor
5fe5352: rw detector
707e584: IDEA-125649
6a28780: notnull
a7d14fe: IDEA-107588 (Mismatched query and update of collection - include Collections.addAll())
39d4dfb: fix 'as Trait' result type
b1e9f66: EA-57003 - NPE: WatchInplaceEditor.doOKAction
2d0aa2a: BlockMarkerCommentsInspection changes after review
98954e2: EA-57004 - NPE: XBreakpointManagerImpl.createBreakpointDefaults
3b09eea: fix compilation
40f7150: low priority 'create getters/setters' quickfixes
a34a01d: duplicated code
c6d539f: disable assert for Groovy clients
7459b0b: cleanup
f008f98: IDEA-125584 Groovy: NPE at org.jetbrains.plugins.groovy.annotator.intentions.CreateMethodFromUsageFix.invokeImpl
93d7ac9: IDEA-125576 Groovy: 'Create trait' could be added to 'Create From Usage'
6975411: get rid of 'public' keyword in templates
53fbe15: IDEA-125556 New Groovy class dialog contains trait option IDEA-125577 new icons for Groovy traits
90ec82d: more diagnostics for gdsl scripts
60c7d6f: EA-57072 - IOOBE: EditorImpl.offsetToLogicalLine
5801886: External-system: IDEA-124927 Don't refresh projects on opening when auto-import is disabled
2b0a1b9: One more condition for go to actions history
3ab65e6: (EA-55107) case with empty parents in history fixed
d67e9b4: IDEA-118279 create constructor params: apply cleanup
11d1e29: one test rewritten in Kotlin
9b3b90d: EA-56987 - NPE: DebuggerTreeNodeImpl.updateCaches
91005a8: added a separator above annotate action
32874b1: renamed to PropertiesPlugin.xml to avoid conflict inside upsource jar
05191a3: renamed to GroovyPlugin.xml to avoid conflict inside upsource jar
08caf4f: add to watches action should work from evaluate and inspect
d85d443: more moves to groovy-psi
fadd451: moved properties to properties-psi
b9fa2ab: register folding builder in env
ab8b582: moved to psi
c1da4f3: moved away from openapi
4bf725a: moved away from java-impl
41f2d2c: moved to core
5366e96: moved to psi
cf298fc: ensure editor is released in EDT
5b09e28: EA-57008 (pair was good enough)
1144d7b: extend java-class instead of groovy-class (to migrate to Kotlin)
3b85f7c: removing obsolete extension point
7ac28ba: remove outdated action id
53ddc21: Simplify condition in go to actions history
2807e38: rerun failed: include concrete class if containing is abstract (IDEA-125425)
9758f97: return inside finally: stop at lambda (IDEA-125605)
b90111f: more reliable keeping of reference on stack (following CR-IC-5487)
203d7fb: remove unused code
75c7630: cleanup
dc11403: cleanup
9d2b9ae: maven compiler tests to use external compiler only
ff05505: standalone jps updated: load path variables specified in gant scripts
05c2f31: history for go to actions, initial
0918150: combine two classes into one to reduce duplication
806c8d2: more accurate collection query detection for method references
19bf6b9: add "stream" and "parallelStream" query names
c0a470f: EA-57015 - SOE: AbstractTreeUi.access$
48a01b0: add common actions to all variable views
0529ff5: NPE if a previous focus owner is null.
d27fd1e: plugin updater: accept older plugin versions for broken plugins (IDEA-125646)
eeca5a8: search for package everywhere again (IDEA-125688)
04a7434: EA-56966 - IAE: XRegularValuePresentation.<init>
f1b4acc: Enabling dialog based implementation because of always on top regression.
5ef4a59: fixing java compilers configuration UI
7322427: EA-56894 - AIOOBE: AppCodeDesignerEditor.findModule - for AppCode designer module don't needed
05e2292: IDEA-125684 appearance of JTextField component in disabled state
4660916: IDEA-125500 Terminal is not locale aware
e3c14f5: following review CR-IC-5487
80a7f69: IDEA-25183
80eba2a: IDEA-42954 Watches are not saved on restart of debug sessions
d174c22: refactoring - following review #525
535844a: IDEA-104441 Wrong auto-completion of closed XML tags: handling unbalanced xml psi
220964b: BlockMarkerCommentInspection moved to java-analysis-impl
6c6a682: Shortcut Promoter initial
dff9280: IDEA-93040
622c1df: NPE
8f1d011: reverted
31d0a47: moved to analysis
a518606: moved to psi
e0d0ffd: moved to core
282862d: moved to core
1ccdeb0: more moved to psi
5d21da5: added equals to LocalsControlFlowPolicy, notnull
15ecfbd: deleting old make implementation
fa243c5: IdePlugin fixed
0427d8e: change default action
487d93d: remove useless source roots
b5fb0b6: IDEA-100200 - Clouds: deployment to clouds ignores the http proxy settings - CloudBees
cef9a6c: IDEA-71997
05b1763: deleting old make implementation
29b98db: deleting old make implementation
f723b07: Tips added (PY-12484).
de95451: Merge remote-tracking branch 'origin/master'
2d108ef: Tips updated (PY-12982).
cc4b248: java: parsing of complex bounds in stub signatures fixed
66d70ab: Cleanup (unneeded concatenation)
259d59a: added dependency from devkit module to its jps-plugin
cff9f70: JPS: added method to process modules and libraries in order
36e275f: Gradle: handling of project build classpath resolving errors related issues: http://youtrack.jetbrains.com/issue/IDEA-125592 http://youtrack.jetbrains.com/issue/IDEA-124839
6e512d0: [ review #701 ] introduce field where required to avoid multiple objects creation
98edcf4: Ruby highlighting lexer refactored for upsource core environment
bbb4d67: removed jsf-iml
c8b081a: DevKit: Goto EP declaration in plugin.xml (IDEA-86100) CR-IC-5473
c96948d: show initial value in "set value" editor
758adbb: make sure document reference is cached reliably
19cd6d5: show progress for editors opening
311406c: select only required editor in window
68aadaf: init foldings for all opened editors (otherwise saved folding state will not be restored for them)
c0511af: remove dead code
e5708cd: open editors in EDT
ffcd49d: IDEA-41226 Reference debugger-marked objects in expressions
0034f61: Merge remote-tracking branch 'origin/master'
a7e0137: externalization: suppress unused to .xml compatibility
0f8912f: enforce string copying (trim substring() result for java 6)
152503a: new exception creation without args: completely ignore exceptions with only no param constructor (IDEA-125660)
d64d714: customizations: check group is included in correct root group; allow to invoke moved action group, e.g. Create Run Configurations group (IDEA-125484)
aaa01e4: fix module leaks via CompilerTester
1551266: Added output folders to ModuleExtendedModel.
9874668: IDEA-104441 Wrong auto-completion of closed XML tags
b71fe91: simplification & cleanup postfix templates
9835800: Maven: plexus-archiver lib added to licenses
a7aa0df: lambda: extract parameters incompatibility check
0fac1ec: Merge remote-tracking branch 'origin/master'
5eeea43: PY-13084 Variables passed to url kwargs are not suggested to template
8a3ad93: hide lang-api refactoring actions if no handlers present
86d0ff8: Merge branch 'fix4' of https://github.com/krasa/intellij-community into fix4
6b46fcf: dfa: contracts validation should not exclude notnull validation
0212832: Better comments
463a90c: force check for update on exception from non-bundled plugin
4e95814: nullify: to run on pooled thread without progress
90b27a4: IDEA-122929 Hg: remove unrelated urls paths from pull/push dialog.
e2e243b: CompositeFilter#forceUseAllFilters=false by default to restore previous behaviour Deprecated public fields in Filter#Result and getters to give warning about possible danger
aa83182: Merge branch 'python-fixes'
a9aaf0c: Maven: fix artifact layouts tests for added generated manifest.mf
a1d93e0: Use union of types of members as iteration type for tuples
06a130f: Interpret tuple default parameter value as a weak type (PY-10967)
24b18f8: IDEA-119804 second click on item in watches panel should toggle edit mode
a479d46: IDEA-81789 Expression Evaluation goes crazy when multiline expression is inserted
3f1d913: Merge remote-tracking branch 'origin/master'
1b010d0: PY-12981 django apps don't resolve when INSTALLED_APPS is set with '+='
846b42a: Nullity annotations and explicit TypeEvalContext for PyUnionType.excludeNull()
5352177: IDEA-97915 Mercurial incoming/outgoing widgets updated
e618345: EA-51820 check that root from mappings is a valid vcs root
2f5f8f9: IDEA-122562 - Warning from SettingsEditor#applyEditorTo prevents runconfig editor from closing
12272ec: cosmetic: "Remember on disk" -> "Save on disk" in all places
ef5ae1c: ensure rename is performed inside project only, do not search for a package inside libraries!
0dd4ead: generate missed tests intention (IDEA-90247; IDEA-122790)
8ee7f6d: ignore setup/teardown generation when methods already exist and additional methods are not expected
dc043ce: IDEA-121972 - Map help button of the Clouds page
71f507b: Cleanup
2322568: Don't suggest Python live templates inside parameter list (PY-12395)
9b96bc0: common style for expressions
f9685fd: Don't suggest Python live templates in string literals (PY-12349)
a554bba: Don't suggest Python live templates in comments (PY-13076)
511b7db: IDEA-125624 Run tool window does not have deployments list in debug mode
73dce39: Use 'Python' context for 'super' live template (PY-13080)
8e0bbd5: cover with tests
ce036b5: IDEA-125129 I would like to reopen IDEA-117698: regression fixed
2475299: IDEA-61480 DocBook5: complains about xlink:href in <link>
2fd7151: IDEA-125557 Start From Scratch: on Darcula selecting as UI Theme in the Customize IDEA wisard it is applied incorrectly
fa9f7fe: Fixed messy usage of colons in the Breakpoints window
6b7841e: format
f3c2fa2: IDEA-117949 Xml editor doesn't treat xml namespace correctly
08c14cb: Cleanup (optimization)
298bf22: Cleanup (formatting)
c026ff3: java: missing deprecated attribute on inner classes fixed
301b5e7: java: injected methods excluded from enum stub
06f261c: Maven: artifact's manifest generation support related issues: http://youtrack.jetbrains.com/issue/IDEA-82725 http://youtrack.jetbrains.com/issue/IDEA-91497 http://youtrack.jetbrains.com/issue/IDEA-47990
1913bdc: IDEA-119640 Problem with goto declaration of XML attribute defined in XSD: re-fixed, completion fixed
ee89d4f: cleanup
560924a: Merge remote-tracking branch 'origin/master'
80dbfb5: byte code viewer in same colors as editor
7fea4ff: fix failing tests: OverrideImplementTest.testEnumConstant ImplementMethodsTest.runSingle(EnumConstantWithoutClassInitializer.java)
590e025: add example to postfix templates tree
9457946: cleanup
9307a77: better colors for ctrl + shift + a
Change-Id: I63f543234051b4bfd5588e9307dad56cdff7aa1b
Diffstat (limited to 'java/java-impl/src/com')
89 files changed, 1339 insertions, 3095 deletions
diff --git a/java/java-impl/src/com/intellij/analysis/JavaAnalysisScope.java b/java/java-impl/src/com/intellij/analysis/JavaAnalysisScope.java deleted file mode 100644 index 1c49c3be174e..000000000000 --- a/java/java-impl/src/com/intellij/analysis/JavaAnalysisScope.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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. - */ - -/* - * User: anna - * Date: 14-Jan-2008 - */ -package com.intellij.analysis; - -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.PackageScope; -import com.intellij.psi.search.SearchScope; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.psi.util.FileTypeUtils; -import org.jetbrains.annotations.NotNull; - -import java.util.HashSet; -import java.util.Set; - -public class JavaAnalysisScope extends AnalysisScope { - public static final int PACKAGE = 5; - - public JavaAnalysisScope(PsiPackage pack, Module module) { - super(pack.getProject()); - myModule = module; - myElement = pack; - myType = PACKAGE; - } - - public JavaAnalysisScope(final PsiJavaFile psiFile) { - super(psiFile); - } - - @Override - @NotNull - public AnalysisScope getNarrowedComplementaryScope(@NotNull Project defaultProject) { - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(defaultProject).getFileIndex(); - final HashSet<Module> modules = new HashSet<Module>(); - if (myType == FILE) { - if (myElement instanceof PsiJavaFile && !FileTypeUtils.isInServerPageFile(myElement)) { - PsiJavaFile psiJavaFile = (PsiJavaFile)myElement; - final PsiClass[] classes = psiJavaFile.getClasses(); - boolean onlyPackLocalClasses = true; - for (final PsiClass aClass : classes) { - if (aClass.hasModifierProperty(PsiModifier.PUBLIC)) { - onlyPackLocalClasses = false; - } - } - if (onlyPackLocalClasses) { - final PsiDirectory psiDirectory = psiJavaFile.getContainingDirectory(); - if (psiDirectory != null) { - return new JavaAnalysisScope(JavaDirectoryService.getInstance().getPackage(psiDirectory), null); - } - } - } - } - else if (myType == PACKAGE) { - final PsiDirectory[] directories = ((PsiPackage)myElement).getDirectories(); - for (PsiDirectory directory : directories) { - modules.addAll(getAllInterestingModules(fileIndex, directory.getVirtualFile())); - } - return collectScopes(defaultProject, modules); - } - return super.getNarrowedComplementaryScope(defaultProject); - } - - - - @Override - public String getShortenName() { - if (myType == PACKAGE) - return AnalysisScopeBundle.message("scope.package", ((PsiPackage)myElement).getQualifiedName()); - return super.getShortenName(); - } - - @Override - public String getDisplayName() { - if (myType == PACKAGE) { - return AnalysisScopeBundle.message("scope.package", ((PsiPackage)myElement).getQualifiedName()); - } - return super.getDisplayName(); - } - - @Override - protected void initFilesSet() { - if (myType == PACKAGE) { - myFilesSet = new HashSet<VirtualFile>(); - accept(createFileSearcher()); - return; - } - super.initFilesSet(); - } - - @Override - protected void accept(@NotNull final PsiElementVisitor visitor, final boolean needReadAction) { - if (myElement instanceof PsiPackage) { - final PsiPackage pack = (PsiPackage)myElement; - final Set<PsiDirectory> dirs = new HashSet<PsiDirectory>(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ContainerUtil.addAll(dirs, pack.getDirectories(GlobalSearchScope.projectScope(myElement.getProject()))); - } - }); - for (PsiDirectory dir : dirs) { - accept(dir, visitor, needReadAction); - } - } else { - super.accept(visitor, needReadAction); - } - } - - @NotNull - @Override - public SearchScope toSearchScope() { - if (myType == PACKAGE) { - return new PackageScope((PsiPackage)myElement, true, true); - } - return super.toSearchScope(); - } -} diff --git a/java/java-impl/src/com/intellij/analysis/PackagesScopesProvider.java b/java/java-impl/src/com/intellij/analysis/PackagesScopesProvider.java deleted file mode 100644 index b1bb15cf594e..000000000000 --- a/java/java-impl/src/com/intellij/analysis/PackagesScopesProvider.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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. - */ - -/* - * User: anna - * Date: 16-Jan-2008 - */ -package com.intellij.analysis; - -import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.project.Project; -import com.intellij.psi.search.scope.ProjectProductionScope; -import com.intellij.psi.search.scope.TestsScope; -import com.intellij.psi.search.scope.packageSet.CustomScopesProviderEx; -import com.intellij.psi.search.scope.packageSet.NamedScope; -import org.jetbrains.annotations.NotNull; - -import java.util.Arrays; -import java.util.List; - -/** - * @author Konstantin Bulenkov - */ -public class PackagesScopesProvider extends CustomScopesProviderEx { - private final NamedScope myProjectProductionScope; - private final List<NamedScope> myScopes; - - public static PackagesScopesProvider getInstance(Project project) { - return Extensions.findExtension(CUSTOM_SCOPES_PROVIDER, project, PackagesScopesProvider.class); - } - - public PackagesScopesProvider() { - myProjectProductionScope = new ProjectProductionScope(); - final NamedScope projectTestScope = new TestsScope(); - myScopes = Arrays.asList(myProjectProductionScope, projectTestScope); - } - - @Override - @NotNull - public List<NamedScope> getCustomScopes() { - return myScopes; - } - - public NamedScope getProjectProductionScope() { - return myProjectProductionScope; - } -}
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java index 7ff2d6f9e4bc..08a071231410 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -938,7 +938,6 @@ public class ExpectedTypesProvider { for (CandidateInfo candidate : methodCandidates) { PsiMethod method = (PsiMethod)candidate.getElement(); PsiSubstitutor substitutor = candidate.getSubstitutor(); - assert method != null; PsiParameter[] params = method.getParameterList().getParameters(); if (params.length <= index) continue; PsiParameter param = params[index]; diff --git a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsLineMarkerProvider.java b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsLineMarkerProvider.java index ce73a96d6351..d5d927cf44fc 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsLineMarkerProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsLineMarkerProvider.java @@ -42,9 +42,7 @@ import org.jetbrains.annotations.Nullable; import java.awt.event.MouseEvent; import java.util.Collection; -import java.util.HashSet; import java.util.List; -import java.util.Set; public class ExternalAnnotationsLineMarkerProvider implements LineMarkerProvider { @Nullable @@ -81,7 +79,7 @@ public class ExternalAnnotationsLineMarkerProvider implements LineMarkerProvider return XmlStringUtil.wrapInHtml(JavaDocInfoGenerator.generateSignature(owner)); } }; - return new LineMarkerInfo<PsiModifierListOwner>(owner, owner.getTextOffset(), AllIcons.Nodes.Annotationtype, + return new LineMarkerInfo<PsiModifierListOwner>(owner, owner.getTextOffset(), AllIcons.Gutter.ExtAnnotation, Pass.UPDATE_ALL, annotationsCollector, new MyIconGutterHandler(), GutterIconRenderer.Alignment.LEFT); diff --git a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java index 8680943f258d..81968fed0a5d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java @@ -63,6 +63,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; +import com.intellij.psi.impl.PsiModificationTrackerImpl; import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; @@ -115,10 +116,12 @@ public class ExternalAnnotationsManagerImpl extends ReadableExternalAnnotationsM private void notifyAfterAnnotationChanging(@NotNull PsiModifierListOwner owner, @NotNull String annotationFQName, boolean successful) { myBus.syncPublisher(TOPIC).afterExternalAnnotationChanging(owner, annotationFQName, successful); + ((PsiModificationTrackerImpl)myPsiManager.getModificationTracker()).incCounter(); } private void notifyChangedExternally() { myBus.syncPublisher(TOPIC).externalAnnotationsChangedExternally(); + ((PsiModificationTrackerImpl)myPsiManager.getModificationTracker()).incCounter(); } @Override diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java b/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java index 2b3ef76b6957..311e8bd590a1 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java @@ -3,16 +3,21 @@ package com.intellij.codeInsight.completion; import com.intellij.codeInsight.ExpectedTypeInfo; import com.intellij.codeInsight.ExpectedTypesProvider; import com.intellij.codeInsight.generation.GenerateMembersUtil; +import com.intellij.codeInsight.generation.OverrideImplementExploreUtil; import com.intellij.codeInsight.generation.OverrideImplementUtil; import com.intellij.codeInsight.generation.PsiGenerationInfo; +import com.intellij.codeInsight.intention.impl.TypeExpression; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupElementDecorator; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.codeInsight.lookup.PsiTypeLookupItem; +import com.intellij.codeInsight.template.*; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.application.Result; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; @@ -25,6 +30,7 @@ import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -241,17 +247,28 @@ public class ConstructorInsertHandler implements InsertHandler<LookupElementDeco editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); + final PsiReferenceParameterList parameterList = parent.getBaseClassReference().getParameterList(); + final PsiTypeElement[] parameters = parameterList != null ? parameterList.getTypeParameterElements() : null; + if (shouldStartTypeTemplate(parameters)) { + startTemplate(parent, editor, createOverrideRunnable(editor, file, project), parameters); + return null; + } + + return createOverrideRunnable(editor, file, project); + } + + private static Runnable createOverrideRunnable(final Editor editor, final PsiFile file, final Project project) { return new Runnable() { @Override - public void run(){ + public void run() { + PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); + final PsiAnonymousClass + aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false); + if (aClass == null) return; CommandProcessor.getInstance().executeCommand(project, new Runnable() { @Override public void run() { - PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); - final PsiAnonymousClass aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false); - if (aClass == null) return; - - final Collection<CandidateInfo> candidatesToImplement = OverrideImplementUtil.getMethodsToOverrideImplement(aClass, true); + final Collection<CandidateInfo> candidatesToImplement = OverrideImplementExploreUtil.getMethodsToOverrideImplement(aClass, true); for (Iterator<CandidateInfo> iterator = candidatesToImplement.iterator(); iterator.hasNext(); ) { final CandidateInfo candidate = iterator.next(); final PsiElement element = candidate.getElement(); @@ -260,29 +277,70 @@ public class ConstructorInsertHandler implements InsertHandler<LookupElementDeco } } boolean invokeOverride = candidatesToImplement.isEmpty(); - if (invokeOverride){ + if (invokeOverride) { OverrideImplementUtil.chooseAndOverrideOrImplementMethods(project, editor, aClass, false); } - else{ + else { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { - try{ + try { List<PsiMethod> methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false); List<PsiGenerationInfo<PsiMethod>> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods); - List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes); + List<PsiGenerationInfo<PsiMethod>> resultMembers = + GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes); resultMembers.get(0).positionCaret(editor, true); } - catch(IncorrectOperationException ioe){ + catch (IncorrectOperationException ioe) { LOG.error(ioe); } } }); } - } - }, CompletionBundle.message("completion.smart.type.generate.anonymous.body"), null, UndoConfirmationPolicy.DEFAULT, editor.getDocument()); + }, getCommandName(), getCommandName(), UndoConfirmationPolicy.DEFAULT, editor.getDocument()); } }; } + + @Contract("null -> false") + private static boolean shouldStartTypeTemplate(PsiTypeElement[] parameters) { + if (parameters != null && parameters.length > 0) { + for (PsiTypeElement parameter : parameters) { + if (parameter.getType().equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { + return true; + } + } + } + return false; + } + + private static void startTemplate(final PsiAnonymousClass aClass, final Editor editor, final Runnable runnable, @NotNull final PsiTypeElement[] parameters) { + final Project project = aClass.getProject(); + new WriteCommandAction(project, getCommandName(), getCommandName()) { + @Override + protected void run(@NotNull Result result) throws Throwable { + PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument()); + editor.getCaretModel().moveToOffset(aClass.getTextOffset()); + final TemplateBuilderImpl templateBuilder = (TemplateBuilderImpl)TemplateBuilderFactory.getInstance().createTemplateBuilder(aClass); + for (int i = 0; i < parameters.length; i++) { + PsiTypeElement parameter = parameters[i]; + templateBuilder.replaceElement(parameter, "param" + i, new TypeExpression(project, new PsiType[]{parameter.getType()}), true); + } + Template template = templateBuilder.buildInlineTemplate(); + TemplateManager.getInstance(project).startTemplate(editor, template, false, null, new TemplateEditingAdapter() { + @Override + public void templateFinished(Template template, boolean brokenOff) { + if (!brokenOff) { + runnable.run(); + } + } + }); + } + }.execute(); + } + + private static String getCommandName() { + return CompletionBundle.message("completion.smart.type.generate.anonymous.body"); + } } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java index 036ddcbded22..5ac14956fe4c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java @@ -465,8 +465,10 @@ public class JavaCompletionData extends JavaAwareCompletionData { result.addElement(TailTypeDecorator.withTail(createKeyword(position, PsiKeyword.NEW), TailType.INSERT_SPACE)); result.addElement(createKeyword(position, PsiKeyword.NULL)); } - result.addElement(createKeyword(position, PsiKeyword.TRUE)); - result.addElement(createKeyword(position, PsiKeyword.FALSE)); + if (mayExpectBoolean(parameters)) { + result.addElement(createKeyword(position, PsiKeyword.TRUE)); + result.addElement(createKeyword(position, PsiKeyword.FALSE)); + } } PsiFile file = position.getContainingFile(); @@ -527,6 +529,14 @@ public class JavaCompletionData extends JavaAwareCompletionData { } } + private static boolean mayExpectBoolean(CompletionParameters parameters) { + for (ExpectedTypeInfo info : JavaSmartCompletionContributor.getExpectedTypes(parameters)) { + PsiType type = info.getType(); + if (type instanceof PsiClassType || type == PsiType.BOOLEAN) return true; + } + return false; + } + private static boolean isExpressionPosition(PsiElement position) { return EXPR_KEYWORDS.accepts(position) || psiElement().insideStarting(psiElement(PsiClassObjectAccessExpression.class)).accepts(position); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaGenerateMemberCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaGenerateMemberCompletionContributor.java index 144be8a5dc52..7015004b7340 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaGenerateMemberCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaGenerateMemberCompletionContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,7 +97,6 @@ public class JavaGenerateMemberCompletionContributor { private static void addSuperSignatureElements(final PsiClass parent, boolean implemented, CompletionResultSet result, Set<MethodSignature> addedSignatures) { for (CandidateInfo candidate : OverrideImplementExploreUtil.getMethodsToOverrideImplement(parent, implemented)) { PsiMethod baseMethod = (PsiMethod)candidate.getElement(); - assert baseMethod != null; PsiClass baseClass = baseMethod.getContainingClass(); PsiSubstitutor substitutor = candidate.getSubstitutor(); if (!baseMethod.isConstructor() && baseClass != null && addedSignatures.add(baseMethod.getSignature(substitutor))) { diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/proc/VariablesProcessor.java b/java/java-impl/src/com/intellij/codeInsight/completion/proc/VariablesProcessor.java deleted file mode 100644 index c05a29b5b9a2..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/completion/proc/VariablesProcessor.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * 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. - */ - -/** - * Created by IntelliJ IDEA. - * User: igork - * Date: Nov 25, 2002 - * Time: 1:44:25 PM - * To change this template use Options | File Templates. - */ -package com.intellij.codeInsight.completion.proc; - -import com.intellij.openapi.util.Key; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiModifier; -import com.intellij.psi.PsiVariable; -import com.intellij.psi.ResolveState; -import com.intellij.psi.scope.BaseScopeProcessor; -import com.intellij.psi.scope.ElementClassHint; -import com.intellij.psi.scope.JavaScopeProcessorEvent; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.List; - - -/** Simple processor to get all visible variables - * @see com.intellij.psi.scope.util.PsiScopesUtil - */ -public class VariablesProcessor - extends BaseScopeProcessor implements ElementClassHint{ - private final String myPrefix; - private boolean myStaticScopeFlag = false; - private final boolean myStaticSensitiveFlag; - private final List<PsiVariable> myResultList; - - /** Collecting _all_ variables in scope */ - public VariablesProcessor(String _prefix, boolean staticSensitiveFlag){ - this(_prefix, staticSensitiveFlag, new ArrayList<PsiVariable>()); - } - - /** Collecting _all_ variables in scope */ - public VariablesProcessor(String _prefix, boolean staticSensitiveFlag, List<PsiVariable> lst){ - myPrefix = _prefix; - myStaticSensitiveFlag = staticSensitiveFlag; - myResultList = lst; - } - - @Override - public boolean shouldProcess(DeclarationKind kind) { - return kind == DeclarationKind.VARIABLE || kind == DeclarationKind.FIELD || kind == DeclarationKind.ENUM_CONST; - } - - /** Always return true since we wanna get all vars in scope */ - @Override - public boolean execute(@NotNull PsiElement pe, @NotNull ResolveState state){ - if(pe instanceof PsiVariable){ - final PsiVariable pvar = (PsiVariable)pe; - final String pvar_name = pvar.getName(); - if(pvar_name.startsWith(myPrefix)){ - if(!myStaticSensitiveFlag || (!myStaticScopeFlag || pvar.hasModifierProperty(PsiModifier.STATIC))){ - myResultList.add(pvar); - } - } - } - - return true; - } - - @Override - public final void handleEvent(@NotNull Event event, Object associated){ - if(event == JavaScopeProcessorEvent.START_STATIC) - myStaticScopeFlag = true; - } - - /** sometimes it is important to get results as array */ - public PsiVariable[] getResultsAsArray(){ - PsiVariable[] ret = new PsiVariable[myResultList.size()]; - myResultList.toArray(ret); - return ret; - } - - @Override - public <T> T getHint(@NotNull Key<T> hintKey) { - if (hintKey == ElementClassHint.KEY) { - return (T)this; - } - - return super.getHint(hintKey); - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/scope/CompletionElement.java b/java/java-impl/src/com/intellij/codeInsight/completion/scope/CompletionElement.java deleted file mode 100644 index a6f3e94dbc09..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/completion/scope/CompletionElement.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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 com.intellij.codeInsight.completion.scope; - -import com.intellij.psi.*; -import org.jetbrains.annotations.Nullable; - -/** - * Created by IntelliJ IDEA. - * User: ik - * Date: 20.01.2003 - * Time: 16:17:14 - * To change this template use Options | File Templates. - */ -public class CompletionElement{ - private final Object myElement; - private final PsiSubstitutor mySubstitutor; - - public CompletionElement(Object element, PsiSubstitutor substitutor) { - myElement = element; - mySubstitutor = substitutor; - } - - public PsiSubstitutor getSubstitutor(){ - return mySubstitutor; - } - - public Object getElement(){ - return myElement; - } - - @Nullable - Object getUniqueId(){ - if(myElement instanceof PsiClass){ - return ((PsiClass)myElement).getQualifiedName(); - } - if(myElement instanceof PsiPackage){ - return ((PsiPackage)myElement).getQualifiedName(); - } - if(myElement instanceof PsiMethod){ - return ((PsiMethod)myElement).getSignature(mySubstitutor); - } - if (myElement instanceof PsiVariable) { - return getVariableUniqueId((PsiVariable)myElement); - } - - return null; - } - - public static String getVariableUniqueId(final PsiVariable variable) { - return "#" + variable.getName(); - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java b/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java deleted file mode 100644 index 58e6fafa38c8..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * 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. - */ - -/* - * User: anna - * Date: 21-Feb-2008 - */ -package com.intellij.codeInsight.daemon; - -import com.intellij.codeInspection.ModifiableModel; -import com.intellij.codeInspection.ex.InspectionToolWrapper; -import com.intellij.codeInspection.javaDoc.JavaDocLocalInspection; -import com.intellij.codeInspection.javaDoc.JavaDocLocalInspectionBase; -import com.intellij.profile.codeInspection.InspectionProfileManager; -import org.jdom.Element; -import org.jetbrains.annotations.NonNls; - -public class JavaAwareInspectionProfileCoverter extends InspectionProfileConvertor{ - private String myAdditionalJavadocTags; - @NonNls private static final String ADDITONAL_JAVADOC_TAGS_OPTION = "ADDITIONAL_JAVADOC_TAGS"; - - public JavaAwareInspectionProfileCoverter(InspectionProfileManager manager) { - super(manager); - } - - @Override - protected boolean processElement(final Element option, final String name) { - if (super.processElement(option, name)) { - return true; - } - if (name.equals(ADDITONAL_JAVADOC_TAGS_OPTION)) { - myAdditionalJavadocTags = option.getAttributeValue(VALUE_ATT); - return true; - } - return false; - } - - @Override - protected void fillErrorLevels(final ModifiableModel profile) { - super.fillErrorLevels(profile); - - //javadoc attributes - final InspectionToolWrapper toolWrapper = profile.getInspectionTool(JavaDocLocalInspectionBase.SHORT_NAME, null); - JavaDocLocalInspection inspection = (JavaDocLocalInspection)toolWrapper.getTool(); - inspection.myAdditionalJavadocTags = myAdditionalJavadocTags; - } -}
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/JavaProblemHighlightFilter.java b/java/java-impl/src/com/intellij/codeInsight/daemon/JavaProblemHighlightFilter.java deleted file mode 100644 index 956de9369369..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/JavaProblemHighlightFilter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * 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 com.intellij.codeInsight.daemon; - -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.roots.JavaProjectRootsUtil; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiFile; -import org.jetbrains.annotations.NotNull; - - -public class JavaProblemHighlightFilter extends ProblemHighlightFilter { - @Override - public boolean shouldHighlight(@NotNull PsiFile psiFile) { - return psiFile.getFileType() != StdFileTypes.JAVA || !JavaProjectRootsUtil.isOutsideJavaSourceRoot(psiFile); - } - - @Override - public boolean shouldProcessInBatch(@NotNull PsiFile psiFile) { - final boolean shouldHighlight = shouldHighlightFile(psiFile); - if (shouldHighlight) { - if (psiFile.getFileType() == StdFileTypes.JAVA) { - final VirtualFile virtualFile = psiFile.getVirtualFile(); - if (virtualFile != null && ProjectRootManager.getInstance(psiFile.getProject()).getFileIndex().isInLibrarySource(virtualFile)) { - return false; - } - } - } - return shouldHighlight; - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/GutterIconTooltipHelper.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/GutterIconTooltipHelper.java deleted file mode 100644 index d539559efc25..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/GutterIconTooltipHelper.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * 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. - */ - -/* - * @author max - */ -package com.intellij.codeInsight.daemon.impl; - -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.presentation.java.ClassPresentationUtil; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; - -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.Set; - -public class GutterIconTooltipHelper { - private GutterIconTooltipHelper() { - } - - public static String composeText(@NotNull PsiElement[] elements, String start, final String pattern) { - return composeText(Arrays.asList(elements), start, pattern); - } - - public static String composeText(@NotNull Iterable<? extends PsiElement> elements, String start, final String pattern) { - @NonNls StringBuilder result = new StringBuilder(); - result.append("<html><body>"); - result.append(start); - Set<String> names = new LinkedHashSet<String>(); - for (PsiElement element : elements) { - String descr = ""; - if (element instanceof PsiClass) { - String className = ClassPresentationUtil.getNameForClass((PsiClass)element, true); - descr = MessageFormat.format(pattern, className); - } - else if (element instanceof PsiMethod) { - String methodName = ((PsiMethod)element).getName(); - PsiClass aClass = ((PsiMethod)element).getContainingClass(); - String className = aClass == null ? "" : ClassPresentationUtil.getNameForClass(aClass, true); - descr = MessageFormat.format(pattern, methodName, className); - } - else if (element instanceof PsiFile) { - descr = MessageFormat.format(pattern, ((PsiFile)element).getName()); - } - names.add(descr); - } - - @NonNls String sep = ""; - for (String name : names) { - result.append(sep); - sep = "<br>"; - result.append(name); - } - - result.append("</body></html>"); - return result.toString(); - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaChangeLocalityDetector.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaChangeLocalityDetector.java deleted file mode 100644 index 4f5557486e2b..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaChangeLocalityDetector.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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. - */ - -/* - * @author max - */ -package com.intellij.codeInsight.daemon.impl; - -import com.intellij.codeInsight.daemon.ChangeLocalityDetector; -import com.intellij.psi.*; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class JavaChangeLocalityDetector implements ChangeLocalityDetector { - @Override - @Nullable - public PsiElement getChangeHighlightingDirtyScopeFor(@NotNull final PsiElement element) { - // optimization - PsiElement parent = element.getParent(); - PsiElement grand; - if (element instanceof PsiCodeBlock - && parent instanceof PsiMethod - && !((PsiMethod)parent).isConstructor() - && (grand = parent.getParent()) instanceof PsiClass - && !(grand instanceof PsiAnonymousClass)) { - // for changes inside method, rehighlight codeblock only - // do not use this optimization for constructors and class initializers - to update non-initialized fields - return parent; - } - return null; - } -}
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaDocAnnotator.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaDocAnnotator.java deleted file mode 100644 index 82c9080b9b9b..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaDocAnnotator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * 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 com.intellij.codeInsight.daemon.impl; - -import com.intellij.lang.annotation.Annotation; -import com.intellij.lang.annotation.AnnotationHolder; -import com.intellij.lang.annotation.Annotator; -import com.intellij.openapi.editor.colors.CodeInsightColors; -import com.intellij.psi.PsiElement; -import com.intellij.psi.javadoc.PsiDocTag; -import com.intellij.psi.javadoc.PsiDocTagValue; -import org.jetbrains.annotations.NotNull; - -/** - * @author Dmitry Avdeev - * Date: 11/8/11 - */ -public class JavaDocAnnotator implements Annotator { - @Override - public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { - if (element instanceof PsiDocTag) { - String name = ((PsiDocTag)element).getName(); - if ("param".equals(name)) { - PsiDocTagValue tagValue = ((PsiDocTag)element).getValueElement(); - if (tagValue != null) { - Annotation annotation = holder.createInfoAnnotation(tagValue, null); - annotation.setTextAttributes(CodeInsightColors.DOC_COMMENT_TAG_VALUE); - } - } - } - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressWarningsFoldingBuilder.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressWarningsFoldingBuilder.java deleted file mode 100644 index f99abde5f685..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressWarningsFoldingBuilder.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * 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. - */ - -/* - * User: anna - * Date: 25-May-2010 - */ -package com.intellij.codeInsight.daemon.impl.actions; - -import com.intellij.codeInsight.folding.JavaCodeFoldingSettings; -import com.intellij.lang.ASTNode; -import com.intellij.lang.folding.FoldingBuilderEx; -import com.intellij.lang.folding.FoldingDescriptor; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.psi.*; -import com.intellij.psi.util.PsiUtil; -import com.intellij.util.Function; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.List; - -public class SuppressWarningsFoldingBuilder extends FoldingBuilderEx { - @NotNull - @Override - public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) { - if (!(root instanceof PsiJavaFile) || quick || !JavaCodeFoldingSettings.getInstance().isCollapseSuppressWarnings()) { - return FoldingDescriptor.EMPTY; - } - if (!PsiUtil.isLanguageLevel5OrHigher(root)) { - return FoldingDescriptor.EMPTY; - } - final List<FoldingDescriptor> result = new ArrayList<FoldingDescriptor>(); - root.accept(new JavaRecursiveElementWalkingVisitor(){ - @Override - public void visitAnnotation(PsiAnnotation annotation) { - if (Comparing.strEqual(annotation.getQualifiedName(), SuppressWarnings.class.getName())) { - result.add(new FoldingDescriptor(annotation, annotation.getTextRange())); - } - super.visitAnnotation(annotation); - } - }); - return result.toArray(new FoldingDescriptor[result.size()]); - } - - @Override - public String getPlaceholderText(@NotNull ASTNode node) { - final PsiElement element = node.getPsi(); - if (element instanceof PsiAnnotation) { - return "/" + StringUtil.join(((PsiAnnotation)element).getParameterList().getAttributes(), new Function<PsiNameValuePair, String>() { - @Override - public String fun(PsiNameValuePair value) { - return getMemberValueText(value.getValue()); - } - }, ", ") + "/"; - } - return element.getText(); - } - - private static String getMemberValueText(PsiAnnotationMemberValue memberValue) { - if (memberValue instanceof PsiArrayInitializerMemberValue) { - final PsiAnnotationMemberValue[] initializers = ((PsiArrayInitializerMemberValue)memberValue).getInitializers(); - return StringUtil.join(initializers, new Function<PsiAnnotationMemberValue, String>() { - @Override - public String fun(PsiAnnotationMemberValue psiAnnotationMemberValue) { - return getMemberValueText(psiAnnotationMemberValue); - } - }, ", "); - } - if (memberValue instanceof PsiLiteral) { - final Object o = ((PsiLiteral)memberValue).getValue(); - if (o != null) { - return o.toString(); - } - } - return memberValue != null ? memberValue.getText() : ""; - } - - - @Override - public boolean isCollapsedByDefault(@NotNull ASTNode node) { - return JavaCodeFoldingSettings.getInstance().isCollapseSuppressWarnings(); - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/JavadocErrorFilter.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/JavadocErrorFilter.java deleted file mode 100644 index 660b241d5b7f..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/JavadocErrorFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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 com.intellij.codeInsight.daemon.impl.analysis; - -import com.intellij.codeInsight.highlighting.HighlightErrorFilter; -import com.intellij.psi.PsiErrorElement; -import com.intellij.psi.javadoc.PsiDocComment; -import com.intellij.psi.util.PsiTreeUtil; -import org.jetbrains.annotations.NotNull; - -/** - * @author yole - */ -public class JavadocErrorFilter extends HighlightErrorFilter { - - @Override - public boolean shouldHighlightErrorElement(@NotNull final PsiErrorElement element) { - return !value(element); - } - - public static boolean value(final PsiErrorElement element) { - return PsiTreeUtil.getParentOfType(element, PsiDocComment.class) != null; - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMissingRequiredAnnotationParametersFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMissingRequiredAnnotationParametersFix.java new file mode 100644 index 000000000000..348fcdeda8e5 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMissingRequiredAnnotationParametersFix.java @@ -0,0 +1,163 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * 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 com.intellij.codeInsight.daemon.impl.quickfix; + +import com.intellij.codeInsight.daemon.QuickFixBundle; +import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.codeInsight.template.TemplateBuilderImpl; +import com.intellij.codeInsight.template.TemplateManager; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.psi.*; +import com.intellij.util.IncorrectOperationException; +import com.intellij.util.containers.ContainerUtil; +import com.intellij.util.containers.HashSet; +import gnu.trove.TObjectIntHashMap; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.Comparator; +import java.util.SortedSet; +import java.util.TreeSet; + +/** +* @author Dmitry Batkovich +*/ +public class AddMissingRequiredAnnotationParametersFix implements IntentionAction { + private static final Logger LOG = Logger.getInstance(AddMissingRequiredAnnotationParametersFix.class); + + private final PsiAnnotation myAnnotation; + private final PsiMethod[] myAnnotationMethods; + private final Collection<String> myMissedElements; + + public AddMissingRequiredAnnotationParametersFix(final PsiAnnotation annotation, + final PsiMethod[] annotationMethods, + final Collection<String> missedElements) { + if (missedElements.isEmpty()) { + throw new IllegalArgumentException("missedElements can't be empty"); + } + myAnnotation = annotation; + myAnnotationMethods = annotationMethods; + myMissedElements = missedElements; + } + + @NotNull + @Override + public String getText() { + return myMissedElements.size() == 1 + ? QuickFixBundle.message("add.missing.annotation.single.parameter.fix", ContainerUtil.getFirstItem(myMissedElements)) + : QuickFixBundle.message("add.missing.annotation.parameters.fix", StringUtil.join(myMissedElements, ", ")); + } + + @NotNull + @Override + public String getFamilyName() { + return QuickFixBundle.message("annotations.fix"); + } + + @Override + public boolean isAvailable(@NotNull final Project project, final Editor editor, final PsiFile file) { + return true; + } + + @Override + public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { + final PsiNameValuePair[] addedParameters = myAnnotation.getParameterList().getAttributes(); + + final TObjectIntHashMap<String> annotationsOrderMap = getAnnotationsOrderMap(); + final SortedSet<Pair<String, PsiAnnotationMemberValue>> + newParameters = new TreeSet<Pair<String, PsiAnnotationMemberValue>>(new Comparator<Pair<String, PsiAnnotationMemberValue>>() { + @Override + public int compare(final Pair<String, PsiAnnotationMemberValue> o1, final Pair<String, PsiAnnotationMemberValue> o2) { + return annotationsOrderMap.get(o1.getFirst()) - annotationsOrderMap.get(o2.getFirst()); + } + }); + final boolean order = isAlreadyAddedOrdered(annotationsOrderMap, addedParameters); + if (order) { + if (addedParameters.length != 0) { + final PsiAnnotationParameterList parameterList = myAnnotation.getParameterList(); + parameterList.deleteChildRange(addedParameters[0], addedParameters[addedParameters.length - 1]); + for (final PsiNameValuePair addedParameter : addedParameters) { + final String name = addedParameter.getName(); + final PsiAnnotationMemberValue value = addedParameter.getValue(); + if (name == null || value == null) { + LOG.error(String.format("Invalid annotation parameter name = %s, value = %s", name, value)); + continue; + } + newParameters.add(Pair.create(name, value)); + } + } + } + + final PsiExpression nullValue = JavaPsiFacade.getElementFactory(myAnnotation.getProject()).createExpressionFromText(PsiKeyword.NULL, null); + for (final String misssedParameter : myMissedElements) { + newParameters.add(Pair.<String, PsiAnnotationMemberValue>create(misssedParameter, nullValue)); + } + + TemplateBuilderImpl builder = null; + for (final Pair<String, PsiAnnotationMemberValue> newParameter : newParameters) { + final PsiAnnotationMemberValue value = + myAnnotation.setDeclaredAttributeValue(newParameter.getFirst(), newParameter.getSecond()); + if (myMissedElements.contains(newParameter.getFirst())) { + if (builder == null) { + builder = new TemplateBuilderImpl(myAnnotation.getParameterList()); + } + builder.replaceElement(value, new EmptyExpression(), true); + } + } + + editor.getCaretModel().moveToOffset(myAnnotation.getParameterList().getTextRange().getStartOffset()); + final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); + final Document document = documentManager.getDocument(file); + if (document == null) { + throw new IllegalStateException(); + } + documentManager.doPostponedOperationsAndUnblockDocument(document); + TemplateManager.getInstance(project).startTemplate(editor, builder.buildInlineTemplate(), null); + } + + @Override + public boolean startInWriteAction() { + return true; + } + + private TObjectIntHashMap<String> getAnnotationsOrderMap() { + final TObjectIntHashMap<String> map = new TObjectIntHashMap<String>(); + for (int i = 0; i < myAnnotationMethods.length; i++) { + map.put(myAnnotationMethods[i].getName(), i); + } + return map; + } + + private static boolean isAlreadyAddedOrdered(final TObjectIntHashMap<String> orderMap, final PsiNameValuePair[] addedParameters) { + if (addedParameters.length <= 1) { + return true; + } + int previousOrder = orderMap.get(addedParameters[0].getName()); + for (int i = 1; i < addedParameters.length; i++) { + final int currentOrder = orderMap.get(addedParameters[i].getName()); + if (currentOrder < previousOrder) { + return false; + } + previousOrder = currentOrder; + } + return true; + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java index f47a780b599a..14e7478ad025 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java @@ -25,6 +25,7 @@ import com.intellij.codeInsight.generation.PsiMethodMember; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.impl.AssignFieldFromParameterAction; import com.intellij.codeInsight.intention.impl.FieldFromParameterUtils; +import com.intellij.codeInspection.ex.GlobalInspectionContextBase; import com.intellij.ide.util.MemberChooser; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; @@ -123,6 +124,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { } } }); + final List<PsiElement> cleanupElements = new ArrayList<PsiElement>(); final ArrayList<PsiMethod> constrs = filterConstructorsIfFieldAlreadyAssigned(constructors, getField()); if (constrs.size() > 1) { final PsiMethodMember[] members = new PsiMethodMember[constrs.size()]; @@ -142,7 +144,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { } for (PsiMethodMember member : elements) { - if (!addParameterToConstructor(project, file, editor, member.getElement(), new PsiField[] {getField()})) break; + if (!addParameterToConstructor(project, file, editor, member.getElement(), new PsiField[] {getField()}, cleanupElements)) break; } } else if (!constrs.isEmpty()) { @@ -177,12 +179,13 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { addParameterToConstructor(project, file, editor, constructor, constrs.size() == constructors.length ? fields.toArray(new PsiField[fields.size()]) - : new PsiField[]{getField()}); + : new PsiField[]{getField()}, cleanupElements); } finally { fieldsToFix.clear(); } } + GlobalInspectionContextBase.cleanupElements(project, null, cleanupElements.toArray(new PsiElement[cleanupElements.size()])); } @NotNull @@ -231,7 +234,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { final PsiFile file, final Editor editor, final PsiMethod constructor, - final PsiField[] fields) throws IncorrectOperationException { + final PsiField[] fields, final List<PsiElement> cleanupElements) throws IncorrectOperationException { final PsiParameterList parameterList = constructor.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); ParameterInfoImpl[] newParamInfos = new ParameterInfoImpl[parameters.length + fields.length]; @@ -267,7 +270,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { return ApplicationManager.getApplication().runWriteAction(new Computable<Boolean>() { @Override public Boolean compute() { - return doCreate(project, editor, parameters, constructorPointer, resultParams, usedFields); + return doCreate(project, editor, parameters, constructorPointer, resultParams, usedFields, cleanupElements); } }); } @@ -309,7 +312,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { } private static boolean doCreate(Project project, Editor editor, PsiParameter[] parameters, SmartPsiElementPointer constructorPointer, - ParameterInfoImpl[] parameterInfos, HashMap<PsiField, String> fields) { + ParameterInfoImpl[] parameterInfos, HashMap<PsiField, String> fields, List<PsiElement> cleanupElements) { PsiMethod constructor = (PsiMethod)constructorPointer.getElement(); assert constructor != null; PsiParameter[] newParameters = constructor.getParameterList().getParameters(); @@ -324,7 +327,11 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { continue; } notNull(project, field, parameter); - AssignFieldFromParameterAction.addFieldAssignmentStatement(project, field, parameter, editor); + cleanupElements.add(parameter); + final PsiElement assignmentStatement = AssignFieldFromParameterAction.addFieldAssignmentStatement(project, field, parameter, editor); + if (assignmentStatement != null) { + cleanupElements.add(assignmentStatement); + } created = true; } } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java index a66a75855a23..c5763cc2691e 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java @@ -28,6 +28,7 @@ import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.FileTemplateUtil; import com.intellij.ide.fileTemplates.JavaTemplateUtil; +import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; @@ -135,7 +136,10 @@ public class CreateFromUsageUtils { JVMElementFactory factory = JVMElementFactories.getFactory(aClass.getLanguage(), aClass.getProject()); - LOG.assertTrue(!aClass.isInterface() || method.hasModifierProperty(PsiModifier.DEFAULT) || method.hasModifierProperty(PsiModifier.STATIC), "Interface bodies should be already set up"); + LOG.assertTrue(!aClass.isInterface() || + method.hasModifierProperty(PsiModifier.DEFAULT) || + method.hasModifierProperty(PsiModifier.STATIC) || + method.getLanguage() != JavaLanguage.INSTANCE, "Interface bodies should be already set up"); FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(template.getExtension()); Properties properties = new Properties(); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ShowModulePropertiesFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ShowModulePropertiesFix.java index 203612ee1cec..16b2c2db4831 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ShowModulePropertiesFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ShowModulePropertiesFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ package com.intellij.codeInsight.daemon.impl.quickfix; -import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.codeInspection.IntentionAndQuickFixAction; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.IdeActions; @@ -26,20 +26,23 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; -import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -public class ShowModulePropertiesFix implements IntentionAction { +public class ShowModulePropertiesFix extends IntentionAndQuickFixAction { private final String myModuleName; public ShowModulePropertiesFix(@NotNull PsiElement context) { - Module module = ModuleUtilCore.findModuleForPsiElement(context); + this(ModuleUtilCore.findModuleForPsiElement(context)); + } + + public ShowModulePropertiesFix(@Nullable Module module) { myModuleName = module == null ? null : module.getName(); } - @Override @NotNull - public String getText() { + @Override + public String getName() { AnAction action = ActionManager.getInstance().getAction(IdeActions.MODULE_SETTINGS); return action.getTemplatePresentation().getText(); } @@ -56,7 +59,7 @@ public class ShowModulePropertiesFix implements IntentionAction { } @Override - public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { + public void applyFix(@NotNull Project project, PsiFile file, @Nullable Editor editor) { ProjectSettingsService.getInstance(project).showModuleConfigurationDialog(myModuleName, null); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SurroundWithQuotesAnnotationParameterValueFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SurroundWithQuotesAnnotationParameterValueFix.java new file mode 100644 index 000000000000..0468ec844a1a --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SurroundWithQuotesAnnotationParameterValueFix.java @@ -0,0 +1,75 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * 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 com.intellij.codeInsight.daemon.impl.quickfix; + +import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.psi.*; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; + +/** + * @author Dmitry Batkovich + */ +public class SurroundWithQuotesAnnotationParameterValueFix implements IntentionAction { + private final PsiAnnotationMemberValue myValue; + private final PsiType myExpectedType; + + public SurroundWithQuotesAnnotationParameterValueFix(final PsiAnnotationMemberValue value, final PsiType expectedType) { + myValue = value; + myExpectedType = expectedType; + } + + @Override + public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { + if (!myValue.isValid() || !(myExpectedType instanceof PsiClassType)) { + return false; + } + final PsiClass resolvedType = ((PsiClassType)myExpectedType).resolve(); + return resolvedType != null && CommonClassNames.JAVA_LANG_STRING.equals(resolvedType.getQualifiedName()) && myValue instanceof PsiLiteralExpression; + } + + @Override + public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { + String newText = myValue.getText(); + newText = StringUtil.stripQuotesAroundValue(newText); + newText = "\"" + newText + "\""; + PsiElement newToken = JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText(newText, null); + final PsiElement newElement = myValue.replace(newToken); + editor.getCaretModel().moveToOffset(newElement.getTextOffset() + newElement.getTextLength()); + } + + @NotNull + @Override + public String getFamilyName() { + return "Surround annotation parameter value with quotes"; + } + + @NotNull + @Override + public String getText() { + return getFamilyName(); + } + + @Override + public boolean startInWriteAction() { + return true; + } + + +} diff --git a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java index c6cdb9822a4f..8646805b3a2f 100644 --- a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java +++ b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,9 @@ package com.intellij.codeInsight.folding.impl; import com.intellij.codeInsight.ExpectedTypeInfo; import com.intellij.codeInsight.ExpectedTypesProvider; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; -import org.jetbrains.annotations.Nullable; public class JavaFoldingBuilder extends JavaFoldingBuilderBase { @@ -42,14 +40,5 @@ public class JavaFoldingBuilder extends JavaFoldingBuilderBase { ExpectedTypeInfo[] types = ExpectedTypesProvider.getExpectedTypes(expression, false); return types.length != 1 || !types[0].getType().equals(anonymousClass.getBaseClassType()); } - - @Nullable - @Override - public TextRange getRangeToFold(PsiElement element) { - if (element instanceof SyntheticElement) { - return null; - } - return super.getRangeToFold(element); //To change body of overridden methods use File | Settings | File Templates. - } } diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java index 6b33a3b2966c..f1652470218c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java @@ -136,8 +136,7 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan } } - AnalysisScope scope = new AnalysisScope(new LocalSearchScope(elements.toArray(new PsiElement[elements.size()])), project); - GlobalInspectionContextBase.codeCleanup(project, scope, null); + GlobalInspectionContextBase.cleanupElements(project, null, elements.toArray(new PsiElement[elements.size()])); } final ArrayList<TemplateGenerationInfo> templates = new ArrayList<TemplateGenerationInfo>(); diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/AddAnnotationFix.java b/java/java-impl/src/com/intellij/codeInsight/intention/AddAnnotationFix.java deleted file mode 100644 index f8d250176717..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/intention/AddAnnotationFix.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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 com.intellij.codeInsight.intention; - -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiModifierListOwner; -import com.intellij.psi.PsiNameValuePair; -import com.intellij.util.IncorrectOperationException; -import org.jetbrains.annotations.NotNull; - -/** - * @author ven - */ -public class AddAnnotationFix extends AddAnnotationPsiFix implements IntentionAction { - public AddAnnotationFix(@NotNull String fqn, @NotNull PsiModifierListOwner modifierListOwner, @NotNull String... annotationsToRemove) { - this(fqn, modifierListOwner, PsiNameValuePair.EMPTY_ARRAY, annotationsToRemove); - } - - public AddAnnotationFix(@NotNull String fqn, - @NotNull PsiModifierListOwner modifierListOwner, - @NotNull PsiNameValuePair[] values, - @NotNull String... annotationsToRemove) { - super(fqn, modifierListOwner, values, annotationsToRemove); - } - - @Override - public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { - return isAvailable(); - } - - @Override - public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { - applyFix(); - } - - @Override - public boolean startInWriteAction() { - return true; - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddJavadocIntention.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddJavadocIntention.java new file mode 100644 index 000000000000..a26e78ac85c7 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddJavadocIntention.java @@ -0,0 +1,57 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * 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 com.intellij.codeInsight.intention.impl; + +import com.intellij.codeInsight.editorActions.FixDocCommentAction; +import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; + +/** + * @author Dmitry Batkovich + */ +public class AddJavadocIntention extends PsiElementBaseIntentionAction { + @Override + public void invoke(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) throws IncorrectOperationException { + final PsiDocCommentOwner docCommentOwner = (PsiDocCommentOwner)element.getParent(); + FixDocCommentAction.generateOrFixComment(docCommentOwner, project, editor); + } + + @Override + public boolean isAvailable(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) { + if (!(element instanceof PsiIdentifier)) { + return false; + } + final PsiElement docCommentOwner = element.getParent(); + return docCommentOwner instanceof PsiDocCommentOwner && + !(docCommentOwner instanceof PsiAnonymousClass) && ((PsiDocCommentOwner)docCommentOwner).getDocComment() == null; + } + + @NotNull + @Override + public String getFamilyName() { + return "Add Javadoc"; + } + + @NotNull + @Override + public String getText() { + return getFamilyName(); + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/AssignFieldFromParameterAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/AssignFieldFromParameterAction.java index 016d144575d4..1edb896636ab 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/AssignFieldFromParameterAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/AssignFieldFromParameterAction.java @@ -99,19 +99,19 @@ public class AssignFieldFromParameterAction extends BaseIntentionAction { return field; } - public static void addFieldAssignmentStatement(@NotNull Project project, - @NotNull PsiField field, - @NotNull PsiParameter parameter, - @NotNull Editor editor) throws IncorrectOperationException { + public static PsiElement addFieldAssignmentStatement(@NotNull Project project, + @NotNull PsiField field, + @NotNull PsiParameter parameter, + @NotNull Editor editor) throws IncorrectOperationException { final PsiMethod method = (PsiMethod)parameter.getDeclarationScope(); final PsiCodeBlock methodBody = method.getBody(); - if (methodBody == null) return; + if (methodBody == null) return null; final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); final String fieldName = field.getName(); final String parameterName = parameter.getName(); final boolean isMethodStatic = method.hasModifierProperty(PsiModifier.STATIC); final PsiClass targetClass = method.getContainingClass(); - if (targetClass == null) return; + if (targetClass == null) return null; String stmtText = fieldName + " = " + parameterName + ";"; if (Comparing.strEqual(fieldName, parameterName) || JavaPsiFacade.getInstance(project).getResolveHelper().resolveReferencedVariable(fieldName, methodBody) != field) { @@ -131,5 +131,6 @@ public class AssignFieldFromParameterAction extends BaseIntentionAction { } editor.getCaretModel().moveToOffset(inserted.getTextRange().getEndOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + return inserted; } } diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateClassDialog.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateClassDialog.java index e21f032c5d2e..a9a6d60b759a 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateClassDialog.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateClassDialog.java @@ -17,7 +17,7 @@ package com.intellij.codeInsight.intention.impl; import com.intellij.CommonBundle; import com.intellij.codeInsight.CodeInsightBundle; -import com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind; +import com.intellij.codeInsight.daemon.impl.quickfix.ClassKind; import com.intellij.ide.util.PackageUtil; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; @@ -88,7 +88,7 @@ public class CreateClassDialog extends DialogWrapper { @NotNull String title, @NotNull String targetClassName, @NotNull String targetPackageName, - @NotNull CreateClassKind kind, + @NotNull ClassKind kind, boolean classNameEditable, @Nullable Module defaultModule) { super(project, true); diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateSwitchIntention.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateSwitchIntention.java new file mode 100644 index 000000000000..e599e03f99c1 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateSwitchIntention.java @@ -0,0 +1,95 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * 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 com.intellij.codeInsight.intention.impl; + +import com.intellij.codeInsight.FileModificationService; +import com.intellij.codeInsight.intention.BaseElementAtCaretIntentionAction; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.psi.codeStyle.CodeStyleManager; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.PsiUtil; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author Dmitry Batkovich + */ +public class CreateSwitchIntention extends BaseElementAtCaretIntentionAction { + public static final String TEXT = "Create switch statement"; + + @Override + public void invoke(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) throws IncorrectOperationException { + if (!FileModificationService.getInstance().preparePsiElementsForWrite(element)) { + return; + } + final PsiExpressionStatement expressionStatement = resolveExpressionStatement(element); + final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); + PsiSwitchStatement switchStatement = (PsiSwitchStatement)elementFactory + .createStatementFromText(String.format("switch (%s) {}", expressionStatement.getExpression().getText()), null); + switchStatement = (PsiSwitchStatement)expressionStatement.replace(switchStatement); + CodeStyleManager.getInstance(project).reformat(switchStatement); + + final PsiJavaToken lBrace = switchStatement.getBody().getLBrace(); + editor.getCaretModel().moveToOffset(lBrace.getTextOffset() + lBrace.getTextLength()); + } + + @Override + public boolean isAvailable(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) { + final PsiExpressionStatement expressionStatement = resolveExpressionStatement(element); + return expressionStatement != null && isValidTypeForSwitch(expressionStatement.getExpression().getType(), expressionStatement); + } + + private static PsiExpressionStatement resolveExpressionStatement(final PsiElement element) { + if (element instanceof PsiExpressionStatement) { + return (PsiExpressionStatement)element; + } else { + final PsiStatement psiStatement = PsiTreeUtil.getParentOfType(element, PsiStatement.class); + return psiStatement instanceof PsiExpressionStatement ? (PsiExpressionStatement)psiStatement : null; + } + } + + private static boolean isValidTypeForSwitch(@Nullable final PsiType type, final PsiElement context) { + if (type == null) { + return false; + } + + if (type instanceof PsiClassType) { + final PsiClass resolvedClass = ((PsiClassType)type).resolve(); + if (resolvedClass == null) { + return false; + } + return (PsiUtil.isLanguageLevel5OrHigher(context) && resolvedClass.isEnum()) + || (PsiUtil.isLanguageLevel7OrHigher(context) && CommonClassNames.JAVA_LANG_STRING.equals(resolvedClass.getQualifiedName())); + } + return type.equals(PsiType.INT) || type.equals(PsiType.BYTE) || type.equals(PsiType.SHORT) || type.equals(PsiType.CHAR); + } + + @NotNull + @Override + public String getFamilyName() { + return TEXT; + } + + @NotNull + @Override + public String getText() { + return getFamilyName(); + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java index a66a85802d56..e934a9f387cf 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java @@ -44,6 +44,7 @@ import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; @@ -61,6 +62,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; @@ -333,9 +335,14 @@ public class QuickFixFactoryImpl extends QuickFixFactory { @NotNull @Override - public IntentionAction createShowModulePropertiesFix(@NotNull PsiElement element) { + public IntentionAndQuickFixAction createShowModulePropertiesFix(@NotNull PsiElement element) { return new ShowModulePropertiesFix(element); } + @NotNull + @Override + public IntentionAndQuickFixAction createShowModulePropertiesFix(@NotNull Module module) { + return new ShowModulePropertiesFix(module); + } @NotNull @Override @@ -740,6 +747,21 @@ public class QuickFixFactoryImpl extends QuickFixFactory { }); } + @NotNull + @Override + public IntentionAction createAddMissingRequiredAnnotationParametersFix(@NotNull final PsiAnnotation annotation, + @NotNull final PsiMethod[] annotationMethods, + @NotNull final Collection<String> missedElements) { + return new AddMissingRequiredAnnotationParametersFix(annotation, annotationMethods, missedElements); + } + + @NotNull + @Override + public IntentionAction createSurroundWithQuotesAnnotationParameterValueFix(@NotNull PsiAnnotationMemberValue value, + @NotNull PsiType expectedType) { + return new SurroundWithQuotesAnnotationParameterValueFix(value, expectedType); + } + private static boolean timeToOptimizeImports(@NotNull PsiFile file) { if (!CodeInsightSettings.getInstance().OPTIMIZE_IMPORTS_ON_THE_FLY) return false; diff --git a/java/java-impl/src/com/intellij/codeInsight/template/impl/TextExpression.java b/java/java-impl/src/com/intellij/codeInsight/template/impl/TextExpression.java deleted file mode 100644 index b9b5578b0d97..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/template/impl/TextExpression.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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 com.intellij.codeInsight.template.impl; - -import com.intellij.codeInsight.lookup.LookupElement; -import com.intellij.codeInsight.template.Expression; -import com.intellij.codeInsight.template.ExpressionContext; -import com.intellij.codeInsight.template.Result; -import com.intellij.codeInsight.template.TextResult; - -/** - * @author Maxim - */ -public class TextExpression extends Expression { - private final String myString; - - public TextExpression(String string) { myString = string; } - - @Override - public Result calculateResult(ExpressionContext expressionContext) { - return new TextResult(myString); - } - - @Override - public Result calculateQuickResult(ExpressionContext expressionContext) { - return calculateResult(expressionContext); - } - - @Override - public LookupElement[] calculateLookupItems(ExpressionContext expressionContext) { - return LookupElement.EMPTY_ARRAY; - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/AssertStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/AssertStatementPostfixTemplate.java index 90812945f7e6..0af5d4e0ce2c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/AssertStatementPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/AssertStatementPostfixTemplate.java @@ -15,20 +15,22 @@ */ package com.intellij.codeInsight.template.postfix.templates; +import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.IS_BOOLEAN; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.JAVA_PSI_INFO; -public class AssertStatementPostfixTemplate extends JavaStatementWrapPostfixTemplate { +public class AssertStatementPostfixTemplate extends StringBasedPostfixTemplate { public AssertStatementPostfixTemplate() { - super("assert", "assert expr;", JAVA_PSI_INFO, IS_BOOLEAN); + super("assert", "assert expr", JAVA_PSI_INFO, IS_BOOLEAN); } - @NotNull + @Nullable @Override - protected String getHead() { - return "assert "; + public String getTemplateString(@NotNull PsiElement element) { + return "assert $expr$;$END$"; } }
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForIndexedPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForIndexedPostfixTemplate.java index 38ea87df927f..922a8bbfec30 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForIndexedPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForIndexedPostfixTemplate.java @@ -43,22 +43,20 @@ public abstract class ForIndexedPostfixTemplate extends StringBasedPostfixTempla } @Override - public void expandWithTemplateManager(TemplateManager manager, PsiElement expression, Editor editor) { - PsiExpression expr = (PsiExpression)expression; + public void setVariables(@NotNull Template template, @NotNull PsiElement element) { + MacroCallNode index = new MacroCallNode(new SuggestVariableNameMacro()); + template.addVariable("index", index, index, true); + } + + @Override + public final String getTemplateString(@NotNull PsiElement element) { + PsiExpression expr = (PsiExpression)element; String bound = getExpressionBound(expr); if (bound == null) { - PostfixTemplatesUtils.showErrorHint(expr.getProject(), editor); - return; + return null; } - String templateWithMacro = getStringTemplate(expr).replace("$bound$", bound).replace("$type$", suggestIndexType(expr)); - - Template template = manager.createTemplate("", "", templateWithMacro); - - template.setToReformat(true); - MacroCallNode index = new MacroCallNode(new SuggestVariableNameMacro()); - template.addVariable("index", index, index, true); - manager.startTemplate(editor, template); + return getStringTemplate(expr).replace("$bound$", bound).replace("$type$", suggestIndexType(expr)); } @NotNull @@ -87,4 +85,9 @@ public abstract class ForIndexedPostfixTemplate extends StringBasedPostfixTempla } return "int"; } + + @Override + protected boolean shouldAddExpressionToContext() { + return false; + } }
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForeachPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForeachPostfixTemplate.java index 56976bec7202..5d98a01fa418 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForeachPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForeachPostfixTemplate.java @@ -16,15 +16,13 @@ package com.intellij.codeInsight.template.postfix.templates; import com.intellij.codeInsight.template.Template; -import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.MacroCallNode; -import com.intellij.codeInsight.template.impl.TextExpression; import com.intellij.codeInsight.template.impl.VariableNode; import com.intellij.codeInsight.template.macro.IterableComponentTypeMacro; import com.intellij.codeInsight.template.macro.SuggestVariableNameMacro; -import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.codeStyle.JavaCodeStyleSettingsFacade; +import org.jetbrains.annotations.NotNull; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.IS_ITERABLE_OR_ARRAY; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.JAVA_PSI_INFO; @@ -35,18 +33,17 @@ public class ForeachPostfixTemplate extends StringBasedPostfixTemplate { } @Override - public void expandWithTemplateManager(TemplateManager manager, PsiElement expression, Editor editor) { - - String finalPart = JavaCodeStyleSettingsFacade.getInstance(expression.getProject()).isGenerateFinalLocals() ? "final " : ""; - Template template = manager.createTemplate("", "", "for (" + finalPart + "$type$ $name$ : $variable$) {\n $END$\n}"); + public void setVariables(@NotNull Template template, @NotNull PsiElement element) { MacroCallNode type = new MacroCallNode(new IterableComponentTypeMacro()); MacroCallNode name = new MacroCallNode(new SuggestVariableNameMacro()); - String variable = "variable"; - type.addParameter(new VariableNode(variable, null)); + type.addParameter(new VariableNode("expr", null)); template.addVariable("type", type, type, false); template.addVariable("name", name, name, true); - template.addVariable(variable, new TextExpression(expression.getText()), false); + } - manager.startTemplate(editor, template); + @Override + public String getTemplateString(@NotNull PsiElement element) { + String finalPart = JavaCodeStyleSettingsFacade.getInstance(element.getProject()).isGenerateFinalLocals() ? "final " : ""; + return "for (" + finalPart + "$type$ $name$ : $expr$) {\n $END$\n}"; } }
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/FormatPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/FormatPostfixTemplate.java index f312d44d1d7c..0e61b454d246 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/FormatPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/FormatPostfixTemplate.java @@ -15,17 +15,17 @@ */ package com.intellij.codeInsight.template.postfix.templates; -import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.Condition; import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiType; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.JAVA_PSI_INFO; -public class FormatPostfixTemplate extends JavaStatementWrapPostfixTemplate { +public class FormatPostfixTemplate extends StringBasedPostfixTemplate { private static final Condition<PsiElement> IS_STRING = new Condition<PsiElement>() { @Override public boolean value(PsiElement expr) { @@ -39,24 +39,13 @@ public class FormatPostfixTemplate extends JavaStatementWrapPostfixTemplate { public FormatPostfixTemplate() { - super("format", "String.format(expr);", JAVA_PSI_INFO, IS_STRING); + super("format", "String.format(expr)", JAVA_PSI_INFO, IS_STRING); } - @Override - protected void afterExpand(@NotNull PsiElement newElement, @NotNull Editor editor) { - editor.getCaretModel().moveToOffset(newElement.getTextRange().getEndOffset() - 2); - JavaPostfixTemplateProvider.doNotDeleteSemicolon(newElement.getContainingFile()); - } - - @NotNull - @Override - protected String getHead() { - return "String.format("; - } - @NotNull + @Nullable @Override - protected String getTail() { - return ", );"; + public String getTemplateString(@NotNull PsiElement element) { + return "String.format($expr$, $END$);"; } } diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IntroduceFieldPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IntroduceFieldPostfixTemplate.java index 7d0547205cfe..40da7fd94b88 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IntroduceFieldPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IntroduceFieldPostfixTemplate.java @@ -25,7 +25,7 @@ import org.jetbrains.annotations.NotNull; public class IntroduceFieldPostfixTemplate extends JavaPostfixTemplateWithChooser { public IntroduceFieldPostfixTemplate() { - super("field", "myField = expr;"); + super("field", "myField = expr"); } @Override diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IntroduceVariablePostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IntroduceVariablePostfixTemplate.java index bde745a01261..57c03f9501fa 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IntroduceVariablePostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IntroduceVariablePostfixTemplate.java @@ -31,7 +31,7 @@ import org.jetbrains.annotations.NotNull; // todo: support for int[].var (parses as .class access!) public class IntroduceVariablePostfixTemplate extends JavaPostfixTemplateWithChooser { public IntroduceVariablePostfixTemplate() { - super("var", "T name = expr;"); + super("var", "T name = expr"); } @Override diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java index e629b03e68d7..148f4bb187db 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java @@ -114,7 +114,7 @@ public class JavaPostfixTemplateProvider implements PostfixTemplateProvider { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { - addedSemicolon.delete(); + addedSemicolon.delete(); } }); } @@ -143,10 +143,6 @@ public class JavaPostfixTemplateProvider implements PostfixTemplateProvider { }); } - public static void doNotDeleteSemicolon(@NotNull PsiFile file) { - file.putUserData(ADDED_SEMICOLON, null); - } - private static boolean isSemicolonNeeded(@NotNull PsiFile file, @NotNull Editor editor) { return JavaCompletionContributor.semicolonNeeded(editor, file, CompletionInitializationContext.calcStartOffset(editor)); } diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaStatementWrapPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaStatementWrapPostfixTemplate.java deleted file mode 100644 index b88a702fe31b..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaStatementWrapPostfixTemplate.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * 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 com.intellij.codeInsight.template.postfix.templates; - - -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.util.Condition; -import com.intellij.psi.PsiElement; -import org.jetbrains.annotations.NotNull; - -public abstract class JavaStatementWrapPostfixTemplate extends StatementWrapPostfixTemplate { - - protected JavaStatementWrapPostfixTemplate(@NotNull String name, - @NotNull String descr, - @NotNull PostfixTemplatePsiInfo psiInfo, - @NotNull Condition<PsiElement> typeChecker) { - super(name, descr, psiInfo, typeChecker); - } - - @Override - protected void afterExpand(@NotNull PsiElement newElement, @NotNull Editor editor) { - super.afterExpand(newElement, editor); - JavaPostfixTemplateProvider.doNotDeleteSemicolon(newElement.getContainingFile()); - } - - @NotNull - @Override - protected String getTail() { - return ";"; - } -} diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ReturnStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ReturnStatementPostfixTemplate.java index 4f60680e788e..2ce69c0e0892 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ReturnStatementPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ReturnStatementPostfixTemplate.java @@ -15,19 +15,22 @@ */ package com.intellij.codeInsight.template.postfix.templates; +import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.IS_NON_VOID; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.JAVA_PSI_INFO; -public class ReturnStatementPostfixTemplate extends JavaStatementWrapPostfixTemplate { +public class ReturnStatementPostfixTemplate extends StringBasedPostfixTemplate { public ReturnStatementPostfixTemplate() { - super("return", "return expr;", JAVA_PSI_INFO, IS_NON_VOID); + super("return", "return expr", JAVA_PSI_INFO, IS_NON_VOID); } - @NotNull + @Nullable @Override - protected String getHead() { - return "return "; + public String getTemplateString(@NotNull PsiElement element) { + + return "return $expr$;$END$"; } } diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SoutPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SoutPostfixTemplate.java index 149141840f5f..b2074e7d3a07 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SoutPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SoutPostfixTemplate.java @@ -15,25 +15,22 @@ */ package com.intellij.codeInsight.template.postfix.templates; +import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.IS_NON_VOID; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.JAVA_PSI_INFO; -public class SoutPostfixTemplate extends JavaStatementWrapPostfixTemplate { +public class SoutPostfixTemplate extends StringBasedPostfixTemplate { public SoutPostfixTemplate() { - super("sout", "System.out.println(expr);", JAVA_PSI_INFO, IS_NON_VOID); + super("sout", "System.out.println(expr)", JAVA_PSI_INFO, IS_NON_VOID); } - @NotNull - @Override - protected String getHead() { - return "System.out.println("; - } - @NotNull + @Nullable @Override - protected String getTail() { - return ");"; + public String getTemplateString(@NotNull PsiElement element) { + return "System.out.println($expr$);$END$"; } } diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SwitchStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SwitchStatementPostfixTemplate.java index 21122d0f0128..a1e986615048 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SwitchStatementPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SwitchStatementPostfixTemplate.java @@ -15,23 +15,19 @@ */ package com.intellij.codeInsight.template.postfix.templates; -import com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.Condition; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.JAVA_PSI_INFO; -public class SwitchStatementPostfixTemplate extends JavaStatementWrapPostfixTemplate { +public class SwitchStatementPostfixTemplate extends StringBasedPostfixTemplate { private static final Condition<PsiElement> SWITCH_TYPE = new Condition<PsiElement>() { @Override public boolean value(PsiElement expression) { - if (!(expression instanceof PsiExpression)) { - return false; - } + if (!(expression instanceof PsiExpression)) return false; PsiType type = ((PsiExpression)expression).getType(); @@ -44,7 +40,6 @@ public class SwitchStatementPostfixTemplate extends JavaStatementWrapPostfixTemp } if (type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { - if (ApplicationManager.getApplication().isUnitTestMode()) return true; // todo: mock jdk 6 and 7 PsiFile containingFile = expression.getContainingFile(); if (containingFile instanceof PsiJavaFile) { LanguageLevel level = ((PsiJavaFile)containingFile).getLanguageLevel(); @@ -60,20 +55,9 @@ public class SwitchStatementPostfixTemplate extends JavaStatementWrapPostfixTemp super("switch", "switch (expr)", JAVA_PSI_INFO, SWITCH_TYPE); } + @Nullable @Override - protected void afterExpand(@NotNull PsiElement newStatement, @NotNull Editor editor) { - JavaPostfixTemplatesUtils.formatPsiCodeBlock(newStatement, editor); - } - - @NotNull - @Override - protected String getHead() { - return "switch ("; - } - - @NotNull - @Override - protected String getTail() { - return ") {\nst;\n}"; + public String getTemplateString(@NotNull PsiElement element) { + return "switch ($expr$){\n$END$\n}"; } } diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SynchronizedStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SynchronizedStatementPostfixTemplate.java index b2f6fd25ffe3..5dbce1101c2b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SynchronizedStatementPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SynchronizedStatementPostfixTemplate.java @@ -15,34 +15,22 @@ */ package com.intellij.codeInsight.template.postfix.templates; -import com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils; -import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.IS_NOT_PRIMITIVE; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.JAVA_PSI_INFO; -public class SynchronizedStatementPostfixTemplate extends JavaStatementWrapPostfixTemplate { +public class SynchronizedStatementPostfixTemplate extends StringBasedPostfixTemplate { public SynchronizedStatementPostfixTemplate() { super("synchronized", "synchronized (expr)", JAVA_PSI_INFO, IS_NOT_PRIMITIVE); } - @Override - protected void afterExpand(@NotNull PsiElement newStatement, @NotNull Editor editor) { - JavaPostfixTemplatesUtils.formatPsiCodeBlock(newStatement, editor); - } - - @NotNull - @Override - protected String getHead() { - return "synchronized ("; - } - @NotNull + @Nullable @Override - protected String getTail() { - return ") {\nst;\n}"; + public String getTemplateString(@NotNull PsiElement element) { + return "synchronized ($expr$) {\n$END$\n}"; } - }
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ThrowExceptionPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ThrowExceptionPostfixTemplate.java index b8dbd640d246..bb309401653d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ThrowExceptionPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ThrowExceptionPostfixTemplate.java @@ -16,16 +16,18 @@ package com.intellij.codeInsight.template.postfix.templates; import com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils; +import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -public class ThrowExceptionPostfixTemplate extends JavaStatementWrapPostfixTemplate { +public class ThrowExceptionPostfixTemplate extends StringBasedPostfixTemplate { public ThrowExceptionPostfixTemplate() { - super("throw", "throw expr;", JavaPostfixTemplatesUtils.JAVA_PSI_INFO, JavaPostfixTemplatesUtils.IS_THROWABLE); + super("throw", "throw expr", JavaPostfixTemplatesUtils.JAVA_PSI_INFO, JavaPostfixTemplatesUtils.IS_THROWABLE); } - @NotNull + @Nullable @Override - protected String getHead() { - return "throw "; + public String getTemplateString(@NotNull PsiElement element) { + return "throw $expr$;$END$"; } }
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryStatementPostfixTemplate.java index 0c58e42e7430..71d181890383 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryStatementPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryStatementPostfixTemplate.java @@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull; public class TryStatementPostfixTemplate extends PostfixTemplate { protected TryStatementPostfixTemplate() { - super("try", "try { exp } catch(Ex e) { e.printStackTrace(); }"); + super("try", "try { exp } catch(Exception e)"); } @Override diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplate.java index b112eecc0457..3b2ffe5a6832 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplate.java @@ -38,7 +38,7 @@ import java.util.Collections; public class TryWithResourcesPostfixTemplate extends PostfixTemplate { protected TryWithResourcesPostfixTemplate() { - super("twr", "try(Type f = new Type()) {} catch (Ex e) {}"); + super("twr", "try(Type f = new Type()) catch (Exception e)"); } @Override diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/WhileStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/WhileStatementPostfixTemplate.java index ba301df53591..fbee12adbadc 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/WhileStatementPostfixTemplate.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/WhileStatementPostfixTemplate.java @@ -15,35 +15,28 @@ */ package com.intellij.codeInsight.template.postfix.templates; -import com.intellij.openapi.editor.Editor; -import com.intellij.psi.*; +import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.IS_BOOLEAN; import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.JAVA_PSI_INFO; -public class WhileStatementPostfixTemplate extends TypedPostfixTemplate { +public class WhileStatementPostfixTemplate extends StringBasedPostfixTemplate { public WhileStatementPostfixTemplate() { super("while", "while (expr)", JAVA_PSI_INFO, IS_BOOLEAN); } + + @Nullable @Override - public void expand(@NotNull PsiElement context, @NotNull Editor editor) { - PsiElement expression = myPsiInfo.getTopmostExpression(context); - assert expression != null; + public String getTemplateString(@NotNull PsiElement element) { + return "while ($expr$)$END$"; + } - PsiElementFactory factory = JavaPsiFacade.getElementFactory(context.getProject()); - PsiWhileStatement whileStatement = (PsiWhileStatement)factory.createStatementFromText("while(expr)", context); - PsiExpression condition = whileStatement.getCondition(); - assert condition != null; - condition.replace(expression); - PsiElement replacedWhileStatement = expression.replace(whileStatement); - if (replacedWhileStatement instanceof PsiWhileStatement) { - PsiJavaToken parenth = ((PsiWhileStatement)replacedWhileStatement).getRParenth(); - if (parenth != null) { - editor.getCaretModel().moveToOffset(parenth.getTextRange().getEndOffset()); - } - } + @Override + protected boolean shouldReformat() { + return false; } } diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java index a6a13f7068d9..e217175cdab9 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java @@ -16,14 +16,10 @@ package com.intellij.codeInsight.template.postfix.util; import com.intellij.codeInsight.CodeInsightServicesUtil; -import com.intellij.codeInsight.CodeInsightUtilCore; import com.intellij.codeInsight.template.postfix.templates.PostfixTemplatePsiInfoBase; import com.intellij.openapi.editor.Document; -import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.Condition; -import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; -import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiExpressionTrimRenderer; import com.intellij.psi.util.PsiTreeUtil; @@ -184,20 +180,7 @@ public abstract class JavaPostfixTemplatesUtils { @Nullable public static PsiExpression getTopmostExpression(PsiElement context) { PsiExpressionStatement statement = PsiTreeUtil.getNonStrictParentOfType(context, PsiExpressionStatement.class); - return statement != null ? PsiTreeUtil.getChildOfType(statement, PsiExpression.class) : null; - } - - public static void formatPsiCodeBlock(PsiElement newStatement, Editor editor) { - CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(newStatement.getProject()); - PsiElement statement = newStatement.replace(codeStyleManager.reformat(newStatement)); - - PsiCodeBlock type = PsiTreeUtil.getChildOfType(statement, PsiCodeBlock.class); - assert type != null; - PsiCodeBlock block = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(type); - TextRange range = block.getStatements()[0].getTextRange(); - editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset()); - - editor.getCaretModel().moveToOffset(range.getStartOffset()); + return statement != null ? statement.getExpression() : null; } } diff --git a/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java b/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java deleted file mode 100644 index 22d61cb6e02e..000000000000 --- a/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * 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 com.intellij.codeInspection; - -import com.intellij.codeInspection.ex.GlobalInspectionContextBase; -import com.intellij.codeInspection.ex.InspectionManagerEx; -import com.intellij.psi.PsiFile; - -/** - * User: anna - * Date: 11/27/13 - */ -public class RedundantSuppressInspection extends RedundantSuppressInspectionBase { - @Override - protected GlobalInspectionContextBase createContext(PsiFile file) { - final InspectionManagerEx inspectionManagerEx = ((InspectionManagerEx)InspectionManager.getInstance(file.getProject())); - return inspectionManagerEx.createNewGlobalContext(false); - } -} diff --git a/java/java-impl/src/com/intellij/codeInspection/RemoveAssignmentFix.java b/java/java-impl/src/com/intellij/codeInspection/RemoveAssignmentFix.java new file mode 100644 index 000000000000..b80e3a07121d --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInspection/RemoveAssignmentFix.java @@ -0,0 +1,65 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * 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 com.intellij.codeInspection; + +import com.intellij.codeInsight.FileModificationService; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.psi.util.PsiUtil; +import org.jetbrains.annotations.NotNull; + +public class RemoveAssignmentFix extends RemoveInitializerFix { + @NotNull + @Override + public String getName() { + return InspectionsBundle.message("inspection.unused.assignment.remove.assignment.quickfix"); + } + + @Override + public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + final PsiElement parent; + if (element instanceof PsiReferenceExpression) { + parent = element.getParent(); + } else { + parent = element; + } + if (!(parent instanceof PsiAssignmentExpression)) return; + final PsiExpression rExpression = ((PsiAssignmentExpression)parent).getRExpression(); + final PsiElement gParent = parent.getParent(); + if (gParent instanceof PsiExpression && rExpression != null) { + if (!FileModificationService.getInstance().prepareFileForWrite(gParent.getContainingFile())) return; + if (gParent instanceof PsiParenthesizedExpression) { + gParent.replace(rExpression); + } else { + parent.replace(rExpression); + } + return; + } + + PsiElement resolve = null; + if (element instanceof PsiReferenceExpression) { + resolve = ((PsiReferenceExpression)element).resolve(); + } else { + final PsiExpression lExpr = PsiUtil.deparenthesizeExpression(((PsiAssignmentExpression)parent).getLExpression()); + if (lExpr instanceof PsiReferenceExpression) { + resolve = ((PsiReferenceExpression)lExpr).resolve(); + } + } + if (!(resolve instanceof PsiVariable)) return; + sideEffectAwareRemove(project, rExpression, parent, (PsiVariable)resolve); + } +} diff --git a/java/java-impl/src/com/intellij/codeInspection/RemoveInitializerFix.java b/java/java-impl/src/com/intellij/codeInspection/RemoveInitializerFix.java new file mode 100644 index 000000000000..58755b0ad740 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInspection/RemoveInitializerFix.java @@ -0,0 +1,98 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * 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 com.intellij.codeInspection; + +import com.intellij.codeInsight.FileModificationService; +import com.intellij.codeInsight.daemon.impl.quickfix.RemoveUnusedVariableFix; +import com.intellij.codeInsight.daemon.impl.quickfix.RemoveUnusedVariableUtil; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.fileEditor.FileEditorManager; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.psi.util.PsiExpressionTrimRenderer; +import com.intellij.psi.util.PsiUtil; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; + +public class RemoveInitializerFix implements LocalQuickFix { + private static final Logger LOG = Logger.getInstance("#" + RemoveInitializerFix.class.getName()); + + @Override + @NotNull + public String getName() { + return InspectionsBundle.message("inspection.unused.assignment.remove.quickfix"); + } + + @Override + public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { + final PsiElement psiInitializer = descriptor.getPsiElement(); + if (!(psiInitializer instanceof PsiExpression)) return; + if (!(psiInitializer.getParent() instanceof PsiVariable)) return; + + final PsiVariable variable = (PsiVariable)psiInitializer.getParent(); + sideEffectAwareRemove(project, psiInitializer, psiInitializer, variable); + } + + protected void sideEffectAwareRemove(Project project, PsiElement psiInitializer, PsiElement elementToDelete, PsiVariable variable) { + if (!FileModificationService.getInstance().prepareFileForWrite(elementToDelete.getContainingFile())) return; + + final PsiElement declaration = variable.getParent(); + final List<PsiElement> sideEffects = new ArrayList<PsiElement>(); + boolean hasSideEffects = RemoveUnusedVariableUtil.checkSideEffects(psiInitializer, variable, sideEffects); + int res = RemoveUnusedVariableUtil.DELETE_ALL; + if (hasSideEffects) { + hasSideEffects = PsiUtil.isStatement(psiInitializer); + res = RemoveUnusedVariableFix.showSideEffectsWarning(sideEffects, variable, + FileEditorManager.getInstance(project).getSelectedTextEditor(), + hasSideEffects, sideEffects.get(0).getText(), + variable.getTypeElement().getText() + + " " + + variable.getName() + + ";<br>" + + PsiExpressionTrimRenderer + .render((PsiExpression)psiInitializer) + ); + } + try { + if (res == RemoveUnusedVariableUtil.DELETE_ALL) { + elementToDelete.delete(); + } + else if (res == RemoveUnusedVariableUtil.MAKE_STATEMENT) { + final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + final PsiStatement statementFromText = factory.createStatementFromText(psiInitializer.getText() + ";", null); + final PsiElement parent = elementToDelete.getParent(); + if (parent instanceof PsiExpressionStatement) { + parent.replace(statementFromText); + } else { + declaration.getParent().addAfter(statementFromText, declaration); + elementToDelete.delete(); + } + } + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + } + + @Override + @NotNull + public String getFamilyName() { + return getName(); + } +} diff --git a/java/java-impl/src/com/intellij/codeInspection/SuppressManagerImpl.java b/java/java-impl/src/com/intellij/codeInspection/SuppressManagerImpl.java deleted file mode 100644 index ca3131d325eb..000000000000 --- a/java/java-impl/src/com/intellij/codeInspection/SuppressManagerImpl.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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. - */ - -/* - * User: anna - * Date: 24-Dec-2007 - */ -package com.intellij.codeInspection; - -import com.intellij.codeInsight.daemon.HighlightDisplayKey; -import com.intellij.psi.PsiDocCommentOwner; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiModifierListOwner; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; - -public class SuppressManagerImpl extends SuppressManager { - @Override - @NotNull - public SuppressIntentionAction[] createSuppressActions(@NotNull final HighlightDisplayKey displayKey) { - SuppressQuickFix[] batchSuppressActions = createBatchSuppressActions(displayKey); - return SuppressIntentionActionFromFix.convertBatchToSuppressIntentionActions(batchSuppressActions); - } - - @Override - public boolean isSuppressedFor(@NotNull final PsiElement element, final String toolId) { - return JavaSuppressionUtil.getElementToolSuppressedIn(element, toolId) != null; - } - - @Override - @Nullable - public PsiElement getElementMemberSuppressedIn(@NotNull final PsiDocCommentOwner owner, final String inspectionToolID) { - return JavaSuppressionUtil.getElementMemberSuppressedIn(owner, inspectionToolID); - } - - @Override - @Nullable - public PsiElement getAnnotationMemberSuppressedIn(@NotNull final PsiModifierListOwner owner, final String inspectionToolID) { - return JavaSuppressionUtil.getAnnotationMemberSuppressedIn(owner, inspectionToolID); - } - - @Override - @Nullable - public PsiElement getDocCommentToolSuppressedIn(@NotNull final PsiDocCommentOwner owner, final String inspectionToolID) { - return JavaSuppressionUtil.getDocCommentToolSuppressedIn(owner, inspectionToolID); - } - - @Override - @NotNull - public Collection<String> getInspectionIdsSuppressedInAnnotation(@NotNull final PsiModifierListOwner owner) { - return JavaSuppressionUtil.getInspectionIdsSuppressedInAnnotation(owner); - } - - @Override - @Nullable - public String getSuppressedInspectionIdsIn(@NotNull PsiElement element) { - return JavaSuppressionUtil.getSuppressedInspectionIdsIn(element); - } - - @Override - @Nullable - public PsiElement getElementToolSuppressedIn(@NotNull final PsiElement place, final String toolId) { - return JavaSuppressionUtil.getElementToolSuppressedIn(place, toolId); - } - - @Override - public boolean canHave15Suppressions(@NotNull final PsiElement file) { - return JavaSuppressionUtil.canHave15Suppressions(file); - } - - @Override - public boolean alreadyHas14Suppressions(@NotNull final PsiDocCommentOwner commentOwner) { - return JavaSuppressionUtil.alreadyHas14Suppressions(commentOwner); - } -} diff --git a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java index e80dd146ff28..73d8848d4d17 100644 --- a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java @@ -16,11 +16,7 @@ package com.intellij.codeInspection.dataFlow; import com.intellij.codeInsight.NullableNotNullDialog; -import com.intellij.codeInspection.AddAssertStatementFix; -import com.intellij.codeInspection.InspectionsBundle; -import com.intellij.codeInspection.LocalQuickFix; -import com.intellij.codeInspection.SurroundWithIfFix; -import com.intellij.codeInspection.defUse.DefUseInspection; +import com.intellij.codeInspection.*; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.project.Project; @@ -54,7 +50,7 @@ public class DataFlowInspection extends DataFlowInspectionBase { if (toRemove && !onTheFly) { return LocalQuickFix.EMPTY_ARRAY; } - return new LocalQuickFix[]{toRemove ? new DefUseInspection.RemoveAssignmentFix() : createSimplifyToAssignmentFix()}; + return new LocalQuickFix[]{toRemove ? new RemoveAssignmentFix() : createSimplifyToAssignmentFix()}; } @Override diff --git a/java/java-impl/src/com/intellij/codeInspection/dataFlow/EditContractIntention.java b/java/java-impl/src/com/intellij/codeInspection/dataFlow/EditContractIntention.java index c962e2ee25fc..66c438dd337e 100644 --- a/java/java-impl/src/com/intellij/codeInspection/dataFlow/EditContractIntention.java +++ b/java/java-impl/src/com/intellij/codeInspection/dataFlow/EditContractIntention.java @@ -83,7 +83,7 @@ public class EditContractIntention extends BaseIntentionAction { public String getErrorText(String inputString) { if (StringUtil.isEmpty(inputString)) return null; - return DataFlowInspectionBase.checkContract(method, inputString); + return ContractInspection.checkContract(method, inputString); } @Override diff --git a/java/java-impl/src/com/intellij/codeInspection/deadCode/DummyEntryPointsTool.java b/java/java-impl/src/com/intellij/codeInspection/deadCode/DummyEntryPointsTool.java deleted file mode 100644 index 2b216dc844de..000000000000 --- a/java/java-impl/src/com/intellij/codeInspection/deadCode/DummyEntryPointsTool.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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 com.intellij.codeInspection.deadCode; - -import com.intellij.analysis.AnalysisScope; -import com.intellij.codeInspection.GlobalInspectionContext; -import com.intellij.codeInspection.InspectionManager; -import com.intellij.codeInspection.InspectionsBundle; -import com.intellij.codeInspection.ProblemDescriptionsProcessor; -import com.intellij.codeInspection.ex.JobDescriptor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * @author max - */ -public class DummyEntryPointsTool extends UnusedDeclarationInspection { - public DummyEntryPointsTool() { - } - - @Override - public void runInspection(@NotNull AnalysisScope scope, - @NotNull InspectionManager manager, - @NotNull GlobalInspectionContext globalContext, - @NotNull ProblemDescriptionsProcessor problemDescriptionsProcessor) { - } - - @Nullable - @Override - public JobDescriptor[] getAdditionalJobs() { - return JobDescriptor.EMPTY_ARRAY; - } - - @Override - @NotNull - public String getDisplayName() { - return InspectionsBundle.message("inspection.dead.code.entry.points.display.name"); - } - - @Override - @NotNull - public String getGroupDisplayName() { - return ""; - } - - @Override - @NotNull - public String getShortName() { - return ""; - } -} diff --git a/java/java-impl/src/com/intellij/codeInspection/deadCode/RefEntryPointFilter.java b/java/java-impl/src/com/intellij/codeInspection/deadCode/RefEntryPointFilter.java deleted file mode 100644 index 03ab97994afd..000000000000 --- a/java/java-impl/src/com/intellij/codeInspection/deadCode/RefEntryPointFilter.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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. - */ - -/* - * Created by IntelliJ IDEA. - * User: max - * Date: Dec 2, 2001 - * Time: 12:05:14 AM - * To change template for new class use - * Code Style | Class Templates options (Tools | IDE Options). - */ -package com.intellij.codeInspection.deadCode; - -import com.intellij.codeInspection.reference.RefJavaElement; -import com.intellij.codeInspection.reference.RefParameter; -import com.intellij.codeInspection.util.RefFilter; -import org.jetbrains.annotations.NotNull; - -public class RefEntryPointFilter extends RefFilter { - @Override - public int getElementProblemCount(@NotNull RefJavaElement refElement) { - if (refElement instanceof RefParameter) return 0; - return refElement.isEntry() && !refElement.isSyntheticJSP() ? 1 : 0; - } -} diff --git a/java/java-impl/src/com/intellij/codeInspection/defUse/DefUseInspection.java b/java/java-impl/src/com/intellij/codeInspection/defUse/DefUseInspection.java index 5d2ab663f35b..33c52c70547c 100644 --- a/java/java-impl/src/com/intellij/codeInspection/defUse/DefUseInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/defUse/DefUseInspection.java @@ -24,26 +24,10 @@ */ package com.intellij.codeInspection.defUse; -import com.intellij.codeInsight.FileModificationService; -import com.intellij.codeInsight.daemon.impl.quickfix.RemoveUnusedVariableFix; -import com.intellij.codeInsight.daemon.impl.quickfix.RemoveUnusedVariableUtil; -import com.intellij.codeInspection.InspectionsBundle; -import com.intellij.codeInspection.LocalQuickFix; -import com.intellij.codeInspection.ProblemDescriptor; +import com.intellij.codeInspection.*; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.fileEditor.FileEditorManager; -import com.intellij.openapi.project.Project; -import com.intellij.psi.*; -import com.intellij.psi.util.PsiExpressionTrimRenderer; -import com.intellij.psi.util.PsiUtil; -import com.intellij.util.IncorrectOperationException; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.List; public class DefUseInspection extends DefUseInspectionBase { - private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.defUse.DefUseInspection"); @Override protected LocalQuickFix createRemoveInitializerFix() { @@ -54,99 +38,4 @@ public class DefUseInspection extends DefUseInspectionBase { protected LocalQuickFix createRemoveAssignmentFix() { return new RemoveAssignmentFix(); } - - public static class RemoveAssignmentFix extends RemoveInitializerFix { - @NotNull - @Override - public String getName() { - return InspectionsBundle.message("inspection.unused.assignment.remove.assignment.quickfix"); - } - - @Override - public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { - final PsiElement left = descriptor.getPsiElement(); - if (!(left instanceof PsiReferenceExpression)) return; - final PsiElement parent = left.getParent(); - if (!(parent instanceof PsiAssignmentExpression)) return; - final PsiExpression rExpression = ((PsiAssignmentExpression)parent).getRExpression(); - final PsiElement gParent = parent.getParent(); - if (gParent instanceof PsiExpression && rExpression != null) { - if (!FileModificationService.getInstance().prepareFileForWrite(gParent.getContainingFile())) return; - if (gParent instanceof PsiParenthesizedExpression) { - gParent.replace(rExpression); - } else { - parent.replace(rExpression); - } - return; - } - - final PsiElement resolve = ((PsiReferenceExpression)left).resolve(); - if (!(resolve instanceof PsiVariable)) return; - sideEffectAwareRemove(project, rExpression, parent, (PsiVariable)resolve); - } - } - private static class RemoveInitializerFix implements LocalQuickFix { - @Override - @NotNull - public String getName() { - return InspectionsBundle.message("inspection.unused.assignment.remove.quickfix"); - } - - @Override - public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { - final PsiElement psiInitializer = descriptor.getPsiElement(); - if (!(psiInitializer instanceof PsiExpression)) return; - if (!(psiInitializer.getParent() instanceof PsiVariable)) return; - - final PsiVariable variable = (PsiVariable)psiInitializer.getParent(); - sideEffectAwareRemove(project, psiInitializer, psiInitializer, variable); - } - - protected void sideEffectAwareRemove(Project project, PsiElement psiInitializer, PsiElement elementToDelete, PsiVariable variable) { - if (!FileModificationService.getInstance().prepareFileForWrite(elementToDelete.getContainingFile())) return; - - final PsiElement declaration = variable.getParent(); - final List<PsiElement> sideEffects = new ArrayList<PsiElement>(); - boolean hasSideEffects = RemoveUnusedVariableUtil.checkSideEffects(psiInitializer, variable, sideEffects); - int res = RemoveUnusedVariableUtil.DELETE_ALL; - if (hasSideEffects) { - hasSideEffects = PsiUtil.isStatement(psiInitializer); - res = RemoveUnusedVariableFix.showSideEffectsWarning(sideEffects, variable, - FileEditorManager.getInstance(project).getSelectedTextEditor(), - hasSideEffects, sideEffects.get(0).getText(), - variable.getTypeElement().getText() + - " " + - variable.getName() + - ";<br>" + - PsiExpressionTrimRenderer - .render((PsiExpression)psiInitializer) - ); - } - try { - if (res == RemoveUnusedVariableUtil.DELETE_ALL) { - elementToDelete.delete(); - } - else if (res == RemoveUnusedVariableUtil.MAKE_STATEMENT) { - final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); - final PsiStatement statementFromText = factory.createStatementFromText(psiInitializer.getText() + ";", null); - final PsiElement parent = elementToDelete.getParent(); - if (parent instanceof PsiExpressionStatement) { - parent.replace(statementFromText); - } else { - declaration.getParent().addAfter(statementFromText, declaration); - elementToDelete.delete(); - } - } - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - - @Override - @NotNull - public String getFamilyName() { - return getName(); - } - } } diff --git a/java/java-impl/src/com/intellij/codeInspection/inconsistentLanguageLevel/InconsistentLanguageLevelInspection.java b/java/java-impl/src/com/intellij/codeInspection/inconsistentLanguageLevel/InconsistentLanguageLevelInspection.java deleted file mode 100644 index ecd1dcad59cd..000000000000 --- a/java/java-impl/src/com/intellij/codeInspection/inconsistentLanguageLevel/InconsistentLanguageLevelInspection.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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. - */ - -/* - * User: anna - * Date: 03-Nov-2009 - */ -package com.intellij.codeInspection.inconsistentLanguageLevel; - -import com.intellij.analysis.AnalysisScope; -import com.intellij.codeInsight.daemon.GroupNames; -import com.intellij.codeInspection.*; -import com.intellij.codeInspection.reference.RefManager; -import com.intellij.codeInspection.reference.RefModule; -import com.intellij.codeInspection.unnecessaryModuleDependency.UnnecessaryModuleDependencyInspection; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleUtilCore; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.project.ProjectBundle; -import com.intellij.openapi.roots.*; -import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; -import com.intellij.pom.java.LanguageLevel; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiElementVisitor; -import gnu.trove.THashSet; -import org.jetbrains.annotations.Nls; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; - -import java.util.Set; - -public class InconsistentLanguageLevelInspection extends GlobalInspectionTool { - @Override - public boolean isGraphNeeded() { - return false; - } - - @Override - public void runInspection(@NotNull AnalysisScope scope, - @NotNull InspectionManager manager, - @NotNull GlobalInspectionContext globalContext, - @NotNull ProblemDescriptionsProcessor problemProcessor) { - final Set<Module> modules = new THashSet<Module>(); - scope.accept(new PsiElementVisitor(){ - @Override - public void visitElement(PsiElement element) { - final Module module = ModuleUtilCore.findModuleForPsiElement(element); - if (module != null) { - modules.add(module); - } - } - }); - - LanguageLevel projectLanguageLevel = LanguageLevelProjectExtension.getInstance(manager.getProject()).getLanguageLevel(); - for (Module module : modules) { - LanguageLevel languageLevel = LanguageLevelModuleExtension.getInstance(module).getLanguageLevel(); - if (languageLevel == null) { - languageLevel = projectLanguageLevel; - } - RefManager refManager = globalContext.getRefManager(); - final RefModule refModule = refManager.getRefModule(module); - for (OrderEntry entry : ModuleRootManager.getInstance(module).getOrderEntries()) { - if (!(entry instanceof ModuleOrderEntry)) continue; - final Module dependantModule = ((ModuleOrderEntry)entry).getModule(); - if (dependantModule == null) continue; - LanguageLevel dependantLanguageLevel = LanguageLevelModuleExtension.getInstance(dependantModule).getLanguageLevel(); - if (dependantLanguageLevel == null) { - dependantLanguageLevel = projectLanguageLevel; - } - if (languageLevel.compareTo(dependantLanguageLevel) < 0) { - final CommonProblemDescriptor problemDescriptor = manager.createProblemDescriptor( - "Inconsistent language level settings: module " + module.getName() + " with language level " + languageLevel + - " depends on module " + dependantModule.getName() +" with language level " + dependantLanguageLevel, - new UnnecessaryModuleDependencyInspection.RemoveModuleDependencyFix(module, dependantModule), - new OpenModuleSettingsFix(module)); - problemProcessor.addProblemElement(refModule, problemDescriptor); - } - } - } - } - - @Override - public boolean isEnabledByDefault() { - return false; - } - - @Override - @Nls - @NotNull - public String getGroupDisplayName() { - return GroupNames.MODULARIZATION_GROUP_NAME; - } - - @Override - @NotNull - public String getDisplayName() { - return "Inconsistent language level settings"; - } - - @Override - @NonNls - @NotNull - public String getShortName() { - return "InconsistentLanguageLevel"; - } - - private static class OpenModuleSettingsFix implements QuickFix { - private final Module myModule; - - private OpenModuleSettingsFix(Module module) { - myModule = module; - } - - @Override - @NotNull - public String getName() { - return "Open module " + myModule.getName() + " settings"; - } - - @Override - @NotNull - public String getFamilyName() { - return getName(); - } - - @Override - public void applyFix(@NotNull Project project, @NotNull CommonProblemDescriptor descriptor) { - if (!myModule.isDisposed()) { - ProjectSettingsService.getInstance(project).showModuleConfigurationDialog(myModule.getName(), ProjectBundle.message("modules.classpath.title")); - } - } - } -} diff --git a/java/java-impl/src/com/intellij/codeInspection/reference/RefJavaManagerImpl.java b/java/java-impl/src/com/intellij/codeInspection/reference/RefJavaManagerImpl.java deleted file mode 100644 index ea4b7dac3fa0..000000000000 --- a/java/java-impl/src/com/intellij/codeInspection/reference/RefJavaManagerImpl.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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 com.intellij.codeInspection.reference; - -import com.intellij.codeInspection.*; -import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection; -import com.intellij.codeInspection.ex.*; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.Ref; -import com.intellij.openapi.util.UserDataCache; -import com.intellij.psi.*; -import com.intellij.psi.javadoc.PsiDocComment; -import com.intellij.psi.javadoc.PsiDocTag; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.util.IncorrectOperationException; -import gnu.trove.THashMap; -import org.jdom.Element; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * @author anna - * Date: 20-Dec-2007 - */ -public class RefJavaManagerImpl extends RefJavaManager { - private static final Logger LOG = Logger.getInstance("#" + RefJavaManagerImpl.class.getName()); - private PsiMethod myAppMainPattern; - private PsiMethod myAppPremainPattern; - private PsiMethod myAppAgentmainPattern; - private PsiClass myApplet; - private PsiClass myServlet; - private RefPackage myDefaultPackage; - private THashMap<String, RefPackage> myPackages; - private final RefManagerImpl myRefManager; - private PsiElementVisitor myProjectIterator; - private EntryPointsManager myEntryPointsManager; - - public RefJavaManagerImpl(@NotNull RefManagerImpl manager) { - myRefManager = manager; - final Project project = manager.getProject(); - final PsiManager psiManager = PsiManager.getInstance(project); - PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); - try { - myAppMainPattern = factory.createMethodFromText("void main(String[] args);", null); - myAppPremainPattern = factory.createMethodFromText("void premain(String[] args, java.lang.instrument.Instrumentation i);", null); - myAppAgentmainPattern = factory.createMethodFromText("void agentmain(String[] args, java.lang.instrument.Instrumentation i);", null); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - - myApplet = JavaPsiFacade.getInstance(psiManager.getProject()).findClass("java.applet.Applet", GlobalSearchScope.allScope(project)); - myServlet = JavaPsiFacade.getInstance(psiManager.getProject()).findClass("javax.servlet.Servlet", GlobalSearchScope.allScope(project)); - - } - - @Override - public RefPackage getPackage(String packageName) { - if (myPackages == null) { - myPackages = new THashMap<String, RefPackage>(); - } - - RefPackage refPackage = myPackages.get(packageName); - if (refPackage == null) { - refPackage = new RefPackageImpl(packageName, myRefManager); - myPackages.put(packageName, refPackage); - - int dotIndex = packageName.lastIndexOf('.'); - if (dotIndex >= 0) { - ((RefPackageImpl)getPackage(packageName.substring(0, dotIndex))).add(refPackage); - } - else { - ((RefProjectImpl)myRefManager.getRefProject()).add(refPackage); - } - } - - return refPackage; - } - - - public boolean isEntryPoint(final RefElement element) { - UnusedDeclarationInspection tool = getDeadCodeTool(element); - return tool != null && tool.isEntryPoint(element); - } - - @Nullable - private UnusedDeclarationInspection getDeadCodeTool(RefElement element) { - PsiFile file = ((RefElementImpl)element).getContainingFile(); - if (file == null) return null; - - return getDeadCodeTool(file); - } - - private static final UserDataCache<Ref<UnusedDeclarationInspection>, PsiFile, RefManagerImpl> DEAD_CODE_TOOL = new UserDataCache<Ref<UnusedDeclarationInspection>, PsiFile, RefManagerImpl>("DEAD_CODE_TOOL") { - @Override - protected Ref<UnusedDeclarationInspection> compute(PsiFile file, RefManagerImpl refManager) { - Tools tools = ((GlobalInspectionContextImpl)refManager.getContext()).getTools().get(UnusedDeclarationInspection.SHORT_NAME); - InspectionToolWrapper toolWrapper = tools == null ? null : tools.getEnabledTool(file); - InspectionProfileEntry tool = toolWrapper == null ? null : toolWrapper.getTool(); - return Ref.create(tool instanceof UnusedDeclarationInspection ? (UnusedDeclarationInspection)tool : null); - } - }; - - @Nullable - private UnusedDeclarationInspection getDeadCodeTool(PsiElement element) { - PsiFile file = element.getContainingFile(); - return file != null ? DEAD_CODE_TOOL.get(file, myRefManager).get() : null; - } - - @Override - public RefPackage getDefaultPackage() { - if (myDefaultPackage == null) { - myDefaultPackage = getPackage(InspectionsBundle.message("inspection.reference.default.package")); - } - return myDefaultPackage; - } - - @Override - public PsiMethod getAppMainPattern() { - return myAppMainPattern; - } - - @Override - public PsiMethod getAppPremainPattern() { - return myAppPremainPattern; - } - - @Override - public PsiMethod getAppAgentmainPattern() { - return myAppAgentmainPattern; - } - - @Override - public PsiClass getApplet() { - return myApplet; - } - - @Override - public PsiClass getServlet() { - return myServlet; - } - - @Override - public RefParameter getParameterReference(PsiParameter param, int index) { - LOG.assertTrue(myRefManager.isValidPointForReference(), "References may become invalid after process is finished"); - RefElement ref = myRefManager.getFromRefTable(param); - - if (ref == null) { - ref = new RefParameterImpl(param, index, myRefManager); - ((RefParameterImpl)ref).initialize(); - myRefManager.putToRefTable(param, ref); - } - - return (RefParameter)ref; - } - - - - @Override - public void iterate(@NotNull final RefVisitor visitor) { - if (myPackages != null) { - for (RefPackage refPackage : myPackages.values()) { - refPackage.accept(visitor); - } - } - for (RefElement refElement : myRefManager.getSortedElements()) { - if (refElement instanceof RefClass) { - RefClass refClass = (RefClass)refElement; - RefMethod refDefaultConstructor = refClass.getDefaultConstructor(); - if (refDefaultConstructor instanceof RefImplicitConstructor) { - refClass.getDefaultConstructor().accept(visitor); - } - } - } - } - - @Override - public void cleanup() { - if (myEntryPointsManager != null) { - Disposer.dispose(myEntryPointsManager); - myEntryPointsManager = null; - } - myPackages = null; - myApplet = null; - myAppMainPattern = null; - myAppPremainPattern = null; - myAppAgentmainPattern = null; - myServlet = null; - myDefaultPackage = null; - myProjectIterator = null; - } - - @Override - public void removeReference(final RefElement refElement) { - if (refElement instanceof RefMethod) { - RefMethod refMethod = (RefMethod)refElement; - RefParameter[] params = refMethod.getParameters(); - for (RefParameter param : params) { - myRefManager.removeReference(param); - } - } - } - - @Override - @Nullable - public RefElement createRefElement(final PsiElement elem) { - if (elem instanceof PsiClass) { - return new RefClassImpl((PsiClass)elem, myRefManager); - } - else if (elem instanceof PsiMethod) { - final PsiMethod method = (PsiMethod)elem; - final RefElement ref = myRefManager.getReference(method.getContainingClass(), true); - if (ref instanceof RefClass) { - return new RefMethodImpl((RefClass)ref, method, myRefManager); - } - } - else if (elem instanceof PsiField) { - final PsiField field = (PsiField)elem; - final RefElement ref = myRefManager.getReference(field.getContainingClass(), true); - if (ref instanceof RefClass) { - return new RefFieldImpl((RefClass)ref, field, myRefManager); - } - } - else if (elem instanceof PsiJavaFile) { - return new RefJavaFileImpl((PsiJavaFile)elem, myRefManager); - } - return null; - } - - @Override - @Nullable - public RefEntity getReference(final String type, final String fqName) { - if (METHOD.equals(type)) { - return RefMethodImpl.methodFromExternalName(myRefManager, fqName); - } - else if (CLASS.equals(type)) { - return RefClassImpl.classFromExternalName(myRefManager, fqName); - } - else if (FIELD.equals(type)) { - return RefFieldImpl.fieldFromExternalName(myRefManager, fqName); - } - else if (PARAMETER.equals(type)) { - return RefParameterImpl.parameterFromExternalName(myRefManager, fqName); - } - else if (PACKAGE.equals(type)) { - return RefPackageImpl.packageFromFQName(myRefManager, fqName); - } - return null; - } - - @Override - @Nullable - public String getType(final RefEntity ref) { - if (ref instanceof RefMethod) { - return METHOD; - } - else if (ref instanceof RefClass) { - return CLASS; - } - else if (ref instanceof RefField) { - return FIELD; - } - else if (ref instanceof RefParameter) { - return PARAMETER; - } - else if (ref instanceof RefPackage) { - return PACKAGE; - } - return null; - } - - @NotNull - @Override - public RefEntity getRefinedElement(@NotNull final RefEntity ref) { - if (ref instanceof RefImplicitConstructor) { - return ((RefImplicitConstructor)ref).getOwnerClass(); - } - return ref; - } - - @Override - public void visitElement(final PsiElement element) { - if (myProjectIterator == null) { - myProjectIterator = new MyJavaElementVisitor(); - } - element.accept(myProjectIterator); - } - - @Override - @Nullable - public String getGroupName(final RefEntity entity) { - if (entity instanceof RefFile && !(entity instanceof RefJavaFileImpl)) return null; - return RefJavaUtil.getInstance().getPackageName(entity); - } - - @Override - public boolean belongsToScope(final PsiElement psiElement) { - return !(psiElement instanceof PsiTypeParameter); - } - - @Override - public void export(@NotNull final RefEntity refEntity, @NotNull final Element element) { - if (refEntity instanceof RefElement) { - final SmartPsiElementPointer pointer = ((RefElement)refEntity).getPointer(); - if (pointer != null) { - final PsiFile psiFile = pointer.getContainingFile(); - if (psiFile instanceof PsiJavaFile) { - appendPackageElement(element, ((PsiJavaFile)psiFile).getPackageName()); - } - } - } - } - - @Override - public void onEntityInitialized(RefElement refElement, PsiElement psiElement) { - if (isEntryPoint(refElement)) { - getEntryPointsManager().addEntryPoint(refElement, false); - } - - if (psiElement instanceof PsiClass) { - PsiClass psiClass = (PsiClass)psiElement; - - EntryPointsManager entryPointsManager = getEntryPointsManager(); - if (psiClass.isAnnotationType()){ - entryPointsManager.addEntryPoint(refElement, false); - for (PsiMethod psiMethod : psiClass.getMethods()) { - entryPointsManager.addEntryPoint(myRefManager.getReference(psiMethod), false); - } - } - else if (psiClass.isEnum()) { - entryPointsManager.addEntryPoint(refElement, false); - } - } - } - - private static void appendPackageElement(final Element element, final String packageName) { - final Element packageElement = new Element("package"); - packageElement.addContent(packageName.isEmpty() ? InspectionsBundle.message("inspection.export.results.default") : packageName); - element.addContent(packageElement); - } - - @Override - public EntryPointsManager getEntryPointsManager() { - if (myEntryPointsManager == null) { - final Project project = myRefManager.getProject(); - myEntryPointsManager = new EntryPointsManagerImpl(project); - ((EntryPointsManagerBase)myEntryPointsManager).addAllPersistentEntries(EntryPointsManagerBase.getInstance(project)); - } - return myEntryPointsManager; - } - - private class MyJavaElementVisitor extends JavaElementVisitor { - private final RefJavaUtil myRefUtil; - - public MyJavaElementVisitor() { - myRefUtil = RefJavaUtil.getInstance(); - } - - @Override - public void visitReferenceExpression(PsiReferenceExpression expression) { - visitElement(expression); - } - - @Override - public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { - } - - - @Override - public void visitReferenceParameterList(final PsiReferenceParameterList list) { - super.visitReferenceParameterList(list); - final PsiMember member = PsiTreeUtil.getParentOfType(list, PsiMember.class); - - if (member instanceof PsiTypeParameter) { - final PsiMember owner = ((PsiTypeParameter)member).getOwner(); - if (owner != null) { - for (PsiClassType type : ((PsiTypeParameter)member).getExtendsListTypes()) { - myRefUtil.addTypeReference(owner, type, myRefManager); - } - } - } - - final PsiType[] typeArguments = list.getTypeArguments(); - for (PsiType type : typeArguments) { - myRefUtil.addTypeReference(member, type, myRefManager); - } - } - - @Override - public void visitClass(PsiClass aClass) { - if (!(aClass instanceof PsiTypeParameter)) { - super.visitClass(aClass); - RefElement refClass = myRefManager.getReference(aClass); - if (refClass != null) { - ((RefClassImpl)refClass).buildReferences(); - } - } - } - - @Override - public void visitMethod(final PsiMethod method) { - super.visitMethod(method); - final RefElement refElement = myRefManager.getReference(method); - if (refElement instanceof RefMethodImpl) { - ((RefMethodImpl)refElement).buildReferences(); - } - } - - @Override - public void visitField(final PsiField field) { - super.visitField(field); - final RefElement refElement = myRefManager.getReference(field); - if (refElement instanceof RefFieldImpl) { - ((RefFieldImpl)refElement).buildReferences(); - } - } - - @Override - public void visitDocComment(PsiDocComment comment) { - super.visitDocComment(comment); - final PsiDocTag[] tags = comment.getTags(); - for (PsiDocTag tag : tags) { - if (Comparing.strEqual(tag.getName(), SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME)) { - final PsiElement[] dataElements = tag.getDataElements(); - if (dataElements != null && dataElements.length > 0) { - final PsiModifierListOwner listOwner = PsiTreeUtil.getParentOfType(comment, PsiModifierListOwner.class); - if (listOwner != null) { - final RefElementImpl element = (RefElementImpl)myRefManager.getReference(listOwner); - if (element != null) { - String suppression = ""; - for (PsiElement dataElement : dataElements) { - suppression += "," + dataElement.getText(); - } - element.addSuppression(suppression); - } - } - } - } - } - } - - @Override - public void visitAnnotation(PsiAnnotation annotation) { - super.visitAnnotation(annotation); - if (Comparing.strEqual(annotation.getQualifiedName(), BatchSuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME)) { - final PsiModifierListOwner listOwner = PsiTreeUtil.getParentOfType(annotation, PsiModifierListOwner.class); - if (listOwner != null) { - final RefElementImpl element = (RefElementImpl)myRefManager.getReference(listOwner); - if (element != null) { - StringBuilder buf = new StringBuilder(); - final PsiNameValuePair[] nameValuePairs = annotation.getParameterList().getAttributes(); - for (PsiNameValuePair nameValuePair : nameValuePairs) { - buf.append(",").append(nameValuePair.getText().replaceAll("[{}\"\"]", "")); - } - if (buf.length() > 0) { - element.addSuppression(buf.substring(1)); - } - } - } - } - } - - @Override - public void visitVariable(PsiVariable variable) { - super.visitVariable(variable); - myRefUtil.addTypeReference(variable, variable.getType(), myRefManager); - } - - @Override - public void visitInstanceOfExpression(PsiInstanceOfExpression expression) { - super.visitInstanceOfExpression(expression); - final PsiTypeElement typeElement = expression.getCheckType(); - if (typeElement != null) { - myRefUtil.addTypeReference(expression, typeElement.getType(), myRefManager); - } - } - - @Override - public void visitThisExpression(PsiThisExpression expression) { - super.visitThisExpression(expression); - final PsiJavaCodeReferenceElement qualifier = expression.getQualifier(); - if (qualifier != null) { - myRefUtil.addTypeReference(expression, expression.getType(), myRefManager); - RefClass ownerClass = myRefUtil.getOwnerClass(myRefManager, expression); - if (ownerClass != null) { - RefClassImpl refClass = (RefClassImpl)myRefManager.getReference(qualifier.resolve()); - if (refClass != null) { - refClass.addInstanceReference(ownerClass); - } - } - } - } - } -} diff --git a/java/java-impl/src/com/intellij/codeInspection/sameParameterValue/SameParameterValueInspection.java b/java/java-impl/src/com/intellij/codeInspection/sameParameterValue/SameParameterValueInspection.java index 12e26f8bd673..baab93de8d25 100644 --- a/java/java-impl/src/com/intellij/codeInspection/sameParameterValue/SameParameterValueInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/sameParameterValue/SameParameterValueInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,9 @@ */ package com.intellij.codeInspection.sameParameterValue; -import com.intellij.analysis.AnalysisScope; -import com.intellij.codeInsight.daemon.GroupNames; -import com.intellij.codeInspection.*; -import com.intellij.codeInspection.reference.*; +import com.intellij.codeInspection.InspectionsBundle; +import com.intellij.codeInspection.LocalQuickFix; +import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; @@ -32,7 +31,6 @@ import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.InlineUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; @@ -41,102 +39,13 @@ import java.util.List; /** * @author max */ -public class SameParameterValueInspection extends GlobalJavaBatchInspectionTool { - private static final Logger LOG = Logger.getInstance("#" + SameParameterValueInspection.class.getName()); - - @Override - @Nullable - public CommonProblemDescriptor[] checkElement(@NotNull RefEntity refEntity, - @NotNull AnalysisScope scope, - @NotNull InspectionManager manager, - @NotNull GlobalInspectionContext globalContext, - @NotNull ProblemDescriptionsProcessor processor) { - List<ProblemDescriptor> problems = null; - if (refEntity instanceof RefMethod) { - final RefMethod refMethod = (RefMethod)refEntity; - - if (refMethod.hasSuperMethods()) return null; - - if (refMethod.isEntry()) return null; - - RefParameter[] parameters = refMethod.getParameters(); - for (RefParameter refParameter : parameters) { - String value = refParameter.getActualValueIfSame(); - if (value != null) { - if (problems == null) problems = new ArrayList<ProblemDescriptor>(1); - final String paramName = refParameter.getName(); - problems.add(manager.createProblemDescriptor(refParameter.getElement(), InspectionsBundle.message( - "inspection.same.parameter.problem.descriptor", "<code>" + paramName + "</code>", "<code>" + value + "</code>"), - new InlineParameterValueFix(paramName, value), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false)); - } - } - } - - return problems == null ? null : problems.toArray(new CommonProblemDescriptor[problems.size()]); - } - - - @Override - protected boolean queryExternalUsagesRequests(@NotNull final RefManager manager, @NotNull final GlobalJavaInspectionContext globalContext, - @NotNull final ProblemDescriptionsProcessor processor) { - manager.iterate(new RefJavaVisitor() { - @Override public void visitElement(@NotNull RefEntity refEntity) { - if (refEntity instanceof RefElement && processor.getDescriptions(refEntity) != null) { - refEntity.accept(new RefJavaVisitor() { - @Override public void visitMethod(@NotNull final RefMethod refMethod) { - globalContext.enqueueMethodUsagesProcessor(refMethod, new GlobalJavaInspectionContext.UsagesProcessor() { - @Override - public boolean process(PsiReference psiReference) { - processor.ignoreElement(refMethod); - return false; - } - }); - } - }); - } - } - }); - - return false; - } +public class SameParameterValueInspection extends SameParameterValueInspectionBase { + private static final Logger LOG = Logger.getInstance("#" + SameParameterValueInspectionBase.class.getName()); - @Override - @NotNull - public String getDisplayName() { - return InspectionsBundle.message("inspection.same.parameter.display.name"); - } - - @Override - @NotNull - public String getGroupDisplayName() { - return GroupNames.DECLARATION_REDUNDANCY; - } - - @Override - @NotNull - public String getShortName() { - return "SameParameterValue"; - } - - @Override - @Nullable - public QuickFix getQuickFix(final String hint) { - if (hint == null) return null; - final int spaceIdx = hint.indexOf(' '); - if (spaceIdx == -1 || spaceIdx >= hint.length() - 1) return null; //invalid hint - final String paramName = hint.substring(0, spaceIdx); - final String value = hint.substring(spaceIdx + 1); + protected LocalQuickFix createFix(String paramName, String value) { return new InlineParameterValueFix(paramName, value); } - @Override - @Nullable - public String getHint(@NotNull final QuickFix fix) { - final InlineParameterValueFix valueFix = (InlineParameterValueFix)fix; - return valueFix.getParamName() + " " + valueFix.getValue(); - } - public static class InlineParameterValueFix implements LocalQuickFix { private final String myValue; private final String myParameterName; @@ -147,6 +56,11 @@ public class SameParameterValueInspection extends GlobalJavaBatchInspectionTool } @Override + public String toString() { + return getParamName() + " " + getValue(); + } + + @Override @NotNull public String getName() { return InspectionsBundle.message("inspection.same.parameter.fix.name", myParameterName, myValue); diff --git a/java/java-impl/src/com/intellij/codeInspection/util/IgnorableRefFilter.java b/java/java-impl/src/com/intellij/codeInspection/sillyAssignment/SillyAssignmentInspection.java index 2a36345d7b7a..70edc6b1e9f8 100644 --- a/java/java-impl/src/com/intellij/codeInspection/util/IgnorableRefFilter.java +++ b/java/java-impl/src/com/intellij/codeInspection/sillyAssignment/SillyAssignmentInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.codeInspection.util; +package com.intellij.codeInspection.sillyAssignment; -import com.intellij.codeInspection.reference.RefElement; +import com.intellij.codeInspection.LocalQuickFix; +import com.intellij.codeInspection.RemoveAssignmentFix; -public abstract class IgnorableRefFilter extends RefFilter { - public abstract void addIgnoreList(RefElement refElement); -}
\ No newline at end of file +/** + * User: anna + * Date: 15-Nov-2005 + */ +public class SillyAssignmentInspection extends SillyAssignmentInspectionBase { + + @Override + protected LocalQuickFix createRemoveAssignmentFix() { + return new RemoveAssignmentFix(); + } +} diff --git a/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java b/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java index 570efa1de671..13c48c2aab77 100644 --- a/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java +++ b/java/java-impl/src/com/intellij/ide/actions/CreateClassAction.java @@ -84,6 +84,11 @@ public class CreateClassAction extends JavaCreateTemplateInPackageAction<PsiClas } @Override + protected String removeExtension(String templateName, String className) { + return StringUtil.trimEnd(className, ".java"); + } + + @Override protected String getErrorTitle() { return IdeBundle.message("title.cannot.create.class"); } diff --git a/java/java-impl/src/com/intellij/psi/NonClasspathClassFinder.java b/java/java-impl/src/com/intellij/psi/NonClasspathClassFinder.java deleted file mode 100644 index 7e98b3608f82..000000000000 --- a/java/java-impl/src/com/intellij/psi/NonClasspathClassFinder.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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 com.intellij.psi; - -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.impl.file.PsiPackageImpl; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.NonClasspathDirectoryScope; -import com.intellij.util.ArrayUtil; -import com.intellij.util.Processor; -import com.intellij.util.containers.ContainerUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.*; -import java.util.concurrent.atomic.AtomicLong; - -/** - * @author peter - */ -public abstract class NonClasspathClassFinder extends PsiElementFinder { - private static final Logger LOG = Logger.getInstance("#com.intellij.psi.NonClasspathClassFinder"); - private final AtomicLong myLastStamp = new AtomicLong(); - protected final Project myProject; - private volatile List<VirtualFile> myCache; - private final PsiManager myManager; - private final String[] myFileExtensions; - - public NonClasspathClassFinder(Project project, String... fileExtensions) { - myProject = project; - myManager = PsiManager.getInstance(myProject); - myFileExtensions = ArrayUtil.append(fileExtensions, "class"); - } - - protected List<VirtualFile> getClassRoots(@Nullable GlobalSearchScope scope) { - return getClassRoots(); - } - - protected List<VirtualFile> getClassRoots() { - List<VirtualFile> cache = myCache; - long stamp = myManager.getModificationTracker().getModificationCount(); - if (myLastStamp.get() != stamp) { - cache = null; - } - - if (cache != null && !cache.isEmpty()) { - for (VirtualFile file : cache) { - if (!file.isValid()) { - cache = null; - break; - } - } - } - - if (cache == null) { - myCache = cache = calcClassRoots(); - myLastStamp.set(stamp); - } - return cache; - } - - @Override - public PsiClass findClass(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) { - final List<VirtualFile> classRoots = getClassRoots(scope); - if (classRoots.isEmpty()) { - return null; - } - - final String relPath = qualifiedName.replace('.', '/'); - for (final VirtualFile classRoot : classRoots) { - if (scope.contains(classRoot)) { - VirtualFile virtualFile = findFileByRelativePath(classRoot, relPath, myFileExtensions); - if (virtualFile != null) { - if (!virtualFile.isValid()) { - LOG.error( - "Invalid child of valid parent: " + virtualFile.getPath() + "; " + classRoot.isValid() + " path=" + classRoot.getPath()); - return null; - } - final PsiFile file = myManager.findFile(virtualFile); - if (file instanceof PsiClassOwner) { - final PsiClass[] classes = ((PsiClassOwner)file).getClasses(); - if (classes.length == 1) { - return classes[0]; - } - } - } - } - } - return null; - } - - protected abstract List<VirtualFile> calcClassRoots(); - - @NotNull - @Override - public PsiClass[] getClasses(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { - final List<VirtualFile> classRoots = getClassRoots(scope); - if (classRoots.isEmpty()) { - return PsiClass.EMPTY_ARRAY; - } - - List<PsiClass> result = new ArrayList<PsiClass>(); - for (final VirtualFile classRoot : classRoots) { - if (scope.contains(classRoot)) { - final String pkgName = psiPackage.getQualifiedName(); - final VirtualFile dir = classRoot.findFileByRelativePath(pkgName.replace('.', '/')); - if (dir != null && dir.isDirectory()) { - for (final VirtualFile file : dir.getChildren()) { - if (!file.isDirectory()) { - final PsiFile psi = myManager.findFile(file); - if (psi instanceof PsiClassOwner) { - ContainerUtil.addAll(result, ((PsiClassOwner)psi).getClasses()); - } - } - } - } - } - } - return result.toArray(new PsiClass[result.size()]); - } - - - @NotNull - @Override - public Set<String> getClassNames(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { - final List<VirtualFile> classRoots = getClassRoots(scope); - if (classRoots.isEmpty()) { - return Collections.emptySet(); - } - - final Set<String> result = new HashSet<String>(); - for (final VirtualFile classRoot : classRoots) { - if (scope.contains(classRoot)) { - final String pkgName = psiPackage.getQualifiedName(); - final VirtualFile dir = classRoot.findFileByRelativePath(pkgName.replace('.', '/')); - if (dir != null && dir.isDirectory()) { - for (final VirtualFile file : dir.getChildren()) { - if (!file.isDirectory() && ArrayUtil.contains(file.getExtension(), myFileExtensions)) { - result.add(file.getNameWithoutExtension()); - } - } - } - } - } - return result; - } - - @Override - public PsiPackage findPackage(@NotNull String qualifiedName) { - final List<VirtualFile> classRoots = getClassRoots(); - if (classRoots.isEmpty()) { - return null; - } - - for (final VirtualFile classRoot : classRoots) { - final VirtualFile dir = classRoot.findFileByRelativePath(qualifiedName.replace('.', '/')); - if (dir != null && dir.isDirectory()) { - return createPackage(qualifiedName); - } - } - return null; - } - - private PsiPackageImpl createPackage(String qualifiedName) { - return new PsiPackageImpl(myManager, qualifiedName); - } - - @Override - public boolean processPackageDirectories(@NotNull PsiPackage psiPackage, - @NotNull GlobalSearchScope scope, - @NotNull Processor<PsiDirectory> consumer, - boolean includeLibrarySources) { - final List<VirtualFile> classRoots = getClassRoots(scope); - if (classRoots.isEmpty()) { - return true; - } - - final String qname = psiPackage.getQualifiedName(); - final PsiManager psiManager = psiPackage.getManager(); - for (final VirtualFile classRoot : classRoots) { - if (scope.contains(classRoot)) { - final VirtualFile dir = classRoot.findFileByRelativePath(qname.replace('.', '/')); - if (dir != null && dir.isDirectory()) { - final PsiDirectory psiDirectory = ApplicationManager.getApplication().runReadAction(new Computable<PsiDirectory>() { - @Override - @Nullable - public PsiDirectory compute() { - return dir.isValid() ? psiManager.findDirectory(dir) : null; - } - }); - if (psiDirectory != null && !consumer.process(psiDirectory)) { - return false; - } - } - } - } - return true; - } - - @NotNull - @Override - public PsiPackage[] getSubPackages(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { - final List<VirtualFile> classRoots = getClassRoots(scope); - if (classRoots.isEmpty()) { - return super.getSubPackages(psiPackage, scope); - } - - List<PsiPackage> result = new ArrayList<PsiPackage>(); - for (final VirtualFile classRoot : classRoots) { - if (scope.contains(classRoot)) { - final String pkgName = psiPackage.getQualifiedName(); - final VirtualFile dir = classRoot.findFileByRelativePath(pkgName.replace('.', '/')); - if (dir != null && dir.isDirectory()) { - for (final VirtualFile file : dir.getChildren()) { - if (file.isDirectory()) { - result.add(createPackage(pkgName + "." + file.getName())); - } - } - } - } - } - return result.toArray(new PsiPackage[result.size()]); - } - - @NotNull - @Override - public PsiClass[] findClasses(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) { - final PsiClass psiClass = findClass(qualifiedName, scope); - return psiClass == null ? PsiClass.EMPTY_ARRAY : new PsiClass[]{psiClass}; - } - - @NotNull - public static GlobalSearchScope addNonClasspathScope(Project project, GlobalSearchScope base) { - GlobalSearchScope scope = base; - for (PsiElementFinder finder : Extensions.getExtensions(EP_NAME, project)) { - if (finder instanceof NonClasspathClassFinder) { - scope = scope.uniteWith(NonClasspathDirectoryScope.compose(((NonClasspathClassFinder)finder).getClassRoots())); - } - } - return scope; - } - - public PsiManager getPsiManager() { - return myManager; - } - - @Nullable - private static VirtualFile findFileByRelativePath(@NotNull VirtualFile root, - @NotNull String relPath, - @NotNull String[] extensions) { - VirtualFile file = null; - for (String extension : extensions) { - file = root.findFileByRelativePath(relPath + '.' + extension); - if (file != null) break; - } - return file; - } -} diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java index d4e9c7928fca..3651fa1afe3a 100644 --- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java +++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java @@ -70,7 +70,7 @@ public class JavaArrangementVisitor extends JavaRecursiveElementVisitor { @NotNull private final ArrangementSectionDetector mySectionDetector; @Nullable private final Document myDocument; - @Nullable private Set<PsiField> classFields; + @NotNull private HashMap<PsiClass, Set<PsiField>> myCachedClassFields = ContainerUtil.newHashMap(); @NotNull private Set<PsiComment> myProcessedSectionsComments = ContainerUtil.newHashSet(); @@ -172,7 +172,7 @@ public class JavaArrangementVisitor extends JavaRecursiveElementVisitor { @Override public void run() { PsiExpressionList list = aClass.getArgumentList(); - if (list != null) { + if (list != null && list.getTextLength() > 0) { JavaElementArrangementEntry listEntry = createNewEntry(list, list.getTextRange(), ANON_CLASS_PARAMETER_LIST, aClass.getName(), true); processEntry(listEntry, null, list); } @@ -266,15 +266,18 @@ public class JavaArrangementVisitor extends JavaRecursiveElementVisitor { return referencedElements; } + Set<PsiField> classFields = myCachedClassFields.get(containingClass); if (classFields == null) { classFields = ContainerUtil.map2Set(containingClass.getFields(), new Function.Self<PsiField, PsiField>()); + myCachedClassFields.put(containingClass, classFields); } + final Set<PsiField> containingClassFields = classFields; fieldInitializer.accept(new JavaRecursiveElementVisitor() { @Override public void visitReferenceExpression(PsiReferenceExpression expression) { PsiElement ref = expression.resolve(); - if (ref instanceof PsiField && classFields.contains(ref)) { + if (ref instanceof PsiField && containingClassFields.contains(ref)) { referencedElements.add((PsiField)ref); } } diff --git a/java/java-impl/src/com/intellij/psi/filters/getters/MembersGetter.java b/java/java-impl/src/com/intellij/psi/filters/getters/MembersGetter.java index 9e13bdc576de..14f4e7e67731 100644 --- a/java/java-impl/src/com/intellij/psi/filters/getters/MembersGetter.java +++ b/java/java-impl/src/com/intellij/psi/filters/getters/MembersGetter.java @@ -90,11 +90,11 @@ public abstract class MembersGetter { public void processMembers(final Consumer<LookupElement> results, @Nullable final PsiClass where, final boolean acceptMethods, final boolean searchInheritors) { - if (where == null || CommonClassNames.JAVA_LANG_STRING.equals(where.getQualifiedName())) return; + if (where == null || isPrimitiveClass(where)) return; final boolean searchFactoryMethods = searchInheritors && !CommonClassNames.JAVA_LANG_OBJECT.equals(where.getQualifiedName()) && - !CommonClassNames.JAVA_LANG_STRING.equals(where.getQualifiedName()); + !isPrimitiveClass(where); final Project project = myPlace.getProject(); final GlobalSearchScope scope = myPlace.getResolveScope(); @@ -127,6 +127,12 @@ public abstract class MembersGetter { } } + private static boolean isPrimitiveClass(PsiClass where) { + String qname = where.getQualifiedName(); + if (qname == null || !qname.startsWith("java.lang.")) return false; + return CommonClassNames.JAVA_LANG_STRING.equals(qname) || InheritanceUtil.isInheritor(where, CommonClassNames.JAVA_LANG_NUMBER); + } + private void doProcessMembers(boolean acceptMethods, Consumer<LookupElement> results, boolean isExpectedTypeMember, Collection<? extends PsiElement> declarations) { diff --git a/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java b/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java index 58476c6fc799..8ea592fd99aa 100644 --- a/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java @@ -23,6 +23,7 @@ import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.StdFileTypes; +import com.intellij.openapi.module.EffectiveLanguageLevelUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; @@ -39,6 +40,7 @@ import com.intellij.psi.impl.compiled.ClsClassImpl; import com.intellij.psi.impl.source.codeStyle.ImportHelper; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.PsiUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; @@ -137,9 +139,35 @@ public class JavaPsiImplementationHelperImpl extends JavaPsiImplementationHelper return clsFile; } - @Nullable + @NotNull @Override - public LanguageLevel getClassesLanguageLevel(VirtualFile virtualFile) { + public LanguageLevel getEffectiveLanguageLevel(@Nullable VirtualFile virtualFile) { + if (virtualFile == null) return PsiUtil.getLanguageLevel(myProject); + + final VirtualFile folder = virtualFile.getParent(); + if (folder != null) { + final LanguageLevel level = folder.getUserData(LanguageLevel.KEY); + if (level != null) return level; + } + + final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); + Module module = index.getModuleForFile(virtualFile); + if (module != null && index.isInSourceContent(virtualFile)) { + return EffectiveLanguageLevelUtil.getEffectiveLanguageLevel(module); + } + + LanguageLevel classesLanguageLevel = getClassesLanguageLevel(virtualFile); + return classesLanguageLevel != null ? classesLanguageLevel : PsiUtil.getLanguageLevel(myProject); + } + + /** + * For files under a library source root, returns the language level configured for the corresponding classes root. + * + * @param virtualFile virtual file for which language level is requested. + * @return language level for classes root or null if file is not under a library source root or no matching classes root is found. + */ + @Nullable + private LanguageLevel getClassesLanguageLevel(VirtualFile virtualFile) { final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); final VirtualFile sourceRoot = index.getSourceRootForFile(virtualFile); final VirtualFile folder = virtualFile.getParent(); diff --git a/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java b/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java index 5464c6cbd83d..005629c81cd9 100644 --- a/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/file/JavaDirectoryServiceImpl.java @@ -27,17 +27,13 @@ import com.intellij.ide.fileTemplates.JavaTemplateUtil; import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.module.LanguageLevelUtil; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; +import com.intellij.psi.impl.JavaPsiImplementationHelper; import com.intellij.psi.util.PsiUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; @@ -162,7 +158,7 @@ public class JavaDirectoryServiceImpl extends CoreJavaDirectoryService { } private static String getIncorrectTemplateMessage(String templateName) { - return PsiBundle.message("psi.error.incorroect.class.template.message", + return PsiBundle.message("psi.error.incorrect.class.template.message", FileTemplateManager.getInstance().internalTemplateToSubject(templateName), templateName); } @@ -177,7 +173,7 @@ public class JavaDirectoryServiceImpl extends CoreJavaDirectoryService { String fileName = name + "." + StdFileTypes.JAVA.getDefaultExtension(); directory.checkCreateFile(fileName); - PsiNameHelper helper = JavaPsiFacade.getInstance(directory.getProject()).getNameHelper(); + PsiNameHelper helper = PsiNameHelper.getInstance(directory.getProject()); PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory); String qualifiedName = aPackage == null ? null : aPackage.getQualifiedName(); if (!StringUtil.isEmpty(qualifiedName) && !helper.isQualifiedName(qualifiedName)) { @@ -192,28 +188,9 @@ public class JavaDirectoryServiceImpl extends CoreJavaDirectoryService { return file.equals(sourceRoot); } - private static final Key<LanguageLevel> LANG_LEVEL_IN_DIRECTORY = new Key<LanguageLevel>("LANG_LEVEL_IN_DIRECTORY"); @Override public LanguageLevel getLanguageLevel(@NotNull PsiDirectory dir) { - synchronized (PsiLock.LOCK) { - LanguageLevel level = dir.getUserData(LANG_LEVEL_IN_DIRECTORY); - if (level == null) { - level = getLanguageLevelInner(dir); - dir.putUserData(LANG_LEVEL_IN_DIRECTORY, level); - } - return level; - } - } - - private static LanguageLevel getLanguageLevelInner(@NotNull PsiDirectory dir) { - final VirtualFile virtualFile = dir.getVirtualFile(); - final Project project = dir.getProject(); - final Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile); - if (module != null) { - return LanguageLevelUtil.getEffectiveLanguageLevel(module); - } - - return LanguageLevelProjectExtension.getInstance(project).getLanguageLevel(); + return JavaPsiImplementationHelper.getInstance(dir.getProject()).getEffectiveLanguageLevel(dir.getVirtualFile()); } } diff --git a/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java b/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java deleted file mode 100644 index 8e52d775a846..000000000000 --- a/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * 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. - */ - -/* - * @author max - */ -package com.intellij.psi.impl.search; - -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; -import com.intellij.psi.impl.PsiManagerImpl; -import com.intellij.psi.impl.java.stubs.index.JavaAnnotationIndex; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.PsiSearchHelper; -import com.intellij.psi.search.SearchScope; -import com.intellij.psi.search.searches.AnnotatedPackagesSearch; -import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.util.Processor; -import com.intellij.util.QueryExecutor; -import org.jetbrains.annotations.NotNull; - -import java.util.Collection; - -public class AnnotatedPackagesSearcher implements QueryExecutor<PsiPackage, AnnotatedPackagesSearch.Parameters> { - private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.AnnotatedPackagesSearcher"); - - @Override - public boolean execute(@NotNull final AnnotatedPackagesSearch.Parameters p, @NotNull final Processor<PsiPackage> consumer) { - final PsiClass annClass = p.getAnnotationClass(); - assert annClass.isAnnotationType() : "Annotation type should be passed to annotated packages search"; - - final String annotationFQN = annClass.getQualifiedName(); - assert annotationFQN != null; - - final PsiManagerImpl psiManager = (PsiManagerImpl)annClass.getManager(); - final SearchScope useScope = p.getScope(); - - final String annotationShortName = annClass.getName(); - assert annotationShortName != null; - - final GlobalSearchScope scope = useScope instanceof GlobalSearchScope ? (GlobalSearchScope)useScope : null; - - final Collection<PsiAnnotation> annotations = JavaAnnotationIndex.getInstance().get(annotationShortName, psiManager.getProject(), scope); - for (PsiAnnotation annotation : annotations) { - PsiModifierList modlist = (PsiModifierList)annotation.getParent(); - final PsiElement owner = modlist.getParent(); - if (!(owner instanceof PsiClass)) continue; - PsiClass candidate = (PsiClass)owner; - if (!"package-info".equals(candidate.getName())) continue; - - LOG.assertTrue(candidate.isValid()); - - final PsiJavaCodeReferenceElement ref = annotation.getNameReferenceElement(); - if (ref == null) continue; - - if (!psiManager.areElementsEquivalent(ref.resolve(), annClass)) continue; - if (useScope instanceof GlobalSearchScope && - !((GlobalSearchScope)useScope).contains(candidate.getContainingFile().getVirtualFile())) { - continue; - } - final String qname = candidate.getQualifiedName(); - if (qname != null && !consumer.process(JavaPsiFacade.getInstance(psiManager.getProject()).findPackage( - qname.substring(0, qname.lastIndexOf('.'))))) { - return false; - } - } - - PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(psiManager.getProject()); - final GlobalSearchScope infoFilesFilter = new PackageInfoFilesOnly(); - - GlobalSearchScope infoFiles = - useScope instanceof GlobalSearchScope ? ((GlobalSearchScope)useScope).intersectWith(infoFilesFilter) : infoFilesFilter; - - final boolean[] wantmore = {true}; - helper.processAllFilesWithWord(annotationShortName, infoFiles, new Processor<PsiFile>() { - @Override - public boolean process(final PsiFile psiFile) { - PsiPackageStatement stmt = PsiTreeUtil.getChildOfType(psiFile, PsiPackageStatement.class); - if (stmt == null) return true; - - final PsiModifierList annotations = stmt.getAnnotationList(); - if (annotations == null) return true; - final PsiAnnotation ann = annotations.findAnnotation(annotationFQN); - if (ann == null) return true; - - final PsiJavaCodeReferenceElement ref = ann.getNameReferenceElement(); - if (ref == null) return true; - - if (!psiManager.areElementsEquivalent(ref.resolve(), annClass)) return true; - - wantmore[0] = consumer.process(JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(stmt.getPackageName())); - return wantmore[0]; - } - }, true); - - return wantmore[0]; - } - - private static class PackageInfoFilesOnly extends GlobalSearchScope { - @Override - public int compare(@NotNull final VirtualFile file1, @NotNull final VirtualFile file2) { - return 0; - } - - @Override - public boolean contains(@NotNull final VirtualFile file) { - return "package-info.java".equals(file.getName()); - } - - @Override - public boolean isSearchInLibraries() { - return false; - } - - @Override - public boolean isSearchInModuleContent(@NotNull final Module aModule) { - return true; - } - } -}
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/psi/impl/search/VariableInIncompleteCodeSearcher.java b/java/java-impl/src/com/intellij/psi/impl/search/VariableInIncompleteCodeSearcher.java deleted file mode 100644 index fc0ca69b6a4c..000000000000 --- a/java/java-impl/src/com/intellij/psi/impl/search/VariableInIncompleteCodeSearcher.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * 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 com.intellij.psi.impl.search; - -import com.intellij.lang.java.JavaLanguage; -import com.intellij.openapi.application.QueryExecutorBase; -import com.intellij.psi.*; -import com.intellij.psi.search.LocalSearchScope; -import com.intellij.psi.search.PsiElementProcessor; -import com.intellij.psi.search.SearchScope; -import com.intellij.psi.search.searches.ReferencesSearch; -import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.util.Processor; -import org.jetbrains.annotations.NotNull; - -/** - * Looks for references to local variable or method parameter in invalid (incomplete) code. - */ -public class VariableInIncompleteCodeSearcher extends QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters> { - public VariableInIncompleteCodeSearcher() { - super(true); - } - - @Override - public void processQuery(@NotNull final ReferencesSearch.SearchParameters p, @NotNull final Processor<PsiReference> consumer) { - final PsiElement refElement = p.getElementToSearch(); - if (!refElement.isValid() || !(refElement instanceof PsiLocalVariable || refElement instanceof PsiParameter)) return; - - final String name = ((PsiVariable)refElement).getName(); - if (name == null) return; - - final SearchScope scope = p.getEffectiveSearchScope(); - if (!(scope instanceof LocalSearchScope)) return; - - PsiElement[] elements = ((LocalSearchScope)scope).getScope(); - if (elements == null || elements.length == 0) return; - - PsiElementProcessor processor = new PsiElementProcessor() { - @Override - public boolean execute(@NotNull final PsiElement element) { - if (element instanceof PsiJavaCodeReferenceElement) { - final PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement)element; - if (!ref.isQualified() && name.equals(ref.getText()) && - ref.resolve() == null && ref.advancedResolve(true).getElement() == refElement) { - consumer.process(ref); - } - } - return true; - } - }; - - for (PsiElement element : elements) { - if (element.getLanguage().isKindOf(JavaLanguage.INSTANCE)) { - PsiTreeUtil.processElements(element, processor); - } - } - } -} diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/manipulators/PsiDocTagValueManipulator.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/manipulators/PsiDocTagValueManipulator.java deleted file mode 100644 index 34c1d9df885f..000000000000 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/manipulators/PsiDocTagValueManipulator.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * 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 com.intellij.psi.impl.source.resolve.reference.impl.manipulators; - -import com.intellij.openapi.util.TextRange; -import com.intellij.psi.AbstractElementManipulator; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiElement; -import com.intellij.psi.javadoc.PsiDocTag; -import com.intellij.util.IncorrectOperationException; -import org.jetbrains.annotations.NotNull; - -/** - * @author Gregory.Shrago - */ -public class PsiDocTagValueManipulator extends AbstractElementManipulator<PsiDocTag> { - - @Override - public PsiDocTag handleContentChange(@NotNull PsiDocTag tag, @NotNull TextRange range, String newContent) throws IncorrectOperationException { - final StringBuilder replacement = new StringBuilder( tag.getText() ); - - replacement.replace( - range.getStartOffset(), - range.getEndOffset(), - newContent - ); - return (PsiDocTag)tag.replace(JavaPsiFacade.getInstance(tag.getProject()).getElementFactory().createDocTagFromText(replacement.toString())); - } - - @NotNull - @Override - public TextRange getRangeInElement(@NotNull final PsiDocTag tag) { - final PsiElement[] elements = tag.getDataElements(); - if (elements.length == 0) { - final PsiElement name = tag.getNameElement(); - final int offset = name.getStartOffsetInParent() + name.getTextLength(); - return new TextRange(offset, offset); - } - final PsiElement first = elements[0]; - final PsiElement last = elements[elements.length - 1]; - return new TextRange(first.getStartOffsetInParent(), last.getStartOffsetInParent()+last.getTextLength()); - } -}
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/manipulators/StringLiteralManipulator.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/manipulators/StringLiteralManipulator.java deleted file mode 100644 index 9d9b1f1ce9e2..000000000000 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/manipulators/StringLiteralManipulator.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * 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 com.intellij.psi.impl.source.resolve.reference.impl.manipulators; - -import com.intellij.openapi.util.TextRange; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.psi.*; -import com.intellij.util.IncorrectOperationException; -import org.jetbrains.annotations.NotNull; - -/** - * @author ven - */ -public class StringLiteralManipulator extends AbstractElementManipulator<PsiLiteralExpression> { - @Override - public PsiLiteralExpression handleContentChange(@NotNull PsiLiteralExpression expr, @NotNull TextRange range, String newContent) throws IncorrectOperationException { - String oldText = expr.getText(); - if (oldText.startsWith("\"")) { - newContent = StringUtil.escapeStringCharacters(newContent); - } - else if (oldText.startsWith("'") && newContent.length() <= 1) { - newContent = newContent.length() == 1 && newContent.charAt(0) == '\''? "\\'" : newContent; - } - else { - throw new IncorrectOperationException("cannot handle content change for: " + oldText + ", expr: " + expr); - } - - String newText = oldText.substring(0, range.getStartOffset()) + newContent + oldText.substring(range.getEndOffset()); - final PsiExpression newExpr = JavaPsiFacade.getInstance(expr.getProject()).getElementFactory().createExpressionFromText(newText, null); - return (PsiLiteralExpression)expr.replace(newExpr); - } - - @NotNull - @Override - public TextRange getRangeInElement(@NotNull final PsiLiteralExpression element) { - return getValueRange(element); - } - - public static TextRange getValueRange(PsiLiteralExpression element) { - final Object value = element.getValue(); - if (!(value instanceof String || value instanceof Character)) return TextRange.from(0, element.getTextLength()); - return new TextRange(1, Math.max(1, element.getTextLength() - 1)); - } -} diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/GenericReferenceProvider.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/GenericReferenceProvider.java deleted file mode 100644 index 216dcddb351f..000000000000 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/GenericReferenceProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * 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 com.intellij.psi.impl.source.resolve.reference.impl.providers; - -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiReferenceProvider; -import com.intellij.psi.scope.PsiScopeProcessor; -import com.intellij.psi.scope.util.PsiScopesUtil; - -/** - * Created by IntelliJ IDEA. - * User: ik - * Date: 27.03.2003 - * Time: 17:23:43 - * To change this template use Options | File Templates. - */ -public abstract class GenericReferenceProvider extends PsiReferenceProvider { - private boolean mySoft = false; - - public void handleEmptyContext(PsiScopeProcessor processor, PsiElement position) { - PsiScopesUtil.treeWalkUp(processor, position, null); - } - - public void setSoft(boolean softFlag) { - mySoft = softFlag; - } - - public boolean isSoft() { - return mySoft; - } -} diff --git a/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java b/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java index cd8613dd05e5..a13d3d0058f2 100644 --- a/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java +++ b/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java @@ -26,13 +26,16 @@ import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.usageView.UsageInfo; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.SequentialModalProgressTask; +import com.intellij.util.SequentialTask; import com.intellij.util.containers.HashSet; import java.util.Collection; +import java.util.Iterator; import java.util.Set; public class OptimizeImportsRefactoringHelper implements RefactoringHelper<Set<PsiJavaFile>> { - private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.OptimizeImportsRefactoringHelper"); + private static final String REMOVING_REDUNDANT_IMPORTS_TITLE = "Removing redundant imports"; @Override public Set<PsiJavaFile> prepareOperation(final UsageInfo[] usages) { @@ -90,36 +93,75 @@ public class OptimizeImportsRefactoringHelper implements RefactoringHelper<Set<P } }; - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(findRedundantImports, "Removing redundant imports", false, project)) return; + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(findRedundantImports, REMOVING_REDUNDANT_IMPORTS_TITLE, false, project)) return; ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { - try { - for (final SmartPsiElementPointer<PsiImportStatementBase> pointer : redundants) { - final PsiImportStatementBase importStatement = pointer.getElement(); - if (importStatement != null && importStatement.isValid()) { - final PsiJavaCodeReferenceElement ref = importStatement.getImportReference(); - //Do not remove non-resolving refs - if (ref == null) { - continue; - } - final PsiElement resolve = ref.resolve(); - if (resolve == null) { - continue; - } + final SequentialModalProgressTask progressTask = new SequentialModalProgressTask(project, REMOVING_REDUNDANT_IMPORTS_TITLE, false); + progressTask.setMinIterationTime(200); + progressTask.setTask(new OptimizeImportsTask(progressTask, redundants)); + ProgressManager.getInstance().run(progressTask); + } + }); + } +} - if (resolve instanceof PsiPackage && ((PsiPackage)resolve).getDirectories(ref.getResolveScope()).length == 0) { - continue; - } - importStatement.delete(); - } + +class OptimizeImportsTask implements SequentialTask { + private static final Logger LOG = Logger.getInstance("#" + OptimizeImportsTask.class.getName()); + + private final Iterator<SmartPsiElementPointer<PsiImportStatementBase>> myPointers; + private final SequentialModalProgressTask myTask; + private final int myTotal; + private int myCount; + + public OptimizeImportsTask(SequentialModalProgressTask progressTask, Set<SmartPsiElementPointer<PsiImportStatementBase>> pointers) { + myTask = progressTask; + myTotal = pointers.size(); + myPointers = pointers.iterator(); + } + + @Override + public void prepare() { + } + + @Override + public boolean isDone() { + return !myPointers.hasNext(); + } + + @Override + public boolean iteration() { + final ProgressIndicator indicator = myTask.getIndicator(); + if (indicator != null) { + indicator.setFraction(((double)myCount ++) / myTotal); + } + + final SmartPsiElementPointer<PsiImportStatementBase> pointer = myPointers.next(); + + final PsiImportStatementBase importStatement = pointer.getElement(); + if (importStatement != null && importStatement.isValid()) { + final PsiJavaCodeReferenceElement ref = importStatement.getImportReference(); + //Do not remove non-resolving refs + if (ref != null) { + final PsiElement resolve = ref.resolve(); + if (resolve != null && + (!(resolve instanceof PsiPackage) || ((PsiPackage)resolve).getDirectories(ref.getResolveScope()).length != 0)) { + try { + importStatement.delete(); + } + catch (IncorrectOperationException e) { + LOG.error(e); } - } - catch (IncorrectOperationException e) { - LOG.error(e); } } - }); + } + + return isDone(); } -} + + @Override + public void stop() { + } +}
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaMethodSignatureEditor.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaMethodSignatureEditor.java deleted file mode 100644 index 5d2ef50bac04..000000000000 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaMethodSignatureEditor.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * 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 com.intellij.refactoring.changeSignature; - -import com.intellij.openapi.util.TextRange; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.psi.*; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; - -/** - * @author Konstantin Bulenkov - */ -public class JavaMethodSignatureEditor extends MethodSignatureEditor<PsiMethod> { - public JavaMethodSignatureEditor(@NotNull PsiMethod method) { - super(method, PsiMethod.class); - } - - @Override - public TextRange getSignatureTextRange() { - final PsiMethod method = getMethod(); - final TextRange methodTextRange = method.getTextRange(); - final TextRange paramsRange = method.getParameterList().getTextRange(); - return TextRange.create(methodTextRange.getStartOffset(), paramsRange.getEndOffset()); - } - - @Override - protected void indexParameters(PsiMethod method, @NotNull ParameterIndexer indexer) { - final PsiParameter[] parameters = method.getParameterList().getParameters(); - for (int i = 0; i < parameters.length; i++) { - indexer.setIndex(parameters[i], i); - } - } - - @Override - protected String formatMethod() { - - @NonNls StringBuilder buffer = new StringBuilder(); - PsiMethod method = getMethod(); - PsiModifierList modifierList = method.getModifierList(); - String modifiers = modifierList.getText(); - - buffer.append(modifiers); - if (modifiers.length() > 0 && - !StringUtil.endsWithChar(modifiers, '\n') && - !StringUtil.endsWithChar(modifiers, '\r') && - !StringUtil.endsWithChar(modifiers, ' ')) { - buffer.append(" "); - } - - if (!method.isConstructor()) { - final PsiType returnType = method.getReturnType(); - if (returnType != null) { - buffer.append(returnType.getPresentableText()); - } - buffer.append(" "); - } - buffer.append(method.getName()); - buffer.append("("); - - final String indent = " "; - PsiParameter[] items = method.getParameterList().getParameters(); - for (int i = 0; i < items.length; i++) { - PsiParameter item = items[i]; - if (i > 0) { - buffer.append(","); - } - buffer.append("\n"); - buffer.append(indent); - buffer.append(item.getTypeElement().getType().getPresentableText()); - buffer.append(" "); - buffer.append(item.getName()); - } - if (items.length != 0) { - buffer.append("\n"); - } - buffer.append(")"); - - PsiClassType[] thrownExceptionsFragments = method.getThrowsList().getReferencedTypes(); - if (thrownExceptionsFragments.length > 0) { - buffer.append("\n"); - buffer.append("throws\n"); - for (int i = 0; i < thrownExceptionsFragments.length; i++) { - String text = thrownExceptionsFragments[i].getPresentableText(); - buffer.append(indent); - buffer.append(text); - if (i < thrownExceptionsFragments.length - 1) { - buffer.append(","); - buffer.append("\n"); - } - } - } - return buffer.toString(); - } -} diff --git a/java/java-impl/src/com/intellij/refactoring/encapsulateFields/JavaEncapsulateFieldHelper.java b/java/java-impl/src/com/intellij/refactoring/encapsulateFields/JavaEncapsulateFieldHelper.java index 19a6fb15ee0d..e9d597449e2f 100644 --- a/java/java-impl/src/com/intellij/refactoring/encapsulateFields/JavaEncapsulateFieldHelper.java +++ b/java/java-impl/src/com/intellij/refactoring/encapsulateFields/JavaEncapsulateFieldHelper.java @@ -236,19 +236,10 @@ public class JavaEncapsulateFieldHelper extends EncapsulateFieldHelper { PsiReferenceExpression expr, PsiClass aClass, PsiMethod setter) throws IncorrectOperationException { - PsiElementFactory factory = JavaPsiFacade.getInstance(expr.getProject()).getElementFactory(); final String setterName = fieldDescriptor.getSetterName(); @NonNls String text = setterName + "(a)"; - PsiExpression qualifier = expr.getQualifierExpression(); - if (qualifier != null){ - text = "q." + text; - } - PsiMethodCallExpression methodCall = (PsiMethodCallExpression)factory.createExpressionFromText(text, expr); - + PsiMethodCallExpression methodCall = prepareMethodCall(expr, text); methodCall.getArgumentList().getExpressions()[0].replace(setterArgument); - if (qualifier != null){ - methodCall.getMethodExpression().getQualifierExpression().replace(qualifier); - } methodCall = checkMethodResolvable(methodCall, setter, expr, aClass); if (methodCall == null) { VisibilityUtil.escalateVisibility(fieldDescriptor.getField(), expr); @@ -261,19 +252,9 @@ public class JavaEncapsulateFieldHelper extends EncapsulateFieldHelper { PsiReferenceExpression expr, PsiClass aClass, PsiMethod getter) throws IncorrectOperationException { - PsiElementFactory factory = JavaPsiFacade.getInstance(expr.getProject()).getElementFactory(); final String getterName = fieldDescriptor.getGetterName(); @NonNls String text = getterName + "()"; - PsiExpression qualifier = expr.getQualifierExpression(); - if (qualifier != null) { - text = "q." + text; - } - PsiMethodCallExpression methodCall = (PsiMethodCallExpression)factory.createExpressionFromText(text, expr); - - if (qualifier != null) { - methodCall.getMethodExpression().getQualifierExpression().replace(qualifier); - } - + PsiMethodCallExpression methodCall = prepareMethodCall(expr, text); methodCall = checkMethodResolvable(methodCall, getter, expr, aClass); if (methodCall == null) { VisibilityUtil.escalateVisibility(fieldDescriptor.getField(), expr); @@ -281,6 +262,18 @@ public class JavaEncapsulateFieldHelper extends EncapsulateFieldHelper { return methodCall; } + private static PsiMethodCallExpression prepareMethodCall(PsiReferenceExpression expr, String text) { + PsiExpression qualifier = expr.getQualifierExpression(); + if (qualifier != null) { + final PsiElement referenceNameElement = expr.getReferenceNameElement(); + if (referenceNameElement != null) { + text = expr.getText().substring(0, referenceNameElement.getStartOffsetInParent()) + text; + } + } + final PsiElementFactory factory = JavaPsiFacade.getInstance(expr.getProject()).getElementFactory(); + return (PsiMethodCallExpression)factory.createExpressionFromText(text, expr); + } + @Nullable private static PsiMethodCallExpression checkMethodResolvable(PsiMethodCallExpression methodCall, PsiMethod targetMethod, diff --git a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodStaticProcessor.java b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodStaticProcessor.java index bd8ed35c3cb7..de5efa573d8a 100644 --- a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodStaticProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodStaticProcessor.java @@ -112,6 +112,7 @@ public class MakeMethodStaticProcessor extends MakeMethodOrClassStaticProcessor< final PsiModifierList modifierList = myMember.getModifierList(); modifierList.setModifierProperty(PsiModifier.STATIC, true); modifierList.setModifierProperty(PsiModifier.FINAL, false); + modifierList.setModifierProperty(PsiModifier.DEFAULT, false); } protected void changeInternalUsage(InternalUsageInfo usage, PsiElementFactory factory) diff --git a/java/java-impl/src/com/intellij/refactoring/makeStatic/Settings.java b/java/java-impl/src/com/intellij/refactoring/makeStatic/Settings.java index 53c4335dfb27..c08de3870f0f 100644 --- a/java/java-impl/src/com/intellij/refactoring/makeStatic/Settings.java +++ b/java/java-impl/src/com/intellij/refactoring/makeStatic/Settings.java @@ -55,8 +55,7 @@ public final class Settings { } - public Settings(boolean replaceUsages, String classParameterName, - VariableData[] variableDatum) { + public Settings(boolean replaceUsages, @Nullable String classParameterName, @Nullable VariableData[] variableDatum) { myReplaceUsages = replaceUsages; myMakeClassParameter = classParameterName != null; myClassParameterName = classParameterName; diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveDirectoryWithClassesHelper.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveDirectoryWithClassesHelper.java index 41e0a2bef057..88f815157665 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveDirectoryWithClassesHelper.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveDirectoryWithClassesHelper.java @@ -3,6 +3,7 @@ package com.intellij.refactoring.move.moveClassesOrPackages; import com.intellij.codeInsight.ChangeContextUtil; import com.intellij.openapi.project.Project; import com.intellij.psi.*; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.listeners.RefactoringElementListener; @@ -47,7 +48,7 @@ public class JavaMoveDirectoryWithClassesHelper extends MoveDirectoryWithClasses } } if (remainsNothing) { - for (PsiReference reference : ReferencesSearch.search(aPackage)) { + for (PsiReference reference : ReferencesSearch.search(aPackage, GlobalSearchScope.projectScope(project))) { final PsiElement element = reference.getElement(); final PsiImportStatementBase statementBase = PsiTreeUtil.getParentOfType(element, PsiImportStatementBase.class); if (statementBase != null && statementBase.isOnDemand()) { diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/JavaMoveFilesOrDirectoriesHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/JavaMoveFilesOrDirectoriesHandler.java index 0b92f9983262..c7d131647d6d 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/JavaMoveFilesOrDirectoriesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/JavaMoveFilesOrDirectoriesHandler.java @@ -37,14 +37,6 @@ import java.util.*; public class JavaMoveFilesOrDirectoriesHandler extends MoveFilesOrDirectoriesHandler { @Override - public boolean canMove(PsiElement[] elements, PsiElement targetContainer) { - final PsiElement[] srcElements = adjustForMove(null, elements, targetContainer); - assert srcElements != null; - - return super.canMove(srcElements, targetContainer); - } - - @Override public PsiElement adjustTargetForMove(DataContext dataContext, PsiElement targetContainer) { if (targetContainer instanceof PsiPackage) { final Module module = LangDataKeys.TARGET_MODULE.getData(dataContext); @@ -60,6 +52,11 @@ public class JavaMoveFilesOrDirectoriesHandler extends MoveFilesOrDirectoriesHan @Override public PsiElement[] adjustForMove(Project project, PsiElement[] sourceElements, PsiElement targetElement) { + sourceElements = super.adjustForMove(project, sourceElements, targetElement); + if (sourceElements == null) { + return null; + } + Set<PsiElement> result = new LinkedHashSet<PsiElement>(); for (PsiElement sourceElement : sourceElements) { result.add(sourceElement instanceof PsiClass ? sourceElement.getContainingFile() : sourceElement); @@ -70,6 +67,10 @@ public class JavaMoveFilesOrDirectoriesHandler extends MoveFilesOrDirectoriesHan @Override public void doMove(final Project project, PsiElement[] elements, PsiElement targetContainer, MoveCallback callback) { + elements = super.adjustForMove(project, elements, targetContainer); + if (elements == null) { + return; + } MoveFilesOrDirectoriesUtil .doMove(project, elements, new PsiElement[]{targetContainer}, callback, new Function<PsiElement[], PsiElement[]>() { @Override @@ -89,7 +90,7 @@ public class JavaMoveFilesOrDirectoriesHandler extends MoveFilesOrDirectoriesHan adjustedElements.add(containingFile); continue; } - } + } } adjustedElements.add(element); } diff --git a/java/java-impl/src/com/intellij/refactoring/rename/FieldHidesLocalUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/rename/FieldHidesLocalUsageInfo.java new file mode 100644 index 000000000000..c56d2ba43e88 --- /dev/null +++ b/java/java-impl/src/com/intellij/refactoring/rename/FieldHidesLocalUsageInfo.java @@ -0,0 +1,44 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * 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. + */ + +/* + * Created by IntelliJ IDEA. + * User: dsl + * Date: 05.06.2002 + * Time: 12:43:27 + * To change template for new class use + * Code Style | Class Templates options (Tools | IDE Options). + */ +package com.intellij.refactoring.rename; + +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiMethod; +import com.intellij.refactoring.RefactoringBundle; +import com.intellij.refactoring.util.CommonRefactoringUtil; +import com.intellij.refactoring.util.RefactoringUIUtil; +import com.intellij.usageView.UsageViewUtil; + +public class FieldHidesLocalUsageInfo extends UnresolvableCollisionUsageInfo { + public FieldHidesLocalUsageInfo(PsiElement element, PsiElement referencedElement) { + super(element, referencedElement); + } + + public String getDescription() { + String descr = RefactoringBundle.message("local.will.be.hidden.renamed", + RefactoringUIUtil.getDescription(getElement(), true)); + return CommonRefactoringUtil.capitalize(descr); + } +} diff --git a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaVariableProcessor.java b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaVariableProcessor.java index 85f26f1b128f..73623205b438 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaVariableProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaVariableProcessor.java @@ -24,9 +24,11 @@ import com.intellij.openapi.ui.Messages; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.VariableKind; +import com.intellij.psi.controlFlow.ControlFlowUtil; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.search.searches.OverridingMethodsSearch; import com.intellij.psi.util.PropertyUtil; +import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.HelpID; import com.intellij.refactoring.JavaRefactoringSettings; @@ -350,6 +352,18 @@ public class RenameJavaVariableProcessor extends RenameJavaMemberProcessor { PsiField conflictingField = inheritor.findFieldByName(newName, false); if (conflictingField != null) { result.add(new SubmemberHidesMemberUsageInfo(conflictingField, field)); + } + else { //local class + final PsiMember member = PsiTreeUtil.getParentOfType(inheritor, PsiMember.class); + if (member != null) { + final ArrayList<PsiVariable> variables = new ArrayList<PsiVariable>(); + ControlFlowUtil.collectOuterLocals(variables, inheritor, inheritor, member); + for (PsiVariable variable : variables) { + if (newName.equals(variable.getName())) { + result.add(new FieldHidesLocalUsageInfo(variable, field)); + } + } + } } } } diff --git a/java/java-impl/src/com/intellij/refactoring/typeMigration/ChangeTypeSignatureHandler.java b/java/java-impl/src/com/intellij/refactoring/typeMigration/ChangeTypeSignatureHandler.java index e75b825bf87b..ad5bea350524 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeMigration/ChangeTypeSignatureHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/typeMigration/ChangeTypeSignatureHandler.java @@ -74,6 +74,9 @@ public class ChangeTypeSignatureHandler implements RefactoringActionHandler { protected static boolean isClassArgument(PsiElement element) { if (element instanceof PsiReferenceParameterList) { final PsiMember member = PsiTreeUtil.getParentOfType(element, PsiMember.class); + if (member instanceof PsiAnonymousClass) { + return ((PsiAnonymousClass)member).getBaseClassReference().getParameterList() == element; + } if (member instanceof PsiClass) { final PsiReferenceList implementsList = ((PsiClass)member).getImplementsList(); final PsiReferenceList extendsList = ((PsiClass)member).getExtendsList(); diff --git a/java/java-impl/src/com/intellij/testIntegration/BaseGenerateTestSupportMethodAction.java b/java/java-impl/src/com/intellij/testIntegration/BaseGenerateTestSupportMethodAction.java index cf363e5b4b47..40a97cf93981 100644 --- a/java/java-impl/src/com/intellij/testIntegration/BaseGenerateTestSupportMethodAction.java +++ b/java/java-impl/src/com/intellij/testIntegration/BaseGenerateTestSupportMethodAction.java @@ -24,6 +24,7 @@ import com.intellij.codeInsight.generation.actions.BaseGenerateAction; import com.intellij.codeInsight.hint.HintManager; import com.intellij.ide.fileTemplates.FileTemplateDescriptor; import com.intellij.ide.fileTemplates.impl.AllFileTemplatesConfigurable; +import com.intellij.ide.util.EditSourceUtil; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; @@ -199,6 +200,26 @@ public class BaseGenerateTestSupportMethodAction extends BaseGenerateAction { private void doGenerate(final Editor editor, final PsiFile file, final PsiClass targetClass, final TestFramework framework) { + if (framework instanceof JavaTestFramework && ((JavaTestFramework)framework).isSingleConfig()) { + PsiElement alreadyExist = null; + switch (myMethodKind) { + case SET_UP: + alreadyExist = framework.findSetUpMethod(targetClass); + break; + case TEAR_DOWN: + alreadyExist = framework.findTearDownMethod(targetClass); + break; + default: + break; + } + + if (alreadyExist instanceof PsiMethod) { + editor.getCaretModel().moveToOffset(alreadyExist.getNavigationElement().getTextOffset()); + HintManager.getInstance().showErrorHint(editor, "Method " + ((PsiMethod)alreadyExist).getName() + " already exists"); + return; + } + } + if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; WriteCommandAction.runWriteCommandAction(file.getProject(), new Runnable() { diff --git a/java/java-impl/src/com/intellij/testIntegration/JavaTestFinder.java b/java/java-impl/src/com/intellij/testIntegration/JavaTestFinder.java index 5bf07904d7fe..92fe17ad085e 100644 --- a/java/java-impl/src/com/intellij/testIntegration/JavaTestFinder.java +++ b/java/java-impl/src/com/intellij/testIntegration/JavaTestFinder.java @@ -25,6 +25,8 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; +import com.intellij.util.CommonProcessors; +import com.intellij.util.Processor; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -80,22 +82,29 @@ public class JavaTestFinder implements TestFinder { PsiClass klass = findSourceElement(element); if (klass == null) return Collections.emptySet(); + List<Pair<? extends PsiNamedElement, Integer>> classesWithProximities = new ArrayList<Pair<? extends PsiNamedElement, Integer>>(); + final CommonProcessors.CollectProcessor<Pair<? extends PsiNamedElement, Integer>> processor = + new CommonProcessors.CollectProcessor<Pair<? extends PsiNamedElement, Integer>>(classesWithProximities); + collectTests(klass, processor); + + return TestFinderHelper.getSortedElements(classesWithProximities, true); + } + + private static boolean collectTests(PsiClass klass, Processor<Pair<? extends PsiNamedElement, Integer>> processor) { GlobalSearchScope scope; - Module module = getModule(element); + Module module = getModule(klass); if (module != null) { scope = GlobalSearchScope.moduleWithDependentsScope(module); } else { - scope = GlobalSearchScope.projectScope(element.getProject()); + scope = GlobalSearchScope.projectScope(klass.getProject()); } - PsiShortNamesCache cache = PsiShortNamesCache.getInstance(element.getProject()); + PsiShortNamesCache cache = PsiShortNamesCache.getInstance(klass.getProject()); String klassName = klass.getName(); Pattern pattern = Pattern.compile(".*" + klassName + ".*"); - List<Pair<? extends PsiNamedElement, Integer>> classesWithProximities = new ArrayList<Pair<? extends PsiNamedElement, Integer>>(); - HashSet<String> names = new HashSet<String>(); cache.getAllClassNames(names); final TestFrameworks frameworks = TestFrameworks.getInstance(); @@ -103,14 +112,14 @@ public class JavaTestFinder implements TestFinder { if (pattern.matcher(eachName).matches()) { for (PsiClass eachClass : cache.getClassesByName(eachName, scope)) { if (frameworks.isTestClass(eachClass) || frameworks.isPotentialTestClass(eachClass)) { - classesWithProximities.add( - Pair.create(eachClass, TestFinderHelper.calcTestNameProximity(klassName, eachName))); + if (!processor.process(Pair.create(eachClass, TestFinderHelper.calcTestNameProximity(klassName, eachName)))) { + return true; + } } } } } - - return TestFinderHelper.getSortedElements(classesWithProximities, true); + return false; } @Nullable @@ -122,4 +131,13 @@ public class JavaTestFinder implements TestFinder { public boolean isTest(@NotNull PsiElement element) { return TestIntegrationUtils.isTest(element); } + + public static boolean hasTestsForClass(PsiClass aClass) { + return collectTests(aClass, new CommonProcessors.FindProcessor<Pair<? extends PsiNamedElement, Integer>>() { + @Override + protected boolean accept(Pair<? extends PsiNamedElement, Integer> pair) { + return true; + } + }); + } } diff --git a/java/java-impl/src/com/intellij/testIntegration/JavaTestFramework.java b/java/java-impl/src/com/intellij/testIntegration/JavaTestFramework.java index 6dfb54116bbb..1277dc59526e 100644 --- a/java/java-impl/src/com/intellij/testIntegration/JavaTestFramework.java +++ b/java/java-impl/src/com/intellij/testIntegration/JavaTestFramework.java @@ -124,4 +124,8 @@ public abstract class JavaTestFramework implements TestFramework { public void setupLibrary(Module module) { OrderEntryFix.addJarToRoots(getLibraryPath(), module, null); } + + public boolean isSingleConfig() { + return false; + } } diff --git a/java/java-impl/src/com/intellij/testIntegration/TestIntegrationUtils.java b/java/java-impl/src/com/intellij/testIntegration/TestIntegrationUtils.java index a4a5cb5e3162..9ac0cb014157 100644 --- a/java/java-impl/src/com/intellij/testIntegration/TestIntegrationUtils.java +++ b/java/java-impl/src/com/intellij/testIntegration/TestIntegrationUtils.java @@ -146,7 +146,14 @@ public class TestIntegrationUtils { final PsiMethod method, @Nullable String name, boolean automatic, Set<String> existingNames) { - Template template = createTestMethodTemplate(methodKind, framework, targetClass, name, automatic, existingNames); + runTestMethodTemplate(editor, targetClass, method, automatic, + createTestMethodTemplate(methodKind, framework, targetClass, name, automatic, existingNames)); + } + + public static void runTestMethodTemplate(final Editor editor, + final PsiClass targetClass, + final PsiMethod method, + boolean automatic, final Template template) { final TextRange range = method.getTextRange(); editor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), ""); diff --git a/java/java-impl/src/com/intellij/testIntegration/createTest/GenerateMissedTestsAction.java b/java/java-impl/src/com/intellij/testIntegration/createTest/GenerateMissedTestsAction.java new file mode 100644 index 000000000000..882fb723ee86 --- /dev/null +++ b/java/java-impl/src/com/intellij/testIntegration/createTest/GenerateMissedTestsAction.java @@ -0,0 +1,121 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * 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 com.intellij.testIntegration.createTest; + +import com.intellij.codeInsight.CodeInsightUtil; +import com.intellij.codeInsight.TestFrameworks; +import com.intellij.codeInsight.hint.HintManager; +import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction; +import com.intellij.ide.util.PsiClassListCellRenderer; +import com.intellij.openapi.command.WriteCommandAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.popup.JBPopupFactory; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiModifier; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.testIntegration.TestFinderHelper; +import com.intellij.testIntegration.TestFramework; +import com.intellij.ui.components.JBList; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class GenerateMissedTestsAction extends PsiElementBaseIntentionAction { + + @NotNull + public String getText() { + return "Generate missed test methods"; + } + + @NotNull + public String getFamilyName() { + return getText(); + } + + public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { + if (Extensions.getExtensions(TestFramework.EXTENSION_NAME).length == 0) return false; + + final PsiElement parent = element.getParent(); + if (!(parent instanceof PsiMethod)) return false; + + if (!((PsiMethod)parent).hasModifierProperty(PsiModifier.PUBLIC) || + ((PsiMethod)parent).hasModifierProperty(PsiModifier.ABSTRACT)) { + return false; + } + + return PsiTreeUtil.getParentOfType(element, PsiClass.class) != null; + } + + @Override + public void invoke(final @NotNull Project project, final Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { + final PsiClass srcClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); + + if (srcClass == null) return; + + final List<PsiElement> testClasses = TestFinderHelper.findTestsForClass(srcClass); + + if (testClasses.isEmpty()) { + HintManager.getInstance().showErrorHint(editor, "No tests found."); + return; + } + + if (testClasses.size() == 1) { + generateMissedTests((PsiClass)testClasses.get(0), srcClass); + return; + } + + final JBList list = new JBList(testClasses); + list.setCellRenderer(new PsiClassListCellRenderer()); + JBPopupFactory.getInstance().createListPopupBuilder(list) + .setItemChoosenCallback(new Runnable() { + @Override + public void run() { + generateMissedTests((PsiClass)list.getSelectedValue(), srcClass); + } + }) + .setTitle("Choose Test") + .createPopup().showInBestPositionFor(editor); + } + + private static void generateMissedTests(final PsiClass testClass, PsiClass srcClass) { + if (testClass != null) { + final TestFramework framework = TestFrameworks.detectFramework(testClass); + if (framework != null) { + final Project project = testClass.getProject(); + final Editor editor = CodeInsightUtil.positionCursor(project, testClass.getContainingFile(), testClass.getLBrace()); + final MissedTestsDialog dialog = new MissedTestsDialog(project, srcClass, testClass, framework); + dialog.show(); + if (dialog.isOK()) { + WriteCommandAction.runWriteCommandAction(project, new Runnable() { + @Override + public void run() { + JavaTestGenerator.addTestMethods(editor, testClass, framework, dialog.getSelectedMethods(), false, false); + } + }); + } + } + } + } + + public boolean startInWriteAction() { + return false; + } +}
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/testIntegration/createTest/JavaTestGenerator.java b/java/java-impl/src/com/intellij/testIntegration/createTest/JavaTestGenerator.java index 172019430800..abde9233f535 100644 --- a/java/java-impl/src/com/intellij/testIntegration/createTest/JavaTestGenerator.java +++ b/java/java-impl/src/com/intellij/testIntegration/createTest/JavaTestGenerator.java @@ -156,12 +156,12 @@ public class JavaTestGenerator implements TestGenerator { return JavaPsiFacade.getInstance(project).findClass(fqName, scope); } - private static void addTestMethods(Editor editor, - PsiClass targetClass, - final TestFramework descriptor, - Collection<MemberInfo> methods, - boolean generateBefore, - boolean generateAfter) throws IncorrectOperationException { + public static void addTestMethods(Editor editor, + PsiClass targetClass, + final TestFramework descriptor, + Collection<MemberInfo> methods, + boolean generateBefore, + boolean generateAfter) throws IncorrectOperationException { final Set<String> existingNames = new HashSet<String>(); if (generateBefore && descriptor.findSetUpMethod(targetClass) == null) { generateMethod(TestIntegrationUtils.MethodKind.SET_UP, descriptor, targetClass, editor, null, existingNames); @@ -170,8 +170,7 @@ public class JavaTestGenerator implements TestGenerator { generateMethod(TestIntegrationUtils.MethodKind.TEAR_DOWN, descriptor, targetClass, editor, null, existingNames); } - final Template template = TestIntegrationUtils .createTestMethodTemplate(TestIntegrationUtils.MethodKind.TEST, descriptor, targetClass, - null, true, existingNames); + final Template template = TestIntegrationUtils.createTestMethodTemplate(TestIntegrationUtils.MethodKind.TEST, descriptor, targetClass, null, true, existingNames); final String prefix = JavaPsiFacade.getElementFactory(targetClass.getProject()).createMethodFromText(template.getTemplateText(), targetClass).getName(); existingNames.addAll(ContainerUtil.map(targetClass.getMethods(), new Function<PsiMethod, String>() { @Override diff --git a/java/java-impl/src/com/intellij/testIntegration/createTest/MissedTestsDialog.java b/java/java-impl/src/com/intellij/testIntegration/createTest/MissedTestsDialog.java new file mode 100644 index 000000000000..b34d28e3f6f4 --- /dev/null +++ b/java/java-impl/src/com/intellij/testIntegration/createTest/MissedTestsDialog.java @@ -0,0 +1,120 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * 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 com.intellij.testIntegration.createTest; + +import com.intellij.codeInsight.CodeInsightBundle; +import com.intellij.codeInsight.template.Template; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiMember; +import com.intellij.psi.PsiMethod; +import com.intellij.refactoring.ui.MemberSelectionPanel; +import com.intellij.refactoring.ui.MemberSelectionTable; +import com.intellij.refactoring.util.classMembers.MemberInfo; +import com.intellij.testIntegration.TestFramework; +import com.intellij.testIntegration.TestIntegrationUtils; +import com.intellij.ui.ScrollPaneFactory; +import com.intellij.ui.SeparatorFactory; +import com.intellij.ui.components.JBCheckBox; +import com.intellij.util.Function; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.*; +import java.util.List; + +public class MissedTestsDialog extends DialogWrapper { + private final PsiClass mySourceClass; + private final PsiClass myTestClass; + private TestFramework myDescriptor; + private MemberSelectionTable myTable; + private JBCheckBox myIncludeInheritedCb = new JBCheckBox(CodeInsightBundle.message("intention.create.test.dialog.show.inherited")); + + public MissedTestsDialog(@Nullable Project project, PsiClass sourceClass, PsiClass testClass, TestFramework descriptor) { + super(project, true); + mySourceClass = sourceClass; + myTestClass = testClass; + myDescriptor = descriptor; + setTitle("Create Missed Tests"); + init(); + } + + public Collection<MemberInfo> getSelectedMethods() { + return myTable.getSelectedMemberInfos(); + } + + @Nullable + @Override + protected JComponent createCenterPanel() { + final List<MemberInfo> info = TestIntegrationUtils.extractClassMethods(mySourceClass, false); + + disableMethodsWithTests(info); + + final JPanel panel = new JPanel(new BorderLayout()); + myTable = new MemberSelectionTable(info, null); + panel.add(ScrollPaneFactory.createScrollPane(myTable), BorderLayout.CENTER); + panel.add(myIncludeInheritedCb, BorderLayout.NORTH); + myIncludeInheritedCb.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateMethodsTable(); + } + }); + return panel; + } + + private void disableMethodsWithTests(List<MemberInfo> info) { + final Set<String> existingNames = new HashSet<String>(); + final Template template = TestIntegrationUtils + .createTestMethodTemplate(TestIntegrationUtils.MethodKind.TEST, myDescriptor, myTestClass, null, true, existingNames); + final String prefix = JavaPsiFacade.getElementFactory(myTestClass.getProject()).createMethodFromText(template.getTemplateText(), myTestClass).getName(); + + existingNames.addAll(ContainerUtil.map(myTestClass.getMethods(), new Function<PsiMethod, String>() { + @Override + public String fun(PsiMethod method) { + return StringUtil.decapitalize(StringUtil.trimStart(method.getName(), prefix)); + } + })); + + + for (MemberInfo memberInfo : info) { + final PsiMember member = memberInfo.getMember(); + memberInfo.setChecked(!(member instanceof PsiMethod && existingNames.contains(member.getName()))); + } + } + + private void updateMethodsTable() { + List<MemberInfo> infos = TestIntegrationUtils.extractClassMethods(mySourceClass, myIncludeInheritedCb.isSelected()); + + Set<PsiMember> selectedMethods = new HashSet<PsiMember>(); + for (MemberInfo each : myTable.getSelectedMemberInfos()) { + selectedMethods.add(each.getMember()); + } + + for (MemberInfo each : infos) { + each.setChecked(selectedMethods.contains(each.getMember())); + } + + myTable.setMemberInfos(infos); + } +} |