diff --git a/.gitignore b/.gitignore index 5d9693f..6527bbc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,40 @@ +#Autosave files +*~ + +#build +[Oo]bj/ +[Bb]in/ packages/ -bin -obj -.DS_Store -*userprefs +TestResults/ -# Ignore NuGet Packages -*.nupkg -# Ignore the packages folder -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config +# globs +Makefile.in +*.DS_Store +*.sln.cache +*.suo +*.cache +*.pidb +*.userprefs +*.usertasks +config.log +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.user +*.tar.gz +tarballs/ +test-results/ +Thumbs.db -*/build/PlayScript.MSBuild.Tasks.dll +#Mac bundle stuff +*.dmg +*.app -TestResult.xml +#resharper +*_Resharper.* +*.Resharper +#dotCover +*.dotCover diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 0b315a6..0000000 --- a/.gitmodules +++ /dev/null @@ -1,12 +0,0 @@ -[submodule "external/NRefactory"] - path = external/NRefactory - url = https://github.com/PlayScriptRedux/NRefactory.git -[submodule "external/ikvm-fork"] - path = external/ikvm-fork - url = https://github.com/mono/ikvm-fork -[submodule "external/ikvm"] - path = external/ikvm - url = https://github.com/mono/ikvm-fork -[submodule "external/cecil"] - path = external/cecil - url = https://www.github.com/jbevain/cecil.git diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index bd0ade3..0000000 --- a/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -####Copyright 2015 by SushiHangover/RobertN - -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](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. - diff --git a/Makefile b/Makefile deleted file mode 100644 index a48a241..0000000 --- a/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -CONFIG?=Debug - -all: - xbuild /p:Configuration=${CONFIG} ${ARGS} - -clean: - xbuild /t:Clean ${ARGS} - -# Clean does not always really clean, so clean hard ;-) -cleanhard: - find . -name "obj" -print0 | xargs -0 -n 1 rm -Rf - find . -name "bin" -print0 | xargs -0 -n 1 rm -Rf - -install: - xbuild /p:InstallAddin=True /p:Configuration=${CONFIG} ${ARGS} - diff --git a/PlayScript.AOT.Nuget/LICENSE.md b/PlayScript.AOT.Nuget/LICENSE.md deleted file mode 100644 index bd0ade3..0000000 --- a/PlayScript.AOT.Nuget/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -####Copyright 2015 by SushiHangover/RobertN - -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](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. - diff --git a/PlayScript.AOT.Nuget/Makefile b/PlayScript.AOT.Nuget/Makefile deleted file mode 100644 index 084d507..0000000 --- a/PlayScript.AOT.Nuget/Makefile +++ /dev/null @@ -1,20 +0,0 @@ - -all: clean copy pack content - -pack: - nuget pack - -clean: - -find lib -name "*.dll" -print0 | xargs -0 -n 1 rm - -rm PlayScript.AOT.*.nupkg - -content: - unzip -l PlayScript.AOT.*.nupkg - -copy: - cp ../../playscript/mcs/class/lib/net_4_5/pscorlib_aot.dll lib/net45 - cp ../../playscript/mcs/class/lib/net_4_5/PlayScript.Dynamic_aot.dll lib/net45 - -publish: all - source mygetapikey.sh - nuget push PlayScript.AOT.*.nupkg $(MyGetApiKey) -source https://www.myget.org/F/playscript/api/v2 diff --git a/PlayScript.AOT.Nuget/PlayScript.AOT.nuspec b/PlayScript.AOT.Nuget/PlayScript.AOT.nuspec deleted file mode 100644 index 58499cc..0000000 --- a/PlayScript.AOT.Nuget/PlayScript.AOT.nuspec +++ /dev/null @@ -1,37 +0,0 @@ - - - - PlayScript.AOT - 5.10.2.1 - SushiHangover\RobertN - SushiHangover\RobertN - https://github.com/PlayScriptRedux/PlayScript.Addin - https://raw.githubusercontent.com/PlayScriptRedux/PlayScript.Addin/playscript/PlayScript.AOT.Nuget/img/PlayScript.AOT.png - https://github.com/PlayScriptRedux/PlayScript.Addin/blob/playscript/PlayScript.AOT.Nuget/LICENSE.md - false - - Adds PlayScripts AOT Libraries to your project. - - - Adds PlayScripts AOT Libraries to your project. - - * PCLs will be in a future release - * Requires the MonoDevelop.PlayScript.5.10.2.x Addin is installed - - requirement to be removed in a future release - - - PlayScript.AOT release notes: - - 5.10.2.1 Update : Update pscorlib - 5.10.2.0 New : Initial Public Release - - en-US - Copyright (c) SushiHangover\RobertN (sushihangover@outlook.com) - true - playscript actionscript - - - - - - diff --git a/PlayScript.AOT.Nuget/img/PlayScript.AOT.png b/PlayScript.AOT.Nuget/img/PlayScript.AOT.png deleted file mode 100644 index ad456de..0000000 Binary files a/PlayScript.AOT.Nuget/img/PlayScript.AOT.png and /dev/null differ diff --git a/PlayScript.Addin.sln b/PlayScript.Addin.sln index 12e141a..b53cb4c 100644 --- a/PlayScript.Addin.sln +++ b/PlayScript.Addin.sln @@ -1,177 +1,17 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlayScript.Addin", "PlayScript.Addin\PlayScript.Addin.csproj", "{07CC7654-27D6-421D-A64C-0FFA40456FA2}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NRefactory.PlayScript", "NRefactory.PlayScript", "{2AC59157-9886-470E-A84A-68554F40FCAB}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.PlayScript", "external\NRefactory\ICSharpCode.NRefactory.PlayScript\ICSharpCode.NRefactory.PlayScript.csproj", "{0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.PlayScript.IKVM", "external\NRefactory\ICSharpCode.NRefactory.IKVM\ICSharpCode.NRefactory.PlayScript.IKVM.csproj", "{6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.PlayScript.Refactoring", "external\NRefactory\ICSharpCode.NRefactory.PlayScript.Refactoring\ICSharpCode.NRefactory.PlayScript.Refactoring.csproj", "{D9654D35-F86C-4105-B4E6-FAA656487BF8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.PlayScript.Xml", "external\NRefactory\ICSharpCode.NRefactory.Xml\ICSharpCode.NRefactory.PlayScript.Xml.csproj", "{B1AF7070-8E25-4117-A441-14684219F4FD}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.Ps", "external\NRefactory\ICSharpCode.NRefactory\ICSharpCode.NRefactory.Ps.csproj", "{CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.PlayScript.GtkDemo", "external\NRefactory\ICSharpCode.NRefactory.GtkDemo\ICSharpCode.NRefactory.PlayScript.GtkDemo.csproj", "{BF360491-0779-4ADA-B4B4-70265417E672}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.PlayScript.AstVerifier", "external\NRefactory\ICSharpCode.NRefactory.PlayScript.AstVerifier\ICSharpCode.NRefactory.PlayScript.AstVerifier.csproj", "{54C56049-DD33-4AD4-AF45-4D1AAF883449}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.PlayScript.Cecil", "external\NRefactory\ICSharpCode.NRefactory.Cecil\ICSharpCode.NRefactory.PlayScript.Cecil.csproj", "{C2B518AC-75DD-4267-A18A-8E310CCF9181}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MonoDevelop", "MonoDevelop", "{8A17756F-3C04-4F26-8D37-5A46366BA535}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.Decompiler", "external\ICSharpCode.Decompiler\ICSharpCode.Decompiler.csproj", "{984CC812-9470-4A13-AFF9-CC44068D666C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlayScript.MSBuild.Tasks", "PlayScript.MSBuild.Tasks\PlayScript.MSBuild.Tasks.csproj", "{BA27E73E-B4F4-48B6-937E-E48D59ADD839}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlayScript.MSBuild.Tasks.Test", "PlayScript.MSBuild.Tasks.Test\PlayScript.MSBuild.Tasks.Test.csproj", "{5A10410E-0971-40D6-8135-EC5F77B8630A}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - Debug - AST|Any CPU = Debug - AST|Any CPU - net_4_5_Debug|Any CPU = net_4_5_Debug|Any CPU - net_4_5_Release|Any CPU = net_4_5_Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.net_4_5_Debug|Any CPU.ActiveCfg = Debug|Any CPU - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.net_4_5_Debug|Any CPU.Build.0 = Debug|Any CPU - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.net_4_5_Release|Any CPU.ActiveCfg = Debug|Any CPU - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.net_4_5_Release|Any CPU.Build.0 = Debug|Any CPU - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {07CC7654-27D6-421D-A64C-0FFA40456FA2}.Release|Any CPU.Build.0 = Release|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894}.Release|Any CPU.Build.0 = Release|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.Debug|Any CPU.Build.0 = Debug|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.net_4_5_Debug|Any CPU.ActiveCfg = Debug|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.net_4_5_Debug|Any CPU.Build.0 = Debug|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.net_4_5_Release|Any CPU.ActiveCfg = Debug|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.net_4_5_Release|Any CPU.Build.0 = Debug|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.Release|Any CPU.ActiveCfg = Release|Any CPU - {54C56049-DD33-4AD4-AF45-4D1AAF883449}.Release|Any CPU.Build.0 = Release|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.net_4_5_Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.net_4_5_Debug|Any CPU.Build.0 = Debug|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.net_4_5_Release|Any CPU.ActiveCfg = Debug|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.net_4_5_Release|Any CPU.Build.0 = Debug|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5A10410E-0971-40D6-8135-EC5F77B8630A}.Release|Any CPU.Build.0 = Release|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.net_4_5_Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.net_4_5_Debug|Any CPU.Build.0 = Debug|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.net_4_5_Release|Any CPU.ActiveCfg = Debug|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.net_4_5_Release|Any CPU.Build.0 = Debug|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F}.Release|Any CPU.Build.0 = Release|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.net_4_5_Debug|Any CPU.ActiveCfg = Debug|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.net_4_5_Debug|Any CPU.Build.0 = Debug|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.net_4_5_Release|Any CPU.ActiveCfg = Debug|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.net_4_5_Release|Any CPU.Build.0 = Debug|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {984CC812-9470-4A13-AFF9-CC44068D666C}.Release|Any CPU.Build.0 = Release|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B1AF7070-8E25-4117-A441-14684219F4FD}.Release|Any CPU.Build.0 = Release|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.net_4_5_Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.net_4_5_Debug|Any CPU.Build.0 = Debug|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.net_4_5_Release|Any CPU.ActiveCfg = Debug|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.net_4_5_Release|Any CPU.Build.0 = Debug|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BA27E73E-B4F4-48B6-937E-E48D59ADD839}.Release|Any CPU.Build.0 = Release|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.net_4_5_Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.net_4_5_Debug|Any CPU.Build.0 = Debug|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.net_4_5_Release|Any CPU.ActiveCfg = Debug|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.net_4_5_Release|Any CPU.Build.0 = Debug|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BF360491-0779-4ADA-B4B4-70265417E672}.Release|Any CPU.Build.0 = Release|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C2B518AC-75DD-4267-A18A-8E310CCF9181}.Release|Any CPU.Build.0 = Release|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187}.Release|Any CPU.Build.0 = Release|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.Debug - AST|Any CPU.ActiveCfg = Debug|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.Debug - AST|Any CPU.Build.0 = Debug|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D9654D35-F86C-4105-B4E6-FAA656487BF8}.Release|Any CPU.Build.0 = Release|Any CPU - {99FD191B-5567-46EC-B89A-3EA83E775087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {99FD191B-5567-46EC-B89A-3EA83E775087}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A727169F-D94F-443F-B305-B057D7F3B420}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A727169F-D94F-443F-B305-B057D7F3B420}.Release|Any CPU.ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {0D8EC1C8-9706-4D8B-96F2-8636F2C9F894} = {2AC59157-9886-470E-A84A-68554F40FCAB} - {6FBE63EB-4D01-4BED-BC3E-F4AB31AB7D6F} = {2AC59157-9886-470E-A84A-68554F40FCAB} - {D9654D35-F86C-4105-B4E6-FAA656487BF8} = {2AC59157-9886-470E-A84A-68554F40FCAB} - {B1AF7070-8E25-4117-A441-14684219F4FD} = {2AC59157-9886-470E-A84A-68554F40FCAB} - {CBDF3A0D-8B3A-4DEE-B9F9-6FA492A06187} = {2AC59157-9886-470E-A84A-68554F40FCAB} - {BF360491-0779-4ADA-B4B4-70265417E672} = {2AC59157-9886-470E-A84A-68554F40FCAB} - {54C56049-DD33-4AD4-AF45-4D1AAF883449} = {2AC59157-9886-470E-A84A-68554F40FCAB} - {C2B518AC-75DD-4267-A18A-8E310CCF9181} = {2AC59157-9886-470E-A84A-68554F40FCAB} - {984CC812-9470-4A13-AFF9-CC44068D666C} = {8A17756F-3C04-4F26-8D37-5A46366BA535} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlayScript.Addin", "PlayScript.Addin\PlayScript.Addin.csproj", "{DAE22D85-7821-4492-96BB-73B73CC6BA6D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DAE22D85-7821-4492-96BB-73B73CC6BA6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DAE22D85-7821-4492-96BB-73B73CC6BA6D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DAE22D85-7821-4492-96BB-73B73CC6BA6D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DAE22D85-7821-4492-96BB-73B73CC6BA6D}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/PlayScript.Addin/MSBuild.targets/Microsoft.Common.targets b/PlayScript.Addin/MSBuild.targets/Microsoft.Common.targets deleted file mode 100644 index 1422a09..0000000 --- a/PlayScript.Addin/MSBuild.targets/Microsoft.Common.targets +++ /dev/null @@ -1,938 +0,0 @@ - - - true - true - - - - - - - - Exe - .exe - .exe - .dll - .netmodule - - - - $(MSBuildProjectDirectory)\ - - - - - 11.0 - - - - $(MSBuildProjectName) - $(OutputPath)\ - bin\Debug\ - 2 - - .NETFramework - v4.0 - - $(TargetFrameworkIdentifier),Version=$(TargetFrameworkVersion),Profile=$(TargetFrameworkProfile) - $(TargetFrameworkIdentifier),Version=$(TargetFrameworkVersion) - - - - $(OutputPath) - $(OutDir)\ - - <_OriginalConfiguration>$(Configuration) - Debug - $(Configuration) - - <_OriginalPlatform>$(Platform) - AnyCPU - $(Platform) - - true - System.Core;$(AdditionalExplicitAssemblyReferences) - - - - true - - - - obj\ - $(BaseIntermediateOutputPath)\ - $(MSBuildProjectFile).FilesWrittenAbsolute.txt - - - - $(BaseIntermediateOutputPath)$(Configuration)\ - $(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\ - - - - $(IntermediateOutputPath)\ - - - - - - - <_OutDirItem Include="$(OutDir)"/> - - - - $(AssemblyName) - $(TargetName)$(TargetExt) - @(_OutDirItem->'%(FullPath)') - @(_OutDirItem->'%(FullPath)\$(TargetFileName)') - $(MSBuildAllProjects);$(MSBuildProjectFullPath);$(MSBuildToolsPath)\Microsoft.Common.targets - $(AssemblyOriginatorKeyFile) - true - - - - - - - - - - - - - AssignLinkMetadata - - - - - - - - - - - - - - - - - - - - - - - - - <_EmbeddedResourceWithLinkAssigned Remove="@(_EmbeddedResourceWithLinkAssigned)" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_TargetFrameworkDirectories Include="$(_TargetFrameworkDirectories);$(TargetFrameworkDirectory)" KeepDuplicates="false" /> - - - @(_TargetFrameworkDirectories) - - - - - - <_DesignTimeFacadeAssemblies Include="%(DesignTimeFacadeDirectories.Identity)\*.dll"/> - - - - $(TargetFrameworkDirectory);@(DesignTimeFacadeDirectories) - - - - - - - .exe; - .dll - - - - .exe.mdb; - .dll.mdb; - .xml - - - - {CandidateAssemblyFiles}; - $(ReferencePath); - @(AdditionalReferencePath); - {HintPathFromItem}; - {TargetFrameworkDirectory}; - {PkgConfig}; - {GAC}; - {RawFileName}; - $(OutDir) - - - - BeforeResolveReferences; - ResolveProjectReferences; - ResolveAssemblyReferences; - AfterResolveReferences - - - - GetFrameworkPaths; - GetReferenceAssemblyPaths; - PrepareForBuild - - - - - $(IntermediateOutputPath)$(TargetFrameworkMoniker).AssemblyAttribute$(DefaultLanguageSourceExtension) - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BuildOnlySettings; - BeforeBuild; - CoreBuild; - AfterBuild - - - - - - - - - - - - PrepareForBuild; - GetFrameworkPaths; - GetReferenceAssemblyPaths; - PreBuildEvent; - ResolveReferences; - CopyFilesMarkedCopyLocal; - PrepareResources; - Compile; - PrepareForRun; - DeployOutputFiles; - _RecordCleanFile; - PostBuildEvent - - - - - - - - - - - - - ResolveReferences; - GenerateTargetFrameworkMonikerAttribute; - BeforeCompile; - _TimestampBeforeCompile; - CoreCompile; - _TimestampAfterCompile; - AfterCompile - - - - - - - - - - - DeployOutputFiles - - - - - - - AssignTargetPaths; - SplitResourcesByCulture; - CreateManifestResourceNames; - CopyNonResxEmbeddedResources; - GenerateResources; - GenerateSatelliteAssemblies; - CompileLicxFiles - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BeforeRebuild; - Clean; - $(MSBuildProjectDefaultTargets); - AfterRebuild; - - - - BeforeRebuild; - Clean; - Build; - AfterRebuild; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BeforeClean; - CleanReferencedProjects; - CoreClean; - AfterClean - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - $(ResolveReferencesDependsOn); - ImplicitlyExpandDesignTimeFacades - - - - $(ImplicitlyExpandDesignTimeFacadesDependsOn); - GetReferenceAssemblyPaths - - - - - - - <_HasReferenceToSystemRuntime Condition="'%(_ResolvedDependencyFiles.Filename)' == 'System.Runtime'">true - - - - - - - false - false - ImplicitlyExpandDesignTimeFacades - - <_ResolveAssemblyReferenceResolvedFiles Include="@(ReferencePath)" Condition="'%(ReferencePath.ResolvedFrom)' == 'ImplicitlyExpandDesignTimeFacades'" /> - - - - - - - - diff --git a/PlayScript.Addin/MSBuild.targets/PlayScript.targets b/PlayScript.Addin/MSBuild.targets/PlayScript.targets deleted file mode 100644 index a744881..0000000 --- a/PlayScript.Addin/MSBuild.targets/PlayScript.targets +++ /dev/null @@ -1,181 +0,0 @@ - - - .cs - PlayScript - - - - false - - - - - - - - $(MSBuildAllProjects);$(MSBuildToolsPath)\PlayScript.Targets - - - - true - - - - - - - - - - <_ExplicitReference Include="@(_TargetFrameworkDirectories->'%(FullPath)\mscorlib.dll')" Condition="Exists('%(FullPath)\mscorlib.dll')"> - false - - - - <_ExplicitMSCorlibPath>$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPathToStandardLibraries ('$(TargetFrameworkIdentifier)', '$(TargetFrameworkVersion)', '$(TargetFrameworkProfile)'))\mscorlib.dll - - - <_ExplicitReference Include="@(_TargetFrameworkDirectories->'%(FullPath)\mscorlib.dll')" Condition="Exists('%(FullPath)\mscorlib.dll')"> - false - - - - <_ExplicitReference Include="$(_ExplicitMSCorlibPath)" Condition="Exists('$(_ExplicitMSCorlibPath)')"> - false - - - - - - - /Users/sushi/Library/Application Support/XamarinStudio-5.0/LocalInstall/Addins/MonoDevelop.PlayScript.5.10.2/MonoDevelop.PlayScript.SupportPackages - psc - $(PsBuildBinPath) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(ResolveAssemblyReferencesDependsOn);_AddCorlibReference - - - - -// <autogenerated /> -[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute("$(TargetFrameworkMoniker)", FrameworkDisplayName = "$(TargetFrameworkMonikerDisplayName)")] - - - - diff --git a/PlayScript.Addin/Makefile b/PlayScript.Addin/Makefile deleted file mode 100644 index 59d24c4..0000000 --- a/PlayScript.Addin/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -CONFIG?=Debug - -all: - xbuild /p:Configuration=${CONFIG} ${ARGS} - -clean: - xbuild /t:Clean ${ARGS} - -# Clean does not always really clean, so clean hard ;-) -cleanhard: - find . -name "obj" -print0 | xargs -0 -n 1 rm -Rf - find . -name "bin" -print0 | xargs -0 -n 1 rm -Rf - -install: - xbuild /p:InstallAddin=True /p:Configuration=${CONFIG} ${ARGS} - -find . -name "*.mpack" diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/AbstractGenerateAction.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/AbstractGenerateAction.cs deleted file mode 100644 index 7c0d274..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/AbstractGenerateAction.cs +++ /dev/null @@ -1,159 +0,0 @@ -// -// AbstractGenerateAction.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using System.Text; -using Gtk; -using System.Collections.Generic; -using MonoDevelop.Refactoring; -using MonoDevelop.Ide; -using MonoDevelop.Ide.TypeSystem; -using MonoDevelop.Components; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - public abstract class AbstractGenerateAction : IGenerateAction - { - readonly TreeStore store = new TreeStore (typeof(bool), typeof(Xwt.Drawing.Image), typeof(string), typeof(object)); - readonly CodeGenerationOptions options; - - public CodeGenerationOptions Options { - get { - return options; - } - } - - public TreeStore Store { - get { return store; } - } - - protected AbstractGenerateAction (CodeGenerationOptions options) - { - this.options = options; - } - - public void Initialize (TreeView treeView) - { - var column = new TreeViewColumn (); - - var toggleRenderer = new CellRendererToggle (); - toggleRenderer.Toggled += ToggleRendererToggled; - column.PackStart (toggleRenderer, false); - column.AddAttribute (toggleRenderer, "active", 0); - - var pixbufRenderer = new CellRendererImage (); - column.PackStart (pixbufRenderer, false); - column.AddAttribute (pixbufRenderer, "image", 1); - - var textRenderer = new CellRendererText (); - column.PackStart (textRenderer, true); - column.AddAttribute (textRenderer, "text", 2); - column.Expand = true; - - treeView.AppendColumn (column); - Ambience ambience = AmbienceService.GetAmbienceForFile (options.Document.FileName); - foreach (object obj in GetValidMembers ()) { - var member = obj as IEntity; - if (member != null) { - Store.AppendValues (false, ImageService.GetIcon (member.GetStockIcon (), IconSize.Menu), ambience.GetString (member, OutputFlags.ClassBrowserEntries), member); - continue; - } - - var tuple = obj as Tuple; - if (tuple != null) { - Store.AppendValues (false, ImageService.GetIcon (tuple.Item1.GetStockIcon (), IconSize.Menu), ambience.GetString (tuple.Item1, OutputFlags.ClassBrowserEntries), tuple); - continue; - } - - var variable = obj as IVariable; - if (variable != null) - Store.AppendValues (false, ImageService.GetIcon (variable.GetStockIcon (), IconSize.Menu), variable.Name, variable); - } - - treeView.Model = store; - } - - void ToggleRendererToggled (object o, ToggledArgs args) - { - TreeIter iter; - if (store.GetIterFromString (out iter, args.Path)) { - bool active = (bool)store.GetValue (iter, 0); - store.SetValue (iter, 0, !active); - } - } - - protected abstract IEnumerable GetValidMembers (); - - public bool IsValid () - { - return GetValidMembers ().Any (); - } - - protected abstract IEnumerable GenerateCode (List includedMembers); - - static string AddIndent (string text, string indent) - { - var doc = new Mono.TextEditor.TextDocument (); - doc.Text = text; - var result = new StringBuilder (); - foreach (var line in doc.Lines) { - result.Append (indent); - result.Append (doc.GetTextAt (line.SegmentIncludingDelimiter)); - } - return result.ToString (); - } - - public void GenerateCode () - { - TreeIter iter; - if (!store.GetIterFirst (out iter)) - return; - var includedMembers = new List (); - do { - bool include = (bool)store.GetValue (iter, 0); - if (include) - includedMembers.Add (store.GetValue (iter, 3)); - } while (store.IterNext (ref iter)); - - var output = new StringBuilder (); - string indent = RefactoringOptions.GetIndent (options.Document, (IEntity)options.EnclosingMember ?? options.EnclosingType) + "\t"; - foreach (string nodeText in GenerateCode (includedMembers)) { - if (output.Length > 0) { - output.AppendLine (); - output.AppendLine (); - } - output.Append (AddIndent (nodeText, indent)); - } - - if (output.Length > 0) { - var data = options.Document.Editor; - data.InsertAtCaret (output.ToString ().TrimStart ()); - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/CodeGenerationCommands.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/CodeGenerationCommands.cs deleted file mode 100644 index edae605..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/CodeGenerationCommands.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -// CodeGenerationCommand.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - enum CodeGenerationCommands - { - ShowCodeGenerationWindow - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/CodeGenerationOptions.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/CodeGenerationOptions.cs deleted file mode 100644 index 9f1abcf..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/CodeGenerationOptions.cs +++ /dev/null @@ -1,173 +0,0 @@ -// -// CodeGenerationOptions.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System.Linq; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide; -using MonoDevelop.Ide.TypeSystem; -using MonoDevelop.Core; -using System; -using System.Threading; -using ICSharpCode.NRefactory.TypeSystem; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.Resolver; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - public class CodeGenerationOptions - { - public Document Document { - get; - private set; - } - - public ITypeDefinition EnclosingType { - get; - private set; - } - - public IUnresolvedTypeDefinition EnclosingPart { - get; - private set; - } - - public IMember EnclosingMember { - get; - private set; - } - - public string MimeType { - get { - return DesktopService.GetMimeTypeForUri (Document.FileName); - } - } - - public CSharpFormattingOptions FormattingOptions { - get { - var doc = Document; - var policyParent = doc.Project != null ? doc.Project.Policies : null; - var types = DesktopService.GetMimeTypeInheritanceChain (doc.Editor.MimeType); - var codePolicy = policyParent != null ? policyParent.Get (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy (types); - return codePolicy.CreateOptions (); - } - } - - static AstNode FirstExpressionChild (AstNode parent) - { - AstNode node = parent.FirstChild; - if (node == null) - return null; - while (node != null && !(node is Expression || node is Statement)) { - node = node.NextSibling; - } - return node; - } - - static AstNode NextExpression (AstNode parent) - { - AstNode node = parent.GetNextNode (); - if (node == null) - return null; - while (node != null && !(node is Expression || node is Statement)) { - node = node.GetNextNode (); - } - return node; - } - - readonly Lazy currentState; - public CSharpResolver CurrentState { - get { - return currentState.Value; - } - } - - public CodeGenerationOptions () - { - currentState = new Lazy (() => { - var parsedDocument = Document.ParsedDocument; - if (parsedDocument == null) - return null; - var unit = parsedDocument.GetAst ().Clone (); - var file = parsedDocument.ParsedFile as CSharpUnresolvedFile; - - var resolvedNode = unit.GetNodeAt (Document.Editor.Caret.Location); - if (resolvedNode == null) - return null; - - var expr = new IdentifierExpression ("foo"); - resolvedNode.Add (expr); - - var ctx = file.GetTypeResolveContext (Document.Compilation, Document.Editor.Caret.Location); - - var resolver = new CSharpResolver (ctx); - - var astResolver = new CSharpAstResolver (resolver, unit, file); - astResolver.ApplyNavigator (new NodeListResolveVisitorNavigator (expr), CancellationToken.None); - astResolver.Resolve (expr); - return astResolver.GetResolverStateBefore (expr); - }); - } - - public AstType CreateShortType (IType fullType) - { - var parsedFile = Document.ParsedDocument.ParsedFile as CSharpUnresolvedFile; - - var compilation = Document.Compilation; - fullType = compilation.Import (fullType); - var csResolver = parsedFile.GetResolver (compilation, Document.Editor.Caret.Location); - - var builder = new ICSharpCode.NRefactory.PlayScript.Refactoring.TypeSystemAstBuilder (csResolver); - return builder.ConvertType (fullType); - } - - public CodeGenerator CreateCodeGenerator () - { - var result = CodeGenerator.CreateGenerator (Document); - if (result == null) - LoggingService.LogError ("Generator can't be generated for : " + Document.Editor.MimeType); - return result; - } - - public static CodeGenerationOptions CreateCodeGenerationOptions (Document document) - { - document.UpdateParseDocument (); - var options = new CodeGenerationOptions { - Document = document - }; - if (document.ParsedDocument != null && document.ParsedDocument.ParsedFile != null) { - options.EnclosingPart = document.ParsedDocument.ParsedFile.GetInnermostTypeDefinition (document.Editor.Caret.Location); - var project = document.Project; - if (options.EnclosingPart != null && project != null) - options.EnclosingType = options.EnclosingPart.Resolve (project).GetDefinition (); - if (options.EnclosingType != null) { - options.EnclosingMember = options.EnclosingType.Members.FirstOrDefault (m => !m.IsSynthetic && m.Region.FileName == document.FileName && m.Region.IsInside (document.Editor.Caret.Location)); - } - } - return options; - } - - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/CreateConstructorGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/CreateConstructorGenerator.cs deleted file mode 100644 index 84795ef..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/CreateConstructorGenerator.cs +++ /dev/null @@ -1,167 +0,0 @@ -// -// CreateConstructorGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using Gtk; -using System.Collections.Generic; -using MonoDevelop.Core; -using System.Linq; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class CreateConstructorGenerator : ICodeGenerator - { - public string Icon { - get { - return "md-newmethod"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("Constructor"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select members to be initialized by the constructor."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - var createConstructor = new CreateConstructor (options); - return createConstructor.IsValid (); - } - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, TreeView treeView) - { - var createConstructor = new CreateConstructor (options); - createConstructor.Initialize (treeView); - return createConstructor; - } - - class CreateConstructor : AbstractGenerateAction - { - public CreateConstructor (CodeGenerationOptions options) : base (options) - { - } - - protected override IEnumerable GetValidMembers () - { - if (Options.EnclosingType == null || Options.EnclosingMember != null) - yield break; - - var bt = Options.EnclosingType.DirectBaseTypes.FirstOrDefault (t => t.Kind != TypeKind.Interface); - - if (bt != null) { - var ctors = bt.GetConstructors (m => !m.IsSynthetic).ToList (); - foreach (var ctor in ctors) { - if (ctor.Parameters.Count > 0 || ctors.Count > 1) { - yield return ctor; - } - } - } - - foreach (IField field in Options.EnclosingType.Fields) { - if (field.IsSynthetic) - continue; - yield return field; - } - - foreach (IProperty property in Options.EnclosingType.Properties) { - if (property.IsSynthetic) - continue; - if (!property.CanSet) - continue; - yield return property; - } - } - - static string CreateParameterName (IMember member) - { - if (char.IsUpper (member.Name[0])) - return char.ToLower (member.Name[0]) + member.Name.Substring (1); - return member.Name; - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - bool gotConstructorOverrides = false; - foreach (IMethod m in includedMembers.OfType ().Where (m => m.SymbolKind == SymbolKind.Constructor)) { - gotConstructorOverrides = true; - var init = new ConstructorInitializer { - ConstructorInitializerType = ConstructorInitializerType.Base - }; - - var overridenConstructor = new ConstructorDeclaration { - Name = Options.EnclosingType.Name, - Modifiers = Modifiers.Public, - Body = new BlockStatement (), - }; - - if (m.Parameters.Count > 0) - overridenConstructor.Initializer = init; - - foreach (var par in m.Parameters) { - overridenConstructor.Parameters.Add (new ParameterDeclaration (Options.CreateShortType (par.Type), par.Name)); - init.Arguments.Add (new IdentifierExpression(par.Name)); - } - foreach (var member in includedMembers.OfType ()) { - if (member.SymbolKind == SymbolKind.Constructor) - continue; - overridenConstructor.Parameters.Add (new ParameterDeclaration (Options.CreateShortType (member.ReturnType), CreateParameterName (member))); - - var memberReference = new MemberReferenceExpression (new ThisReferenceExpression (), member.Name); - var assign = new AssignmentExpression (memberReference, AssignmentOperatorType.Assign, new IdentifierExpression (CreateParameterName (member))); - overridenConstructor.Body.Statements.Add (new ExpressionStatement (assign)); - } - - yield return overridenConstructor.ToString (Options.FormattingOptions); - } - if (gotConstructorOverrides) - yield break; - var constructorDeclaration = new ConstructorDeclaration { - Name = Options.EnclosingType.Name, - Modifiers = Modifiers.Public, - Body = new BlockStatement () - }; - - foreach (IMember member in includedMembers) { - constructorDeclaration.Parameters.Add (new ParameterDeclaration (Options.CreateShortType (member.ReturnType), CreateParameterName (member))); - - var memberReference = new MemberReferenceExpression (new ThisReferenceExpression (), member.Name); - var assign = new AssignmentExpression (memberReference, AssignmentOperatorType.Assign, new IdentifierExpression (CreateParameterName (member))); - constructorDeclaration.Body.Statements.Add (new ExpressionStatement (assign)); - } - - yield return constructorDeclaration.ToString (Options.FormattingOptions); - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/EqualityMembersGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/EqualityMembersGenerator.cs deleted file mode 100644 index bc911a1..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/EqualityMembersGenerator.cs +++ /dev/null @@ -1,159 +0,0 @@ -// -// EqualityMembersGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System.Collections.Generic; -using MonoDevelop.Core; -using ICSharpCode.NRefactory.TypeSystem; -using ICSharpCode.NRefactory.PlayScript; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class EqualityMembersGenerator : ICodeGenerator - { - public string Icon { - get { - return "md-newmethod"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("Equality members"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select members to include in equality."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - return new CreateEquality (options).IsValid (); - } - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView) - { - var createEventMethod = new CreateEquality (options); - createEventMethod.Initialize (treeView); - return createEventMethod; - } - - class CreateEquality : AbstractGenerateAction - { - public CreateEquality (CodeGenerationOptions options) : base (options) - { - } - - protected override IEnumerable GetValidMembers () - { - if (Options.EnclosingType == null || Options.EnclosingMember != null) - yield break; - foreach (IField field in Options.EnclosingType.Fields) { - if (field.IsSynthetic) - continue; - yield return field; - } - - foreach (IProperty property in Options.EnclosingType.Properties) { - if (property.IsSynthetic) - continue; - if (property.CanGet) - yield return property; - } - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - // Genereate Equals - var methodDeclaration = new MethodDeclaration (); - methodDeclaration.Name = "Equals"; - - methodDeclaration.ReturnType = new PrimitiveType ("bool"); - methodDeclaration.Modifiers = Modifiers.Public | Modifiers.Override; - methodDeclaration.Body = new BlockStatement (); - methodDeclaration.Parameters.Add (new ParameterDeclaration (new PrimitiveType ("object"), "obj")); - var paramId = new IdentifierExpression ("obj"); - var ifStatement = new IfElseStatement (); - ifStatement.Condition = new BinaryOperatorExpression (paramId, BinaryOperatorType.Equality, new PrimitiveExpression (null)); - ifStatement.TrueStatement = new ReturnStatement (new PrimitiveExpression (false)); - methodDeclaration.Body.Statements.Add (ifStatement); - - ifStatement = new IfElseStatement (); - var arguments = new List (); - arguments.Add (new ThisReferenceExpression ()); - arguments.Add (paramId.Clone ()); - ifStatement.Condition = new InvocationExpression (new IdentifierExpression ("ReferenceEquals"), arguments); - ifStatement.TrueStatement = new ReturnStatement (new PrimitiveExpression (true)); - methodDeclaration.Body.Statements.Add (ifStatement); - - ifStatement = new IfElseStatement (); - ifStatement.Condition = new BinaryOperatorExpression (new InvocationExpression (new MemberReferenceExpression (paramId.Clone (), "GetType")), BinaryOperatorType.InEquality, new TypeOfExpression (new SimpleType (Options.EnclosingType.Name))); - ifStatement.TrueStatement = new ReturnStatement (new PrimitiveExpression (false)); - methodDeclaration.Body.Statements.Add (ifStatement); - - var varType = new SimpleType (Options.EnclosingType.Name); - var varDecl = new VariableDeclarationStatement (varType, "other", new CastExpression (varType.Clone (), paramId.Clone ())); - methodDeclaration.Body.Statements.Add (varDecl); - - var otherId = new IdentifierExpression ("other"); - Expression binOp = null; - foreach (IMember member in includedMembers) { - Expression right = new BinaryOperatorExpression (new IdentifierExpression (member.Name), BinaryOperatorType.Equality, new MemberReferenceExpression (otherId.Clone (), member.Name)); - binOp = binOp == null ? right : new BinaryOperatorExpression (binOp, BinaryOperatorType.ConditionalAnd, right); - } - - methodDeclaration.Body.Statements.Add (new ReturnStatement (binOp)); - yield return methodDeclaration.ToString (Options.FormattingOptions); - - methodDeclaration = new MethodDeclaration (); - methodDeclaration.Name = "GetHashCode"; - - methodDeclaration.ReturnType = new PrimitiveType ("int"); - methodDeclaration.Modifiers = Modifiers.Public | Modifiers.Override; - methodDeclaration.Body = new BlockStatement (); - - binOp = null; - foreach (IMember member in includedMembers) { - Expression right; - right = new InvocationExpression (new MemberReferenceExpression (new IdentifierExpression (member.Name), "GetHashCode")); - - IType type = member.ReturnType; - if (type != null && type.Kind != TypeKind.Struct && type.Kind != TypeKind.Enum) - right = new ParenthesizedExpression (new ConditionalExpression (new BinaryOperatorExpression (new IdentifierExpression (member.Name), BinaryOperatorType.InEquality, new PrimitiveExpression (null)), right, new PrimitiveExpression (0))); - - binOp = binOp == null ? right : new BinaryOperatorExpression (binOp, BinaryOperatorType.ExclusiveOr, right); - } - var uncheckedBlock = new BlockStatement (); - uncheckedBlock.Statements.Add (new ReturnStatement (binOp)); - - methodDeclaration.Body.Statements.Add (new UncheckedStatement (uncheckedBlock)); - yield return methodDeclaration.ToString (Options.FormattingOptions); - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ExportCodeGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ExportCodeGenerator.cs deleted file mode 100644 index 373da29..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ExportCodeGenerator.cs +++ /dev/null @@ -1,331 +0,0 @@ -// -// ExportCodeGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using Gtk; -using System.Collections.Generic; -using ICSharpCode.NRefactory.PlayScript; -using MonoDevelop.Core; -using ICSharpCode.NRefactory.TypeSystem; -using System.Linq; -using ICSharpCode.NRefactory.PlayScript.Refactoring; -using MonoDevelop.PlayScript.Refactoring.CodeActions; -//using MonoDevelop.CodeGeneration; -using MonoDevelop.PlayScript.Completion; -using MonoDevelop.PlayScript; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - abstract class BaseExportCodeGenerator : ICodeGenerator - { - public abstract bool IsValidMember (IMember member); - - #region ICodeGenerator implementation - - bool ICodeGenerator.IsValid (CodeGenerationOptions options) - { - return new ExportMethods (this, options).IsValid (); - } - - IGenerateAction ICodeGenerator.InitalizeSelection (CodeGenerationOptions options, TreeView treeView) - { - var exportMethods = new ExportMethods (this, options); - exportMethods.Initialize (treeView); - return exportMethods; - } - - string ICodeGenerator.Icon { - get { - return "md-method"; - } - } - - public abstract string Text { - get; - } - - public abstract string GenerateDescription { - get; - } - - #endregion - - public static bool HasProtocolAttribute (IType type, out string name) - { - foreach (var attrs in type.GetDefinition ().GetAttributes ()) { - if (attrs.AttributeType.Name == "ProtocolAttribute" && MonoCSharpCompletionEngine.IsFoundationNamespace (attrs.AttributeType.Namespace)) { - foreach (var na in attrs.NamedArguments) { - if (na.Key.Name != "Name") - continue; - name = na.Value.ConstantValue as string; - if (name != null) - return true; - } - } - } - name = null; - return false; - } - - public static Attribute GenerateExportAttribute (RefactoringContext ctx, IMember member) - { - if (member == null) - return null; - - bool useMonoTouchNamespace = false; - var exportAttribute = member.GetAttribute (new FullTypeName (new TopLevelTypeName ("Foundation", "ExportAttribute"))); - if (exportAttribute == null) { - useMonoTouchNamespace = true; - exportAttribute = member.GetAttribute (new FullTypeName (new TopLevelTypeName ("MonoTouch.Foundation", "ExportAttribute"))); - } - - if (exportAttribute == null || exportAttribute.PositionalArguments.Count == 0) - return null; - - var astType = useMonoTouchNamespace - ? CreateMonoTouchExportAttributeAst (ctx) - : CreateUnifiedExportAttributeAst (ctx); - - var attr = new Attribute { - Type = astType, - }; - - attr.Arguments.Add (new PrimitiveExpression (exportAttribute.PositionalArguments [0].ConstantValue)); - return attr; - } - - static AstType CreateUnifiedExportAttributeAst (RefactoringContext ctx) - { - var astType = ctx.CreateShortType ("Foundation", "ExportAttribute"); - if (astType is SimpleType) { - astType = new SimpleType ("Export"); - } else { - astType = new MemberType (new SimpleType ("Foundation"), "Export"); - } - return astType; - } - - static AstType CreateMonoTouchExportAttributeAst (RefactoringContext ctx) - { - var astType = ctx.CreateShortType ("MonoTouch.Foundation", "ExportAttribute"); - if (astType is SimpleType) { - astType = new SimpleType ("Export"); - } else { - astType = new MemberType (new MemberType (new SimpleType ("MonoTouch"), "Foundation"), "Export"); - } - return astType; - } - - static IMember GetProtocolMember (RefactoringContext ctx, IType protocolType, IMember member) - { - foreach (var m in protocolType.GetMembers (m => m.SymbolKind == member.SymbolKind && m.Name == member.Name)) { - if (!SignatureComparer.Ordinal.Equals (m, member)) - return null; - var prop = m as IProperty; - if (prop != null) { - if (prop.CanGet && GenerateExportAttribute (ctx, prop.Getter) != null || - prop.CanSet && GenerateExportAttribute (ctx, prop.Setter) != null) - return m; - } else { - if (GenerateExportAttribute (ctx, m) != null) - return m; - } - } - return null; - } - - static string GetProtocol (IMember member) - { - var attr = member.Attributes.FirstOrDefault (a => a.AttributeType.Name == "ExportAttribute" && MonoCSharpCompletionEngine.IsFoundationNamespace (a.AttributeType.Namespace)); - if (attr == null || attr.PositionalArguments.Count == 0) - return null; - return attr.PositionalArguments.First ().ConstantValue.ToString (); - } - - public static bool IsImplemented (IType type, IMember protocolMember) - { - foreach (var m in type.GetMembers (m => m.SymbolKind == protocolMember.SymbolKind && m.Name == protocolMember.Name)) { - var p = m as IProperty; - if (p != null) { - if (p.CanGet && ((IProperty)protocolMember).CanGet && GetProtocol (p.Getter) == GetProtocol (((IProperty)protocolMember).Getter)) - return true; - if (p.CanSet && ((IProperty)protocolMember).CanSet && GetProtocol (p.Setter) == GetProtocol (((IProperty)protocolMember).Setter)) - return true; - continue; - } - if (GetProtocol (m) == GetProtocol (protocolMember)) - return true; - } - return false; - } - - class ExportMethods : AbstractGenerateAction - { - readonly BaseExportCodeGenerator cg; - - public ExportMethods (BaseExportCodeGenerator cg, CodeGenerationOptions options) : base (options) - { - this.cg = cg; - } - - - protected override IEnumerable GetValidMembers () - { - var type = Options.EnclosingType; - if (type == null || Options.EnclosingMember != null) - yield break; - foreach (var t in type.DirectBaseTypes) { - string name; - if (!HasProtocolAttribute (t, out name)) - continue; - var protocolType = Options.Document.Compilation.FindType (new FullTypeName (new TopLevelTypeName (t.Namespace, name))); - if (protocolType == null) - break; - foreach (var member in protocolType.GetMethods (null, GetMemberOptions.IgnoreInheritedMembers)) { - if (member.ImplementedInterfaceMembers.Any ()) - continue; - if (!cg.IsValidMember (member)) - continue; - if (IsImplemented (type, member)) - continue; - if (member.Attributes.Any (a => a.AttributeType.Name == "ExportAttribute" && MonoCSharpCompletionEngine.IsFoundationNamespace (a.AttributeType.Namespace))) - yield return member; - } - foreach (var member in protocolType.GetProperties (null, GetMemberOptions.IgnoreInheritedMembers)) { - if (member.ImplementedInterfaceMembers.Any ()) - continue; - if (!cg.IsValidMember (member)) - continue; - if (IsImplemented (type, member)) - continue; - if (member.CanGet && member.Getter.Attributes.Any (a => a.AttributeType.Name == "ExportAttribute" && MonoCSharpCompletionEngine.IsFoundationNamespace (a.AttributeType.Namespace)) || - member.CanSet && member.Setter.Attributes.Any (a => a.AttributeType.Name == "ExportAttribute" && MonoCSharpCompletionEngine.IsFoundationNamespace (a.AttributeType.Namespace))) - yield return member; - } - } - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - var generator = Options.CreateCodeGenerator (); - generator.AutoIndent = false; - var ctx = MDRefactoringContext.Create (Options.Document, Options.Document.Editor.Caret.Location).Result; - if (ctx == null) - yield break; - var builder = ctx.CreateTypeSystemAstBuilder (); - - foreach (IMember member in includedMembers) { - yield return GenerateMemberCode (ctx, builder, member); - } - } - } - - internal static string GenerateMemberCode (MDRefactoringContext ctx, TypeSystemAstBuilder builder, IMember member) - { - var method = builder.ConvertEntity (member) as MethodDeclaration; - if (method != null) { - method.Body = new BlockStatement { - new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException"))) - }; - method.Modifiers &= ~Modifiers.Virtual; - method.Modifiers &= ~Modifiers.Abstract; - method.Attributes.Add (new AttributeSection { - Attributes = { - GenerateExportAttribute (ctx, member) - } - }); - return method.ToString (ctx.FormattingOptions); - } - var property = builder.ConvertEntity (member) as PropertyDeclaration; - if (property == null) - return null; - var p = (IProperty)member; - property.Modifiers &= ~Modifiers.Virtual; - property.Modifiers &= ~Modifiers.Abstract; - if (p.CanGet) { - property.Getter.Body = new BlockStatement { - new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException"))) - }; - property.Getter.Attributes.Add (new AttributeSection { - Attributes = { - GenerateExportAttribute (ctx, p.Getter) - } - }); - } - if (p.CanSet) { - property.Setter.Body = new BlockStatement { - new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException"))) - }; - property.Setter.Attributes.Add (new AttributeSection { - Attributes = { - GenerateExportAttribute (ctx, p.Setter) - } - }); - } - return property.ToString (ctx.FormattingOptions); - } - } - - class OptionalProtocolMemberGenerator : BaseExportCodeGenerator - { - public override string Text { - get { - return GettextCatalog.GetString ("Implement protocol members"); - } - } - - public override string GenerateDescription { - get { - return GettextCatalog.GetString ("Select protocol members to implement"); - } - } - - public override bool IsValidMember (IMember member) - { - return !member.IsAbstract; - } - } - - class RequiredProtocolMemberGenerator : BaseExportCodeGenerator - { - public override string Text { - get { - return GettextCatalog.GetString ("Implement required protocol members"); - } - } - - public override string GenerateDescription { - get { - return GettextCatalog.GetString ("Select protocol members to implement"); - } - } - - public override bool IsValidMember (IMember member) - { - return member.IsAbstract; - } - } - -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/GenerateCodeWindow.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/GenerateCodeWindow.cs deleted file mode 100644 index 7caaff6..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/GenerateCodeWindow.cs +++ /dev/null @@ -1,241 +0,0 @@ -// -// GenerateCodeWindow.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using MonoDevelop.Components; -using Gtk; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Refactoring; -using System.Collections.Generic; -using MonoDevelop.Ide; -using Mono.TextEditor.PopupWindow; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - partial class GenerateCodeWindow : Gtk.Window - { - TreeStore generateActionsStore = new TreeStore (typeof(Xwt.Drawing.Image), typeof (string), typeof (ICodeGenerator)); - - class CustomTreeView : TreeView - { - protected override bool OnKeyPressEvent (Gdk.EventKey evnt) - { - if (evnt.Key == Gdk.Key.Return || evnt.Key == Gdk.Key.KP_Enter) { - OnSubmit (EventArgs.Empty); - return true; - } - if (evnt.Key == Gdk.Key.Escape) { - OnCancel (EventArgs.Empty); - return true; - } - return base.OnKeyPressEvent (evnt); - } - - protected virtual void OnSubmit (EventArgs e) - { - if (Submit != null) - Submit (this, e); - } - public event EventHandler Submit; - - protected virtual void OnCancel (EventArgs e) - { - if (Cancel != null) - Cancel (this, e); - } - public event EventHandler Cancel; - } - - CustomTreeView treeviewSelection = new CustomTreeView (); - CustomTreeView treeviewGenerateActions = new CustomTreeView (); - IGenerateAction curInitializeObject = null; - CodeGenerationOptions options; - - GenerateCodeWindow (CodeGenerationOptions options, MonoDevelop.Ide.CodeCompletion.CodeCompletionContext completionContext) : base(Gtk.WindowType.Toplevel) - { - this.options = options; - this.Build (); - scrolledwindow1.Child = treeviewGenerateActions; - scrolledwindow1.ShowAll (); - - scrolledwindow2.Child = treeviewSelection; - scrolledwindow2.ShowAll (); - - treeviewGenerateActions.Cancel += delegate { - Destroy (); - }; - treeviewGenerateActions.Submit += delegate { - treeviewSelection.GrabFocus (); - }; - - treeviewSelection.Cancel += delegate { - treeviewGenerateActions.GrabFocus (); - }; - - treeviewSelection.Submit += delegate { - if (curInitializeObject != null) { - curInitializeObject.GenerateCode (); - curInitializeObject = null; - } - Destroy (); - }; - - WindowTransparencyDecorator.Attach (this); - - treeviewSelection.HeadersVisible = false; - - treeviewGenerateActions.HeadersVisible = false; - treeviewGenerateActions.Model = generateActionsStore; - TreeViewColumn column = new TreeViewColumn (); - var pixbufRenderer = new CellRendererImage (); - column.PackStart (pixbufRenderer, false); - column.AddAttribute (pixbufRenderer, "image", 0); - - CellRendererText textRenderer = new CellRendererText (); - column.PackStart (textRenderer, true); - column.AddAttribute (textRenderer, "text", 1); - column.Expand = true; - treeviewGenerateActions.AppendColumn (column); - - treeviewGenerateActions.Selection.Changed += TreeviewGenerateActionsSelectionChanged; - this.Remove (this.vbox1); - BorderBox messageArea = new BorderBox (); - messageArea.Add (vbox1); - this.Add (messageArea); - this.ShowAll (); - - int x = completionContext.TriggerXCoord; - int y = completionContext.TriggerYCoord; - - int w, h; - GetSize (out w, out h); - - int myMonitor = Screen.GetMonitorAtPoint (x, y); - Gdk.Rectangle geometry = DesktopService.GetUsableMonitorGeometry (Screen, myMonitor); - - if (x + w > geometry.Right) - x = geometry.Right - w; - - if (y + h > geometry.Bottom) - y = y - completionContext.TriggerTextHeight - h; - - Move (x, y); - } - - void Populate (List validGenerators) - { - foreach (var generator in validGenerators) - generateActionsStore.AppendValues (ImageService.GetIcon (generator.Icon, IconSize.Menu), generator.Text, generator); - - TreeIter iter; - if (generateActionsStore.GetIterFirst (out iter)) - treeviewGenerateActions.Selection.SelectIter (iter); - treeviewGenerateActions.GrabFocus (); - } - - void TreeviewGenerateActionsSelectionChanged (object sender, EventArgs e) - { - treeviewSelection.Model = null; - foreach (TreeViewColumn column in treeviewSelection.Columns) { - treeviewSelection.RemoveColumn (column); - } - - TreeIter iter; - if (treeviewGenerateActions.Selection.GetSelected (out iter)) { - ICodeGenerator codeGenerator = (ICodeGenerator)generateActionsStore.GetValue (iter, 2); - labelDescription.Text = codeGenerator.GenerateDescription; - curInitializeObject = codeGenerator.InitalizeSelection (options, treeviewSelection); - } else { - labelDescription.Text = ""; - curInitializeObject = null; - } - } - - public static void ShowIfValid (Document document, MonoDevelop.Ide.CodeCompletion.CodeCompletionContext completionContext) - { - var options = CodeGenerationOptions.CreateCodeGenerationOptions (document); - - var validGenerators = new List (); - foreach (var generator in CodeGenerationService.CodeGenerators) { - if (generator.IsValid (options)) - validGenerators.Add (generator); - } - if (validGenerators.Count < 1) - return; - - var window = new GenerateCodeWindow (options, completionContext); - window.Populate (validGenerators); - } - - protected override bool OnFocusOutEvent (Gdk.EventFocus evnt) - { - Destroy (); - return base.OnFocusOutEvent (evnt); - } - - class BorderBox : HBox - { - public BorderBox () : base (false, 8) - { - BorderWidth = 3; - } - - protected override bool OnExposeEvent (Gdk.EventExpose evnt) - { - Style.PaintFlatBox (Style, - evnt.Window, - StateType.Normal, - ShadowType.Out, - evnt.Area, - this, - "tooltip", - Allocation.X + 1, - Allocation.Y + 1, - Allocation.Width - 2, - Allocation.Height - 2); - - return base.OnExposeEvent (evnt); - } - } - -/* protected override bool OnExposeEvent (Gdk.EventExpose evnt) - { - Console.WriteLine ("!!!!"); - Style.PaintFlatBox (Style, - evnt.Window, - StateType.Normal, - ShadowType.Out, - evnt.Area, - this, - "tooltip", - Allocation.X + 1, - Allocation.Y + 1, - Allocation.Width - 2, - Allocation.Height - 2); - return base.OnExposeEvent (evnt); - }*/ - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ICodeGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ICodeGenerator.cs deleted file mode 100644 index b2f2165..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ICodeGenerator.cs +++ /dev/null @@ -1,82 +0,0 @@ -// -// ICodeGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using MonoDevelop.Ide.Gui; -using System.Collections.Generic; -using Mono.Addins; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - public interface ICodeGenerator - { - string Icon { - get; - } - - string Text { - get; - } - - string GenerateDescription { - get; - } - - bool IsValid (CodeGenerationOptions options); - - IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView); - } - - public interface IGenerateAction - { - void GenerateCode (); - } - - static class CodeGenerationService - { - static List codeGenerators = new List(); - - static CodeGenerationService () - { - AddinManager.AddExtensionNodeHandler ("/MonoDevelop/Refactoring/CodeGenerators", delegate(object sender, ExtensionNodeEventArgs args) { - switch (args.Change) { - case ExtensionChange.Add: - codeGenerators.Add ((ICodeGenerator)args.ExtensionObject); - break; - case ExtensionChange.Remove: - codeGenerators.Remove ((ICodeGenerator)args.ExtensionObject); - break; - } - }); - } - - public static IEnumerable CodeGenerators { - get { - return codeGenerators; - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ImplementInterfaceMembersGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ImplementInterfaceMembersGenerator.cs deleted file mode 100644 index 4bc5d15..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ImplementInterfaceMembersGenerator.cs +++ /dev/null @@ -1,101 +0,0 @@ -// -// ImplementInterfaceMembersGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using Gtk; -using System.Collections.Generic; -using MonoDevelop.Core; -using MonoDevelop.Refactoring; -using MonoDevelop.Ide.TypeSystem; -using System; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class ImplementInterfaceMembersGenerator : ICodeGenerator - { - public string Icon { - get { - return "md-method"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("Implement interface members"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select members to be implemented."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - return new OverrideMethods (options).IsValid (); - } - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView) - { - OverrideMethods overrideMethods = new OverrideMethods (options); - overrideMethods.Initialize (treeView); - return overrideMethods; - } - - class OverrideMethods : AbstractGenerateAction - { - public OverrideMethods (CodeGenerationOptions options) : base (options) - { - } - - protected override IEnumerable GetValidMembers () - { - var type = Options.EnclosingType; - if (type == null || Options.EnclosingMember != null) - yield break; - - foreach (var baseType in Options.EnclosingType.DirectBaseTypes) { - if (baseType.Kind != TypeKind.Interface) - continue; - bool ifm; - foreach (var t in ICSharpCode.NRefactory.PlayScript.Refactoring.ImplementInterfaceAction.CollectMembersToImplement (type, baseType, false, out ifm)) { - yield return t; - } - } - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - var generator = Options.CreateCodeGenerator (); - generator.AutoIndent = false; - foreach (Tuple member in includedMembers) - yield return generator.CreateMemberImplementation (Options.EnclosingType, Options.EnclosingPart, member.Item1, member.Item2).Code; - } - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/OverrideMembersGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/OverrideMembersGenerator.cs deleted file mode 100644 index d342bce..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/OverrideMembersGenerator.cs +++ /dev/null @@ -1,103 +0,0 @@ -// -// OverrideMethodsGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using Gtk; -using System.Collections.Generic; -using MonoDevelop.Core; -using MonoDevelop.Refactoring; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class OverrideMembersGenerator : ICodeGenerator - { - public string Icon { - get { - return "md-method"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("Override members"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select members to be overridden."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - return new OverrideMethods (options).IsValid (); - } - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView) - { - OverrideMethods overrideMethods = new OverrideMethods (options); - overrideMethods.Initialize (treeView); - return overrideMethods; - } - - class OverrideMethods : AbstractGenerateAction - { - public OverrideMethods (CodeGenerationOptions options) : base (options) - { - } - - protected override IEnumerable GetValidMembers () - { - var type = Options.EnclosingType; - if (type == null || Options.EnclosingMember != null) - yield break; - HashSet memberName = new HashSet (); - foreach (var member in Options.EnclosingType.GetMembers ()) { - if (member.IsSynthetic) - continue; - if (member.IsOverridable) { - string id = AmbienceService.DefaultAmbience.GetString (member, OutputFlags.ClassBrowserEntries); - if (memberName.Contains (id)) - continue; - memberName.Add (id); - yield return member; - } - } - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - var generator = Options.CreateCodeGenerator (); - generator.AutoIndent = false; - foreach (IMember member in includedMembers) - yield return generator.CreateMemberImplementation (Options.EnclosingType, Options.EnclosingPart, member, false).Code; - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/PartialGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/PartialGenerator.cs deleted file mode 100644 index 77e6dad..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/PartialGenerator.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -// PartialGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; -using Gtk; -using MonoDevelop.Core; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class PartialGenerator : ICodeGenerator - { - public string Icon { - get { - return "md-method"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("Partial methods"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select methods to be implemented."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - return new PartialMethods (options).IsValid (); - } - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, TreeView treeView) - { - var overrideMethods = new PartialMethods (options); - overrideMethods.Initialize (treeView); - return overrideMethods; - } - - class PartialMethods : AbstractGenerateAction - { - public PartialMethods (CodeGenerationOptions options) : base (options) - { - } - - protected override IEnumerable GetValidMembers () - { - var type = Options.EnclosingType; - if (type == null || Options.EnclosingMember != null) - yield break; - - foreach (var method in Options.EnclosingType.Methods) { - if (method.IsPartial && method.BodyRegion.IsEmpty) { - yield return method; - } - } - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - var generator = Options.CreateCodeGenerator (); - generator.AutoIndent = false; - foreach (IMethod member in includedMembers) - yield return generator.CreateMemberImplementation (Options.EnclosingType, Options.EnclosingPart, member, false).Code; - } - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/PropertyGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/PropertyGenerator.cs deleted file mode 100644 index 240b011..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/PropertyGenerator.cs +++ /dev/null @@ -1,117 +0,0 @@ -// -// PropertyGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui; -using Gtk; -using System.Collections.Generic; -using MonoDevelop.Refactoring; -using System.Text; -using System.Linq; -using ICSharpCode.NRefactory.TypeSystem; -using ICSharpCode.NRefactory.PlayScript; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class PropertyGenerator : ICodeGenerator - { - public string Icon { - get { - return "md-property"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("Properties"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select members which should be exposed."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - return new CreateProperty (options).IsValid (); - } - - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView) - { - CreateProperty createProperty = new CreateProperty (options); - createProperty.Initialize (treeView); - return createProperty; - } - - internal class CreateProperty : AbstractGenerateAction - { - public bool ReadOnly { - get; - set; - } - - public CreateProperty (CodeGenerationOptions options) : base (options) - { - } - - protected override IEnumerable GetValidMembers () - { - if (Options.EnclosingType == null || Options.EnclosingMember != null) - yield break; - foreach (IField field in Options.EnclosingType.Fields) { - if (field.IsSynthetic) - continue; - var list = Options.EnclosingType.Fields.Where (f => f.Name == CreatePropertyName (field));; - if (!list.Any ()) - yield return field; - } - } - - static string CreatePropertyName (IMember member) - { - int i = 0; - while (i + 1 < member.Name.Length && member.Name[i] == '_') - i++; - if (i + 1 >= member.Name.Length) - return char.ToUpper (member.Name [i]).ToString (); - return char.ToUpper (member.Name [i]) + member.Name.Substring (i + 1); - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - var generator = Options.CreateCodeGenerator (); - generator.AutoIndent = false; - foreach (IField field in includedMembers) - yield return generator.CreateFieldEncapsulation (Options.EnclosingPart, field, CreatePropertyName (field), Accessibility.Public, ReadOnly); - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/RaiseEventMethodGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/RaiseEventMethodGenerator.cs deleted file mode 100644 index 738502d..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/RaiseEventMethodGenerator.cs +++ /dev/null @@ -1,139 +0,0 @@ -// -// RaiseEventMethodGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2012 Xamarin -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; - -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui; -using Gtk; -using System.Collections.Generic; -using MonoDevelop.Refactoring; -using System.Text; -using System.Linq; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class RaiseEventMethodGenerator : ICodeGenerator - { - public string Icon { - get { - return "md-event"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("Event OnXXX method"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select event to generate the method for."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - return new CreateEventMethod (options).IsValid (); - } - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView) - { - var createEventMethod = new CreateEventMethod (options); - createEventMethod.Initialize (treeView); - return createEventMethod; - } - - class CreateEventMethod : AbstractGenerateAction - { - const string handlerName = "handler"; - - public CreateEventMethod (CodeGenerationOptions options) : base (options) - { - } - - static string GetEventMethodName (IMember member) - { - return "On" + member.Name; - } - - protected override IEnumerable GetValidMembers () - { - if (Options.EnclosingType == null || Options.EnclosingMember != null) - yield break; - foreach (var e in Options.EnclosingType.Events) { - if (e.IsSynthetic) - continue; - var invokeMethod = e.ReturnType.GetDelegateInvokeMethod (); - if (invokeMethod == null) - continue; - if (Options.EnclosingType.GetMethods (m => m.Name == GetEventMethodName (e)).Any ()) - continue; - yield return e; - } - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - foreach (IMember member in includedMembers) { - var invokeMethod = member.ReturnType.GetDelegateInvokeMethod (); - if (invokeMethod == null) - continue; - - var methodDeclaration = new MethodDeclaration () { - Name = GetEventMethodName (member), - ReturnType = new PrimitiveType ("void"), - Modifiers = Modifiers.Protected | Modifiers.Virtual, - Parameters = { - new ParameterDeclaration (Options.CreateShortType (invokeMethod.Parameters [1].Type), invokeMethod.Parameters [1].Name) - }, - Body = new BlockStatement () { - new VariableDeclarationStatement ( - new SimpleType ("var"),//Options.CreateShortType (member.ReturnType), - handlerName, - new MemberReferenceExpression (new ThisReferenceExpression (), member.Name) - ), - new IfElseStatement () { - Condition = new BinaryOperatorExpression (new IdentifierExpression (handlerName), BinaryOperatorType.InEquality, new PrimitiveExpression (null)), - TrueStatement = new ExpressionStatement (new InvocationExpression (new IdentifierExpression (handlerName)) { - Arguments = { - new ThisReferenceExpression (), - new IdentifierExpression (invokeMethod.Parameters [1].Name) - } - }) - } - } - }; - - yield return methodDeclaration.ToString (Options.FormattingOptions); - } - } - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ReadonlyPropertyGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ReadonlyPropertyGenerator.cs deleted file mode 100644 index c279b8b..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ReadonlyPropertyGenerator.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// ReadonlyPropertyGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; - -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui; -using Gtk; -using System.Collections.Generic; -using MonoDevelop.Refactoring; -using System.Text; -using System.Linq; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class ReadonlyPropertyGenerator : ICodeGenerator - { - public string Icon { - get { - return "md-property"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("Read-only properties"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select members which should be exposed."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - return new PropertyGenerator.CreateProperty (options).IsValid (); - } - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView) - { - var createProperty = new PropertyGenerator.CreateProperty (options); - createProperty.ReadOnly = true; - createProperty.Initialize (treeView); - return createProperty; - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ToStringGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ToStringGenerator.cs deleted file mode 100644 index 3131210..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/ToStringGenerator.cs +++ /dev/null @@ -1,134 +0,0 @@ -// -// ToStringGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using MonoDevelop.Components; -using Gtk; -using MonoDevelop.Ide.Gui; -using System.Collections.Generic; -using System.Text; -using MonoDevelop.Core; -using MonoDevelop.Refactoring; -using System.Linq; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class ToStringGenerator : ICodeGenerator - { - public string Icon { - get { - return "md-newmethod"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("ToString() implementation"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select members to be outputted."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - return new CreateToString (options).IsValid (); - } - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView) - { - CreateToString createToString = new CreateToString (options); - createToString.Initialize (treeView); - return createToString; - } - - class CreateToString : AbstractGenerateAction - { - public CreateToString (CodeGenerationOptions options) : base (options) - { - } - - protected override IEnumerable GetValidMembers () - { - if (Options.EnclosingType == null || Options.EnclosingMember != null) - yield break; - foreach (IField field in Options.EnclosingType.Fields) { - if (field.IsSynthetic) - continue; - yield return field; - } - - foreach (IProperty property in Options.EnclosingType.Properties) { - if (property.IsSynthetic) - continue; - if (property.CanGet) - yield return property; - } - } - - string GetFormatString (IEnumerable includedMembers) - { - var format = new StringBuilder (); - format.Append ("["); - format.Append (Options.EnclosingType.Name); - format.Append (": "); - int i = 0; - foreach (IEntity member in includedMembers) { - if (i > 0) - format.Append (", "); - format.Append (member.Name); - format.Append ("={"); - format.Append (i++); - format.Append ("}"); - } - format.Append ("]"); - return format.ToString (); - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - yield return new MethodDeclaration () { - Name = "ToString", - ReturnType = new PrimitiveType ("string"), - Modifiers = Modifiers.Public | Modifiers.Override, - Body = new BlockStatement () { - new ReturnStatement ( - new InvocationExpression ( - new MemberReferenceExpression (new TypeReferenceExpression (new PrimitiveType ("string")), "Format"), - new Expression [] { new PrimitiveExpression (GetFormatString (includedMembers)) }.Concat (includedMembers.Select (member => new IdentifierExpression (((IEntity)member).Name))) - ) - ) - } - }.ToString (Options.FormattingOptions); - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/WriteLineGenerator.cs b/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/WriteLineGenerator.cs deleted file mode 100644 index 6eb0aec..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.CodeGeneration/WriteLineGenerator.cs +++ /dev/null @@ -1,146 +0,0 @@ -// -// WriteLineGenerator.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using MonoDevelop.Components; -using Gtk; -using MonoDevelop.Ide.Gui; -using System.Collections.Generic; -using System.Text; -using MonoDevelop.Core; -using MonoDevelop.Refactoring; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.CodeGeneration -{ - class WriteLineGenerator: ICodeGenerator - { - public string Icon { - get { - return "md-newmethod"; - } - } - - public string Text { - get { - return GettextCatalog.GetString ("WriteLine call"); - } - } - - public string GenerateDescription { - get { - return GettextCatalog.GetString ("Select members to be outputted."); - } - } - - public bool IsValid (CodeGenerationOptions options) - { - return new CreateWriteLine (options).IsValid (); - } - - public IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView) - { - var createToString = new CreateWriteLine (options); - createToString.Initialize (treeView); - return createToString; - } - - class CreateWriteLine : AbstractGenerateAction - { - public CreateWriteLine (CodeGenerationOptions options) : base (options) - { - } - - protected override IEnumerable GetValidMembers () - { - if (Options == null || Options.EnclosingType == null || Options.EnclosingMember == null || Options.Document == null) - yield break; - var editor = Options.Document.Editor; - if (editor == null) - yield break; - - - // add local variables - var state = Options.CurrentState; - if (state != null) { - foreach (var v in state.LocalVariables) - yield return v; - } - - // add parameters - if (Options.EnclosingMember is IParameterizedMember) { - foreach (IParameter param in ((IParameterizedMember)Options.EnclosingMember).Parameters) - yield return param; - } - - // add type members - foreach (IField field in Options.EnclosingType.Fields) { - if (field.IsSynthetic) - continue; - yield return field; - } - - foreach (IProperty property in Options.EnclosingType.Properties) { - if (property.IsSynthetic) - continue; - if (property.CanGet) - yield return property; - } - } - - static string GetName (object m) - { - var e = m as IEntity; - if (e != null) - return e.Name; - return ((IVariable)m).Name; - } - - protected override IEnumerable GenerateCode (List includedMembers) - { - StringBuilder format = new StringBuilder (); - int i = 0; - foreach (var member in includedMembers) { - if (i > 0) - format.Append (", "); - format.Append (GetName (member)); - format.Append ("={"); - format.Append (i++); - format.Append ("}"); - } - - var consoleType = typeof (Console).ToTypeReference ().Resolve (Options.Document.Compilation.TypeResolveContext); - var invocationExpression = new InvocationExpression (new MemberReferenceExpression (new TypeReferenceExpression (Options.CreateShortType (consoleType)), "WriteLine")); - invocationExpression.Arguments.Add (new PrimitiveExpression (format.ToString ())); - foreach (var member in includedMembers) { - invocationExpression.Arguments.Add (new IdentifierExpression (GetName (member))); - } - yield return new ExpressionStatement (invocationExpression).ToString (Options.FormattingOptions); - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/AbstractParameterDataProvider.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/AbstractParameterDataProvider.cs deleted file mode 100644 index 854e55c..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/AbstractParameterDataProvider.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// AbstractParameterDataProvider.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Text; - -using MonoDevelop.Core; -using ICSharpCode.NRefactory.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using ICSharpCode.NRefactory.PlayScript.Refactoring; -using MonoDevelop.Ide.CodeCompletion; - -namespace MonoDevelop.PlayScript.Completion -{ - abstract class AbstractParameterDataProvider : ParameterDataProvider - { - protected CSharpCompletionTextEditorExtension ext; - - protected AbstractParameterDataProvider (CSharpCompletionTextEditorExtension ext, int startOffset) : base (startOffset) - { - if (ext == null) - throw new ArgumentNullException ("ext"); - this.ext = ext; - } - - TypeSystemAstBuilder builder; - protected string GetShortType (IType type) - { - if (builder == null) { - var ctx = ext.CSharpUnresolvedFile.GetTypeResolveContext (ext.UnresolvedFileCompilation, ext.Document.Editor.Caret.Location); - var state = new CSharpResolver (ctx); - builder = new TypeSystemAstBuilder (state); - var dt = state.CurrentTypeDefinition; - var declaring = ctx.CurrentTypeDefinition != null ? ctx.CurrentTypeDefinition.DeclaringTypeDefinition : null; - if (declaring != null) { - while (dt != null) { - if (dt.Equals (declaring)) { - builder.AlwaysUseShortTypeNames = true; - break; - } - dt = dt.DeclaringTypeDefinition; - } - } - } - try { - return GLib.Markup.EscapeText (builder.ConvertType(type).ToString (ext.FormattingPolicy.CreateOptions ())); - } catch (Exception e) { - LoggingService.LogError ("Exception while getting short type.", e); - return ""; - } - } - - protected string GetParameterString (IParameter parameter) - { - var sb = new StringBuilder (); - if (parameter.IsOut) - sb.Append ("out "); - if (parameter.IsRef) - sb.Append ("ref "); - sb.Append (GetShortType (parameter.Type)); - sb.Append (" "); - sb.Append (parameter.Name); - return sb.ToString (); - } - - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/ArrayTypeParameterDataProvider.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/ArrayTypeParameterDataProvider.cs deleted file mode 100644 index edefe3c..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/ArrayTypeParameterDataProvider.cs +++ /dev/null @@ -1,87 +0,0 @@ -// -// CSharpCompletionTextEditorExtension.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2011 Xamarin -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using ICSharpCode.NRefactory.PlayScript; -using MonoDevelop.Ide.CodeCompletion; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.PlayScript.Formatting; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; -using Mono.TextEditor; - -namespace MonoDevelop.PlayScript.Completion -{ - class ArrayTypeParameterDataProvider : AbstractParameterDataProvider - { - readonly ArrayType arrayType; - - public ArrayTypeParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, ArrayType arrayType) : base (ext, startOffset) - { - this.arrayType = arrayType; - } - - public override TooltipInformation CreateTooltipInformation (int overload, int currentParameter, bool smartWrap) - { - var tooltipInfo = new TooltipInformation (); - var file = ext.CSharpUnresolvedFile; - var compilation = ext.UnresolvedFileCompilation; - var textEditorData = ext.TextEditorData; - var formattingPolicy = ext.FormattingPolicy; - var resolver = file.GetResolver (compilation, textEditorData.Caret.Location); - var sig = new SignatureMarkupCreator (resolver, formattingPolicy.CreateOptions ()); - sig.HighlightParameter = currentParameter; - tooltipInfo.SignatureMarkup = sig.GetArrayIndexerMarkup (arrayType); - return tooltipInfo; - } - - - #region IParameterDataProvider implementation - public override int GetParameterCount (int overload) - { - if (overload >= Count) - return -1; - return arrayType.Dimensions; - } - - public override string GetParameterName (int overload, int paramIndex) - { - // unused - return ""; - } - - public override bool AllowParameterList (int overload) - { - return false; - } - - public override int Count { - get { - return 1; - } - } - #endregion - } - -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/CSharpCompletionTextEditorExtension.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/CSharpCompletionTextEditorExtension.cs deleted file mode 100644 index c1a267a..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/CSharpCompletionTextEditorExtension.cs +++ /dev/null @@ -1,1704 +0,0 @@ -// -// CSharpCompletionTextEditorExtension.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2011 Xamarin -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Xml; -using ICSharpCode.NRefactory; -using ICSharpCode.NRefactory.Completion; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.PlayScript.Completion; -using ICSharpCode.NRefactory.PlayScript.Refactoring; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; -using ICSharpCode.NRefactory.Semantics; -using ICSharpCode.NRefactory.TypeSystem; -using Mono.TextEditor; -using MonoDevelop.Components.Commands; -using MonoDevelop.Core; -using MonoDevelop.Debugger; -using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.Ide.CodeTemplates; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide.Gui.Content; -using MonoDevelop.Ide.TypeSystem; -using MonoDevelop.PlayScript.CodeGeneration; -using MonoDevelop.PlayScript.Formatting; -using MonoDevelop.PlayScript.Project; -using MonoDevelop.PlayScript.Refactoring.CodeActions; -using MonoDevelop.Projects; -using MonoDevelop.Refactoring; - -using ICompletionData = ICSharpCode.NRefactory.Completion.ICompletionData; -using ICompletionDataFactory = ICSharpCode.NRefactory.PlayScript.Completion.ICompletionDataFactory; -using IEntityCompletionData = ICSharpCode.NRefactory.Completion.IEntityCompletionData; -using IParameterDataProvider = ICSharpCode.NRefactory.Completion.IParameterDataProvider; -using IVariableCompletionData = ICSharpCode.NRefactory.Completion.IVariableCompletionData; - - -namespace MonoDevelop.PlayScript.Completion -{ - public class CSharpCompletionTextEditorExtension : CompletionTextEditorExtension, IParameterCompletionDataFactory, ITextEditorMemberPositionProvider, IDebuggerExpressionResolver - { - internal protected virtual Mono.TextEditor.TextEditorData TextEditorData { - get { - var doc = Document; - if (doc == null) - return null; - return doc.Editor; - } - } - - protected virtual IProjectContent ProjectContent { - get { return Document.GetProjectContext (); } - } - - SyntaxTree unit; - static readonly SyntaxTree emptyUnit = new SyntaxTree (); - SyntaxTree Unit { - get { - return unit ?? emptyUnit; - } - set { - unit = value; - } - } - - public new MonoDevelop.Ide.Gui.Document Document { - get { - return base.document; - } - } - - public ICompilation UnresolvedFileCompilation { - get; - set; - } - - public CSharpUnresolvedFile CSharpUnresolvedFile { - get; - set; - } - - public ParsedDocument ParsedDocument { - get { - return document.ParsedDocument; - } - } - - public virtual ICompilation Compilation { - get { return Project != null ? TypeSystemService.GetCompilation (Project) : ProjectContent.CreateCompilation (); } - } - - public MonoDevelop.Projects.Project Project { - get { - return document.Project; - } - } - - PlayScriptFormattingPolicy policy; - public PlayScriptFormattingPolicy FormattingPolicy { - get { - if (policy == null) { - IEnumerable types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (MonoDevelop.PlayScript.Formatting.CSharpFormatter.MimeType); - if (Document.Project != null && Document.Project.Policies != null) { - policy = base.Document.Project.Policies.Get (types); - } else { - policy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy (types); - } - } - return policy; - } - } - - public override string CompletionLanguage { - get { - return "PlayScript"; - } - } - - internal MDRefactoringContext MDRefactoringCtx { - get; - private set; - } - - - public CSharpCompletionTextEditorExtension () - { - } - - bool addEventHandlersInInitialization = true; - - /// - /// Used in testing environment. - /// - [System.ComponentModel.Browsable(false)] - public CSharpCompletionTextEditorExtension (MonoDevelop.Ide.Gui.Document doc, bool addEventHandlersInInitialization = true) : this () - { - this.addEventHandlersInInitialization = addEventHandlersInInitialization; - Initialize (doc); - } - - public override void Initialize () - { - base.Initialize (); - var parsedDocument = document.ParsedDocument; - if (parsedDocument != null) { - this.Unit = parsedDocument.GetAst (); - this.UnresolvedFileCompilation = Compilation; - this.CSharpUnresolvedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile; - if (addEventHandlersInInitialization) - document.Editor.Caret.PositionChanged += HandlePositionChanged; - } - - if (addEventHandlersInInitialization) - Document.DocumentParsed += HandleDocumentParsed; - } - - CancellationTokenSource src = new CancellationTokenSource (); - - void StopPositionChangedTask () - { - src.Cancel (); - src = new CancellationTokenSource (); - } - - void HandlePositionChanged (object sender, DocumentLocationEventArgs e) - { - StopPositionChangedTask (); - var doc = Document; - if (doc == null || doc.Editor == null) - return; - MDRefactoringContext.Create (doc, doc.Editor.Caret.Location, src.Token).ContinueWith (t => { - MDRefactoringCtx = t.Result; - }, TaskContinuationOptions.ExecuteSynchronously); - } - - [CommandUpdateHandler (CodeGenerationCommands.ShowCodeGenerationWindow)] - public void CheckShowCodeGenerationWindow (CommandInfo info) - { - info.Enabled = TextEditorData != null && Document.GetContent () != null; - } - - [CommandHandler (CodeGenerationCommands.ShowCodeGenerationWindow)] - public void ShowCodeGenerationWindow () - { - var completionWidget = Document.GetContent (); - if (completionWidget == null) - return; - CodeCompletionContext completionContext = completionWidget.CreateCodeCompletionContext (TextEditorData.Caret.Offset); - GenerateCodeWindow.ShowIfValid (Document, completionContext); - } - - public override void Dispose () - { - StopPositionChangedTask (); - unit = null; - CSharpUnresolvedFile = null; - UnresolvedFileCompilation = null; - Document.DocumentParsed -= HandleDocumentParsed; - if (unstableTypeSystemSegmentTree != null) { - unstableTypeSystemSegmentTree.RemoveListener (); - unstableTypeSystemSegmentTree = null; - } - - if (validTypeSystemSegmentTree != null) { - validTypeSystemSegmentTree.RemoveListener (); - validTypeSystemSegmentTree = null; - } - - base.Dispose (); - } - - void HandleDocumentParsed (object sender, EventArgs e) - { - var newDocument = Document.ParsedDocument; - if (newDocument == null) - return; - var newTree = TypeSystemSegmentTree.Create (newDocument, TextEditorData); - - if (unstableTypeSystemSegmentTree != null) - unstableTypeSystemSegmentTree.RemoveListener (); - - if (!newDocument.HasErrors) { - if (validTypeSystemSegmentTree != null) - validTypeSystemSegmentTree.RemoveListener (); - validTypeSystemSegmentTree = newTree; - unstableTypeSystemSegmentTree = null; - } else { - unstableTypeSystemSegmentTree = newTree; - } - newTree.InstallListener (document.Editor.Document); - - this.Unit = newDocument.GetAst (); - this.CSharpUnresolvedFile = newDocument.ParsedFile as CSharpUnresolvedFile; - this.UnresolvedFileCompilation = Compilation; - if (TypeSegmentTreeUpdated != null) - TypeSegmentTreeUpdated (this, EventArgs.Empty); - } - public event EventHandler TypeSegmentTreeUpdated; - - public void UpdateParsedDocument () - { - HandleDocumentParsed (null, null); - } - - public override bool KeyPress (Gdk.Key key, char keyChar, Gdk.ModifierType modifier) - { - bool result = base.KeyPress (key, keyChar, modifier); - - if (/*EnableParameterInsight &&*/ (keyChar == ',' || keyChar == ')') && CanRunParameterCompletionCommand ()) - base.RunParameterCompletionCommand (); - -// if (IsInsideComment ()) -// ParameterInformationWindowManager.HideWindow (CompletionWidget); - return result; - } - - public override ICompletionDataList HandleCodeCompletion (CodeCompletionContext completionContext, char completionChar, ref int triggerWordLength) - { -// if (!EnableCodeCompletion) -// return null; - if (!EnableAutoCodeCompletion && char.IsLetter (completionChar)) - return null; - - // var timer = Counters.ResolveTime.BeginTiming (); - try { - if (char.IsLetterOrDigit (completionChar) || completionChar == '_') { - if (completionContext.TriggerOffset > 1 && char.IsLetterOrDigit (TextEditorData.GetCharAt (completionContext.TriggerOffset - 2))) - return null; - triggerWordLength = 1; - } - return InternalHandleCodeCompletion (completionContext, completionChar, false, ref triggerWordLength); - } catch (Exception e) { - LoggingService.LogError ("Unexpected code completion exception." + Environment.NewLine + - "FileName: " + Document.FileName + Environment.NewLine + - "Position: line=" + completionContext.TriggerLine + " col=" + completionContext.TriggerLineOffset + Environment.NewLine + - "Line text: " + TextEditorData.GetLineText (completionContext.TriggerLine), - e); - return null; - } finally { - // if (timer != null) - // timer.Dispose (); - } - } - - class CSharpCompletionDataList : CompletionDataList - { - public CSharpResolver Resolver { - get; - set; - } - } - - interface IListData - { - CSharpCompletionDataList List { get; set; } - } - - ICompletionContextProvider CreateContextProvider () - { - return new CompletionContextProvider (document.ParsedDocument, TextEditorData, validTypeSystemSegmentTree, unstableTypeSystemSegmentTree); - } - - CSharpTypeResolveContext CreateTypeResolveContext () - { - var compilation = UnresolvedFileCompilation; - if (compilation == null) - return null; - var rctx = new CSharpTypeResolveContext (compilation.MainAssembly); - var loc = TextEditorData.Caret.Location; - rctx = rctx.WithUsingScope (CSharpUnresolvedFile.GetUsingScope (loc).Resolve (compilation)); - int offset = TextEditorData.Caret.Offset; - var curDef = GetTypeAt (offset); - if (curDef != null) { - var resolvedDef = curDef.Resolve (rctx).GetDefinition (); - if (resolvedDef == null) - return rctx; - rctx = rctx.WithCurrentTypeDefinition (resolvedDef); - var foundMember = GetMemberAt (offset); - if (foundMember != null) { - var curMember = resolvedDef.Members.FirstOrDefault (m => m.Region.FileName == foundMember.Region.FileName && m.Region.Begin == foundMember.Region.Begin); - if (curMember != null) - rctx = rctx.WithCurrentMember (curMember); - } - } - - return rctx; - } - CompletionEngineCache cache = new CompletionEngineCache (); - ICompletionDataList InternalHandleCodeCompletion (CodeCompletionContext completionContext, char completionChar, bool ctrlSpace, ref int triggerWordLength) - { - var data = TextEditorData; - if (data.CurrentMode is TextLinkEditMode) { - if (((TextLinkEditMode)data.CurrentMode).TextLinkMode == TextLinkMode.EditIdentifier) - return null; - } - if (Unit == null || CSharpUnresolvedFile == null) - return null; - if(unstableTypeSystemSegmentTree == null && validTypeSystemSegmentTree == null) - return null; - - var list = new CSharpCompletionDataList (); - list.Resolver = CSharpUnresolvedFile != null ? CSharpUnresolvedFile.GetResolver (UnresolvedFileCompilation, TextEditorData.Caret.Location) : new CSharpResolver (Compilation); - var ctx = CreateTypeResolveContext (); - if (ctx == null) - return null; - var completionDataFactory = new CompletionDataFactory (this, new CSharpResolver (ctx)); - if (MDRefactoringCtx == null) { - src.Cancel (); - MDRefactoringCtx = MDRefactoringContext.Create (Document, TextEditorData.Caret.Location).Result; - } - - var engine = new MonoCSharpCompletionEngine ( - this, - data.Document, - CreateContextProvider (), - completionDataFactory, - ProjectContent, - ctx - ); - completionDataFactory.Engine = engine; - engine.AutomaticallyAddImports = AddImportedItemsToCompletionList.Value; - engine.IncludeKeywordsInCompletionList = EnableAutoCodeCompletion || IncludeKeywordsInCompletionList.Value; - engine.CompletionEngineCache = cache; - if (FilterCompletionListByEditorBrowsable) { - engine.EditorBrowsableBehavior = IncludeEditorBrowsableAdvancedMembers ? EditorBrowsableBehavior.IncludeAdvanced : EditorBrowsableBehavior.Normal; - } else { - engine.EditorBrowsableBehavior = EditorBrowsableBehavior.Ignore; - } - if (Document.HasProject && MonoDevelop.Ide.IdeApp.IsInitialized) { - var configuration = Document.Project.GetConfiguration (MonoDevelop.Ide.IdeApp.Workspace.ActiveConfiguration) as DotNetProjectConfiguration; - var par = configuration != null ? configuration.CompilationParameters as PlayScriptCompilerParameters : null; - if (par != null) - engine.LanguageVersion = MonoDevelop.PlayScript.Parser.TypeSystemParser.ConvertLanguageVersion (par.LangVersion); - } - - engine.FormattingPolicy = FormattingPolicy.CreateOptions (); - engine.EolMarker = data.EolMarker; - engine.IndentString = data.Options.IndentationString; - try { - foreach (var cd in engine.GetCompletionData (completionContext.TriggerOffset, ctrlSpace)) { - list.Add (cd); - if (cd is IListData) - ((IListData)cd).List = list; - } - } catch (Exception e) { - LoggingService.LogError ("Error while getting completion data.", e); - } - list.AutoCompleteEmptyMatch = engine.AutoCompleteEmptyMatch; - list.AutoCompleteEmptyMatchOnCurlyBrace = engine.AutoCompleteEmptyMatchOnCurlyBracket; - list.AutoSelect = engine.AutoSelect; - list.DefaultCompletionString = engine.DefaultCompletionString; - list.CloseOnSquareBrackets = engine.CloseOnSquareBrackets; - if (ctrlSpace) - list.AutoCompleteUniqueMatch = true; - return list.Count > 0 ? list : null; - } - - public override ICompletionDataList CodeCompletionCommand (CodeCompletionContext completionContext) - { - int triggerWordLength = 0; - char ch = completionContext.TriggerOffset > 0 ? TextEditorData.GetCharAt (completionContext.TriggerOffset - 1) : '\0'; - return InternalHandleCodeCompletion (completionContext, ch, true, ref triggerWordLength); - } - - static bool HasAllUsedParameters (IParameterDataProvider provider, List list, int n) - { - int pc = provider.GetParameterCount (n); - foreach (var usedParam in list) { - bool found = false; - for (int m = 0; m < pc; m++) { - if (usedParam == provider.GetParameterName (n, m)){ - found = true; - break; - } - } - if (!found) - return false; - } - return true; - } - public override int GuessBestMethodOverload (IParameterDataProvider provider, int currentOverload) - { - var ctx = CreateTypeResolveContext (); - if (ctx == null) - return -1; - var engine = new CSharpParameterCompletionEngine ( - TextEditorData.Document, - CreateContextProvider (), - this, - ProjectContent, - ctx - ); - List list; - int cparam = engine.GetCurrentParameterIndex (provider.StartOffset, TextEditorData.Caret.Offset, out list); - if (cparam > provider.GetParameterCount (currentOverload) && !provider.AllowParameterList (currentOverload) || !HasAllUsedParameters (provider, list, currentOverload)) { - // Look for an overload which has more parameters - int bestOverload = -1; - int bestParamCount = int.MaxValue; - for (int n = 0; n < provider.Count; n++) { - int pc = provider.GetParameterCount (n); - if (pc < bestParamCount && pc >= cparam) { - - if (HasAllUsedParameters (provider, list, n)) { - bestOverload = n; - bestParamCount = pc; - } - } - - - } - if (bestOverload == -1) { - for (int n=0; n m.IsConstructor) == 0) - return true; - return t.Methods.Any (m => m.IsConstructor && m.IsPublic); - } - - -// CompletionDataList result = new ProjectDomCompletionDataList (); -// // "var o = new " needs special treatment. -// if (returnType == null && returnTypeUnresolved != null && returnTypeUnresolved.FullName == "var") -// returnType = returnTypeUnresolved = DomReturnType.Object; -// -// // ExpressionContext.TypeExpressionContext tce = context as ExpressionContext.TypeExpressionContext; -// -// CompletionDataCollector col = new CompletionDataCollector (this, dom, result, Document.CompilationUnit, callingType, location); -// IType type = null; -// if (returnType != null) -// type = dom.GetType (returnType); -// if (type == null) -// type = dom.SearchType (Document.CompilationUnit, callingType, location, returnTypeUnresolved); -// -// // special handling for nullable types: Bug 674516 - new completion for nullables should not include "Nullable" -// if (type is InstantiatedType && ((InstantiatedType)type).UninstantiatedType.FullName == "System.Nullable" && ((InstantiatedType)type).GenericParameters.Count == 1) { -// var genericParameter = ((InstantiatedType)type).GenericParameters [0]; -// returnType = returnTypeUnresolved = Document.CompilationUnit.ShortenTypeName (genericParameter, location); -// type = dom.SearchType (Document.CompilationUnit, callingType, location, genericParameter); -// } -// -// if (type == null || !(type.IsAbstract || type.ClassType == ClassType.Interface)) { -// if (type == null || type.ConstructorCount == 0 || type.Methods.Any (c => c.IsConstructor && c.IsAccessibleFrom (dom, callingType, type, callingType != null && dom.GetInheritanceTree (callingType).Any (x => x.FullName == type.FullName)))) { -// if (returnTypeUnresolved != null) { -// col.FullyQualify = true; -// CompletionData unresovedCompletionData = col.Add (returnTypeUnresolved); -// col.FullyQualify = false; -// // don't set default completion string for arrays, since it interferes with: -// // string[] arr = new string[] vs new { "a"} -// if (returnTypeUnresolved.ArrayDimensions == 0) -// result.DefaultCompletionString = StripGenerics (unresovedCompletionData.CompletionText); -// } else { -// CompletionData unresovedCompletionData = col.Add (returnType); -// if (returnType.ArrayDimensions == 0) -// result.DefaultCompletionString = StripGenerics (unresovedCompletionData.CompletionText); -// } -// } -// } -// -// // if (tce != null && tce.Type != null) { -// // result.DefaultCompletionString = StripGenerics (col.AddCompletionData (result, tce.Type).CompletionString); -// // } -// // else { -// // } -// if (type == null) -// return result; -// HashSet usedNamespaces = new HashSet (GetUsedNamespaces ()); -// if (type.FullName == DomReturnType.Object.FullName) -// AddPrimitiveTypes (col); -// -// foreach (IType curType in dom.GetSubclasses (type)) { -// if (context != null && context.FilterEntry (curType)) -// continue; -// if ((curType.TypeModifier & TypeModifier.HasOnlyHiddenConstructors) == TypeModifier.HasOnlyHiddenConstructors) -// continue; -// if (usedNamespaces.Contains (curType.Namespace)) { -// if (curType.ConstructorCount > 0) { -// if (!(curType.Methods.Any (c => c.IsConstructor && c.IsAccessibleFrom (dom, curType, callingType, callingType != null && dom.GetInheritanceTree (callingType).Any (x => x.FullName == curType.FullName))))) -// continue; -// } -// col.Add (curType); -// } else { -// string nsName = curType.Namespace; -// int idx = nsName.IndexOf ('.'); -// if (idx >= 0) -// nsName = nsName.Substring (0, idx); -// col.Add (new Namespace (nsName)); -// } -// } -// -// // add aliases -// if (returnType != null) { -// foreach (IUsing u in Document.CompilationUnit.Usings) { -// foreach (KeyValuePair alias in u.Aliases) { -// if (alias.Value.ToInvariantString () == returnType.ToInvariantString ()) -// result.Add (alias.Key, "md-class"); -// } -// } -// } -// -// return result; -// } - -// IEnumerable GetDefineCompletionData () -// { -// if (Document.Project == null) -// yield break; -// -// var symbols = new Dictionary (); -// var cp = new ProjectDomCompletionDataList (); -// foreach (DotNetProjectConfiguration conf in Document.Project.Configurations) { -// var cparams = conf.CompilationParameters as CSharpCompilerParameters; -// if (cparams != null) { -// string[] syms = cparams.DefineSymbols.Split (';'); -// foreach (string s in syms) { -// string ss = s.Trim (); -// if (ss.Length > 0 && !symbols.ContainsKey (ss)) { -// symbols [ss] = ss; -// yield return factory.CreateLiteralCompletionData (ss); -// } -// } -// } -// } -// } - - public override ParameterDataProvider HandleParameterCompletion (CodeCompletionContext completionContext, char completionChar) - { -// if (!EnableCodeCompletion) -// return null; - if (Unit == null || CSharpUnresolvedFile == null) - return null; - var ctx = CreateTypeResolveContext (); - if (ctx == null) - return null; - - if (completionChar != '(' && completionChar != ',') - return null; - - try { - var engine = new CSharpParameterCompletionEngine ( - TextEditorData.Document, - CreateContextProvider (), - this, - ProjectContent, - ctx - ); - return engine.GetParameterDataProvider (completionContext.TriggerOffset, completionChar) as ParameterDataProvider; - } catch (Exception e) { - LoggingService.LogError ("Unexpected parameter completion exception." + Environment.NewLine + - "FileName: " + Document.FileName + Environment.NewLine + - "Position: line=" + completionContext.TriggerLine + " col=" + completionContext.TriggerLineOffset + Environment.NewLine + - "Line text: " + TextEditorData.GetLineText (completionContext.TriggerLine), - e); - return null; - } finally { - // if (timer != null) - // timer.Dispose (); - } - } - - List GetUsedNamespaces () - { - var scope = CSharpUnresolvedFile.GetUsingScope (TextEditorData.Caret.Location); - var result = new List (); - while (scope != null) { - result.Add (scope.NamespaceName); - var ctx = CSharpUnresolvedFile.GetResolver (Compilation, scope.Region.Begin); - foreach (var u in scope.Usings) { - var ns = u.ResolveNamespace (ctx); - if (ns == null) - continue; - result.Add (ns.FullName); - } - scope = scope.Parent; - } - return result; - } - - public override bool GetParameterCompletionCommandOffset (out int cpos) - { - var ctx = CreateTypeResolveContext (); - if (ctx == null) { - cpos = -1; - return false; - } - - var engine = new CSharpParameterCompletionEngine ( - TextEditorData.Document, - CreateContextProvider (), - this, - ProjectContent, - ctx - ); - engine.SetOffset (TextEditorData.Caret.Offset); - return engine.GetParameterCompletionCommandOffset (out cpos); - } - - public override int GetCurrentParameterIndex (int startOffset) - { - var ctx = CreateTypeResolveContext (); - if (ctx == null) - return -1; - - var engine = new CSharpParameterCompletionEngine ( - TextEditorData.Document, - CreateContextProvider (), - this, - ProjectContent, - ctx - ); - List list; - return engine.GetCurrentParameterIndex (startOffset, TextEditorData.Caret.Offset, out list); - } - /* - internal int GetCurrentParameterIndex (ICompletionWidget widget, int offset, int memberStart) - { - int cursor = widget.CurrentCodeCompletionContext.TriggerOffset; - int i = offset; - if (i > cursor) - return -1; - if (i == cursor) - return 1; // parameters are 1 based - var types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); - var engine = new CSharpIndentEngine (MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy (types)); - int index = memberStart + 1; - int parentheses = 0; - int bracket = 0; - do { - char c = widget.GetChar (i - 1); - engine.Push (c); - switch (c) { - case '{': - if (!engine.IsInsideOrdinaryCommentOrString) - bracket++; - break; - case '}': - if (!engine.IsInsideOrdinaryCommentOrString) - bracket--; - break; - case '(': - if (!engine.IsInsideOrdinaryCommentOrString) - parentheses++; - break; - case ')': - if (!engine.IsInsideOrdinaryCommentOrString) - parentheses--; - break; - case ',': - if (!engine.IsInsideOrdinaryCommentOrString && parentheses == 1 && bracket == 0) - index++; - break; - } - i++; - } while (i <= cursor && parentheses >= 0); - - return parentheses != 1 || bracket > 0 ? -1 : index; - }*/ - - - #region ICompletionDataFactory implementation - internal class CompletionDataFactory : ICompletionDataFactory - { - internal readonly CSharpCompletionTextEditorExtension ext; -// readonly CSharpResolver state; - readonly TypeSystemAstBuilder builder; - - public CSharpCompletionEngine Engine { - get; - set; - } - - public CompletionDataFactory (CSharpCompletionTextEditorExtension ext, CSharpResolver state) - { -// this.state = state; - if (state != null) - builder = new TypeSystemAstBuilder(state); - this.ext = ext; - } - - ICompletionData ICompletionDataFactory.CreateEntityCompletionData (IEntity entity) - { - return new MemberCompletionData (this, entity, OutputFlags.IncludeGenerics | OutputFlags.HideArrayBrackets | OutputFlags.IncludeParameterName) { - HideExtensionParameter = true - }; - } - - class GenericTooltipCompletionData : CompletionData, IListData - { - readonly Func tooltipFunc; - - #region IListData implementation - - CSharpCompletionDataList list; - public CSharpCompletionDataList List { - get { - return list; - } - set { - list = value; - if (overloads != null) { - foreach (var overload in overloads.Skip (1)) { - var ld = overload as IListData; - if (ld != null) - ld.List = list; - } - } - } - } - - #endregion - - public GenericTooltipCompletionData (Func tooltipFunc, string text, string icon) : base (text, icon) - { - this.tooltipFunc = tooltipFunc; - } - - public GenericTooltipCompletionData (Func tooltipFunc, string text, string icon, string description, string completionText) : base (text, icon, description, completionText) - { - this.tooltipFunc = tooltipFunc; - } - - public override TooltipInformation CreateTooltipInformation (bool smartWrap) - { - return tooltipFunc != null ? tooltipFunc (List, smartWrap) : new TooltipInformation (); - } - - protected List overloads; - public override bool HasOverloads { - get { return overloads != null && overloads.Count > 0; } - } - - public override IEnumerable OverloadedData { - get { - return overloads; - } - } - - public override void AddOverload (ICSharpCode.NRefactory.Completion.ICompletionData data) - { - if (overloads == null) { - overloads = new List (); - overloads.Add (this); - } - overloads.Add (data); - } - - public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier) - { - var currentWord = GetCurrentWord (window); - if (CompletionText == "new()" && keyChar == '(') { - window.CompletionWidget.SetCompletionText (window.CodeCompletionContext, currentWord, "new"); - } else { - window.CompletionWidget.SetCompletionText (window.CodeCompletionContext, currentWord, CompletionText); - } - } - - } - - class LazyGenericTooltipCompletionData : GenericTooltipCompletionData - { - Lazy displayText; - public override string DisplayText { - get { - return displayText.Value; - } - } - - public override string CompletionText { - get { - return displayText.Value; - } - } - - public LazyGenericTooltipCompletionData (Func tooltipFunc, Lazy displayText, string icon) : base (tooltipFunc, null, icon) - { - this.displayText = displayText; - } - } - - class TypeCompletionData : LazyGenericTooltipCompletionData, IListData - { - IType type; - CSharpCompletionTextEditorExtension ext; - CSharpUnresolvedFile file; - ICompilation compilation; -// CSharpResolver resolver; - - string IdString { - get { - return DisplayText + type.TypeParameterCount; - } - } - - public override string CompletionText { - get { - if (type.TypeParameterCount > 0 && !type.IsParameterized) - return type.Name; - return base.CompletionText; - } - } - - public override TooltipInformation CreateTooltipInformation (bool smartWrap) - { - var def = type.GetDefinition (); - var result = def != null ? MemberCompletionData.CreateTooltipInformation (compilation, file, List.Resolver, ext.TextEditorData, ext.FormattingPolicy, def, smartWrap) : new TooltipInformation (); -// if (ConflictingTypes != null) { -// var conflicts = new StringBuilder (); -// var sig = new SignatureMarkupCreator (List.Resolver, ext.FormattingPolicy.CreateOptions ()); -// for (int i = 0; i < ConflictingTypes.Count; i++) { -// var ct = ConflictingTypes[i]; -// if (i > 0) -// conflicts.AppendLine (","); -//// if ((i + 1) % 5 == 0) -//// conflicts.Append (Environment.NewLine + "\t"); -// conflicts.Append (sig.GetTypeReferenceString (((TypeCompletionData)ct).type)); -// } -// result.AddCategory ("Type Conflicts", conflicts.ToString ()); -// } - return result; - } - - public TypeCompletionData (IType type, CSharpCompletionTextEditorExtension ext, Lazy displayText, string icon, bool addConstructors) : base (null, displayText, icon) - { - this.type = type; - this.ext = ext; - this.file = ext.CSharpUnresolvedFile; - this.compilation = ext.UnresolvedFileCompilation; - - } - - Dictionary addedDatas = new Dictionary (); - - List ConflictingTypes = null; - - public override void AddOverload (ICSharpCode.NRefactory.Completion.ICompletionData data) - { - if (overloads == null) - addedDatas [IdString] = this; - - if (data is TypeCompletionData) { - string id = ((TypeCompletionData)data).IdString; - ICompletionData oldData; - if (addedDatas.TryGetValue (id, out oldData)) { - var old = (TypeCompletionData)oldData; - if (old.ConflictingTypes == null) - old.ConflictingTypes = new List (); - old.ConflictingTypes.Add (data); - return; - } - addedDatas [id] = data; - } - - base.AddOverload (data); - } - - } - - ICompletionData ICompletionDataFactory.CreateEntityCompletionData (IEntity entity, string text) - { - return new GenericTooltipCompletionData ((list, sw) => MemberCompletionData.CreateTooltipInformation (ext, list.Resolver, entity, sw), text, entity.GetStockIcon ()); - } - - ICompletionData ICompletionDataFactory.CreateTypeCompletionData (IType type, bool showFullName, bool isInAttributeContext, bool addConstructors) - { - if (addConstructors) { - ICompletionData constructorResult = null; - foreach (var ctor in type.GetConstructors ()) { - if (constructorResult != null) { - constructorResult.AddOverload (((ICompletionDataFactory)this).CreateEntityCompletionData (ctor)); - } else { - constructorResult = ((ICompletionDataFactory)this).CreateEntityCompletionData (ctor); - } - } - return constructorResult; - } - - Lazy displayText = new Lazy (delegate { - string name = showFullName ? builder.ConvertType(type).ToString() : type.Name; - if (isInAttributeContext && name.EndsWith("Attribute") && name.Length > "Attribute".Length) { - name = name.Substring(0, name.Length - "Attribute".Length); - } - return name; - }); - - var result = new TypeCompletionData (type, ext, - displayText, - type.GetStockIcon (), - addConstructors); - return result; - } - - ICompletionData ICompletionDataFactory.CreateMemberCompletionData(IType type, IEntity member) - { - Lazy displayText = new Lazy (delegate { - string name = builder.ConvertType(type).ToString(); - return name + "."+ member.Name; - }); - - var result = new LazyGenericTooltipCompletionData ( - (List, sw) => new TooltipInformation (), - displayText, - member.GetStockIcon ()); - return result; - } - - - ICompletionData ICompletionDataFactory.CreateLiteralCompletionData (string title, string description, string insertText) - { - return new GenericTooltipCompletionData ((list, smartWrap) => { - var sig = new SignatureMarkupCreator (list.Resolver, ext.FormattingPolicy.CreateOptions ()); - sig.BreakLineAfterReturnType = smartWrap; - return sig.GetKeywordTooltip (title, null); - }, title, "md-keyword", description, insertText ?? title); - } - - class XmlDocCompletionData : CompletionData, IListData - { - readonly CSharpCompletionTextEditorExtension ext; - readonly string title; - - #region IListData implementation - - CSharpCompletionDataList list; - public CSharpCompletionDataList List { - get { - return list; - } - set { - list = value; - } - } - - #endregion - - public XmlDocCompletionData (CSharpCompletionTextEditorExtension ext, string title, string description, string insertText) : base (title, "md-keyword", description, insertText ?? title) - { - this.ext = ext; - this.title = title; - } - - public override TooltipInformation CreateTooltipInformation (bool smartWrap) - { - var sig = new SignatureMarkupCreator (List.Resolver, ext.FormattingPolicy.CreateOptions ()); - sig.BreakLineAfterReturnType = smartWrap; - return sig.GetKeywordTooltip (title, null); - } - - - - public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier) - { - var currentWord = GetCurrentWord (window); - var text = CompletionText; - if (keyChar != '>') - text += ">"; - window.CompletionWidget.SetCompletionText (window.CodeCompletionContext, currentWord, text); - } - } - - ICompletionData ICompletionDataFactory.CreateXmlDocCompletionData (string title, string description, string insertText) - { - return new XmlDocCompletionData (ext, title, description, insertText); - } - - ICompletionData ICompletionDataFactory.CreateNamespaceCompletionData (INamespace name) - { - return new CompletionData (name.Name, AstStockIcons.Namespace, "", CSharpAmbience.FilterName (name.Name)); - } - - ICompletionData ICompletionDataFactory.CreateVariableCompletionData (IVariable variable) - { - return new VariableCompletionData (ext, variable); - } - - ICompletionData ICompletionDataFactory.CreateVariableCompletionData (ITypeParameter parameter) - { - return new CompletionData (parameter.Name, parameter.GetStockIcon ()); - } - - ICompletionData ICompletionDataFactory.CreateEventCreationCompletionData (string varName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType) - { - return new EventCreationCompletionData (ext, varName, delegateType, evt, parameterDefinition, currentMember, currentType); - } - - ICompletionData ICompletionDataFactory.CreateNewOverrideCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IMember m) - { - return new NewOverrideCompletionData (ext, declarationBegin, type, m); - } - ICompletionData ICompletionDataFactory.CreateNewPartialCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IUnresolvedMember m) - { - var ctx = ext.CSharpUnresolvedFile.GetTypeResolveContext (ext.UnresolvedFileCompilation, ext.TextEditorData.Caret.Location); - return new NewOverrideCompletionData (ext, declarationBegin, type, m.CreateResolved (ctx)); - } - IEnumerable ICompletionDataFactory.CreateCodeTemplateCompletionData () - { - var result = new CompletionDataList (); - if (EnableAutoCodeCompletion || IncludeCodeSnippetsInCompletionList.Value) { - CodeTemplateService.AddCompletionDataForMime ("text/x-playscript", result); - } - return result; - } - - IEnumerable ICompletionDataFactory.CreatePreProcessorDefinesCompletionData () - { - var project = ext.document.Project; - if (project == null) - yield break; - var configuration = project.GetConfiguration (MonoDevelop.Ide.IdeApp.Workspace.ActiveConfiguration) as DotNetProjectConfiguration; - if (configuration == null) - yield break; - foreach (var define in configuration.GetDefineSymbols ()) - yield return new CompletionData (define, "md-keyword"); - - } - - class FormatItemCompletionData : CompletionData - { - string format; - string description; - object example; - - public FormatItemCompletionData (string format, string description, object example) - { - this.format = format; - this.description = description; - this.example = example; - } - - - public override string DisplayText { - get { - return format; - } - } - public override string GetDisplayDescription (bool isSelected) - { - return "- " + description + ""; - } - - - string rightSideDescription = null; - public override string GetRightSideDescription (bool isSelected) - { - if (rightSideDescription == null) { - try { - rightSideDescription = "" + string.Format ("{0:" +format +"}", example) +""; - } catch (Exception e) { - rightSideDescription = ""; - LoggingService.LogError ("Format error.", e); - } - } - return rightSideDescription; - } - - public override string CompletionText { - get { - return format; - } - } - - public override int CompareTo (object obj) - { - return 0; - } - } - - - ICompletionData ICompletionDataFactory.CreateFormatItemCompletionData(string format, string description, object example) - { - return new FormatItemCompletionData (format, description, example); - } - - - class ImportSymbolCompletionData : CompletionData, IEntityCompletionData - { - readonly IType type; - readonly bool useFullName; - readonly CSharpCompletionTextEditorExtension ext; - public IType Type { - get { return this.type; } - } - - public ImportSymbolCompletionData (CSharpCompletionTextEditorExtension ext, bool useFullName, IType type, bool addConstructors) - { - this.ext = ext; - this.useFullName = useFullName; - this.type = type; - this.DisplayFlags |= ICSharpCode.NRefactory.Completion.DisplayFlags.IsImportCompletion; - } - - public override TooltipInformation CreateTooltipInformation (bool smartWrap) - { - return MemberCompletionData.CreateTooltipInformation (ext, null, type.GetDefinition (), smartWrap); - } - - bool initialized = false; - bool generateUsing, insertNamespace; - - void Initialize () - { - if (initialized) - return; - initialized = true; - if (string.IsNullOrEmpty (type.Namespace)) - return; - generateUsing = !useFullName; - insertNamespace = useFullName; - } - - #region IActionCompletionData implementation - public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier) - { - Initialize (); - var doc = ext.document; - using (var undo = doc.Editor.OpenUndoGroup ()) { - string text = insertNamespace ? type.Namespace + "." + type.Name : type.Name; - if (text != GetCurrentWord (window)) { - if (window.WasShiftPressed && generateUsing) - text = type.Namespace + "." + text; - window.CompletionWidget.SetCompletionText (window.CodeCompletionContext, GetCurrentWord (window), text); - } - - if (!window.WasShiftPressed && generateUsing) { - var generator = CodeGenerator.CreateGenerator (doc); - if (generator != null) { - generator.AddGlobalNamespaceImport (doc, type.Namespace); - // reparse - doc.UpdateParseDocument (); - } - } - } - ka |= KeyActions.Ignore; - } - #endregion - - #region ICompletionData implementation - public override IconId Icon { - get { - return type.GetStockIcon (); - } - } - - public override string DisplayText { - get { - return type.Name; - } - } - - static string GetDefaultDisplaySelection (string description, bool isSelected) - { - if (!isSelected) - return "" + description + ""; - return description; - } - - string displayDescription = null; - public override string GetDisplayDescription (bool isSelected) - { - if (displayDescription == null) { - Initialize (); - if (generateUsing || insertNamespace) { - displayDescription = string.Format (GettextCatalog.GetString ("(from '{0}')"), type.Namespace); - } else { - displayDescription = ""; - } - } - return GetDefaultDisplaySelection (displayDescription, isSelected); - } - - public override string Description { - get { - return type.Namespace; - } - } - - public override string CompletionText { - get { - return type.Name; - } - } - #endregion - - - List overloads; - - public override IEnumerable OverloadedData { - get { - yield return this; - if (overloads == null) - yield break; - foreach (var overload in overloads) - yield return overload; - } - } - - public override bool HasOverloads { - get { return overloads != null && overloads.Count > 0; } - } - - public override void AddOverload (ICSharpCode.NRefactory.Completion.ICompletionData data) - { - AddOverload ((ImportSymbolCompletionData)data); - } - - void AddOverload (ImportSymbolCompletionData overload) - { - if (overloads == null) - overloads = new List (); - overloads.Add (overload); - } - - IEntity IEntityCompletionData.Entity { - get { - return type.GetDefinition (); - } - } - } - - - ICompletionData ICompletionDataFactory.CreateImportCompletionData(IType type, bool useFullName, bool addConstructors) - { - return new ImportSymbolCompletionData (ext, useFullName, type, addConstructors); - } - - } - #endregion - - #region IParameterCompletionDataFactory implementation - IParameterDataProvider IParameterCompletionDataFactory.CreateConstructorProvider (int startOffset, IType type) - { - return new ConstructorParameterDataProvider (startOffset, this, type); - } - - IParameterDataProvider IParameterCompletionDataFactory.CreateConstructorProvider (int startOffset, IType type, AstNode initializer) - { - return new ConstructorParameterDataProvider (startOffset, this, type, initializer); - } - - IParameterDataProvider IParameterCompletionDataFactory.CreateMethodDataProvider (int startOffset, IEnumerable methods) - { - return new MethodParameterDataProvider (startOffset, this, methods); - } - - IParameterDataProvider IParameterCompletionDataFactory.CreateDelegateDataProvider (int startOffset, IType type) - { - return new DelegateDataProvider (startOffset, this, type); - } - - IParameterDataProvider IParameterCompletionDataFactory.CreateIndexerParameterDataProvider (int startOffset, IType type, IEnumerable indexers, AstNode resolvedNode) - { - var arrayType = type as ArrayType; - if (arrayType != null) - return new ArrayTypeParameterDataProvider (startOffset, this, arrayType); - return new IndexerParameterDataProvider (startOffset, this, type, indexers, resolvedNode); - } - - IParameterDataProvider IParameterCompletionDataFactory.CreateTypeParameterDataProvider (int startOffset, IEnumerable types) - { - return new TypeParameterDataProvider (startOffset, this, types); - } - - IParameterDataProvider IParameterCompletionDataFactory.CreateTypeParameterDataProvider (int startOffset, IEnumerable methods) - { - return new TypeParameterDataProvider (startOffset, this, methods); - } - #endregion - - #region IDebuggerExpressionResolver implementation - - static string GetIdentifierName (TextEditorData editor, Identifier id, out int startOffset) - { - startOffset = editor.LocationToOffset (id.StartLocation.Line, id.StartLocation.Column); - - return editor.GetTextBetween (id.StartLocation, id.EndLocation); - } - - internal static string ResolveExpression (TextEditorData editor, ResolveResult result, AstNode node, out int startOffset) - { - Console.WriteLine ("result is a {0}", result.GetType ().Name); - startOffset = -1; - - if (result is NamespaceResolveResult || - result is ConversionResolveResult || - result is ConstantResolveResult || - result is ForEachResolveResult || - result is TypeIsResolveResult || - result is TypeOfResolveResult || - result is ErrorResolveResult) - return null; - - if (result.IsCompileTimeConstant) - return null; - - startOffset = editor.LocationToOffset (node.StartLocation.Line, node.StartLocation.Column); - - if (result is InvocationResolveResult) { - var ir = (InvocationResolveResult) result; - if (ir.Member.Name == ".ctor") { - // if the user is hovering over something like "new Abc (...)", we want to show them type information for Abc - return ir.Member.DeclaringType.FullName; - } - - // do not support general method invocation for tooltips because it could cause side-effects - return null; - } else if (result is LocalResolveResult) { - if (node is ParameterDeclaration) { - // user is hovering over a method parameter, but we don't want to include the parameter type - var param = (ParameterDeclaration) node; - - return GetIdentifierName (editor, param.NameToken, out startOffset); - } - - if (node is VariableInitializer) { - // user is hovering over something like "int fubar = 5;", but we don't want the expression to include the " = 5" - var variable = (VariableInitializer) node; - - return GetIdentifierName (editor, variable.NameToken, out startOffset); - } - } else if (result is MemberResolveResult) { - var mr = (MemberResolveResult) result; - - if (node is PropertyDeclaration) { - var prop = (PropertyDeclaration) node; - var name = GetIdentifierName (editor, prop.NameToken, out startOffset); - - // if the property is static, then we want to return "Full.TypeName.Property" - if (prop.Modifiers.HasFlag (Modifiers.Static)) - return mr.Member.DeclaringType.FullName + "." + name; - - // otherwise we want to return "this.Property" so that it won't conflict with anything else in the local scope - return "this." + name; - } - - if (node is FieldDeclaration) { - var field = (FieldDeclaration) node; - var name = GetIdentifierName (editor, field.NameToken, out startOffset); - - // if the field is static, then we want to return "Full.TypeName.Field" - if (field.Modifiers.HasFlag (Modifiers.Static)) - return mr.Member.DeclaringType.FullName + "." + name; - - // otherwise we want to return "this.Field" so that it won't conflict with anything else in the local scope - return "this." + name; - } - - if (node is VariableInitializer) { - // user is hovering over a field declaration that includes initialization - var variable = (VariableInitializer) node; - var name = GetIdentifierName (editor, variable.NameToken, out startOffset); - - // walk up the AST to find the FieldDeclaration so that we can determine if it is static or not - var field = variable.GetParent (); - - // if the field is static, then we want to return "Full.TypeName.Field" - if (field.Modifiers.HasFlag (Modifiers.Static)) - return mr.Member.DeclaringType.FullName + "." + name; - - // otherwise we want to return "this.Field" so that it won't conflict with anything else in the local scope - return "this." + name; - } - - if (node is NamedExpression) { - // user is hovering over 'Property' in an expression like: var fubar = new Fubar () { Property = baz }; - var variable = node.GetParent (); - if (variable != null) { - var variableName = GetIdentifierName (editor, variable.NameToken, out startOffset); - var name = GetIdentifierName (editor, ((NamedExpression) node).NameToken, out startOffset); - - return variableName + "." + name; - } - } - } else if (result is TypeResolveResult) { - return ((TypeResolveResult) result).Type.FullName; - } - - return editor.GetTextBetween (node.StartLocation, node.EndLocation); - } - - static bool TryResolveAt (Document doc, DocumentLocation loc, out ResolveResult result, out AstNode node) - { - if (doc == null) - throw new ArgumentNullException ("doc"); - - result = null; - node = null; - - var parsedDocument = doc.ParsedDocument; - if (parsedDocument == null) - return false; - - var unit = parsedDocument.GetAst (); - var parsedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile; - - if (unit == null || parsedFile == null) - return false; - - try { - result = ResolveAtLocation.Resolve (new Lazy (() => doc.Compilation), parsedFile, unit, loc, out node); - if (result == null || node is Statement) - return false; - } catch { - return false; - } - - return true; - } - - string IDebuggerExpressionResolver.ResolveExpression (TextEditorData editor, Document doc, int offset, out int startOffset) - { - ResolveResult result; - AstNode node; - - var loc = editor.OffsetToLocation (offset); - if (!TryResolveAt (doc, loc, out result, out node)) { - startOffset = -1; - return null; - } - - return ResolveExpression (editor, result, node, out startOffset); - } - - #endregion - - #region TypeSystemSegmentTree - - TypeSystemSegmentTree validTypeSystemSegmentTree; - TypeSystemSegmentTree unstableTypeSystemSegmentTree; - - internal class TypeSystemTreeSegment : TreeSegment - { - public IUnresolvedEntity Entity { - get; - private set; - } - - public TypeSystemTreeSegment (int offset, int length, IUnresolvedEntity entity) : base (offset, length) - { - this.Entity = entity; - } - } - - internal TypeSystemTreeSegment GetMemberSegmentAt (int offset) - { - TypeSystemTreeSegment result = null; - if (unstableTypeSystemSegmentTree != null) - result = unstableTypeSystemSegmentTree.GetMemberSegmentAt (offset); - if (result == null && validTypeSystemSegmentTree != null) - result = validTypeSystemSegmentTree.GetMemberSegmentAt (offset); - return result; - } - - internal class TypeSystemSegmentTree : SegmentTree - { - public IUnresolvedTypeDefinition GetTypeAt (int offset) - { - IUnresolvedTypeDefinition result = null; - foreach (var seg in GetSegmentsAt (offset).Where (s => s.Entity is IUnresolvedTypeDefinition)) { - if (result == null || result.Region.IsInside (seg.Entity.Region.Begin)) - result = (IUnresolvedTypeDefinition)seg.Entity; - } - return result; - } - - public IUnresolvedMember GetMemberAt (int offset) - { - // Members don't overlap - var seg = GetSegmentsAt (offset).FirstOrDefault (s => s.Entity is IUnresolvedMember); - if (seg == null) - return null; - return (IUnresolvedMember)seg.Entity; - } - - public TypeSystemTreeSegment GetMemberSegmentAt (int offset) - { - // Members don't overlap - var seg = GetSegmentsAt (offset).FirstOrDefault (s => s.Entity is IUnresolvedMember); - if (seg == null) - return null; - return seg; - } - - - internal static TypeSystemSegmentTree Create (ParsedDocument parsedDocument, TextEditorData textEditorData) - { - TypeSystemSegmentTree result = new TypeSystemSegmentTree (); - - foreach (var type in parsedDocument.TopLevelTypeDefinitions) - AddType (textEditorData, result, type); - - return result; - } - - static void AddType (TextEditorData textEditorData, TypeSystemSegmentTree result, IUnresolvedTypeDefinition type) - { - int offset = textEditorData.LocationToOffset (type.Region.Begin); - int endOffset = type.Region.End.IsEmpty ? int.MaxValue : textEditorData.LocationToOffset (type.Region.End); - if (endOffset < 0) - endOffset = int.MaxValue; - result.Add (new TypeSystemTreeSegment (offset, endOffset - offset, type)); - foreach (var entity in type.Members) { - if (entity.IsSynthetic) - continue; - offset = textEditorData.LocationToOffset (entity.Region.Begin); - endOffset = textEditorData.LocationToOffset (entity.Region.End); - if (endOffset < 0) - endOffset = int.MaxValue; - result.Add (new TypeSystemTreeSegment (offset, endOffset - offset, entity)); - } - - foreach (var nested in type.NestedTypes) - AddType (textEditorData, result, nested); - } - } - - public IUnresolvedTypeDefinition GetTypeAt (int offset) - { - if (unstableTypeSystemSegmentTree == null && validTypeSystemSegmentTree == null) - return null; - IUnresolvedTypeDefinition type = null; - if (unstableTypeSystemSegmentTree != null) - type = unstableTypeSystemSegmentTree.GetTypeAt (offset); - if (type == null && validTypeSystemSegmentTree != null) - type = validTypeSystemSegmentTree.GetTypeAt (offset); - return type; - } - - public IUnresolvedMember GetMemberAt (int offset) - { - if (unstableTypeSystemSegmentTree == null && validTypeSystemSegmentTree == null) - return null; - - IUnresolvedMember member = null; - if (unstableTypeSystemSegmentTree != null) - member = unstableTypeSystemSegmentTree.GetMemberAt (offset); - if (member == null && validTypeSystemSegmentTree != null) - member = validTypeSystemSegmentTree.GetMemberAt (offset); - - return member; - } - #endregion - - - class CompletionContextProvider : ICompletionContextProvider - { - readonly ParsedDocument parsedDocument; - readonly TextEditorData textEditorData; - readonly TypeSystemSegmentTree validTypeSystemSegmentTree; - readonly TypeSystemSegmentTree unstableTypeSystemSegmentTree; - - public CompletionContextProvider (ParsedDocument parsedDocument, TextEditorData textEditorData, - TypeSystemSegmentTree validTypeSystemSegmentTree, TypeSystemSegmentTree unstableTypeSystemSegmentTree) - { - this.parsedDocument = parsedDocument; - this.textEditorData = textEditorData; - this.validTypeSystemSegmentTree = validTypeSystemSegmentTree; - this.unstableTypeSystemSegmentTree = unstableTypeSystemSegmentTree; - } - - IList ICompletionContextProvider.ConditionalSymbols { - get { - return parsedDocument.GetAst ().ConditionalSymbols; - } - } - - void ICompletionContextProvider.GetCurrentMembers (int offset, out IUnresolvedTypeDefinition currentType, out IUnresolvedMember currentMember) - { - currentType = GetTypeAt (offset); - currentMember = GetMemberAt (offset); - } - - public IUnresolvedTypeDefinition GetTypeAt (int offset) - { - if (unstableTypeSystemSegmentTree == null && validTypeSystemSegmentTree == null) - return null; - IUnresolvedTypeDefinition type = null; - if (unstableTypeSystemSegmentTree != null) - type = unstableTypeSystemSegmentTree.GetTypeAt (offset); - if (type == null && validTypeSystemSegmentTree != null) - type = validTypeSystemSegmentTree.GetTypeAt (offset); - return type; - } - - public IUnresolvedMember GetMemberAt (int offset) - { - if (unstableTypeSystemSegmentTree == null && validTypeSystemSegmentTree == null) - return null; - - IUnresolvedMember member = null; - if (unstableTypeSystemSegmentTree != null) - member = unstableTypeSystemSegmentTree.GetMemberAt (offset); - if (member == null && validTypeSystemSegmentTree != null) - member = validTypeSystemSegmentTree.GetMemberAt (offset); - return member; - } - - Tuple ICompletionContextProvider.GetMemberTextToCaret (int caretOffset, IUnresolvedTypeDefinition currentType, IUnresolvedMember currentMember) - { - int startOffset; - if (currentMember != null && currentType != null && currentType.Kind != TypeKind.Enum) { - startOffset = textEditorData.LocationToOffset(currentMember.Region.Begin); - } else if (currentType != null) { - startOffset = textEditorData.LocationToOffset(currentType.Region.Begin); - } else { - startOffset = 0; - } - while (startOffset > 0) { - char ch = textEditorData.GetCharAt(startOffset - 1); - if (ch != ' ' && ch != '\t') { - break; - } - --startOffset; - } - return Tuple.Create (caretOffset > startOffset ? textEditorData.GetTextAt (startOffset, caretOffset - startOffset) : "", - (TextLocation)textEditorData.OffsetToLocation (startOffset)); - } - - - CSharpAstResolver ICompletionContextProvider.GetResolver (CSharpResolver resolver, AstNode rootNode) - { - return new CSharpAstResolver (resolver, rootNode, parsedDocument.ParsedFile as CSharpUnresolvedFile); - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/ConstructorParameterDataProvider.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/ConstructorParameterDataProvider.cs deleted file mode 100644 index dbe88ff..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/ConstructorParameterDataProvider.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -// ConstructorParameterDataProvider.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2011 Xamarin -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.Completion; -using ICSharpCode.NRefactory.Completion; -using ICSharpCode.NRefactory.PlayScript; - -namespace MonoDevelop.PlayScript.Completion -{ - class ConstructorParameterDataProvider : MethodParameterDataProvider - { - IType type; - - - public ConstructorParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IType type, AstNode skipInitializer = null) : base (startOffset, ext) - { - this.type = type; - - var ctx = ext.CSharpUnresolvedFile.GetTypeResolveContext (ext.UnresolvedFileCompilation, ext.Document.Editor.Caret.Location) as CSharpTypeResolveContext; - - var lookup = new MemberLookup (ctx.CurrentTypeDefinition, ext.Compilation.MainAssembly); - bool isProtectedAllowed = false; - var typeDefinition = type.GetDefinition (); - if (ctx.CurrentTypeDefinition != null && typeDefinition != null) { - isProtectedAllowed = ctx.CurrentTypeDefinition.IsDerivedFrom (ctx.CurrentTypeDefinition.Compilation.Import (typeDefinition)); - } - foreach (var method in type.GetConstructors ()) { - if (!lookup.IsAccessible (method, isProtectedAllowed)) { - continue; - } - if (!method.IsBrowsable ()) - continue; - if (skipInitializer != null && skipInitializer.Parent.StartLocation == method.Region.Begin) - continue; - methods.Add (method); - } - methods.Sort (MethodComparer); - } - - protected override string GetPrefix (IMethod method) - { - var flags = OutputFlags.ClassBrowserEntries | OutputFlags.IncludeMarkup | OutputFlags.IncludeGenerics; - return ambience.GetString (type, flags) + "."; - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/DelegateDataProvider.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/DelegateDataProvider.cs deleted file mode 100644 index feec968..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/DelegateDataProvider.cs +++ /dev/null @@ -1,98 +0,0 @@ -// -// DelegateDataProvider.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2011 Mike Krüger -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Text; -using System.Xml; - -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.PlayScript.Formatting; -//using MonoDevelop.PlayScript.Parser; -using System.Text.RegularExpressions; -using ICSharpCode.NRefactory.PlayScript; -//using MonoDevelop.PlayScript.Resolver; -using Mono.TextEditor; -using ICSharpCode.NRefactory.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.Completion; -using System.Linq; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; - -namespace MonoDevelop.PlayScript.Completion -{ - class DelegateDataProvider : AbstractParameterDataProvider - { -// IType delegateType; - IMethod delegateMethod; - - ICompilation compilation; - CSharpUnresolvedFile file; - - public DelegateDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IType delegateType) : base (ext, startOffset) - { - compilation = ext.UnresolvedFileCompilation; - file = ext.CSharpUnresolvedFile; - // this.delegateType = delegateType; - this.delegateMethod = delegateType.GetDelegateInvokeMethod (); - } - - public override TooltipInformation CreateTooltipInformation (int overload, int currentParameter, bool smartWrap) - { - return MethodParameterDataProvider.CreateTooltipInformation (ext, compilation, file, delegateMethod, currentParameter, smartWrap); - } - - #region IParameterDataProvider implementation - public override int GetParameterCount (int overload) - { - if (overload >= Count) - return -1; - return delegateMethod.Parameters != null ? delegateMethod.Parameters.Count : 0; - } - - public override bool AllowParameterList (int overload) - { - if (overload >= Count) - return false; - var lastParam = delegateMethod.Parameters.LastOrDefault (); - return lastParam != null && lastParam.IsParams; - } - - public override string GetParameterName (int overload, int paramIndex) - { - return delegateMethod.Parameters[paramIndex].Name; - } - - public override int Count { - get { - return 1; - } - } - #endregion - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/EventCreationCompletionData.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/EventCreationCompletionData.cs deleted file mode 100644 index 364f9b9..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/EventCreationCompletionData.cs +++ /dev/null @@ -1,142 +0,0 @@ -// EventCreationCompletionData.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -using System; -using System.Text; -using System.Linq; -using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide.Gui.Content; -using MonoDevelop.PlayScript.Formatting; -//using MonoDevelop.PlayScript.Parser; -using Mono.TextEditor; -using System.Collections.Generic; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.Completion -{ - class EventCreationCompletionData : CompletionData - { - string parameterList; - IUnresolvedMember callingMember; -// CSharpCompletionTextEditorExtension ext; - int initialOffset; - public bool AddSemicolon = true; - TextEditorData editor; - - public override TooltipInformation CreateTooltipInformation (bool smartWrap) - { - var tooltipInfo = new TooltipInformation (); - return tooltipInfo; - } - - public EventCreationCompletionData (CSharpCompletionTextEditorExtension ext, string methodName, IType delegateType, IEvent evt, string parameterList, IUnresolvedMember callingMember, IUnresolvedTypeDefinition declaringType) : base (null) - { - if (string.IsNullOrEmpty (methodName)) { - this.DisplayText = (evt != null ? evt.Name : ""); - } else { - this.DisplayText = Char.ToUpper (methodName[0]) + methodName.Substring (1) + (evt != null ? evt.Name : ""); - } - - if (declaringType != null && declaringType.Members.Any (m => m.Name == this.DisplayText)) { - for (int i = 1; i < 10000; i++) { - if (!declaringType.Members.Any (m => m.Name == this.DisplayText + i)) { - this.DisplayText = this.DisplayText + i.ToString (); - break; - } - } - } - this.editor = ext.TextEditorData; - this.parameterList = parameterList; - this.callingMember = callingMember; - this.Icon = "md-newmethod"; - this.initialOffset = editor.Caret.Offset; - } - - public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier) - { - // insert add/remove event handler code after +=/-= - editor.Replace (initialOffset, editor.Caret.Offset - initialOffset, this.DisplayText + (AddSemicolon ? ";" : "")); - - // Search opening bracket of member - int pos = callingMember != null && !callingMember.BodyRegion.Begin.IsEmpty ? editor.Document.LocationToOffset (callingMember.BodyRegion.BeginLine, callingMember.BodyRegion.BeginColumn) : initialOffset; - while (pos < editor.Document.TextLength && editor.Document.GetCharAt (pos) != '{') { - pos++; - } - - // Search closing bracket of member - pos = editor.Document.GetMatchingBracketOffset (pos) + 1; - - pos = Math.Max (0, Math.Min (pos, editor.Document.TextLength - 1)); - - // Insert new event handler after closing bracket - var line = callingMember != null ? editor.Document.GetLine (callingMember.Region.BeginLine) : editor.Document.GetLineByOffset (initialOffset); - string indent = line.GetIndentation (editor.Document); - - StringBuilder sb = new StringBuilder (); - sb.Append (editor.EolMarker); - sb.Append (editor.EolMarker); - sb.Append (indent); - if (callingMember != null && callingMember.IsStatic) - sb.Append ("static "); - sb.Append ("void "); - int pos2 = sb.Length; - sb.Append (this.DisplayText); - sb.Append (' '); - sb.Append (this.parameterList); - sb.Append (editor.EolMarker); - sb.Append (indent); - sb.Append ("{"); - sb.Append (editor.EolMarker); - sb.Append (indent); - sb.Append (editor.Options.IndentationString); - int cursorPos = pos + sb.Length; - sb.Append (editor.EolMarker); - sb.Append (indent); - sb.Append ("}"); - editor.Insert (pos, sb.ToString ()); - editor.Caret.Offset = cursorPos; - - // start text link mode after insert - List links = new List (); - TextLink link = new TextLink ("name"); - - link.AddLink (new TextSegment (0, this.DisplayText.Length)); - link.AddLink (new TextSegment (pos - initialOffset + pos2, this.DisplayText.Length)); - links.Add (link); - - var tle = new TextLinkEditMode (editor.Parent, initialOffset, links); - tle.TextLinkMode = TextLinkMode.EditIdentifier; - tle.SetCaretPosition = true; - tle.SelectPrimaryLink = true; - tle.OldMode = editor.CurrentMode; - tle.StartMode (); - editor.CurrentMode = tle; - } - } - - -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/IndexerParameterDataProvider.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/IndexerParameterDataProvider.cs deleted file mode 100644 index c3513fa..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/IndexerParameterDataProvider.cs +++ /dev/null @@ -1,99 +0,0 @@ -// -// NRefactoryIndexerParameterDataProvider.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using System.Collections.Generic; -using System.Text; -using System.Xml; - -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.PlayScript.Formatting; -//using MonoDevelop.PlayScript.Parser; - -using System.Text.RegularExpressions; -using ICSharpCode.NRefactory.PlayScript; -using Mono.TextEditor; -using ICSharpCode.NRefactory.TypeSystem; -using ICSharpCode.NRefactory.Completion; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; - -namespace MonoDevelop.PlayScript.Completion -{ - class IndexerParameterDataProvider : AbstractParameterDataProvider - { -// AstNode resolvedExpression; - List indexers; - - ICompilation compilation; - CSharpUnresolvedFile file; - - public IndexerParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IType type, IEnumerable indexers, AstNode resolvedExpression) : base (ext, startOffset) - { - compilation = ext.UnresolvedFileCompilation; - file = ext.CSharpUnresolvedFile; - // this.resolvedExpression = resolvedExpression; - this.indexers = new List (indexers); - } - - public override TooltipInformation CreateTooltipInformation (int overload, int currentParameter, bool smartWrap) - { - return MethodParameterDataProvider.CreateTooltipInformation (ext, compilation, file, indexers[overload], currentParameter, smartWrap); - } - - #region IParameterDataProvider implementation - public override int GetParameterCount (int overload) - { - if (overload >= Count) - return -1; - var indexer = indexers[overload]; - return indexer != null && indexer.Parameters != null ? indexer.Parameters.Count : 0; - } - - public override bool AllowParameterList (int overload) - { - if (overload >= Count) - return false; - var lastParam = indexers[overload].Parameters.LastOrDefault (); - return lastParam != null && lastParam.IsParams; - } - - public override string GetParameterName (int overload, int paramIndex) - { - var indexer = indexers[overload]; - return indexer.Parameters[paramIndex].Name; - } - - public override int Count { - get { - return indexers != null ? indexers.Count : 0; - } - } - #endregion - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/MemberCompletionData.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/MemberCompletionData.cs deleted file mode 100644 index 3d3b4f0..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/MemberCompletionData.cs +++ /dev/null @@ -1,864 +0,0 @@ -// MemberCompletionData.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Xml; -using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide.Gui.Content; -using ICSharpCode.NRefactory.PlayScript; -using Mono.TextEditor; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Projects; -using ICSharpCode.NRefactory.Completion; -using ICSharpCode.NRefactory.Documentation; -using ICSharpCode.NRefactory.PlayScript.Refactoring; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; -using System.IO; -using MonoDevelop.PlayScript.Formatting; -using Gtk; -using MonoDevelop.Ide; - -namespace MonoDevelop.PlayScript.Completion -{ - class MemberCompletionData : CompletionData, IEntityCompletionData - { - CSharpCompletionTextEditorExtension editorCompletion; - OutputFlags flags; - bool hideExtensionParameter = true; - static CSharpAmbience ambience = new CSharpAmbience (); - string completionString; - string displayText; - Dictionary overloads; - - Mono.TextEditor.TextEditorData Editor { - get { - return editorCompletion.TextEditorData; - } - } - - MonoDevelop.PlayScript.Formatting.PlayScriptFormattingPolicy Policy { - get { - return editorCompletion.FormattingPolicy; - } - } - - public override string Description { - get { - return ""; - } - } - - public override string CompletionText { - get { return completionString; } - set { completionString = value; } - } - - public override string DisplayText { - get { - if (displayText == null) { - displayText = ambience.GetString (Entity.SymbolKind == SymbolKind.Constructor ? Entity.DeclaringTypeDefinition : Entity, flags | OutputFlags.HideGenericParameterNames); - } - return displayText; - } - } - - public override IconId Icon { - get { - return (Entity.SymbolKind == SymbolKind.Constructor ? Entity.DeclaringTypeDefinition : Entity).GetStockIcon (); - } - } - - public bool HideExtensionParameter { - get { - return hideExtensionParameter; - } - set { - hideExtensionParameter = value; - } - } - - bool isDelegateExpected; - public bool IsDelegateExpected { - get { - return isDelegateExpected || factory != null && factory.Engine.PossibleDelegates.Count > 0; - } - set { - isDelegateExpected = value; - } - } - - ICompilation compilation; - CSharpUnresolvedFile file; - CSharpCompletionTextEditorExtension.CompletionDataFactory factory; - - public MemberCompletionData (CSharpCompletionTextEditorExtension.CompletionDataFactory factory, IEntity entity, OutputFlags flags) : this(factory.ext, entity, flags) - { - this.factory = factory; - } - - public MemberCompletionData (CSharpCompletionTextEditorExtension editorCompletion, IEntity entity, OutputFlags flags) - { - compilation = editorCompletion.UnresolvedFileCompilation; - file = editorCompletion.CSharpUnresolvedFile; - - this.editorCompletion = editorCompletion; - this.flags = flags; - SetMember (entity); - DisplayFlags = DisplayFlags.DescriptionHasMarkup; - var m = Entity as IMember; - if (m != null && m.IsObsolete ()) - DisplayFlags |= DisplayFlags.Obsolete; - } - - public bool SearchBracket (int start, out int pos) - { - pos = -1; - - for (int i = start; i < Editor.Length; i++) { - char ch = Editor.GetCharAt (i); - if (ch == '(') { - pos = i + 1; - return true; - } - if (!char.IsWhiteSpace (ch)) - return false; - } - return false; - } - - static bool HasNonMethodMembersWithSameName (IMember member) - { - return member.DeclaringType.GetFields ().Cast () - .Concat (member.DeclaringType.GetProperties ().Cast ()) - .Concat (member.DeclaringType.GetEvents ().Cast ()) - .Concat (member.DeclaringType.GetNestedTypes ().Cast ()) - .Any (e => e.Name == member.Name); - } - - static bool HasAnyOverloadWithParameters (IMethod method) - { - if (method.SymbolKind == SymbolKind.Constructor) - return method.DeclaringType.GetConstructors ().Any (m => m.Parameters.Count > 0); - return method.DeclaringType.GetMethods ().Any (m => m.Name == method.Name && m.Parameters.Count > 0); - } - - public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier) - { - InsertCompletionText (window, ref ka, closeChar, keyChar, modifier, CompletionTextEditorExtension.AddParenthesesAfterCompletion, CompletionTextEditorExtension.AddOpeningOnly); - } - - bool IsBracketAlreadyInserted (IMethod method) - { - int offset = Editor.Caret.Offset; - while (offset < Editor.Length) { - char ch = Editor.GetCharAt (offset); - if (!char.IsLetterOrDigit (ch)) - break; - offset++; - } - while (offset < Editor.Length) { - char ch = Editor.GetCharAt (offset); - if (!char.IsWhiteSpace (ch)) - return ch == '(' || ch == '<' && RequireGenerics (method); - offset++; - } - return false; - } - - bool InsertSemicolon (int exprStart) - { - int offset = exprStart; - while (offset > 0) { - char ch = Editor.GetCharAt (offset); - if (!char.IsWhiteSpace (ch)) { - if (ch != '{' && ch != '}' && ch != ';') - return false; - break; - } - offset--; - } - - offset = Editor.Caret.Offset; - while (offset < Editor.Length) { - char ch = Editor.GetCharAt (offset); - if (!char.IsLetterOrDigit (ch)) - break; - offset++; - } - while (offset < Editor.Length) { - char ch = Editor.GetCharAt (offset); - if (!char.IsWhiteSpace (ch)) - return char.IsLetter (ch) || ch == '}'; - offset++; - } - return true; - } - - public void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier, bool addParens, bool addOpeningOnly) - { - string text = CompletionText; - string partialWord = GetCurrentWord (window); - int skipChars = 0; - bool runParameterCompletionCommand = false; - bool runCompletionCompletionCommand = false; - var method = Entity as IMethod; - if (addParens && !IsDelegateExpected && method != null && !HasNonMethodMembersWithSameName ((IMember)Entity) && !IsBracketAlreadyInserted (method)) { - var line = Editor.GetLine (Editor.Caret.Line); - //var start = window.CodeCompletionContext.TriggerOffset + partialWord.Length + 2; - //var end = line.Offset + line.Length; - //string textToEnd = start < end ? Editor.GetTextBetween (start, end) : ""; - bool addSpace = Policy.BeforeMethodCallParentheses && CSharpTextEditorIndentation.OnTheFlyFormatting; - - int exprStart = window.CodeCompletionContext.TriggerOffset - 1; - while (exprStart > line.Offset) { - char ch = Editor.GetCharAt (exprStart); - if (ch != '.' && ch != '_' && /*ch != '<' && ch != '>' && */!char.IsLetterOrDigit (ch)) - break; - exprStart--; - } - bool insertSemicolon = InsertSemicolon(exprStart); - if (Entity.SymbolKind == SymbolKind.Constructor) - insertSemicolon = false; - //int pos; - - Gdk.Key[] keys = new [] { Gdk.Key.Return, Gdk.Key.Tab, Gdk.Key.space, Gdk.Key.KP_Enter, Gdk.Key.ISO_Enter }; - if (keys.Contains (closeChar) || keyChar == '.') { - if (HasAnyOverloadWithParameters (method)) { - if (addOpeningOnly) { - text += RequireGenerics (method) ? "<|" : (addSpace ? " (|" : "(|"); - skipChars = 0; - } else { - if (keyChar == '.') { - if (RequireGenerics (method)) { - text += addSpace ? "<> ()" : "<>()"; - } else { - text += addSpace ? " ()" : "()"; - } - skipChars = 0; - } else { - if (insertSemicolon) { - if (RequireGenerics (method)) { - text += addSpace ? "<|> ();" : "<|>();"; - skipChars = addSpace ? 5 : 4; - } else { - text += addSpace ? " (|);" : "(|);"; - skipChars = 2; - } - } else { - if (RequireGenerics (method)) { - text += addSpace ? "<|> ()" : "<|>()"; - skipChars = addSpace ? 4 : 3; - } else { - text += addSpace ? " (|)" : "(|)"; - skipChars = 1; - } - } - } - } - runParameterCompletionCommand = true; - } else { - if (addOpeningOnly) { - text += RequireGenerics (method) ? "<|" : (addSpace ? " (|" : "(|"); - skipChars = 0; - } else { - if (keyChar == '.') { - if (RequireGenerics (method)) { - text += addSpace ? "<> ().|" : "<>().|"; - } else { - text += addSpace ? " ().|" : "().|"; - } - skipChars = 0; - } else { - if (insertSemicolon) { - if (RequireGenerics (method)) { - text += addSpace ? "<|> ();" : "<|>();"; - } else { - text += addSpace ? " ();|" : "();|"; - } - - } else { - if (RequireGenerics (method)) { - text += addSpace ? "<|> ()" : "<|>()"; - } else { - text += addSpace ? " ()|" : "()|"; - } - - } - } - } - } - if (keyChar == '(') { - var skipChar = Editor.SkipChars.LastOrDefault (); - if (skipChar != null && skipChar.Offset == (window.CodeCompletionContext.TriggerOffset + partialWord.Length) && skipChar.Char == ')') - Editor.Remove (skipChar.Offset, 1); - } - } - ka |= KeyActions.Ignore; - } - if ((DisplayFlags & DisplayFlags.NamedArgument) == DisplayFlags.NamedArgument && - CompletionTextEditorExtension.AddParenthesesAfterCompletion && - (closeChar == Gdk.Key.Tab || - closeChar == Gdk.Key.KP_Tab || - closeChar == Gdk.Key.ISO_Left_Tab || - closeChar == Gdk.Key.Return || - closeChar == Gdk.Key.KP_Enter || - closeChar == Gdk.Key.ISO_Enter || - closeChar == Gdk.Key.space || - closeChar == Gdk.Key.KP_Space)) { - if (Policy.AroundAssignmentParentheses) - text += " "; - text += "="; - if (Policy.AroundAssignmentParentheses && !(closeChar == Gdk.Key.space || closeChar == Gdk.Key.KP_Space)) - text += " "; - runCompletionCompletionCommand = true; - } - window.CompletionWidget.SetCompletionText (window.CodeCompletionContext, partialWord, text); - int offset = Editor.Caret.Offset; - for (int i = 0; i < skipChars; i++) { - Editor.SetSkipChar (offset, Editor.GetCharAt (offset)); - offset++; - } - - if (runParameterCompletionCommand) - editorCompletion.RunParameterCompletionCommand (); - if (runCompletionCompletionCommand && IdeApp.Workbench != null) { - Application.Invoke (delegate { - editorCompletion.RunCompletionCommand (); - }); - } - } - - bool ContainsType (IType testType, IType searchType) - { - if (testType == searchType) - return true; - foreach (var arg in testType.TypeArguments) - if (ContainsType (arg, searchType)) - return true; - return false; - } - - bool RequireGenerics (IMethod method) - { - if (method.SymbolKind == SymbolKind.Constructor) - return method.DeclaringType.TypeParameterCount > 0; - var testMethod = method.ReducedFrom ?? method; - return testMethod.TypeArguments.Any (t => !testMethod.Parameters.Any (p => ContainsType(p.Type, t))); - } - - void SetMember (IEntity entity) - { - this.Entity = entity; - this.completionString = displayText = (Entity.SymbolKind == SymbolKind.Constructor ? Entity.DeclaringTypeDefinition : Entity).Name; - } - - TypeSystemAstBuilder GetBuilder (ICompilation compilation) - { - var ctx = editorCompletion.CSharpUnresolvedFile.GetTypeResolveContext (editorCompletion.UnresolvedFileCompilation, editorCompletion.Document.Editor.Caret.Location) as CSharpTypeResolveContext; - var state = new CSharpResolver (ctx); - var builder = new TypeSystemAstBuilder (state); - builder.AddTypeReferenceAnnotations = true; - var dt = state.CurrentTypeDefinition; - var declaring = ctx.CurrentTypeDefinition != null ? ctx.CurrentTypeDefinition.DeclaringTypeDefinition : null; - if (declaring != null) { - while (dt != null) { - if (dt.Equals (declaring)) { - builder.AlwaysUseShortTypeNames = true; - break; - } - dt = dt.DeclaringTypeDefinition; - } - } - return builder; - } - - internal class MyAmbience : IAmbience - { - TypeSystemAstBuilder builder; - - public MyAmbience (TypeSystemAstBuilder builder) - { - this.builder = builder; - ConversionFlags = ICSharpCode.NRefactory.TypeSystem.ConversionFlags.StandardConversionFlags; - } - - public ConversionFlags ConversionFlags { get; set; } - #region ConvertEntity - public string ConvertSymbol(ISymbol symbol) - { - if (symbol is IEntity) - return ConvertEntity ((IEntity)symbol); - return symbol.ToString (); - } - - public string ConvertEntity (IEntity entity) - { - if (entity == null) - throw new ArgumentNullException ("entity"); - - StringWriter writer = new StringWriter (); - ConvertEntity (entity, new TextWriterTokenWriter (writer), FormattingOptionsFactory.CreateMono ()); - return writer.ToString (); - } - - public void ConvertEntity (IEntity entity, TextWriterTokenWriter formatter, CSharpFormattingOptions formattingPolicy) - { - if (entity == null) - throw new ArgumentNullException ("entity"); - if (formatter == null) - throw new ArgumentNullException ("formatter"); - if (formattingPolicy == null) - throw new ArgumentNullException ("options"); - - TypeSystemAstBuilder astBuilder = CreateAstBuilder (); - EntityDeclaration node = astBuilder.ConvertEntity (entity); - PrintModifiers (node.Modifiers, formatter); - - if ((ConversionFlags & ConversionFlags.ShowDefinitionKeyword) == ConversionFlags.ShowDefinitionKeyword) { - if (node is TypeDeclaration) { - switch (((TypeDeclaration)node).ClassType) { - case ClassType.Class: - formatter.WriteKeyword (Roles.ClassKeyword, "class"); - break; - case ClassType.Struct: - formatter.WriteKeyword (Roles.StructKeyword, "struct"); - break; - case ClassType.Interface: - formatter.WriteKeyword (Roles.InterfaceKeyword, "interface"); - break; - case ClassType.Enum: - formatter.WriteKeyword (Roles.EnumKeyword, "enum"); - break; - default: - throw new Exception ("Invalid value for ClassType"); - } - formatter.Space (); - } else if (node is DelegateDeclaration) { - formatter.WriteKeyword (Roles.DelegateKeyword, "function"); - formatter.Space (); - } else if (node is EventDeclaration) { - formatter.WriteKeyword (EventDeclaration.EventKeywordRole, "event"); - formatter.Space (); - } - } - - if ((ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType) { - var rt = node.GetChildByRole (Roles.Type); - if (!rt.IsNull) { - rt.AcceptVisitor (new CSharpOutputVisitor (formatter, formattingPolicy)); - formatter.Space (); - } - } - - if (entity is ITypeDefinition) - WriteTypeDeclarationName ((ITypeDefinition)entity, formatter, formattingPolicy); - else - WriteMemberDeclarationName ((IMember)entity, formatter, formattingPolicy); - - if ((ConversionFlags & ConversionFlags.ShowParameterList) == ConversionFlags.ShowParameterList && HasParameters (entity)) { - if (entity.SymbolKind == SymbolKind.Indexer) - formatter.WriteToken (Roles.LBracket, "["); - else - formatter.WriteToken (Roles.LBrace, "("); - bool first = true; - foreach (var param in node.GetChildrenByRole(Roles.Parameter)) { - if (first) { - first = false; - } else { - formatter.WriteToken (Roles.Comma, ","); - formatter.Space (); - } - param.AcceptVisitor (new CSharpOutputVisitor (formatter, formattingPolicy)); - } - if (entity.SymbolKind == SymbolKind.Indexer) - formatter.WriteToken (Roles.RBracket, "]"); - else - formatter.WriteToken (Roles.RBrace, ")"); - } - - if ((ConversionFlags & ConversionFlags.ShowBody) == ConversionFlags.ShowBody && !(node is TypeDeclaration)) { - IProperty property = entity as IProperty; - if (property != null) { - formatter.Space (); - formatter.WriteToken (Roles.LBrace, "{"); - formatter.Space (); - if (property.CanGet) { - formatter.WriteKeyword (PropertyDeclaration.GetKeywordRole, "get"); - formatter.WriteToken (Roles.Semicolon, ";"); - formatter.Space (); - } - if (property.CanSet) { - formatter.WriteKeyword (PropertyDeclaration.SetKeywordRole, "set"); - formatter.WriteToken (Roles.Semicolon, ";"); - formatter.Space (); - } - formatter.WriteToken (Roles.RBrace, "}"); - } else { - formatter.WriteToken (Roles.Semicolon, ";"); - } - } - } - - bool HasParameters (IEntity e) - { - switch (e.SymbolKind) { - case SymbolKind.TypeDefinition: - return ((ITypeDefinition)e).Kind == TypeKind.Delegate; - case SymbolKind.Indexer: - case SymbolKind.Method: - case SymbolKind.Operator: - case SymbolKind.Constructor: - case SymbolKind.Destructor: - return true; - default: - return false; - } - } - public string ConvertConstantValue (object constantValue) - { - if (constantValue == null) - return "null"; - return constantValue.ToString (); - } - - TypeSystemAstBuilder CreateAstBuilder () - { - return builder; - } - - void WriteTypeDeclarationName (ITypeDefinition typeDef, TextWriterTokenWriter formatter, CSharpFormattingOptions formattingPolicy) - { - TypeSystemAstBuilder astBuilder = CreateAstBuilder (); - if (typeDef.DeclaringTypeDefinition != null) { - WriteTypeDeclarationName (typeDef.DeclaringTypeDefinition, formatter, formattingPolicy); - formatter.WriteToken (Roles.Dot, "."); - } else if ((ConversionFlags & ConversionFlags.UseFullyQualifiedTypeNames) == ConversionFlags.UseFullyQualifiedTypeNames) { - formatter.WriteIdentifier (Identifier.Create (typeDef.Namespace)); - formatter.WriteToken (Roles.Dot, "."); - } - formatter.WriteIdentifier (Identifier.Create (typeDef.Name)); - if ((ConversionFlags & ConversionFlags.ShowTypeParameterList) == ConversionFlags.ShowTypeParameterList) { - var outputVisitor = new CSharpOutputVisitor (formatter, formattingPolicy); - outputVisitor.WriteTypeParameters (astBuilder.ConvertEntity (typeDef).GetChildrenByRole (Roles.TypeParameter)); - } - } - - void WriteMemberDeclarationName (IMember member, TextWriterTokenWriter formatter, CSharpFormattingOptions formattingPolicy) - { - TypeSystemAstBuilder astBuilder = CreateAstBuilder (); - if ((ConversionFlags & ConversionFlags.ShowDeclaringType) == ConversionFlags.ShowDeclaringType) { - ConvertType (member.DeclaringType, formatter, formattingPolicy); - formatter.WriteToken (Roles.Dot, "."); - } - switch (member.SymbolKind) { - case SymbolKind.Indexer: - formatter.WriteKeyword (IndexerDeclaration.ThisKeywordRole, "this"); - break; - case SymbolKind.Constructor: - formatter.WriteIdentifier (Identifier.Create (member.DeclaringType.Name)); - break; - case SymbolKind.Destructor: - formatter.WriteToken (DestructorDeclaration.TildeRole, "~"); - formatter.WriteIdentifier (Identifier.Create (member.DeclaringType.Name)); - break; - case SymbolKind.Operator: - switch (member.Name) { - case "op_Implicit": - formatter.WriteKeyword (OperatorDeclaration.ImplicitRole, "implicit"); - formatter.Space (); - formatter.WriteKeyword (OperatorDeclaration.OperatorKeywordRole, "operator"); - formatter.Space (); - ConvertType (member.ReturnType, formatter, formattingPolicy); - break; - case "op_Explicit": - formatter.WriteKeyword (OperatorDeclaration.ExplicitRole, "explicit"); - formatter.Space (); - formatter.WriteKeyword (OperatorDeclaration.OperatorKeywordRole, "operator"); - formatter.Space (); - ConvertType (member.ReturnType, formatter, formattingPolicy); - break; - default: - formatter.WriteKeyword (OperatorDeclaration.OperatorKeywordRole, "operator"); - formatter.Space (); - var operatorType = OperatorDeclaration.GetOperatorType (member.Name); - if (operatorType.HasValue) { - formatter.WriteToken (OperatorDeclaration.GetRole (operatorType.Value), OperatorDeclaration.GetToken (operatorType.Value)); - } - else - formatter.WriteIdentifier (Identifier.Create (member.Name)); - break; - } - break; - default: - formatter.WriteIdentifier (Identifier.Create (member.Name)); - break; - } - if ((ConversionFlags & ConversionFlags.ShowTypeParameterList) == ConversionFlags.ShowTypeParameterList && member.SymbolKind == SymbolKind.Method) { - var outputVisitor = new CSharpOutputVisitor (formatter, formattingPolicy); - outputVisitor.WriteTypeParameters (astBuilder.ConvertEntity (member).GetChildrenByRole (Roles.TypeParameter)); - } - } - - void PrintModifiers (Modifiers modifiers, TextWriterTokenWriter formatter) - { - foreach (var m in CSharpModifierToken.AllModifiers) { - if ((modifiers & m) == m) { - formatter.WriteToken (TypeDeclaration.ModifierRole, CSharpModifierToken.GetModifierName (m)); - formatter.Space (); - } - } - } - - -#endregion - - public string ConvertVariable (IVariable v) - { - TypeSystemAstBuilder astBuilder = CreateAstBuilder (); - AstNode astNode = astBuilder.ConvertVariable (v); - return astNode.ToString ().TrimEnd (';', '\r', '\n'); - } - - public string ConvertType (IType type) - { - if (type == null) - throw new ArgumentNullException ("type"); - - TypeSystemAstBuilder astBuilder = CreateAstBuilder (); - AstType astType = astBuilder.ConvertType (type); - return astType.ToString (); - } - - public void ConvertType (IType type, TextWriterTokenWriter formatter, CSharpFormattingOptions formattingPolicy) - { - TypeSystemAstBuilder astBuilder = CreateAstBuilder (); - AstType astType = astBuilder.ConvertType (type); - astType.AcceptVisitor (new CSharpOutputVisitor (formatter, formattingPolicy)); - } - - public string WrapComment (string comment) - { - return "// " + comment; - } - } - - public static TooltipInformation CreateTooltipInformation (CSharpCompletionTextEditorExtension editorCompletion, CSharpResolver resolver, IEntity entity, bool smartWrap) - { - return CreateTooltipInformation (editorCompletion.UnresolvedFileCompilation, editorCompletion.CSharpUnresolvedFile, resolver, editorCompletion.TextEditorData, editorCompletion.FormattingPolicy, entity, smartWrap); - } - - public static TooltipInformation CreateTooltipInformation (ICompilation compilation, CSharpUnresolvedFile file, TextEditorData textEditorData, MonoDevelop.PlayScript.Formatting.PlayScriptFormattingPolicy formattingPolicy, IEntity entity, bool smartWrap, bool createFooter = false) - { - return CreateTooltipInformation (compilation, file, null, textEditorData, formattingPolicy, entity, smartWrap, createFooter); - } - - public static TooltipInformation CreateTooltipInformation (ICompilation compilation, CSharpUnresolvedFile file, CSharpResolver resolver, TextEditorData textEditorData, MonoDevelop.PlayScript.Formatting.PlayScriptFormattingPolicy formattingPolicy, IEntity entity, bool smartWrap, bool createFooter = false) - { - var tooltipInfo = new TooltipInformation (); - if (resolver == null) - resolver = file != null ? file.GetResolver (compilation, textEditorData.Caret.Location) : new CSharpResolver (compilation); - var sig = new SignatureMarkupCreator (resolver, formattingPolicy.CreateOptions ()); - sig.BreakLineAfterReturnType = smartWrap; - try { - tooltipInfo.SignatureMarkup = sig.GetMarkup (entity); - } catch (Exception e) { - LoggingService.LogError ("Got exception while creating markup for :" + entity, e); - return new TooltipInformation (); - } - tooltipInfo.SummaryMarkup = AmbienceService.GetSummaryMarkup (entity) ?? ""; - - if (entity is IMember) { - var evt = (IMember)entity; - if (evt.ReturnType.Kind == TypeKind.Delegate) { - tooltipInfo.AddCategory (GettextCatalog.GetString ("Delegate Info"), sig.GetDelegateInfo (evt.ReturnType)); - } - } - if (entity is IMethod) { - var method = (IMethod)entity; - if (method.IsExtensionMethod) { - tooltipInfo.AddCategory (GettextCatalog.GetString ("Extension Method from"), method.DeclaringTypeDefinition.FullName); - } - } - if (createFooter) { - tooltipInfo.FooterMarkup = sig.CreateFooter (entity); - } - return tooltipInfo; - } - - public static TooltipInformation CreateTooltipInformation (ICompilation compilation, CSharpUnresolvedFile file, TextEditorData textEditorData, MonoDevelop.PlayScript.Formatting.PlayScriptFormattingPolicy formattingPolicy, IType type, bool smartWrap, bool createFooter = false) - { - var tooltipInfo = new TooltipInformation (); - if (type.Kind == TypeKind.Unknown) - return tooltipInfo; - var resolver = file != null ? file.GetResolver (compilation, textEditorData.Caret.Location) : new CSharpResolver (compilation); - var sig = new SignatureMarkupCreator (resolver, formattingPolicy.CreateOptions ()); - sig.BreakLineAfterReturnType = smartWrap; - try { - tooltipInfo.SignatureMarkup = sig.GetMarkup (type.IsParameterized ? type.GetDefinition () : type); - } catch (Exception e) { - LoggingService.LogError ("Got exception while creating markup for :" + type, e); - return new TooltipInformation (); - } - if (type.IsParameterized) { - var typeInfo = new StringBuilder (); - for (int i = 0; i < type.TypeParameterCount; i++) { - typeInfo.AppendLine (type.GetDefinition ().TypeParameters [i].Name + " is " + sig.GetTypeReferenceString (type.TypeArguments [i])); - } - tooltipInfo.AddCategory ("Type Parameters", typeInfo.ToString ()); - } - - var def = type.GetDefinition (); - if (def != null) { - if (createFooter) - tooltipInfo.FooterMarkup = sig.CreateFooter (def); - tooltipInfo.SummaryMarkup = AmbienceService.GetSummaryMarkup (def) ?? ""; - } - return tooltipInfo; - } - - public override TooltipInformation CreateTooltipInformation (bool smartWrap) - { - return CreateTooltipInformation (compilation, file, editorCompletion.TextEditorData, editorCompletion.FormattingPolicy, Entity, smartWrap); - } - #region IOverloadedCompletionData implementation - - class OverloadSorter : IComparer - { - public OverloadSorter () - { - } - - public int Compare (ICompletionData x, ICompletionData y) - { - var mx = ((MemberCompletionData)x).Entity as IMember; - var my = ((MemberCompletionData)y).Entity as IMember; - int result; - - if (mx is ITypeDefinition && my is ITypeDefinition) { - result = ((((ITypeDefinition)mx).TypeParameters.Count).CompareTo (((ITypeDefinition)my).TypeParameters.Count)); - if (result != 0) - return result; - } - - if (mx is IMethod && my is IMethod) { - return MethodParameterDataProvider.MethodComparer ((IMethod)mx, (IMethod)my); - } - string sx = mx.ReflectionName;// ambience.GetString (mx, flags); - string sy = my.ReflectionName;// ambience.GetString (my, flags); - result = sx.Length.CompareTo (sy.Length); - return result == 0 ? string.Compare (sx, sy) : result; - } - } - - public override IEnumerable OverloadedData { - get { - if (overloads == null) - return new CompletionData[] { this }; - - var sorted = new List (overloads.Values); - sorted.Add (this); - sorted.Sort (new OverloadSorter ()); - return sorted; - } - } - - public override bool HasOverloads { - get { return overloads != null && overloads.Count > 0; } - } - - public override void AddOverload (ICSharpCode.NRefactory.Completion.ICompletionData data) - { - AddOverload ((MemberCompletionData)data); - } - - public void AddOverload (MemberCompletionData overload) - { - if (overloads == null) - overloads = new Dictionary (); - - if (overload.Entity is IMember && Entity is IMember) { - // filter overriden members that came from base classes - // note that the overload tree is traversed top down. - var member = Entity as IMember; - if (member.IsOverride) - return; - - string MemberId = (overload.Entity as IMember).GetIdString (); - if (MemberId != (this.Entity as IMember).GetIdString () && !overloads.ContainsKey (MemberId)) { - overloads [MemberId] = overload; - - //if any of the overloads is obsolete, we should not mark the item obsolete - if (!(overload.Entity as IMember).IsObsolete ()) - DisplayFlags &= ~DisplayFlags.Obsolete; - } - } - } - #endregion - - #region IEntityCompletionData implementation - public IEntity Entity { - get; - set; - } - #endregion - - public override int CompareTo (object obj) - { - int result = base.CompareTo (obj); - if (result == 0) { - var mcd = obj as MemberCompletionData; - if (mcd != null) { - var mc = mcd; - if (this.Entity.SymbolKind == SymbolKind.Method) { - var method = (IMethod)this.Entity; - if (method.IsExtensionMethod) - return 1; - } - if (mc.Entity.SymbolKind == SymbolKind.Method) { - var method = (IMethod)mc.Entity; - if (method.IsExtensionMethod) - return -1; - } - } else { - return -1; - } - } - return result; - } - - public override string ToString () - { - return string.Format ("[MemberCompletionData: Entity={0}]", Entity); - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/MethodParameterDataProvider.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/MethodParameterDataProvider.cs deleted file mode 100644 index a68154c..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/MethodParameterDataProvider.cs +++ /dev/null @@ -1,335 +0,0 @@ -// NRefactoryParameterDataProvider.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -using System; -using System.Collections.Generic; -using System.Text; - -using MonoDevelop.Core; -using System.Text.RegularExpressions; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.Completion; -using System.Linq; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using ICSharpCode.NRefactory.PlayScript.Refactoring; -using ICSharpCode.NRefactory.PlayScript.Completion; -using MonoDevelop.Ide.CodeCompletion; -using Mono.TextEditor; - -namespace MonoDevelop.PlayScript.Completion -{ - class MethodParameterDataProvider : AbstractParameterDataProvider - { - protected List methods = new List (); - protected CSharpAmbience ambience = new CSharpAmbience (); - protected bool staticResolve = false; - - ICompilation compilation; - CSharpUnresolvedFile file; - - - protected MethodParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext) : base (ext, startOffset) - { - compilation = ext.UnresolvedFileCompilation; - file = ext.CSharpUnresolvedFile; - } - - public MethodParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IEnumerable m) : base (ext, startOffset) - { - compilation = ext.UnresolvedFileCompilation; - file = ext.CSharpUnresolvedFile; - - HashSet alreadyAdded = new HashSet (); - foreach (var method in m) { - if (method.IsConstructor) - continue; - if (!method.IsBrowsable ()) - continue; - string str = ambience.GetString (method, OutputFlags.IncludeParameters | OutputFlags.GeneralizeGenerics | OutputFlags.IncludeGenerics); - if (alreadyAdded.Contains (str)) - continue; - alreadyAdded.Add (str); - methods.Add (method); - } - - methods.Sort (MethodComparer); - } - - public MethodParameterDataProvider (CSharpCompletionTextEditorExtension ext, IMethod method) : base (ext, 0) - { - methods.Add (method); - } - - protected internal static int MethodComparer (IMethod left, IMethod right) - { - bool lObs = left.IsObsolete (); - bool rObs = right.IsObsolete (); - - if (lObs && !rObs) - return 1; - if (!lObs && rObs) - return -1; - - var lstate = left.GetEditorBrowsableState (); - var rstate = right.GetEditorBrowsableState (); - if (lstate == rstate) { - if (left.Parameters.Any (p => p.IsParams) && !right.Parameters.Any (p => p.IsParams)) - return 1; - if (!left.Parameters.Any (p => p.IsParams) && right.Parameters.Any (p => p.IsParams)) - return -1; - var cnt = left.Parameters.Count (p => !p.IsOptional) - right.Parameters.Count (p => !p.IsOptional); - if (cnt == 0) - cnt = left.Parameters.Count (p => p.IsOptional) - right.Parameters.Count (p => p.IsOptional); - if (cnt == 0) { - for (int i = 0; i < left.Parameters.Count; i++) { - if (left.Parameters [i].Type.Name == "NSDictionary" && right.Parameters [i].Type.Name != "NSDictionary") - return 1; - if (right.Parameters [i].Type.Name == "NSDictionary" && left.Parameters [i].Type.Name != "NSDictionary") - return -1; - } - } - return cnt; - } - return lstate.CompareTo (rstate); - } - - - public override MonoDevelop.Ide.CodeCompletion.TooltipInformation CreateTooltipInformation (int overload, int currentParameter, bool smartWrap) - { - return CreateTooltipInformation (ext, compilation, file, methods[overload], currentParameter, smartWrap); - } - - public static TooltipInformation CreateTooltipInformation (CSharpCompletionTextEditorExtension ext, ICompilation compilation, CSharpUnresolvedFile file, IParameterizedMember entity, int currentParameter, bool smartWrap) - { - return CreateTooltipInformation (compilation, file, ext.TextEditorData, ext.FormattingPolicy, entity, currentParameter, smartWrap); - } - - public static TooltipInformation CreateTooltipInformation (ICompilation compilation, CSharpUnresolvedFile file, TextEditorData textEditorData, MonoDevelop.PlayScript.Formatting.PlayScriptFormattingPolicy formattingPolicy, IParameterizedMember entity, int currentParameter, bool smartWrap) - { - var tooltipInfo = new TooltipInformation (); - var resolver = file.GetResolver (compilation, textEditorData.Caret.Location); - var sig = new SignatureMarkupCreator (resolver, formattingPolicy.CreateOptions ()); - sig.HighlightParameter = currentParameter; - sig.BreakLineAfterReturnType = smartWrap; - try { - tooltipInfo.SignatureMarkup = sig.GetMarkup (entity); - } catch (Exception e) { - LoggingService.LogError ("Got exception while creating markup for :" + entity, e); - return new TooltipInformation (); - } - tooltipInfo.SummaryMarkup = AmbienceService.GetSummaryMarkup (entity) ?? ""; - - if (entity is IMethod) { - var method = (IMethod)entity; - if (method.IsExtensionMethod) { - tooltipInfo.AddCategory (GettextCatalog.GetString ("Extension Method from"), method.DeclaringTypeDefinition.FullName); - } - } - int paramIndex = currentParameter; - - if (entity is IMethod && ((IMethod)entity).IsExtensionMethod) - paramIndex++; - paramIndex = Math.Min (entity.Parameters.Count - 1, paramIndex); - - var curParameter = paramIndex >= 0 && paramIndex < entity.Parameters.Count ? entity.Parameters [paramIndex] : null; - if (curParameter != null) { - - string docText = AmbienceService.GetDocumentation (entity); - if (!string.IsNullOrEmpty (docText)) { - string text = docText; - Regex paramRegex = new Regex ("(\\.*?\\)", RegexOptions.Compiled); - Match match = paramRegex.Match (docText); - - if (match.Success) { - text = AmbienceService.GetDocumentationMarkup (entity, match.Groups [1].Value); - if (!string.IsNullOrWhiteSpace (text)) - tooltipInfo.AddCategory (GettextCatalog.GetString ("Parameter"), text); - } - } - - if (curParameter.Type.Kind == TypeKind.Delegate) - tooltipInfo.AddCategory (GettextCatalog.GetString ("Delegate Info"), sig.GetDelegateInfo (curParameter.Type)); - } - return tooltipInfo; - } - - #region IParameterDataProvider implementation - - protected virtual string GetPrefix (IMethod method) - { - return GetShortType (method.ReturnType) + " "; - } - /* - public override string GetHeading (int overload, string[] parameterMarkup, int currentParameter) - { - var flags = OutputFlags.ClassBrowserEntries | OutputFlags.IncludeMarkup | OutputFlags.IncludeGenerics; - if (staticResolve) - flags |= OutputFlags.StaticUsage; - - var m = methods [overload]; - - string name = m.EntityType == EntityType.Constructor || m.EntityType == EntityType.Destructor ? m.DeclaringType.Name : m.Name; - var parameters = new StringBuilder (); - int curLen = 0; - string prefix = GetPrefix (m); - - foreach (string parameter in parameterMarkup) { - if (parameters.Length > 0) - parameters.Append (", "); - string text; - Pango.AttrList attrs; - char ch; - Pango.Global.ParseMarkup (parameter, '_', out attrs, out text, out ch); - if (text != null) - curLen += text.Length + 2; - parameters.Append (parameter); - } - var sb = new StringBuilder (); - if (m.IsExtensionMethod) - sb.Append (GettextCatalog.GetString ("(Extension) ")); - sb.Append (prefix); - sb.Append (""); - sb.Append (CSharpAmbience.FilterName (name)); - sb.Append (" ("); - sb.Append (parameters.ToString ()); - sb.Append (")"); - - return sb.ToString (); - } - - public override string GetDescription (int overload, int currentParameter) - { - var flags = OutputFlags.ClassBrowserEntries | OutputFlags.IncludeMarkup | OutputFlags.IncludeGenerics; - if (staticResolve) - flags |= OutputFlags.StaticUsage; - - var m = methods [overload]; - - var sb = new StringBuilder (); - - - if (m.IsObsolete ()) { - sb.AppendLine (); - sb.Append (GettextCatalog.GetString ("[Obsolete]")); - } - - var curParameter = currentParameter >= 0 && currentParameter < m.Parameters.Count ? m.Parameters [currentParameter] : null; - string docText = AmbienceService.GetDocumentation (methods [overload]); - if (!string.IsNullOrEmpty (docText)) { - string text = docText; - if (curParameter != null) { - Regex paramRegex = new Regex ("(\\.*?\\)", RegexOptions.Compiled); - Match match = paramRegex.Match (docText); - - if (match.Success) { - text = match.Groups [1].Value; - text = "" + AmbienceService.GetDocumentationSummary (methods [overload]) + "" + text; - } - } else { - text = "" + AmbienceService.GetDocumentationSummary (methods [overload]) + ""; - } - sb.Append (AmbienceService.GetDocumentationMarkup (text, new AmbienceService.DocumentationFormatOptions { - HighlightParameter = curParameter != null ? curParameter.Name : null, - Ambience = ambience, - SmallText = true, - BoldHeadings = false - })); - } - - if (curParameter != null) { - var returnType = curParameter.Type; - if (returnType.Kind == TypeKind.Delegate) { - if (sb.Length > 0) { - sb.AppendLine (); - sb.AppendLine (); - } - sb.Append (""); - sb.AppendLine (GettextCatalog.GetString ("Delegate information:")); - sb.Append (ambience.GetString (returnType, OutputFlags.ReformatDelegates | OutputFlags.IncludeReturnType | OutputFlags.IncludeParameters | OutputFlags.IncludeParameterName)); - sb.Append (""); - } - } - return sb.ToString (); - } - - public override string GetParameterDescription (int overload, int paramIndex) - { - IMethod method = methods [overload]; - - if (paramIndex < 0 || paramIndex >= method.Parameters.Count) - return ""; - if (method.IsExtensionMethod) - paramIndex++; - var parameter = method.Parameters [paramIndex]; - - return GetParameterString (parameter); - }*/ - - public override int GetParameterCount (int overload) - { - if (overload >= Count) - return -1; - IMethod method = methods [overload]; - if (method == null || method.Parameters == null) - return 0; - - if (method.IsExtensionMethod) - return method.Parameters.Count - 1; - return method.Parameters.Count; - } - - public override string GetParameterName (int overload, int paramIndex) - { - IMethod method = methods [overload]; - return method.Parameters[paramIndex].Name; - } - public override bool AllowParameterList (int overload) - { - if (overload >= Count) - return false; - var lastParam = methods[overload].Parameters.LastOrDefault (); - return lastParam != null && lastParam.IsParams; - } - - public override int Count { - get { - return methods != null ? methods.Count : 0; - } - } - #endregion - - public List Methods { - get { - return methods; - } - set { - methods = value; - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/MonoCSharpCompletionEngine.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/MonoCSharpCompletionEngine.cs deleted file mode 100644 index 41dc87a..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/MonoCSharpCompletionEngine.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -// MonoCSharpCompletionEngine.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; -//using MonoDevelop.CodeGeneration; -using System.Linq; -using MonoDevelop.PlayScript.Refactoring.CodeActions; -using MonoDevelop.PlayScript.CodeGeneration; -using ICSharpCode.NRefactory.PlayScript.Completion; -using ICSharpCode.NRefactory.Editor; -using ICSharpCode.NRefactory.TypeSystem; - -namespace MonoDevelop.PlayScript.Completion -{ - class MonoCSharpCompletionEngine : CSharpCompletionEngine - { - readonly CSharpCompletionTextEditorExtension ext; - - public CSharpCompletionTextEditorExtension Ext { - get { - return ext; - } - } - - public MDRefactoringContext MDRefactoringCtx { - get { - return ext.MDRefactoringCtx; - } - } - - public MonoCSharpCompletionEngine (CSharpCompletionTextEditorExtension ext, ICSharpCode.NRefactory.Editor.IDocument document, ICompletionContextProvider completionContextProvider, ICompletionDataFactory factory, ICSharpCode.NRefactory.TypeSystem.IProjectContent content, ICSharpCode.NRefactory.PlayScript.TypeSystem.CSharpTypeResolveContext ctx) : base (document, completionContextProvider, factory, content, ctx) - { - this.ext = ext; - } - - protected override void AddVirtuals (List alreadyInserted, CompletionDataWrapper col, string modifiers, IType curType, int declarationBegin) - { - base.AddVirtuals (alreadyInserted, col, modifiers, curType, declarationBegin); - foreach (var member in GetProtocolMembers (curType)) { - if (alreadyInserted.Contains (member)) - continue; - if (BaseExportCodeGenerator.IsImplemented (curType, member)) - continue; - alreadyInserted.Add (member); - var data = new ProtocolCompletionData (this, declarationBegin, member); - col.Add (data); - } - } - - internal static bool IsFoundationNamespace (string ns ) - { - return (ns == "MonoTouch.Foundation" || ns == "Foundation"); - } - - IEnumerable GetProtocolMembers (IType curType) - { - foreach (var t in curType.DirectBaseTypes) { - string name; - if (!BaseExportCodeGenerator.HasProtocolAttribute (t, out name)) - continue; - var protocolType = Compilation.FindType (new FullTypeName (new TopLevelTypeName (t.Namespace, name))); - if (protocolType == null) - break; - foreach (var member in protocolType.GetMethods (null, GetMemberOptions.IgnoreInheritedMembers)) { - if (member.ImplementedInterfaceMembers.Any () || member.IsAbstract || !member.IsVirtual) - continue; - if (member.Attributes.Any (a => a.AttributeType.Name == "ExportAttribute" && IsFoundationNamespace (a.AttributeType.Namespace))) { - yield return member; - } - } - foreach (var member in protocolType.GetProperties (null, GetMemberOptions.IgnoreInheritedMembers)) { - if (member.ImplementedInterfaceMembers.Any () || member.IsAbstract || !member.IsVirtual) - continue; - if (member.CanGet && member.Getter.Attributes.Any (a => a.AttributeType.Name == "ExportAttribute" && IsFoundationNamespace (a.AttributeType.Namespace)) || - member.CanSet && member.Setter.Attributes.Any (a => a.AttributeType.Name == "ExportAttribute" && IsFoundationNamespace (a.AttributeType.Namespace))) - yield return member; - } - } - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/NewOverrideCompletionData.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/NewOverrideCompletionData.cs deleted file mode 100644 index 7d5dfc6..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/NewOverrideCompletionData.cs +++ /dev/null @@ -1,119 +0,0 @@ -// NewOverrideCompletionData.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -using System; -using System.Linq; -using System.Text; -using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide.Gui.Content; -using System.Collections.Generic; -using ICSharpCode.NRefactory.PlayScript; -using Mono.TextEditor; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Ide.TypeSystem; - -namespace MonoDevelop.PlayScript.Completion -{ - class NewOverrideCompletionData : CompletionData - { - CSharpCompletionTextEditorExtension ext; - IMember member; - static Ambience ambience = new CSharpAmbience (); - int declarationBegin; - IUnresolvedTypeDefinition type; - - public bool GenerateBody { get; set; } - - public override TooltipInformation CreateTooltipInformation (bool smartWrap) - { - return MemberCompletionData.CreateTooltipInformation (ext, null, member, smartWrap); - } - - public NewOverrideCompletionData (CSharpCompletionTextEditorExtension ext, int declarationBegin, IUnresolvedTypeDefinition type, IMember member) : base (null) - { - this.ext = ext; - this.type = type; - this.member = member; - - this.declarationBegin = declarationBegin; - this.GenerateBody = true; - this.Icon = member.GetStockIcon (); - this.DisplayText = ambience.GetString (member, OutputFlags.IncludeParameters | OutputFlags.IncludeParameterName | OutputFlags.IncludeGenerics | OutputFlags.HideExtensionsParameter| OutputFlags.IncludeAccessor); - this.CompletionText = member.SymbolKind == SymbolKind.Indexer ? "this" : member.Name; - } - - public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier) - { - var editor = ext.TextEditorData; - var generator = CodeGenerator.CreateGenerator (ext.Document); - bool isExplicit = false; - if (member.DeclaringTypeDefinition.Kind == TypeKind.Interface) { - foreach (var m in type.Members) { - if (m.Name == member.Name && !m.ReturnType.Equals (member.ReturnType)) { - isExplicit = true; - break; - } - } - } - var resolvedType = type.Resolve (ext.Project).GetDefinition (); - if (ext.Project != null) - generator.PolicyParent = ext.Project.Policies; - var result = generator.CreateMemberImplementation (resolvedType, type, member, isExplicit); - string sb = result.Code.TrimStart (); - int trimStart = result.Code.Length - sb.Length; - sb = sb.TrimEnd (); - - var lastRegion = result.BodyRegions.LastOrDefault (); - var region = lastRegion == null? null - : new CodeGeneratorBodyRegion (lastRegion.StartOffset - trimStart, lastRegion.EndOffset - trimStart); - - int targetCaretPosition; - int selectionEndPosition = -1; - if (region != null && region.IsValid) { - targetCaretPosition = declarationBegin + region.StartOffset; - if (region.Length > 0) { - if (GenerateBody) { - selectionEndPosition = declarationBegin + region.EndOffset; - } else { - //FIXME: if there are multiple regions, remove all of them - sb = sb.Substring (0, region.StartOffset) + sb.Substring (region.EndOffset); - } - } - } else { - targetCaretPosition = declarationBegin + sb.Length; - } - - editor.Replace (declarationBegin, editor.Caret.Offset - declarationBegin, sb); - if (selectionEndPosition > 0) { - editor.Caret.Offset = selectionEndPosition; - editor.SetSelection (targetCaretPosition, selectionEndPosition); - } else { - editor.Caret.Offset = targetCaretPosition; - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/ProtocolCompletionData.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/ProtocolCompletionData.cs deleted file mode 100644 index 61892ef..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/ProtocolCompletionData.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -// ProtocolCompletionData.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.Ide.TypeSystem; -//using MonoDevelop.CodeGeneration; -using MonoDevelop.PlayScript.CodeGeneration; - -namespace MonoDevelop.PlayScript.Completion -{ - class ProtocolCompletionData : CompletionData - { - readonly MonoCSharpCompletionEngine engine; - readonly IMember member; - readonly static Ambience ambience = new CSharpAmbience (); - readonly int declarationBegin; - - public bool GenerateBody { get; set; } - - public override TooltipInformation CreateTooltipInformation (bool smartWrap) - { - return MemberCompletionData.CreateTooltipInformation (engine.Ext, null, member, smartWrap); - } - - public ProtocolCompletionData (MonoCSharpCompletionEngine engine, int declarationBegin, IMember member) : base (null) - { - this.engine = engine; - this.member = member; - - this.declarationBegin = declarationBegin; - this.GenerateBody = true; - this.Icon = member.GetStockIcon (); - this.DisplayText = ambience.GetString (member, OutputFlags.IncludeParameters | OutputFlags.IncludeParameterName | OutputFlags.IncludeGenerics | OutputFlags.HideExtensionsParameter| OutputFlags.IncludeAccessor); - this.CompletionText = member.SymbolKind == SymbolKind.Indexer ? "this" : member.Name; - } - - public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier) - { - var ext = engine.Ext; - var editor = ext.TextEditorData; - var generator = CodeGenerator.CreateGenerator (ext.Document); - if (ext.Project != null) - generator.PolicyParent = ext.Project.Policies; - var builder = engine.MDRefactoringCtx.CreateTypeSystemAstBuilder (); - - string sb = BaseExportCodeGenerator.GenerateMemberCode (engine.MDRefactoringCtx, builder, member); - sb = sb.TrimEnd (); - - string indent = editor.GetIndentationString (editor.Caret.Location); - sb = sb.Replace (editor.EolMarker, editor.EolMarker + indent); - - int targetCaretPosition = sb.LastIndexOf ("throw", StringComparison.Ordinal); - int selectionEndPosition = sb.LastIndexOf (";", StringComparison.Ordinal); - - editor.Replace (declarationBegin, editor.Caret.Offset - declarationBegin, sb); - if (selectionEndPosition > 0) { - targetCaretPosition += declarationBegin; - selectionEndPosition += declarationBegin; - editor.Caret.Offset = selectionEndPosition; - editor.SetSelection (targetCaretPosition, selectionEndPosition); - } - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/TypeParameterDataProvider.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/TypeParameterDataProvider.cs deleted file mode 100644 index bc04594..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/TypeParameterDataProvider.cs +++ /dev/null @@ -1,163 +0,0 @@ -// -// TemplateParameterDataProvider.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Text; -using System.Xml; - -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.PlayScript.Formatting; -using MonoDevelop.PlayScript.Parser; -using System.Text.RegularExpressions; -using ICSharpCode.NRefactory.PlayScript; -using MonoDevelop.PlayScript.Resolver; -using Mono.TextEditor; -using ICSharpCode.NRefactory.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.Completion; - -namespace MonoDevelop.PlayScript.Completion -{ - class TypeParameterDataProvider: IParameterDataProvider - { - int startOffset; - //CSharpCompletionTextEditorExtension ext; - - List types; - List methods; - CSharpAmbience ambience = new CSharpAmbience (); - - public int StartOffset { - get { - return startOffset; - } - } - - public TypeParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IEnumerable types) - { - this.startOffset = startOffset; - // this.ext = ext; - this.types = new List (types); - } - - public TypeParameterDataProvider (int startOffset, CSharpCompletionTextEditorExtension ext, IEnumerable methods) - { - this.startOffset = startOffset; - // this.ext = ext; - this.methods = new List (methods); - } - - static int TypeComparer (IType left, IType right) - { - return left.TypeParameterCount - right.TypeParameterCount; - } - - #region IParameterDataProvider implementation - - protected virtual string GetPrefix (IMethod method) - { - var flags = OutputFlags.ClassBrowserEntries | OutputFlags.IncludeMarkup | OutputFlags.IncludeGenerics; - return ambience.GetString (method.ReturnType, flags) + " "; - } - - public string GetHeading (int overload, string[] parameterMarkup, int currentParameter) - { - var result = new StringBuilder (); - result.Append (""); - if (methods != null) { - result.Append (ambience.GetString (methods [overload], OutputFlags.UseFullName | OutputFlags.IncludeMarkup)); - } else { - result.Append (ambience.GetString (types [overload], OutputFlags.UseFullName | OutputFlags.IncludeMarkup)); - } - result.Append (""); - result.Append ("<"); - int parameterCount = 0; - foreach (string parameter in parameterMarkup) { - if (parameterCount > 0) - result.Append (", "); - result.Append (parameter); - parameterCount++; - } - result.Append (">"); - - return result.ToString (); - } - - public string GetDescription (int overload, int currentParameter) - { - return ""; - } - - public string GetParameterDescription (int overload, int paramIndex) - { - if (methods != null) - return ambience.GetString (methods[overload].TypeParameters [paramIndex], OutputFlags.AssemblyBrowserDescription | OutputFlags.HideExtensionsParameter | OutputFlags.IncludeGenerics | OutputFlags.IncludeModifiers | OutputFlags.HighlightName); - - var type = types[overload]; - - if (paramIndex < 0 || paramIndex >= type.TypeParameterCount) - return ""; - - return ambience.GetString (type.GetDefinition ().TypeParameters [paramIndex], OutputFlags.AssemblyBrowserDescription | OutputFlags.HideExtensionsParameter | OutputFlags.IncludeGenerics | OutputFlags.IncludeModifiers | OutputFlags.HighlightName); - } - - public int GetParameterCount (int overload) - { - if (overload >= Count) - return -1; - - if (methods != null) - return methods[overload].TypeParameters.Count; - var type = types[overload]; - return type != null ? type.TypeParameterCount : 0; - } - - public string GetParameterName (int overload, int paramIndex) - { - // unused - return "T"; - } - - - public bool AllowParameterList (int overload) - { - return false; - } - - public int Count { - get { - if (methods != null) - return methods.Count; - return types != null ? types.Count : 0; - } - } - #endregion - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/VariableCompletionData.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Completion/VariableCompletionData.cs deleted file mode 100644 index 329f95d..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Completion/VariableCompletionData.cs +++ /dev/null @@ -1,60 +0,0 @@ -// -// VariableCompletionData.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using MonoDevelop.Ide.CodeCompletion; -using ICSharpCode.NRefactory.Completion; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Ide.TypeSystem; - -namespace MonoDevelop.PlayScript.Completion -{ - class VariableCompletionData : CompletionData, IVariableCompletionData - { - readonly CSharpCompletionTextEditorExtension ext; - - public IVariable Variable { - get; - private set; - } - - public override TooltipInformation CreateTooltipInformation (bool smartWrap) - { - var tooltipInfo = new TooltipInformation (); - var resolver = ext.CSharpUnresolvedFile.GetResolver (ext.Compilation, ext.Document.Editor.Caret.Location); - var sig = new SignatureMarkupCreator (resolver, ext.FormattingPolicy.CreateOptions ()); - sig.BreakLineAfterReturnType = smartWrap; - tooltipInfo.SignatureMarkup = sig.GetLocalVariableMarkup (Variable); - return tooltipInfo; - } - - public VariableCompletionData (CSharpCompletionTextEditorExtension ext, IVariable variable) : base (variable.Name, variable.GetStockIcon ()) - { - this.ext = ext; - this.Variable = variable; - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormatter.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormatter.cs deleted file mode 100644 index 1eb8382..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormatter.cs +++ /dev/null @@ -1,155 +0,0 @@ -// -// CSharpFormatter.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; - -using Mono.TextEditor; -using MonoDevelop.PlayScript.Formatting; -using MonoDevelop.Ide.Gui.Content; -using MonoDevelop.Projects.Policies; -using System.Linq; -using MonoDevelop.Ide.CodeFormatting; -using MonoDevelop.Core; -using MonoDevelop.PlayScript.Refactoring; -using ICSharpCode.NRefactory.PlayScript; - -namespace MonoDevelop.PlayScript.Formatting -{ - class CSharpFormatter : AbstractAdvancedFormatter - { - static internal readonly string MimeType = "text/x-playscript"; - - public override bool SupportsOnTheFlyFormatting { get { return true; } } - - public override bool SupportsCorrectingIndent { get { return true; } } - - public override void CorrectIndenting (PolicyContainer policyParent, IEnumerable mimeTypeChain, - TextEditorData data, int line) - { - DocumentLine lineSegment = data.Document.GetLine (line); - if (lineSegment == null) - return; - - try { - var policy = policyParent.Get (mimeTypeChain); - var tracker = new CSharpIndentEngine (data.Document, data.CreateNRefactoryTextEditorOptions (), policy.CreateOptions ()); - - tracker.Update (lineSegment.Offset); - for (int i = lineSegment.Offset; i < lineSegment.Offset + lineSegment.Length; i++) { - tracker.Push (data.Document.GetCharAt (i)); - } - - string curIndent = lineSegment.GetIndentation (data.Document); - - int nlwsp = curIndent.Length; - if (!tracker.LineBeganInsideMultiLineComment || (nlwsp < lineSegment.LengthIncludingDelimiter && data.Document.GetCharAt (lineSegment.Offset + nlwsp) == '*')) { - // Possibly replace the indent - string newIndent = tracker.ThisLineIndent; - if (newIndent != curIndent) - data.Replace (lineSegment.Offset, nlwsp, newIndent); - } - } catch (Exception e) { - LoggingService.LogError ("Error while indenting", e); - } - } - - public override void OnTheFlyFormat (MonoDevelop.Ide.Gui.Document doc, int startOffset, int endOffset) - { - OnTheFlyFormatter.Format (doc, startOffset, endOffset); - } - - - public static string FormatText (PlayScriptFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset) - { - var data = new TextEditorData (); - data.Document.SuppressHighlightUpdate = true; - data.Document.MimeType = mimeType; - data.Document.FileName = "toformat.cs"; - if (textPolicy != null) { - data.Options.TabsToSpaces = textPolicy.TabsToSpaces; - data.Options.TabSize = textPolicy.TabWidth; - data.Options.IndentationSize = textPolicy.IndentWidth; - data.Options.IndentStyle = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart; - } - data.Text = input; - - // System.Console.WriteLine ("-----"); - // System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->")); - // System.Console.WriteLine ("-----"); - - var parser = new PlayScriptParser (); - var compilationUnit = parser.Parse (data); - bool hadErrors = parser.HasErrors; - - if (hadErrors) { - // foreach (var e in parser.ErrorReportPrinter.Errors) - // Console.WriteLine (e.Message); - return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); - } - - var originalVersion = data.Document.Version; - - var textEditorOptions = data.CreateNRefactoryTextEditorOptions (); - var formattingVisitor = new ICSharpCode.NRefactory.PlayScript.CSharpFormatter ( - policy.CreateOptions (), - textEditorOptions - ) { - FormattingMode = FormattingMode.Intrusive - }; - - var changes = formattingVisitor.AnalyzeFormatting (data.Document, compilationUnit); - try { - changes.ApplyChanges (startOffset, endOffset - startOffset); - } catch (Exception e) { - LoggingService.LogError ("Error in code formatter", e); - return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); - } - - // check if the formatter has produced errors - parser = new PlayScriptParser (); - parser.Parse (data); - if (parser.HasErrors) { - LoggingService.LogError ("PlayScript formatter produced source code errors. See console for output."); - return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); - } - - var currentVersion = data.Document.Version; - - string result = data.GetTextBetween (startOffset, originalVersion.MoveOffsetTo (currentVersion, endOffset)); - data.Dispose (); - return result; - } - - public override string FormatText (PolicyContainer policyParent, IEnumerable mimeTypeChain, string input, int startOffset, int endOffset) - { - var policy = policyParent.Get (mimeTypeChain); - var textPolicy = policyParent.Get (mimeTypeChain); - - return FormatText (policy, textPolicy, mimeTypeChain.First (), input, startOffset, endOffset); - - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingPolicy.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingPolicy.cs deleted file mode 100644 index 0775300..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingPolicy.cs +++ /dev/null @@ -1,1741 +0,0 @@ -// -// CSharpFormattingPolicy.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using MonoDevelop.Core; -using MonoDevelop.Core.Serialization; -using System.Reflection; -using System.Xml; -using System.Text; -using System.Linq; -using MonoDevelop.Projects.Policies; -using ICSharpCode.NRefactory.PlayScript; - -namespace MonoDevelop.PlayScript.Formatting -{ - [PolicyType ("PlayScript formatting")] - public class PlayScriptFormattingPolicy : IEquatable - { - readonly CSharpFormattingOptions options = FormattingOptionsFactory.CreateMono (); - - public string Name { - get; - set; - } - - public bool IsBuiltIn { - get; - set; - } - - public PlayScriptFormattingPolicy Clone () - { - return new PlayScriptFormattingPolicy (options.Clone ()); - } - - public CSharpFormattingOptions CreateOptions () - { - return options; - } - - static PlayScriptFormattingPolicy () - { - if (!PolicyService.InvariantPolicies.ReadOnly) - PolicyService.InvariantPolicies.Set (new PlayScriptFormattingPolicy (), "text/x-playscript"); - } - - protected PlayScriptFormattingPolicy (CSharpFormattingOptions options) - { - this.options = options; - } - - - #region Indentation - [ItemProperty] - public bool IndentNamespaceBody { - get { - return options.IndentNamespaceBody; - } - set { - options.IndentNamespaceBody = value; - } - } - - [ItemProperty] - public bool IndentClassBody { - get { - return options.IndentClassBody; - } - set { - options.IndentClassBody = value; - } - } - - [ItemProperty] - public bool IndentInterfaceBody { - get { - return options.IndentInterfaceBody; - } - set { - options.IndentInterfaceBody = value; - } - } - - [ItemProperty] - public bool IndentStructBody { - get { - return options.IndentStructBody; - } - set { - options.IndentStructBody = value; - } - } - - [ItemProperty] - public bool IndentEnumBody { - get { - return options.IndentEnumBody; - } - set { - options.IndentEnumBody = value; - } - } - - [ItemProperty] - public bool IndentMethodBody { - get { - return options.IndentMethodBody; - } - set { - options.IndentMethodBody = value; - } - } - - [ItemProperty] - public bool IndentPropertyBody { - get { - return options.IndentPropertyBody; - } - set { - options.IndentPropertyBody = value; - } - } - - [ItemProperty] - public bool IndentEventBody { - get { - return options.IndentEventBody; - } - set { - options.IndentEventBody = value; - } - } - - [ItemProperty] - public bool IndentBlocks { - get { - return options.IndentBlocks; - } - set { - options.IndentBlocks = value; - } - } - - [ItemProperty] - public bool IndentSwitchBody { - get { - return options.IndentSwitchBody; - } - set { - options.IndentSwitchBody = value; - } - } - - [ItemProperty] - public bool IndentCaseBody { - get { - return options.IndentCaseBody; - } - set { - options.IndentCaseBody = value; - } - } - - [ItemProperty] - public bool IndentBreakStatements { - get { - return options.IndentBreakStatements; - } - set { - options.IndentBreakStatements = value; - } - } - - [ItemProperty] - public bool IndentBlocksInsideExpressions { - get { - return options.IndentBlocksInsideExpressions; - } - set { - options.IndentBlocksInsideExpressions = value; - } - } - - [ItemProperty] - public bool AlignEmbeddedStatements { - get { - return options.AlignEmbeddedStatements; - } - set { - options.AlignEmbeddedStatements = value; - } - } - - [ItemProperty] - public PropertyFormatting SimplePropertyFormatting { - get { - return options.SimplePropertyFormatting; - } - set { - options.SimplePropertyFormatting = value; - } - } - - [ItemProperty] - public PropertyFormatting AutoPropertyFormatting { - get { - return options.AutoPropertyFormatting; - } - set { - options.AutoPropertyFormatting = value; - } - } - - [ItemProperty] - public bool IndentPreprocessorDirectives { - get { - return options.IndentPreprocessorDirectives; - } - set { - options.IndentPreprocessorDirectives = value; - } - } - #endregion - - #region Braces - [ItemProperty] - public BraceStyle NamespaceBraceStyle { - get { - return options.NamespaceBraceStyle; - } - set { - options.NamespaceBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle ClassBraceStyle { - get { - return options.ClassBraceStyle; - } - set { - options.ClassBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle InterfaceBraceStyle { - get { - return options.InterfaceBraceStyle; - } - set { - options.InterfaceBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle StructBraceStyle { - get { - return options.StructBraceStyle; - } - set { - options.StructBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle EnumBraceStyle { - get { - return options.EnumBraceStyle; - } - set { - options.EnumBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle MethodBraceStyle { - get { - return options.MethodBraceStyle; - } - set { - options.MethodBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle AnonymousMethodBraceStyle { - get { - return options.AnonymousMethodBraceStyle; - } - set { - options.AnonymousMethodBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle ConstructorBraceStyle { - get { - return options.ConstructorBraceStyle; - } - set { - options.ConstructorBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle DestructorBraceStyle { - get { - return options.DestructorBraceStyle; - } - set { - options.DestructorBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle PropertyBraceStyle { - get { - return options.PropertyBraceStyle; - } - set { - options.PropertyBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle PropertyGetBraceStyle { - get { - return options.PropertyGetBraceStyle; - } - set { - options.PropertyGetBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle PropertySetBraceStyle { - get { - return options.PropertySetBraceStyle; - } - set { - options.PropertySetBraceStyle = value; - } - } - - [ItemProperty] - public PropertyFormatting SimpleGetBlockFormatting { - get { - return options.SimpleGetBlockFormatting; - } - set { - options.SimpleGetBlockFormatting = value; - } - } - - [ItemProperty] - public PropertyFormatting SimpleSetBlockFormatting { - get { - - return options.SimpleSetBlockFormatting; - } - set { - options.SimpleSetBlockFormatting = value; - } - } - - [ItemProperty] - public BraceStyle EventBraceStyle { - get { - return options.EventBraceStyle; - } - set { - options.EventBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle EventAddBraceStyle { - get { - return options.EventAddBraceStyle; - } - set { - options.EventAddBraceStyle = value; - } - } - - [ItemProperty] - public BraceStyle EventRemoveBraceStyle { - get { - return options.EventRemoveBraceStyle; - } - set { - options.EventRemoveBraceStyle = value; - } - } - - [ItemProperty] - public bool AllowEventAddBlockInline { - get { - return options.AllowEventAddBlockInline; - } - set { - options.AllowEventAddBlockInline = value; - } - } - - [ItemProperty] - public bool AllowEventRemoveBlockInline { - get { - return options.AllowEventRemoveBlockInline; - } - set { - options.AllowEventRemoveBlockInline = value; - } - } - - [ItemProperty] - public BraceStyle StatementBraceStyle { - get { - return options.StatementBraceStyle; - } - set { - options.StatementBraceStyle = value; - } - } - - [ItemProperty] - public bool AllowIfBlockInline { - get { - return options.AllowIfBlockInline; - } - set { - options.AllowIfBlockInline = value; - } - } - - #endregion - - #region NewLines - [ItemProperty] - public NewLinePlacement ElseNewLinePlacement { - get { - return options.ElseNewLinePlacement; - } - set { - options.ElseNewLinePlacement = value; - } - } - - [ItemProperty] - public NewLinePlacement ElseIfNewLinePlacement { - get { - return options.ElseIfNewLinePlacement; - } - set { - options.ElseIfNewLinePlacement = value; - } - } - - [ItemProperty] - public NewLinePlacement CatchNewLinePlacement { - get { - return options.CatchNewLinePlacement; - } - set { - options.CatchNewLinePlacement = value; - } - } - - [ItemProperty] - public NewLinePlacement FinallyNewLinePlacement { - get { - return options.FinallyNewLinePlacement; - } - set { - options.FinallyNewLinePlacement = value; - } - } - - [ItemProperty] - public NewLinePlacement WhileNewLinePlacement { - get { - return options.WhileNewLinePlacement; - } - set { - options.WhileNewLinePlacement = value; - } - } - - [ItemProperty] - public NewLinePlacement EmbeddedStatementPlacement { - get { - return options.EmbeddedStatementPlacement; - } - set { - options.EmbeddedStatementPlacement = value; - } - } - - - - [ItemProperty] - public Wrapping ArrayInitializerWrapping { - get { - return options.ArrayInitializerWrapping; - } - set { - options.ArrayInitializerWrapping = value; - } - } - - [ItemProperty] - public BraceStyle ArrayInitializerBraceStyle { - get { - return options.ArrayInitializerBraceStyle; - } - set { - options.ArrayInitializerBraceStyle = value; - } - } - - [ItemProperty] - public bool KeepCommentsAtFirstColumn { - get { - return options.KeepCommentsAtFirstColumn; - } - set { - options.KeepCommentsAtFirstColumn = value; - } - } - - #endregion - - #region Spaces - // Methods - [ItemProperty] - public bool BeforeMethodDeclarationParentheses { - get { - return options.SpaceBeforeMethodDeclarationParentheses; - } - set { - options.SpaceBeforeMethodDeclarationParentheses = value; - } - } - - [ItemProperty] - public bool BetweenEmptyMethodDeclarationParentheses { - get { - return options.SpaceBetweenEmptyMethodDeclarationParentheses; - } - set { - options.SpaceBetweenEmptyMethodDeclarationParentheses = value; - } - } - - [ItemProperty] - public bool BeforeMethodDeclarationParameterComma { - get { - return options.SpaceBeforeMethodDeclarationParameterComma; - } - set { - options.SpaceBeforeMethodDeclarationParameterComma = value; - } - } - - [ItemProperty] - public bool AfterMethodDeclarationParameterComma { - get { - return options.SpaceAfterMethodDeclarationParameterComma; - } - set { - options.SpaceAfterMethodDeclarationParameterComma = value; - } - } - - [ItemProperty] - public bool WithinMethodDeclarationParentheses { - get { - return options.SpaceWithinMethodDeclarationParentheses; - } - set { - options.SpaceWithinMethodDeclarationParentheses = value; - } - } - - // Method calls - [ItemProperty] - public bool BeforeMethodCallParentheses { - get { - return options.SpaceBeforeMethodCallParentheses; - } - set { - options.SpaceBeforeMethodCallParentheses = value; - } - } - - [ItemProperty] - public bool BetweenEmptyMethodCallParentheses { - get { - return options.SpaceBetweenEmptyMethodCallParentheses; - } - set { - options.SpaceBetweenEmptyMethodCallParentheses = value; - } - } - - [ItemProperty] - public bool BeforeMethodCallParameterComma { - get { - return options.SpaceBeforeMethodCallParameterComma; - } - set { - options.SpaceBeforeMethodCallParameterComma = value; - } - } - - [ItemProperty] - public bool AfterMethodCallParameterComma { - get { - return options.SpaceAfterMethodCallParameterComma; - } - set { - options.SpaceAfterMethodCallParameterComma = value; - } - } - - [ItemProperty] - public bool WithinMethodCallParentheses { - get { - return options.SpaceWithinMethodCallParentheses; - } - set { - options.SpaceWithinMethodCallParentheses = value; - } - } - - // fields - - [ItemProperty] - public bool BeforeFieldDeclarationComma { - get { - return options.SpaceBeforeFieldDeclarationComma; - } - set { - options.SpaceBeforeFieldDeclarationComma = value; - } - } - - [ItemProperty] - public bool AfterFieldDeclarationComma { - get { - return options.SpaceAfterFieldDeclarationComma; - } - set { - options.SpaceAfterFieldDeclarationComma = value; - } - } - - // local variables - - [ItemProperty] - public bool BeforeLocalVariableDeclarationComma { - get { - return options.SpaceBeforeLocalVariableDeclarationComma; - } - set { - options.SpaceBeforeLocalVariableDeclarationComma = value; - } - } - - [ItemProperty] - public bool AfterLocalVariableDeclarationComma { - get { - return options.SpaceAfterLocalVariableDeclarationComma; - } - set { - options.SpaceAfterLocalVariableDeclarationComma = value; - } - } - - // constructors - - [ItemProperty] - public bool BeforeConstructorDeclarationParentheses { - get { - return options.SpaceBeforeConstructorDeclarationParentheses; - } - set { - options.SpaceBeforeConstructorDeclarationParentheses = value; - } - } - - [ItemProperty] - public bool BetweenEmptyConstructorDeclarationParentheses { - get { - return options.SpaceBetweenEmptyConstructorDeclarationParentheses; - } - set { - options.SpaceBetweenEmptyConstructorDeclarationParentheses = value; - } - } - - [ItemProperty] - public bool BeforeConstructorDeclarationParameterComma { - get { - return options.SpaceBeforeConstructorDeclarationParameterComma; - } - set { - options.SpaceBeforeConstructorDeclarationParameterComma = value; - } - } - - [ItemProperty] - public bool AfterConstructorDeclarationParameterComma { - get { - return options.SpaceAfterConstructorDeclarationParameterComma; - } - set { - options.SpaceAfterConstructorDeclarationParameterComma = value; - } - } - - [ItemProperty] - public bool WithinConstructorDeclarationParentheses { - get { - return options.SpaceWithinConstructorDeclarationParentheses; - } - set { - options.SpaceWithinConstructorDeclarationParentheses = value; - } - } - - [ItemProperty] - public NewLinePlacement NewLineBeforeConstructorInitializerColon { - get { - return options.NewLineBeforeConstructorInitializerColon; - } - set { - options.NewLineBeforeConstructorInitializerColon = value; - } - } - - [ItemProperty] - public NewLinePlacement NewLineAfterConstructorInitializerColon { - get { - return options.NewLineAfterConstructorInitializerColon; - } - set { - options.NewLineAfterConstructorInitializerColon = value; - } - } - - // indexer - [ItemProperty] - public bool BeforeIndexerDeclarationBracket { - get { - return options.SpaceBeforeIndexerDeclarationBracket; - } - set { - options.SpaceBeforeIndexerDeclarationBracket = value; - } - } - - [ItemProperty] - public bool WithinIndexerDeclarationBracket { - get { - return options.SpaceWithinIndexerDeclarationBracket; - } - set { - options.SpaceWithinIndexerDeclarationBracket = value; - } - } - - [ItemProperty] - public bool BeforeIndexerDeclarationParameterComma { - get { - return options.SpaceBeforeIndexerDeclarationParameterComma; - } - set { - options.SpaceBeforeIndexerDeclarationParameterComma = value; - } - } - - [ItemProperty] - public bool AfterIndexerDeclarationParameterComma { - get { - return options.SpaceAfterIndexerDeclarationParameterComma; - } - set { - options.SpaceAfterIndexerDeclarationParameterComma = value; - } - } - - // delegates - - [ItemProperty] - public bool BeforeDelegateDeclarationParentheses { - get { - return options.SpaceBeforeDelegateDeclarationParentheses; - } - set { - options.SpaceBeforeDelegateDeclarationParentheses = value; - } - } - - [ItemProperty] - public bool BetweenEmptyDelegateDeclarationParentheses { - get { - return options.SpaceBetweenEmptyDelegateDeclarationParentheses; - } - set { - options.SpaceBetweenEmptyDelegateDeclarationParentheses = value; - } - } - - [ItemProperty] - public bool BeforeDelegateDeclarationParameterComma { - get { - return options.SpaceBeforeDelegateDeclarationParameterComma; - } - set { - options.SpaceBeforeDelegateDeclarationParameterComma = value; - } - } - - [ItemProperty] - public bool AfterDelegateDeclarationParameterComma { - get { - return options.SpaceAfterDelegateDeclarationParameterComma; - } - set { - options.SpaceAfterDelegateDeclarationParameterComma = value; - } - } - - [ItemProperty] - public bool WithinDelegateDeclarationParentheses { - get { - return options.SpaceWithinDelegateDeclarationParentheses; - } - set { - options.SpaceWithinDelegateDeclarationParentheses = value; - } - } - - - [ItemProperty] - public bool NewParentheses { - get { - return options.SpaceBeforeNewParentheses; - } - set { - options.SpaceBeforeNewParentheses = value; - } - } - - [ItemProperty] - public bool IfParentheses { - get { - return options.SpaceBeforeIfParentheses; - } - set { - options.SpaceBeforeIfParentheses = value; - } - } - - [ItemProperty] - public bool WhileParentheses { - get { - return options.SpaceBeforeWhileParentheses; - } - set { - options.SpaceBeforeWhileParentheses = value; - } - } - - [ItemProperty] - public bool ForParentheses { - get { - return options.SpaceBeforeForParentheses; - } - set { - options.SpaceBeforeForParentheses = value; - } - } - - [ItemProperty] - public bool ForeachParentheses { - get { - return options.SpaceBeforeForeachParentheses; - } - set { - options.SpaceBeforeForeachParentheses = value; - } - } - - [ItemProperty] - public bool CatchParentheses { - get { - return options.SpaceBeforeCatchParentheses; - } - set { - options.SpaceBeforeCatchParentheses = value; - } - } - - [ItemProperty] - public bool SwitchParentheses { - get { - return options.SpaceBeforeSwitchParentheses; - } - set { - options.SpaceBeforeSwitchParentheses = value; - } - } - - [ItemProperty] - public bool LockParentheses { - get { - return options.SpaceBeforeLockParentheses; - } - set { - options.SpaceBeforeLockParentheses = value; - } - } - - [ItemProperty] - public bool UsingParentheses { - get { - return options.SpaceBeforeUsingParentheses; - } - set { - options.SpaceBeforeUsingParentheses = value; - } - } - - [ItemProperty] - public bool AroundAssignmentParentheses { - get { - return options.SpaceAroundAssignment; - } - set { - options.SpaceAroundAssignment = value; - } - } - - [ItemProperty] - public bool AroundLogicalOperatorParentheses { - get { - return options.SpaceAroundLogicalOperator; - } - set { - options.SpaceAroundLogicalOperator = value; - } - } - - [ItemProperty] - public bool AroundEqualityOperatorParentheses { - get { - return options.SpaceAroundEqualityOperator; - } - set { - options.SpaceAroundEqualityOperator = value; - } - } - - [ItemProperty] - public bool AroundRelationalOperatorParentheses { - get { - return options.SpaceAroundRelationalOperator; - } - set { - options.SpaceAroundRelationalOperator = value; - } - } - - [ItemProperty] - public bool AroundBitwiseOperatorParentheses { - get { - return options.SpaceAroundBitwiseOperator; - } - set { - options.SpaceAroundBitwiseOperator = value; - } - } - - [ItemProperty] - public bool AroundAdditiveOperatorParentheses { - get { - return options.SpaceAroundAdditiveOperator; - } - set { - options.SpaceAroundAdditiveOperator = value; - } - } - - [ItemProperty] - public bool AroundMultiplicativeOperatorParentheses { - get { - return options.SpaceAroundMultiplicativeOperator; - } - set { - options.SpaceAroundMultiplicativeOperator = value; - } - } - - [ItemProperty] - public bool AroundShiftOperatorParentheses { - get { - return options.SpaceAroundShiftOperator; - } - set { - options.SpaceAroundShiftOperator = value; - } - } - - [ItemProperty] - public bool AroundNullCoalescingOperator { - get { - return options.SpaceAroundNullCoalescingOperator; - } - set { - options.SpaceAroundNullCoalescingOperator = value; - } - } - - [ItemProperty] - public bool SpaceAfterUnsafeAddressOfOperator { - get { - return options.SpaceAfterUnsafeAddressOfOperator; - } - set { - options.SpaceAfterUnsafeAddressOfOperator = value; - } - } - - - [ItemProperty] - public bool SpaceAfterUnsafeAsteriskOfOperator { - get { - return options.SpaceAfterUnsafeAsteriskOfOperator; - } - set { - options.SpaceAfterUnsafeAsteriskOfOperator = value; - } - } - - [ItemProperty] - public bool SpaceAroundUnsafeArrowOperator { - get { - return options.SpaceAroundUnsafeArrowOperator; - } - set { - options.SpaceAroundUnsafeArrowOperator = value; - } - } - - [ItemProperty] - public bool WithinParentheses { - get { - return options.SpacesWithinParentheses; - } - set { - options.SpacesWithinParentheses = value; - } - } - - - [ItemProperty] - public bool WithinIfParentheses { - get { - return options.SpacesWithinIfParentheses; - } - set { - options.SpacesWithinIfParentheses = value; - } - } - - [ItemProperty] - public bool WithinWhileParentheses { - get { - return options.SpacesWithinWhileParentheses; - } - set { - options.SpacesWithinWhileParentheses = value; - } - } - - [ItemProperty] - public bool WithinForParentheses { - get { - return options.SpacesWithinForParentheses; - } - set { - options.SpacesWithinForParentheses = value; - } - } - - [ItemProperty] - public bool WithinForEachParentheses { - get { - return options.SpacesWithinForeachParentheses; - } - set { - options.SpacesWithinForeachParentheses = value; - } - } - - [ItemProperty] - public bool WithinCatchParentheses { - get { - return options.SpacesWithinCatchParentheses; - } - set { - options.SpacesWithinCatchParentheses = value; - } - } - - [ItemProperty] - public bool WithinSwitchParentheses { - get { - return options.SpacesWithinSwitchParentheses; - } - set { - options.SpacesWithinSwitchParentheses = value; - } - } - - [ItemProperty] - public bool WithinLockParentheses { - get { - return options.SpacesWithinLockParentheses; - } - set { - options.SpacesWithinLockParentheses = value; - } - } - - [ItemProperty] - public bool WithinUsingParentheses { - get { - return options.SpacesWithinUsingParentheses; - } - set { - options.SpacesWithinUsingParentheses = value; - } - } - - [ItemProperty] - public bool WithinCastParentheses { - get { - return options.SpacesWithinCastParentheses; - } - set { - options.SpacesWithinCastParentheses = value; - } - } - - [ItemProperty] - public bool WithinSizeOfParentheses { - get { - return options.SpacesWithinSizeOfParentheses; - } - set { - options.SpacesWithinSizeOfParentheses = value; - } - } - - [ItemProperty] - public bool BeforeSizeOfParentheses { - get { - return options.SpaceBeforeSizeOfParentheses; - } - set { - options.SpaceBeforeSizeOfParentheses = value; - } - } - - [ItemProperty] - public bool WithinTypeOfParentheses { - get { - return options.SpacesWithinTypeOfParentheses; - } - set { - options.SpacesWithinTypeOfParentheses = value; - } - } - - [ItemProperty] - public bool WithinNewParentheses { - get { - return options.SpacesWithinNewParentheses; - } - set { - options.SpacesWithinNewParentheses = value; - } - } - - [ItemProperty] - public bool BetweenEmptyNewParentheses { - get { - return options.SpacesBetweenEmptyNewParentheses; - } - set { - options.SpacesBetweenEmptyNewParentheses = value; - } - } - - [ItemProperty] - public bool BeforeNewParameterComma { - get { - return options.SpaceBeforeNewParameterComma; - } - set { - options.SpaceBeforeNewParameterComma = value; - } - } - - [ItemProperty] - public bool AfterNewParameterComma { - get { - return options.SpaceAfterNewParameterComma; - } - set { - options.SpaceAfterNewParameterComma = value; - } - } - - [ItemProperty] - public bool BeforeTypeOfParentheses { - get { - return options.SpaceBeforeTypeOfParentheses; - } - set { - options.SpaceBeforeTypeOfParentheses = value; - } - } - - [ItemProperty] - public bool WithinCheckedExpressionParantheses { - get { - return options.SpacesWithinCheckedExpressionParantheses; - } - set { - options.SpacesWithinCheckedExpressionParantheses = value; - } - } - - [ItemProperty] - public bool ConditionalOperatorBeforeConditionSpace { - get { - return options.SpaceBeforeConditionalOperatorCondition; - } - set { - options.SpaceBeforeConditionalOperatorCondition = value; - } - } - - [ItemProperty] - public bool ConditionalOperatorAfterConditionSpace { - get { - return options.SpaceAfterConditionalOperatorCondition; - } - set { - options.SpaceAfterConditionalOperatorCondition = value; - } - } - - [ItemProperty] - public bool ConditionalOperatorBeforeSeparatorSpace { - get { - return options.SpaceBeforeConditionalOperatorSeparator; - } - set { - options.SpaceBeforeConditionalOperatorSeparator = value; - } - } - - [ItemProperty] - public bool ConditionalOperatorAfterSeparatorSpace { - get { - return options.SpaceAfterConditionalOperatorSeparator; - } - set { - options.SpaceAfterConditionalOperatorSeparator = value; - } - } - - // brackets - [ItemProperty] - public bool SpacesWithinBrackets { - get { - return options.SpacesWithinBrackets; - } - set { - options.SpacesWithinBrackets = value; - } - } - [ItemProperty] - public bool SpacesBeforeBrackets { - get { - return options.SpacesBeforeBrackets; - } - set { - options.SpacesBeforeBrackets = value; - } - } - [ItemProperty] - public bool BeforeBracketComma { - get { - return options.SpaceBeforeBracketComma; - } - set { - options.SpaceBeforeBracketComma = value; - } - } - [ItemProperty] - public bool AfterBracketComma { - get { - return options.SpaceAfterBracketComma; - } - set { - options.SpaceAfterBracketComma = value; - } - } - - - [ItemProperty] - public bool SpacesBeforeForSemicolon { - get { - return options.SpaceBeforeForSemicolon; - } - set { - options.SpaceBeforeForSemicolon = value; - } - } - - [ItemProperty] - public bool SpaceBeforeSemicolon { - get { - return options.SpaceBeforeSemicolon; - } - set { - options.SpaceBeforeSemicolon = value; - } - } - - [ItemProperty] - public bool SpacesAfterForSemicolon { - get { - return options.SpaceAfterForSemicolon; - } - set { - options.SpaceAfterForSemicolon = value; - } - } - - [ItemProperty] - public bool SpacesAfterTypecast { - get { - return options.SpaceAfterTypecast; - } - set { - options.SpaceAfterTypecast = value; - } - } - - [ItemProperty] - public bool SpacesBeforeArrayDeclarationBrackets { - get { - return options.SpaceBeforeArrayDeclarationBrackets; - } - set { - options.SpaceBeforeArrayDeclarationBrackets = value; - } - } - #endregion - - #region Blank Lines - [ItemProperty] - public int BlankLinesBeforeUsings { - get { - return options.MinimumBlankLinesBeforeUsings; - } - set { - options.MinimumBlankLinesBeforeUsings = value; - } - } - - [ItemProperty] - public int BlankLinesAfterUsings { - get { - return options.MinimumBlankLinesAfterUsings; - } - set { - options.MinimumBlankLinesAfterUsings = value; - } - } - - [ItemProperty] - public int BlankLinesBeforeFirstDeclaration { - get { - return options.MinimumBlankLinesBeforeFirstDeclaration; - } - set { - options.MinimumBlankLinesBeforeFirstDeclaration = value; - } - } - - [ItemProperty] - public int BlankLinesBetweenTypes { - get { - return options.MinimumBlankLinesBetweenTypes; - } - set { - options.MinimumBlankLinesBetweenTypes = value; - } - } - - [ItemProperty] - public int BlankLinesBetweenFields { - get { - return options.MinimumBlankLinesBetweenFields; - } - set { - options.MinimumBlankLinesBetweenFields = value; - } - } - - [ItemProperty] - public int BlankLinesBetweenEventFields { - get { - return options.MinimumBlankLinesBetweenEventFields; - } - set { - options.MinimumBlankLinesBetweenEventFields = value; - } - } - - [ItemProperty] - public int BlankLinesBetweenMembers { - get { - return options.MinimumBlankLinesBetweenMembers; - } - set { - options.MinimumBlankLinesBetweenMembers = value; - } - } - - [ItemProperty] - public int BlankLinesAroundRegion { - get { - return options.MinimumBlankLinesAroundRegion; - } - set { - options.MinimumBlankLinesAroundRegion = value; - } - } - - [ItemProperty] - public int BlankLinesInsideRegion { - get { - return options.MinimumBlankLinesInsideRegion; - } - set { - options.MinimumBlankLinesInsideRegion = value; - } - } - #endregion - - #region Wrapping - [ItemProperty] - public Wrapping MethodCallArgumentWrapping { - get { - return options.MethodCallArgumentWrapping; - } - set { - options.MethodCallArgumentWrapping = value; - } - } - - [ItemProperty] - public NewLinePlacement NewLineAferMethodCallOpenParentheses { - get { - return options.NewLineAferMethodCallOpenParentheses; - } - set { - options.NewLineAferMethodCallOpenParentheses = value; - } - } - - [ItemProperty] - public NewLinePlacement MethodCallClosingParenthesesOnNewLine { - get { - return options.MethodCallClosingParenthesesOnNewLine; - } - set { - options.MethodCallClosingParenthesesOnNewLine = value; - } - } - - [ItemProperty] - public bool AlignToFirstMethodCallArgument { - get { - return options.AlignToFirstMethodCallArgument; - } - set { - options.AlignToFirstMethodCallArgument = value; - } - } - - [ItemProperty] - public Wrapping MethodDeclarationParameterWrapping { - get { - return options.MethodDeclarationParameterWrapping; - } - set { - options.MethodDeclarationParameterWrapping = value; - } - } - - [ItemProperty] - public NewLinePlacement NewLineAferMethodDeclarationOpenParentheses { - get { - return options.NewLineAferMethodDeclarationOpenParentheses; - } - set { - options.NewLineAferMethodDeclarationOpenParentheses = value; - } - } - - [ItemProperty] - public NewLinePlacement MethodDeclarationClosingParenthesesOnNewLine { - get { - return options.MethodDeclarationClosingParenthesesOnNewLine; - } - set { - options.MethodDeclarationClosingParenthesesOnNewLine = value; - } - } - - [ItemProperty] - public bool AlignToFirstMethodDeclarationParameter { - get { - return options.AlignToFirstMethodDeclarationParameter; - } - set { - options.AlignToFirstMethodDeclarationParameter = value; - } - } - - [ItemProperty] - public Wrapping IndexerDeclarationParameterWrapping { - get { - return options.IndexerDeclarationParameterWrapping; - } - set { - options.IndexerDeclarationParameterWrapping = value; - } - } - - [ItemProperty] - public NewLinePlacement NewLineAferIndexerDeclarationOpenBracket { - get { - return options.NewLineAferIndexerDeclarationOpenBracket; - } - set { - options.NewLineAferIndexerDeclarationOpenBracket = value; - } - } - - [ItemProperty] - public NewLinePlacement IndexerDeclarationClosingBracketOnNewLine { - get { - return options.IndexerDeclarationClosingBracketOnNewLine; - } - set { - options.IndexerDeclarationClosingBracketOnNewLine = value; - } - } - - [ItemProperty] - public bool AlignToFirstIndexerDeclarationParameter { - get { - return options.AlignToFirstIndexerDeclarationParameter; - } - set { - options.AlignToFirstIndexerDeclarationParameter = value; - } - } - - [ItemProperty] - public Wrapping IndexerArgumentWrapping { - get { - return options.IndexerArgumentWrapping; - } - set { - options.IndexerArgumentWrapping = value; - } - } - - [ItemProperty] - public NewLinePlacement NewLineAferIndexerOpenBracket { - get { - return options.NewLineAferIndexerOpenBracket; - } - set { - options.NewLineAferIndexerOpenBracket = value; - } - } - - [ItemProperty] - public NewLinePlacement IndexerClosingBracketOnNewLine { - get { - return options.IndexerClosingBracketOnNewLine; - } - set { - options.IndexerClosingBracketOnNewLine = value; - } - } - - [ItemProperty] - public bool AlignToFirstIndexerArgument { - get { - return options.AlignToFirstIndexerArgument; - } - set { - options.AlignToFirstIndexerArgument = value; - } - } - - #endregion - - public PlayScriptFormattingPolicy () - { - this.options = FormattingOptionsFactory.CreateMono (); - } - - public static PlayScriptFormattingPolicy Load (FilePath selectedFile) - { - using (var stream = System.IO.File.OpenRead (selectedFile)) { - return Load (stream); - } - } - - public static PlayScriptFormattingPolicy Load (System.IO.Stream input) - { - var result = new PlayScriptFormattingPolicy (); - result.Name = "noname"; - using (var reader = new XmlTextReader (input)) { - while (reader.Read ()) { - if (reader.NodeType == XmlNodeType.Element) { - if (reader.LocalName == "Property") { - var info = typeof (PlayScriptFormattingPolicy).GetProperty (reader.GetAttribute ("name")); - string valString = reader.GetAttribute ("value"); - object value; - if (info.PropertyType == typeof (bool)) { - value = Boolean.Parse (valString); - } else if (info.PropertyType == typeof (int)) { - value = Int32.Parse (valString); - } else { - value = Enum.Parse (info.PropertyType, valString); - } - info.SetValue (result, value, null); - } else if (reader.LocalName == "FormattingProfile") { - result.Name = reader.GetAttribute ("name"); - } - } else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "FormattingProfile") { - //Console.WriteLine ("result:" + result.Name); - return result; - } - } - } - return result; - } - - public void Save (string fileName) - { - using (var writer = new XmlTextWriter (fileName, Encoding.Default)) { - writer.Formatting = System.Xml.Formatting.Indented; - writer.Indentation = 1; - writer.IndentChar = '\t'; - writer.WriteStartElement ("FormattingProfile"); - writer.WriteAttributeString ("name", Name); - foreach (PropertyInfo info in typeof (PlayScriptFormattingPolicy).GetProperties ()) { - if (info.GetCustomAttributes (false).Any (o => o.GetType () == typeof(ItemPropertyAttribute))) { - writer.WriteStartElement ("Property"); - writer.WriteAttributeString ("name", info.Name); - writer.WriteAttributeString ("value", info.GetValue (this, null).ToString ()); - writer.WriteEndElement (); - } - } - writer.WriteEndElement (); - } - } - - public bool Equals (PlayScriptFormattingPolicy other) - { - foreach (PropertyInfo info in typeof (PlayScriptFormattingPolicy).GetProperties ()) { - if (info.GetCustomAttributes (false).Any (o => o.GetType () == typeof(ItemPropertyAttribute))) { - object val = info.GetValue (this, null); - object otherVal = info.GetValue (other, null); - if (val == null) { - if (otherVal == null) - continue; - return false; - } - if (!val.Equals (otherVal)) { - //Console.WriteLine ("!equal"); - return false; - } - } - } - //Console.WriteLine ("== equal"); - return true; - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingPolicyPanel.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingPolicyPanel.cs deleted file mode 100644 index f5f5a5f..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingPolicyPanel.cs +++ /dev/null @@ -1,64 +0,0 @@ -// -// CSharpFormattingPolicyPanel.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using Gtk; -using MonoDevelop.Ide.Gui.Dialogs; -using MonoDevelop.Ide.Gui.Content; - -namespace MonoDevelop.PlayScript.Formatting -{ - class CSharpFormattingPolicyPanel : MimeTypePolicyOptionsPanel - { - CSharpFormattingPolicyPanelWidget panel; - - static CSharpFormattingPolicyPanel () - { - // ensure that custom text editor shemes are loaded. - MonoDevelop.SourceEditor.SourceEditorDisplayBinding.InitSourceEditor (); - } - - public override Widget CreatePanelWidget () - { - return panel = new CSharpFormattingPolicyPanelWidget (); - } - - protected override void LoadFrom (PlayScriptFormattingPolicy policy) - { - panel.SetPolicy (policy.Clone (), GetCurrentOtherPolicy ()); - } - - public override void PanelSelected () - { - panel.SetPolicy (GetCurrentOtherPolicy ()); - } - - protected override PlayScriptFormattingPolicy GetPolicy () - { - // return cloned policy - return panel.Policy; - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingPolicyPanelWidget.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingPolicyPanelWidget.cs deleted file mode 100644 index 9a07378..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingPolicyPanelWidget.cs +++ /dev/null @@ -1,108 +0,0 @@ -// -// CSharpFormattingPolicyPanelWidget.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using MonoDevelop.Ide; -using MonoDevelop.Ide.Gui.Content; - -namespace MonoDevelop.PlayScript.Formatting -{ - [System.ComponentModel.ToolboxItem(true)] - partial class CSharpFormattingPolicyPanelWidget : Gtk.Bin - { - readonly Mono.TextEditor.TextEditor texteditor = new Mono.TextEditor.TextEditor (); -// Gtk.ListStore model = new Gtk.ListStore (typeof(string)); -// List policies = new List (); - const string example = @"using System; -namespace Example { - public class Test - { - public static void Main (string[] args) - { - for (int i = 0; i < 10; i++) { - Console.WriteLine (""{0}: Test"", i); - } - } - } -}"; - TextStylePolicy textStylePolicy; - PlayScriptFormattingPolicy policy; - public PlayScriptFormattingPolicy Policy { - get { - return policy; - } - } - - - public void SetPolicy (PlayScriptFormattingPolicy formattingPolicy, TextStylePolicy textStylePolicy) - { - policy = formattingPolicy; - this.textStylePolicy = textStylePolicy; - FormatSample (); - } - - public void SetPolicy (TextStylePolicy textStylePolicy) - { - this.textStylePolicy = textStylePolicy; - FormatSample (); - } - - public CSharpFormattingPolicyPanelWidget () - { - // ReSharper disable once DoNotCallOverridableMethodsInConstructor - this.Build (); - policy = new PlayScriptFormattingPolicy (); - buttonEdit.Clicked += HandleButtonEditClicked; - - var options = MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance; - texteditor.Options.FontName = options.FontName; - texteditor.Options.ColorScheme = options.ColorScheme; - texteditor.Options.ShowFoldMargin = false; - texteditor.Options.ShowIconMargin = false; - texteditor.Options.ShowLineNumberMargin = false; - texteditor.Document.ReadOnly = true; - texteditor.Document.MimeType = CSharpFormatter.MimeType; - scrolledwindow1.Child = texteditor; - ShowAll (); - } - - public void FormatSample () - { - if (textStylePolicy != null) { - texteditor.Options.IndentationSize = textStylePolicy.IndentWidth; - texteditor.Options.TabSize = textStylePolicy.TabWidth; - texteditor.Options.TabsToSpaces = textStylePolicy.TabsToSpaces; - } - texteditor.Document.Text = CSharpFormatter.FormatText (policy, textStylePolicy, CSharpFormatter.MimeType, example, 0, example.Length); - } - - void HandleButtonEditClicked (object sender, EventArgs e) - { - using (var editDialog = new CSharpFormattingProfileDialog (policy)) - MessageService.ShowCustomDialog (editDialog); - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingProfileDialog.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingProfileDialog.cs deleted file mode 100644 index 192c095..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpFormattingProfileDialog.cs +++ /dev/null @@ -1,1354 +0,0 @@ -// -// CSharpFormattingProfileDialog.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using MonoDevelop.Core; -using Gtk; -using MonoDevelop.Ide; -using System.Reflection; -using System.Collections.Generic; -using System.Linq; -using MonoDevelop.Components; -using ICSharpCode.NRefactory.PlayScript; - -namespace MonoDevelop.PlayScript.Formatting -{ - partial class CSharpFormattingProfileDialog : Dialog - { - readonly Mono.TextEditor.TextEditor texteditor = new Mono.TextEditor.TextEditor (); - readonly PlayScriptFormattingPolicy profile; - TreeStore indentOptions, bacePositionOptions, newLineOptions, whiteSpaceOptions, wrappingOptions; - - static readonly Dictionary arrayInitializerTranslationDictionary = new Dictionary (); - static readonly Dictionary braceStyleTranslationDictionary = new Dictionary (); - //static Dictionary braceForcementTranslationDictionary = new Dictionary (); - static readonly Dictionary propertyFormattingTranslationDictionary = new Dictionary (); - static readonly Dictionary newLinePlacementTranslationDictionary = new Dictionary (); - - static CSharpFormattingProfileDialog () - { - braceStyleTranslationDictionary [BraceStyle.DoNotChange] = GettextCatalog.GetString ("Do not change"); - braceStyleTranslationDictionary [BraceStyle.EndOfLine] = GettextCatalog.GetString ("End of line"); - braceStyleTranslationDictionary [BraceStyle.EndOfLineWithoutSpace] = GettextCatalog.GetString ("End of line without space"); - braceStyleTranslationDictionary [BraceStyle.NextLine] = GettextCatalog.GetString ("Next line"); - braceStyleTranslationDictionary [BraceStyle.NextLineShifted] = GettextCatalog.GetString ("Next line shifted"); - braceStyleTranslationDictionary [BraceStyle.NextLineShifted2] = GettextCatalog.GetString ("Next line shifted2"); - braceStyleTranslationDictionary [BraceStyle.BannerStyle] = GettextCatalog.GetString ("Banner style"); - - propertyFormattingTranslationDictionary [PropertyFormatting.AllowOneLine] = GettextCatalog.GetString ("Allow one line"); - propertyFormattingTranslationDictionary [PropertyFormatting.ForceOneLine] = GettextCatalog.GetString ("Force one line"); - propertyFormattingTranslationDictionary [PropertyFormatting.ForceNewLine] = GettextCatalog.GetString ("Force new line"); - - arrayInitializerTranslationDictionary [Wrapping.DoNotChange] = GettextCatalog.GetString ("Do not change"); - arrayInitializerTranslationDictionary [Wrapping.DoNotWrap] = GettextCatalog.GetString ("Do not Wrap"); - arrayInitializerTranslationDictionary [Wrapping.WrapAlways] = GettextCatalog.GetString ("Wrap always"); - arrayInitializerTranslationDictionary [Wrapping.WrapIfTooLong] = GettextCatalog.GetString ("Wrap if too long"); - - newLinePlacementTranslationDictionary [NewLinePlacement.DoNotCare] = GettextCatalog.GetString ("Allow both"); - newLinePlacementTranslationDictionary [NewLinePlacement.NewLine] = GettextCatalog.GetString ("Always new line"); - newLinePlacementTranslationDictionary [NewLinePlacement.SameLine] = GettextCatalog.GetString ("Always same line"); - } - - public static string TranslateValue (object value) - { - if (value is BraceStyle) - return braceStyleTranslationDictionary [(BraceStyle)value]; -// if (value is BraceForcement) -// return braceForcementTranslationDictionary [(BraceForcement)value]; - if (value is PropertyFormatting) - return propertyFormattingTranslationDictionary [(PropertyFormatting)value]; - if (value is Wrapping) - return arrayInitializerTranslationDictionary [(Wrapping)value]; - if (value is NewLinePlacement) - return newLinePlacementTranslationDictionary [(NewLinePlacement)value]; - throw new Exception ("unknown property type: " + value); - } - - public static object ConvertProperty (Type propertyType, string newText) - { - if (propertyType == typeof(BraceStyle)) - return braceStyleTranslationDictionary.First (p => p.Value == newText).Key; -// if (propertyType == typeof(BraceForcement)) -// return braceForcementTranslationDictionary.First (p => p.Value == newText).Key; - if (propertyType == typeof(PropertyFormatting)) - return propertyFormattingTranslationDictionary.First (p => p.Value == newText).Key; - if (propertyType == typeof(Wrapping)) - return arrayInitializerTranslationDictionary.First (p => p.Value == newText).Key; - if (propertyType == typeof(NewLinePlacement)) - return newLinePlacementTranslationDictionary.First (p => p.Value == newText).Key; - throw new Exception ("unknown property type: " + propertyType); - } - - #region Examples - const string methodSpaceExample = @"class ClassDeclaration { - public static void Main (string[] args) - { - Console.WriteLine (""Hello World!""); - } - }"; - - const string propertyExample = @"class ClassDeclaration { - int myProperty; - int MyProperty { - get { return myProperty;} - set { myProperty = value;} - } - - string Simple { get { ; } set { ; } } - - int myOtherProperty; - int MyOtherProperty { - get { - Console.WriteLine (""get myOtherProperty""); - return myOtherProperty; - } - set { - if (myOtherProperty != value) - myOtherProperty = value; - } - } - - int MyAutoProperty { - get; - set; - } - - int MyOtherAutoProperty { get; set; } - }"; - - const string spaceExample = @"class ClassDeclaration { - public void TestMethod () - { - try { - TestMethod (""""); - } catch (Exception e) { - // Do something - } finally { - // Do something - } - } - - public void TestMethod (string test) - { - lock (this) { - switch (test) { - case ""A"": - Console.WriteLine (""was A""); - break; - case ""B"": - Console.WriteLine (""was B""); - break; - } - } - } - - public void Calculate (int a, int b) - { - if (a < b) { - for (int i = a; i < b; i++) { - Console.WriteLine (i); - } - } else { - using (object o = new object ()) { - while (b < a) { - ConentryNamesole.WriteLine (b++); - } - } - } - } - }"; - const string eventExample = @"class ClassDeclaration { - EventHandler onAction; - public event EventHandler Action { - add { onAction = (EventHandler)Delegate.Combine(onAction, value); } - remove { onAction = (EventHandler)Delegate.Remove(onAction, value);} - } - EventHandler onAnotherAction; - public event EventHandler AnotherAction { - add { if (value != null) - onAnotherAction = (EventHandler)Delegate.Combine(onAnotherAction, value); } - remove { if (value != null) - onAnotherAction = (EventHandler)Delegate.Remove(onAnotherAction, value);} - } - }"; - - const string simpleUsingStatement = @"class ClassDeclaration { - public void Test () - { - using (object o = new object ()) { - Console.WriteLine (""Hello World!""); - } - } - }"; - - const string simpleFixedStatement = @"class ClassDeclaration { - public void Test (Point pt) - { - fixed (int* p = &pt.x) { - *p = 10; - } - } - }"; - - const string simpleIf = @"class ClassDeclaration { - public void Test (int i) - { - if (i == 5) { - Console.WriteLine (""== 5""); - } else if (i > 0) { - Console.WriteLine ("">0""); - } else if (i < 0) { - Console.WriteLine (""<0""); - } else { - Console.WriteLine (""== 0""); - } - } - }"; - const string longMethodCall = @"class ClassDeclaration { - public void Test (int test) - { - LongMethodCallInSameLine (""Hello"", 1, test); - LongMethodCallInMultiple ( -""Hello"", - 1, - test); - - LongMethodCallInMultipleCase2 (""Hello"", - 1, - test); - } -}"; - const string longMethodDeclaration = @"class ClassDeclaration { - public void LongMethodCallInSameLine (int test, string foo, double bar) - { - } - public void LongMethodCallInMultiple ( -int test, -string foo, -double bar) - { - } - public void LongMethodCallInMultipleCase2 (int test, -string foo, -double bar) - { - } -}"; - const string longIndexerDeclaration = @"class ClassDeclaration { - public int this [int test, string foo, double bar] - { - get {} - } - public int this [ -int test, -string foo, -double bar] - { - get {} - } - public int this [int test, -string foo, -double bar] - { - get {} - } -}"; - const string longIndexer = @"class ClassDeclaration { - public void Test (int test) - { - this [""Hello"", 1, test] = 0; - this [ -""Hello"", - 1, - test] = 0; - - this [""Hello"", - 1, - test] = 0; - } -}"; - const string simpleWhile = @"class ClassDeclaration { - public void Test () - { - while (true) { - Console.WriteLine (""Hello World!""); - } - } - }"; - const string simpleCatch = @"class ClassDeclaration { - public void Test () - { - try { - Console.WriteLine (""Hello World!""); - } catch (Exception) { - Console.WriteLine (""Got exception!!""); - } finally { - Console.WriteLine (""finally done.""); - } - } - }"; - - const string simpleDoWhile = @"class ClassDeclaration { - public void Test () - { - int i = 0; - do { - Console.WriteLine (""Hello World!""); - } while (i++ < 10); - } - }"; - - const string simpleArrayInitializer = @"class ClassDeclaration { - public void Test (object o) - { - int[] i = new int[] { 1, 3, 3, 7 }; - } - }"; - const string condOpExample = @"class ClassDeclaration { - public string GetSign (int i) - { - return i < 0 ? ""-"" : ""+""; - } - }"; - const string switchExample = @"class ClassDeclaration { - public void Test (int i) - { - switch (i) { - case 0: - Console.WriteLine (""was zero""); - break; - case 1: - Console.WriteLine (""was one""); - break; - default: - Console.WriteLine (""was "" + i); - break; - } - } - }"; - const string simpleFor = @"class ClassDeclaration { - public void Test () - { - for (int i = 0; i < 10; i++) { - Console.WriteLine (""Hello World!""); - } - } - }"; - const string simpleForeach = @"class ClassDeclaration : ArrayList { - public void Test () - { - foreach (object o in this) { - Console.WriteLine (""Hello World!""); - } - } - }"; - const string simpleLock = @"class ClassDeclaration { - public void Test () - { - lock (this) { - Console.WriteLine (""Hello World!""); - } - } - }"; - const string operatorExample = @"class ClassDeclaration { - public void TestMethod () - { - int a = 5 << 5; - int b = (a + 5 - 3) * 6 / 2; - a += b; - a = a & ~255; - if (a == b || b < a >> 1) { - b -= a; - } - } - object Test (object a, object b) - { - return a ?? b; - } - }"; - const string blankLineExample = @"// Example -using System; -using System.Collections; -namespace TestSpace { - using MyNamespace; - class Test - { - int a; - string b; - public Test (int a, string b) - { - this.a = a; - this.b = b; - } - void Print () - { - Console.WriteLine (""a: {0} b : {1}"", a, b); - } - } - class MyTest - { - } -} -"; - #endregion - - const int propertyColumn = 0; - const int displayTextColumn = 1; - const int exampleTextColumn = 2; - const int toggleVisibleColumn = 3; - const int comboVisibleColumn = 4; - protected ListStore ComboBoxStore = new ListStore (typeof (string), typeof (string)); - - - public CSharpFormattingProfileDialog (PlayScriptFormattingPolicy profile) - { - // ReSharper disable once DoNotCallOverridableMethodsInConstructor - this.Build (); - this.profile = profile; - this.Title = profile.IsBuiltIn ? GettextCatalog.GetString ("Show built-in profile") : GettextCatalog.GetString ("Edit Profile"); - - notebookCategories.SwitchPage += delegate { - TreeView treeView; - switch (notebookCategories.Page) { - case 0: - treeView = treeviewIndentOptions; - break; - case 1: - treeView = treeviewBracePositions; - break; - case 2: // Blank lines - UpdateExample (blankLineExample); - return; - case 3: // white spaces - return; - case 4: - treeView = treeviewNewLines; - break; - default: - return; - } - - TreeModel model; - TreeIter iter; - if (treeView.Selection.GetSelected (out model, out iter)) - UpdateExample (model, iter); - }; - notebookCategories.ShowTabs = false; - comboboxCategories.AppendText (GettextCatalog.GetString ("Indentation")); - comboboxCategories.AppendText (GettextCatalog.GetString ("Braces")); - comboboxCategories.AppendText (GettextCatalog.GetString ("Blank lines")); - comboboxCategories.AppendText (GettextCatalog.GetString ("Wrapping")); - comboboxCategories.AppendText (GettextCatalog.GetString ("White Space")); - comboboxCategories.AppendText (GettextCatalog.GetString ("New Lines")); - comboboxCategories.Changed += delegate { - texteditor.Text = ""; - notebookCategories.Page = comboboxCategories.Active; - }; - comboboxCategories.Active = 0; - - var options = MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance; - texteditor.Options.FontName = options.FontName; - texteditor.Options.ColorScheme = options.ColorScheme; - texteditor.Options.ShowFoldMargin = false; - texteditor.Options.ShowIconMargin = false; - texteditor.Options.ShowLineNumberMargin = false; - texteditor.Document.ReadOnly = true; - texteditor.Document.MimeType = CSharpFormatter.MimeType; - scrolledwindow.Child = texteditor; - ShowAll (); - - #region Indent options - indentOptions = new TreeStore (typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool)); - - var column = new TreeViewColumn (); - // pixbuf column - var pixbufCellRenderer = new CellRendererImage (); - column.PackStart (pixbufCellRenderer, false); - column.SetCellDataFunc (pixbufCellRenderer, RenderIcon); - - // text column - var cellRendererText = new CellRendererText (); - cellRendererText.Ypad = 1; - column.PackStart (cellRendererText, true); - column.SetAttributes (cellRendererText, "text", 1); - - treeviewIndentOptions.Model = indentOptions; - treeviewIndentOptions.HeadersVisible = false; - treeviewIndentOptions.Selection.Changed += TreeSelectionChanged; - treeviewIndentOptions.AppendColumn (column); - - column = new TreeViewColumn (); - var cellRendererCombo = new CellRendererCombo (); - cellRendererCombo.Ypad = 1; - cellRendererCombo.Mode = CellRendererMode.Editable; - cellRendererCombo.TextColumn = 1; - cellRendererCombo.Model = ComboBoxStore; - cellRendererCombo.HasEntry = false; - cellRendererCombo.Editable = !profile.IsBuiltIn; - - cellRendererCombo.Edited += new ComboboxEditedHandler (this, indentOptions).ComboboxEdited; - - column.PackStart (cellRendererCombo, false); - column.SetAttributes (cellRendererCombo, "visible", comboVisibleColumn); - column.SetCellDataFunc (cellRendererCombo, ComboboxDataFunc); - - var cellRendererToggle = new CellRendererToggle (); - cellRendererToggle.Ypad = 1; - cellRendererToggle.Activatable = !profile.IsBuiltIn; - cellRendererToggle.Toggled += new CellRendererToggledHandler (this, treeviewIndentOptions, indentOptions).Toggled; - column.PackStart (cellRendererToggle, false); - column.SetAttributes (cellRendererToggle, "visible", toggleVisibleColumn); - column.SetCellDataFunc (cellRendererToggle, ToggleDataFunc); - - treeviewIndentOptions.AppendColumn (column); - var category = AddOption (indentOptions, null, GettextCatalog.GetString ("Declarations"), null); - AddOption (indentOptions, category, "IndentNamespaceBody", GettextCatalog.GetString ("within namespaces"), "namespace Test { class AClass {} }"); - - AddOption (indentOptions, category, "IndentClassBody", GettextCatalog.GetString ("within classes"), "class AClass { int aField; void AMethod () {}}"); - AddOption (indentOptions, category, "IndentInterfaceBody", GettextCatalog.GetString ("within interfaces"), "interface IAInterfaces { int AProperty {get;set;} void AMethod ();}"); - AddOption (indentOptions, category, "IndentStructBody", GettextCatalog.GetString ("within structs"), "struct AStruct { int aField; void AMethod () {}}"); - AddOption (indentOptions, category, "IndentEnumBody", GettextCatalog.GetString ("within enums"), "enum AEnum { A, B, C }"); - - AddOption (indentOptions, category, "IndentMethodBody", GettextCatalog.GetString ("within methods"), methodSpaceExample); - AddOption (indentOptions, category, "IndentPropertyBody", GettextCatalog.GetString ("within properties"), propertyExample); - AddOption (indentOptions, category, "IndentEventBody", GettextCatalog.GetString ("within events"), eventExample); - - category = AddOption (indentOptions, null, GettextCatalog.GetString ("Statements"), null); - AddOption (indentOptions, category, "IndentBlocks", GettextCatalog.GetString ("within blocks"), spaceExample); - AddOption (indentOptions, category, "IndentSwitchBody", GettextCatalog.GetString ("Indent 'switch' body"), spaceExample); - AddOption (indentOptions, category, "IndentCaseBody", GettextCatalog.GetString ("Indent 'case' body"), spaceExample); - AddOption (indentOptions, category, "IndentBreakStatements", GettextCatalog.GetString ("Indent 'break' statements"), spaceExample); - AddOption (indentOptions, category, "IndentPreprocessorDirectives", GettextCatalog.GetString ("Indent pre processor directives"), - @"#define DEBUG -class Test { - #if DEBUG - void Example () - { - } - #endif -} -"); - - AddOption (indentOptions, category, "IndentBlocksInsideExpressions", GettextCatalog.GetString ("Indent blocks inside expressions"), - @" -class Test -{ - void Example () - { - Test(delegate { - Call (); - }); - } -} -"); - AddOption (indentOptions, category, "AlignEmbeddedStatements", GettextCatalog.GetString ("Align embedded statements"), "class AClass { void AMethod () { if (a) if (b) { int c; } } } "); - treeviewIndentOptions.ExpandAll (); - #endregion - - #region Brace options - bacePositionOptions = new TreeStore (typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool)); - - column = new TreeViewColumn (); - // pixbuf column - column.PackStart (pixbufCellRenderer, false); - column.SetCellDataFunc (pixbufCellRenderer, RenderIcon); - - // text column - cellRendererText = new CellRendererText (); - cellRendererText.Ypad = 1; - column.PackStart (cellRendererText, true); - column.SetAttributes (cellRendererText, "text", 1); - - treeviewBracePositions.Model = bacePositionOptions; - treeviewBracePositions.HeadersVisible = false; - treeviewBracePositions.Selection.Changed += TreeSelectionChanged; - treeviewBracePositions.AppendColumn (column); - - column = new TreeViewColumn (); - cellRendererCombo = new CellRendererCombo (); - cellRendererCombo.Ypad = 1; - cellRendererCombo.Mode = CellRendererMode.Editable; - cellRendererCombo.TextColumn = 1; - cellRendererCombo.Model = ComboBoxStore; - cellRendererCombo.HasEntry = false; - cellRendererCombo.Editable = !profile.IsBuiltIn; - cellRendererCombo.Edited += new ComboboxEditedHandler (this, bacePositionOptions).ComboboxEdited; - - column.PackStart (cellRendererCombo, false); - column.SetAttributes (cellRendererCombo, "visible", comboVisibleColumn); - column.SetCellDataFunc (cellRendererCombo, ComboboxDataFunc); - - cellRendererToggle = new CellRendererToggle (); - cellRendererToggle.Activatable = !profile.IsBuiltIn; - cellRendererToggle.Ypad = 1; - cellRendererToggle.Toggled += new CellRendererToggledHandler (this, treeviewBracePositions, bacePositionOptions).Toggled; - column.PackStart (cellRendererToggle, false); - column.SetAttributes (cellRendererToggle, "visible", toggleVisibleColumn); - column.SetCellDataFunc (cellRendererToggle, ToggleDataFunc); - - treeviewBracePositions.AppendColumn (column); - - AddOption (bacePositionOptions, "NamespaceBraceStyle", GettextCatalog.GetString ("Namespace declaration"), "namespace TestNameSpace {}"); - - AddOption (bacePositionOptions, "ClassBraceStyle", GettextCatalog.GetString ("Class declaration"), "class ClassDeclaration {}"); - AddOption (bacePositionOptions, "InterfaceBraceStyle", GettextCatalog.GetString ("Interface declaration"), "interface InterfaceDeclaraction {}"); - AddOption (bacePositionOptions, "StructBraceStyle", GettextCatalog.GetString ("Struct declaration"), "struct StructDeclaration {}"); - AddOption (bacePositionOptions, "EnumBraceStyle", GettextCatalog.GetString ("Enum declaration"), "enum EnumDeclaration { A, B, C}"); - - AddOption (bacePositionOptions, "MethodBraceStyle", GettextCatalog.GetString ("Method declaration"), "class ClassDeclaration { void MyMethod () {} }"); - AddOption (bacePositionOptions, "AnonymousMethodBraceStyle", GettextCatalog.GetString ("Anonymous methods"), "class ClassDeclaration { void MyMethod () { MyEvent += delegate (object sender, EventArgs e) { if (true) Console.WriteLine (\"Hello World\"); }; } }"); - AddOption (bacePositionOptions, "ConstructorBraceStyle", GettextCatalog.GetString ("Constructor declaration"), "class ClassDeclaration { public ClassDeclaration () {} }"); - AddOption (bacePositionOptions, "DestructorBraceStyle", GettextCatalog.GetString ("Destructor declaration"), "class ClassDeclaration { ~ClassDeclaration () {} }"); - - AddOption (bacePositionOptions, "StatementBraceStyle", GettextCatalog.GetString ("Statements"), spaceExample); - - category = AddOption (bacePositionOptions, "PropertyBraceStyle", GettextCatalog.GetString ("Property declaration"), propertyExample); - AddOption (bacePositionOptions, category, "AutoPropertyFormatting", GettextCatalog.GetString ("Allow automatic property in one line"), propertyExample); - AddOption (bacePositionOptions, category, "SimplePropertyFormatting", GettextCatalog.GetString ("Allow simple property in one line"), propertyExample); - - - AddOption (bacePositionOptions, category, "PropertyGetBraceStyle", GettextCatalog.GetString ("Get declaration"), propertyExample); - AddOption (bacePositionOptions, category, "SimpleGetBlockFormatting", GettextCatalog.GetString ("Allow one line get"), propertyExample); - AddOption (bacePositionOptions, category, "PropertySetBraceStyle", GettextCatalog.GetString ("Set declaration"), propertyExample); - AddOption (bacePositionOptions, category, "SimpleSetBlockFormatting", GettextCatalog.GetString ("Allow one line set"), propertyExample); - - - category = AddOption (bacePositionOptions, "EventBraceStyle", GettextCatalog.GetString ("Event declaration"), eventExample); - AddOption (bacePositionOptions, category, "EventAddBraceStyle", GettextCatalog.GetString ("Add declaration"), eventExample); - AddOption (bacePositionOptions, category, "AllowEventAddBlockInline", GettextCatalog.GetString ("Allow one line add"), eventExample); - AddOption (bacePositionOptions, category, "EventRemoveBraceStyle", GettextCatalog.GetString ("Remove declaration"), eventExample); - AddOption (bacePositionOptions, category, "AllowEventRemoveBlockInline", GettextCatalog.GetString ("Allow one line remove"), eventExample); - - treeviewBracePositions.ExpandAll (); - #endregion - - #region New line options - newLineOptions = new TreeStore (typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool)); - - column = new TreeViewColumn (); - // pixbuf column - column.PackStart (pixbufCellRenderer, false); - column.SetCellDataFunc (pixbufCellRenderer, RenderIcon); - - // text column - cellRendererText.Ypad = 1; - column.PackStart (cellRendererText, true); - column.SetAttributes (cellRendererText, "text", 1); - - treeviewNewLines.Model = newLineOptions; - treeviewNewLines.HeadersVisible = false; - treeviewNewLines.Selection.Changed += TreeSelectionChanged; - treeviewNewLines.AppendColumn (column); - - column = new TreeViewColumn (); - cellRendererCombo = new CellRendererCombo (); - cellRendererCombo.Ypad = 1; - cellRendererCombo.Mode = CellRendererMode.Editable; - cellRendererCombo.TextColumn = 1; - cellRendererCombo.Model = ComboBoxStore; - cellRendererCombo.HasEntry = false; - cellRendererCombo.Editable = !profile.IsBuiltIn; - cellRendererCombo.Edited += new ComboboxEditedHandler (this, newLineOptions).ComboboxEdited; - - column.PackStart (cellRendererCombo, false); - column.SetAttributes (cellRendererCombo, "visible", comboVisibleColumn); - column.SetCellDataFunc (cellRendererCombo, ComboboxDataFunc); - - cellRendererToggle = new CellRendererToggle (); - cellRendererToggle.Activatable = !profile.IsBuiltIn; - cellRendererToggle.Ypad = 1; - cellRendererToggle.Toggled += new CellRendererToggledHandler (this, treeviewNewLines, newLineOptions).Toggled; - column.PackStart (cellRendererToggle, false); - column.SetAttributes (cellRendererToggle, "visible", toggleVisibleColumn); - column.SetCellDataFunc (cellRendererToggle, ToggleDataFunc); - - treeviewNewLines.AppendColumn (column); - - AddOption (newLineOptions, "ElseNewLinePlacement", GettextCatalog.GetString ("Place 'else' on new line"), simpleIf); - AddOption (newLineOptions, "ElseIfNewLinePlacement", GettextCatalog.GetString ("Place 'else if' on new line"), simpleIf); - AddOption (newLineOptions, "CatchNewLinePlacement", GettextCatalog.GetString ("Place 'catch' on new line"), simpleCatch); - AddOption (newLineOptions, "FinallyNewLinePlacement", GettextCatalog.GetString ("Place 'finally' on new line"), simpleCatch); - AddOption (newLineOptions, "WhileNewLinePlacement", GettextCatalog.GetString ("Place 'while' on new line"), simpleDoWhile); - AddOption (newLineOptions, "ArrayInitializerWrapping", GettextCatalog.GetString ("Place array initializers on new line"), simpleArrayInitializer); - AddOption (newLineOptions, "EmbeddedStatementPlacement", GettextCatalog.GetString ("Place embedded statements on new line"), @"class Test -{ - public void Example () - { - if (true) - Call (); - - foreach (var o in col) DoSomething (o); - } -}"); - string constructorInitializer=@"class Test -{ - - public Test () : base () - { - - } - - public Test () - : base () - { - - } - - public Test () : - base () - { - - } - - public Test () - : - base () - { - - } -}"; - AddOption (newLineOptions, "NewLineBeforeConstructorInitializerColon", GettextCatalog.GetString("Place constructor initializer ':' on new line"), constructorInitializer); - AddOption (newLineOptions, "NewLineAfterConstructorInitializerColon", GettextCatalog.GetString("Place constructor initializer 'base/this' on new line"), constructorInitializer); - treeviewNewLines.ExpandAll (); - #endregion - - #region Wrapping options - wrappingOptions = new TreeStore (typeof(string), typeof(string), typeof(string), typeof(bool), typeof(bool)); - - column = new TreeViewColumn (); - // pixbuf column - column.PackStart (pixbufCellRenderer, false); - column.SetCellDataFunc (pixbufCellRenderer, RenderIcon); - - // text column - cellRendererText.Ypad = 1; - column.PackStart (cellRendererText, true); - column.SetAttributes (cellRendererText, "text", 1); - - - treeviewWrappingCategory.Model = wrappingOptions; - treeviewWrappingCategory.HeadersVisible = false; - treeviewWrappingCategory.Selection.Changed += TreeSelectionChanged; - treeviewWrappingCategory.AppendColumn (column); - - column = new TreeViewColumn (); - cellRendererCombo = new CellRendererCombo (); - cellRendererCombo.Ypad = 1; - cellRendererCombo.Mode = CellRendererMode.Editable; - cellRendererCombo.TextColumn = 1; - cellRendererCombo.Model = ComboBoxStore; - cellRendererCombo.HasEntry = false; - cellRendererCombo.Editable = !profile.IsBuiltIn; - cellRendererCombo.Edited += new ComboboxEditedHandler (this, wrappingOptions).ComboboxEdited; - - column.PackStart (cellRendererCombo, false); - column.SetAttributes (cellRendererCombo, "visible", comboVisibleColumn); - column.SetCellDataFunc (cellRendererCombo, ComboboxDataFunc); - - cellRendererToggle = new CellRendererToggle (); - cellRendererToggle.Activatable = !profile.IsBuiltIn; - cellRendererToggle.Ypad = 1; - cellRendererToggle.Toggled += new CellRendererToggledHandler (this, treeviewNewLines, wrappingOptions).Toggled; - column.PackStart (cellRendererToggle, false); - column.SetAttributes (cellRendererToggle, "visible", toggleVisibleColumn); - column.SetCellDataFunc (cellRendererToggle, ToggleDataFunc); - - treeviewWrappingCategory.AppendColumn (column); - - category = AddOption (wrappingOptions, null, GettextCatalog.GetString ("Method declarations"), null); - AddOption (wrappingOptions, category, "MethodDeclarationParameterWrapping", GettextCatalog.GetString ("Parameters"), longMethodDeclaration); - AddOption (wrappingOptions, category, "NewLineAferMethodDeclarationOpenParentheses", GettextCatalog.GetString ("New line after open parentheses"), longMethodDeclaration); - AddOption (wrappingOptions, category, "MethodDeclarationClosingParenthesesOnNewLine", GettextCatalog.GetString ("New line before closing parentheses"), longMethodDeclaration); - AddOption (wrappingOptions, category, "AlignToFirstMethodDeclarationParameter", GettextCatalog.GetString ("Align to first parameter"), longMethodDeclaration); - - category = AddOption (wrappingOptions, null, GettextCatalog.GetString ("Method calls"), null); - AddOption (wrappingOptions, category, "MethodCallArgumentWrapping", GettextCatalog.GetString ("Arguments"), longMethodCall); - AddOption (wrappingOptions, category, "NewLineAferMethodCallOpenParentheses", GettextCatalog.GetString ("New line after open parentheses"), longMethodCall); - AddOption (wrappingOptions, category, "MethodCallClosingParenthesesOnNewLine", GettextCatalog.GetString ("New line before closing parentheses"), longMethodCall); - AddOption (wrappingOptions, category, "AlignToFirstMethodCallArgument", GettextCatalog.GetString ("Align to first argument"), longMethodCall); - - category = AddOption (wrappingOptions, null, GettextCatalog.GetString ("Indexer declarations"), null); - AddOption (wrappingOptions, category, "IndexerDeclarationParameterWrapping", GettextCatalog.GetString ("Parameters"), longIndexerDeclaration); - AddOption (wrappingOptions, category, "NewLineAferIndexerDeclarationOpenBracket", GettextCatalog.GetString ("New line after open parentheses"), longIndexerDeclaration); - AddOption (wrappingOptions, category, "IndexerDeclarationClosingBracketOnNewLine", GettextCatalog.GetString ("New line before closing parentheses"), longIndexerDeclaration); - AddOption (wrappingOptions, category, "AlignToFirstIndexerDeclarationParameter", GettextCatalog.GetString ("Align to first parameter"), longIndexerDeclaration); - - category = AddOption (wrappingOptions, null, GettextCatalog.GetString ("Indexer usage"), null); - AddOption (wrappingOptions, category, "IndexerArgumentWrapping", GettextCatalog.GetString ("Arguments"), longIndexer); - AddOption (wrappingOptions, category, "NewLineAferIndexerOpenBracket", GettextCatalog.GetString ("New line after open bracket"), longIndexer); - AddOption (wrappingOptions, category, "IndexerClosingBracketOnNewLine", GettextCatalog.GetString ("New line before closing bracket"), longIndexer); - AddOption (wrappingOptions, category, "AlignToFirstIndexerArgument", GettextCatalog.GetString ("Align to first parameter"), longIndexer); - - treeviewWrappingCategory.ExpandAll (); - #endregion - - #region White space options - whiteSpaceOptions = new TreeStore (typeof (string), typeof (string), typeof (string), typeof(bool), typeof(bool)); - - - column = new TreeViewColumn (); - // pixbuf column - column.PackStart (pixbufCellRenderer, false); - column.SetCellDataFunc (pixbufCellRenderer, RenderIcon); - - // text column - cellRendererText.Ypad = 1; - column.PackStart (cellRendererText, true); - column.SetAttributes (cellRendererText, "text", 1); - - treeviewInsertWhiteSpaceCategory.Model = whiteSpaceOptions; - treeviewInsertWhiteSpaceCategory.HeadersVisible = false; - treeviewInsertWhiteSpaceCategory.Selection.Changed += TreeSelectionChanged; - treeviewInsertWhiteSpaceCategory.AppendColumn (column); - - column = new TreeViewColumn (); - cellRendererCombo = new CellRendererCombo (); - cellRendererCombo.Ypad = 1; - cellRendererCombo.Mode = CellRendererMode.Editable; - cellRendererCombo.TextColumn = 1; - cellRendererCombo.Model = ComboBoxStore; - cellRendererCombo.HasEntry = false; - cellRendererCombo.Editable = !profile.IsBuiltIn; - cellRendererCombo.Edited += new ComboboxEditedHandler (this, whiteSpaceOptions).ComboboxEdited; - - column.PackStart (cellRendererCombo, false); - column.SetAttributes (cellRendererCombo, "visible", comboVisibleColumn); - column.SetCellDataFunc (cellRendererCombo, ComboboxDataFunc); - - cellRendererToggle = new CellRendererToggle (); - cellRendererToggle.Activatable = !profile.IsBuiltIn; - cellRendererToggle.Ypad = 1; - cellRendererToggle.Toggled += new CellRendererToggledHandler (this, treeviewInsertWhiteSpaceCategory, whiteSpaceOptions).Toggled; - column.PackStart (cellRendererToggle, false); - column.SetAttributes (cellRendererToggle, "visible", toggleVisibleColumn); - column.SetCellDataFunc (cellRendererToggle, ToggleDataFunc); - - treeviewInsertWhiteSpaceCategory.AppendColumn (column); - - string example = @"class Example { - void Test () - { - } - - void Test (int a, int b, int c) - { - } -}"; - category = AddOption (whiteSpaceOptions, null, GettextCatalog.GetString ("Declarations"), example); - AddOption (whiteSpaceOptions, category, "BeforeMethodDeclarationParentheses", GettextCatalog.GetString ("before opening parenthesis"), example); - AddOption (whiteSpaceOptions, category, "WithinMethodDeclarationParentheses", GettextCatalog.GetString ("within parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BetweenEmptyMethodDeclarationParentheses", GettextCatalog.GetString ("between empty parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BeforeMethodDeclarationParameterComma", GettextCatalog.GetString ("before comma in parenthesis"), example); - AddOption (whiteSpaceOptions, category, "AfterMethodDeclarationParameterComma", GettextCatalog.GetString ("after comma in parenthesis"), example); - - example = @"class Example { - int a, b, c; -}"; - category = AddOption (whiteSpaceOptions, null, GettextCatalog.GetString ("Fields"), example); - AddOption (whiteSpaceOptions, category, "BeforeFieldDeclarationComma", GettextCatalog.GetString ("before comma in multiple field declarations"), example); - AddOption (whiteSpaceOptions, category, "AfterFieldDeclarationComma", GettextCatalog.GetString ("after comma in multiple field declarations"), example); - - example = @"class Example { - Example () - { - } - - Example (int a, int b, int c) - { - } -}"; - category = AddOption (whiteSpaceOptions, null, GettextCatalog.GetString ("Constructors"), example); - AddOption (whiteSpaceOptions, category, "BeforeConstructorDeclarationParentheses", GettextCatalog.GetString ("before opening parenthesis"), example); - AddOption (whiteSpaceOptions, category, "WithinConstructorDeclarationParentheses", GettextCatalog.GetString ("within parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BetweenEmptyConstructorDeclarationParentheses", GettextCatalog.GetString ("between empty parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BeforeConstructorDeclarationParameterComma", GettextCatalog.GetString ("before comma in parenthesis"), example); - AddOption (whiteSpaceOptions, category, "AfterConstructorDeclarationParameterComma", GettextCatalog.GetString ("after comma in parenthesis"), example); - - example = @"class Example { - public int this[int a, int b] { - get { - return a + b; - } - } -}"; - category = AddOption (whiteSpaceOptions, null, GettextCatalog.GetString ("Indexer"), example); - AddOption (whiteSpaceOptions, category, "BeforeIndexerDeclarationBracket", GettextCatalog.GetString ("before opening bracket"), example); - AddOption (whiteSpaceOptions, category, "WithinIndexerDeclarationBracket", GettextCatalog.GetString ("within brackets"), example); - AddOption (whiteSpaceOptions, category, "BeforeIndexerDeclarationParameterComma", GettextCatalog.GetString ("before comma in brackets"), example); - AddOption (whiteSpaceOptions, category, "AfterIndexerDeclarationParameterComma", GettextCatalog.GetString ("after comma in brackets"), example); - - example = @"delegate void FooBar (int a, int b, int c); -delegate void BarFoo (); -"; - - category = AddOption (whiteSpaceOptions, null, GettextCatalog.GetString ("Delegates"), example); - AddOption (whiteSpaceOptions, category, "BeforeDelegateDeclarationParentheses", GettextCatalog.GetString ("before opening parenthesis"), example); - AddOption (whiteSpaceOptions, category, "WithinDelegateDeclarationParentheses", GettextCatalog.GetString ("within parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BetweenEmptyDelegateDeclarationParentheses", GettextCatalog.GetString ("between empty parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BeforeDelegateDeclarationParameterComma", GettextCatalog.GetString ("before comma in parenthesis"), example); - AddOption (whiteSpaceOptions, category, "AfterDelegateDeclarationParameterComma", GettextCatalog.GetString ("after comma in parenthesis"), example); - - var upperCategory = AddOption (whiteSpaceOptions, null, GettextCatalog.GetString ("Statements"), null); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'if'"), simpleIf); - AddOption (whiteSpaceOptions, category, "IfParentheses", GettextCatalog.GetString ("before opening parenthesis"), simpleIf); - AddOption (whiteSpaceOptions, category, "WithinIfParentheses", GettextCatalog.GetString ("within parenthesis"), simpleIf); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'while'"), simpleWhile); - AddOption (whiteSpaceOptions, category, "WhileParentheses", GettextCatalog.GetString ("before opening parenthesis"), simpleWhile); - AddOption (whiteSpaceOptions, category, "WithinWhileParentheses", GettextCatalog.GetString ("within parenthesis"), simpleWhile); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'for'"), simpleFor); - AddOption (whiteSpaceOptions, category, "ForParentheses", GettextCatalog.GetString ("before opening parenthesis"), simpleFor); - AddOption (whiteSpaceOptions, category, "WithinForParentheses", GettextCatalog.GetString ("within parenthesis"), simpleFor); - AddOption (whiteSpaceOptions, category, "SpacesBeforeForSemicolon", GettextCatalog.GetString ("before semicolon"), simpleFor); - AddOption (whiteSpaceOptions, category, "SpacesAfterForSemicolon", GettextCatalog.GetString ("after semicolon"), simpleFor); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'foreach'"), simpleForeach); - AddOption (whiteSpaceOptions, category, "ForeachParentheses", GettextCatalog.GetString ("before opening parenthesis"), simpleForeach); - AddOption (whiteSpaceOptions, category, "WithinForEachParentheses", GettextCatalog.GetString ("within parenthesis"), simpleForeach); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'catch'"), simpleCatch); - AddOption (whiteSpaceOptions, category, "CatchParentheses", GettextCatalog.GetString ("before opening parenthesis"), simpleCatch); - AddOption (whiteSpaceOptions, category, "WithinCatchParentheses", GettextCatalog.GetString ("within parenthesis"), simpleCatch); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'switch'"), switchExample); - AddOption (whiteSpaceOptions, category, "SwitchParentheses", GettextCatalog.GetString ("before opening parenthesis"), switchExample); - AddOption (whiteSpaceOptions, category, "WithinSwitchParentheses", GettextCatalog.GetString ("within parenthesis"), switchExample); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'lock'"), simpleLock); - AddOption (whiteSpaceOptions, category, "LockParentheses", GettextCatalog.GetString ("before opening parenthesis"), simpleLock); - AddOption (whiteSpaceOptions, category, "WithinLockParentheses", GettextCatalog.GetString ("within parenthesis"), simpleLock); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'using'"), simpleUsingStatement); - AddOption (whiteSpaceOptions, category, "UsingParentheses", GettextCatalog.GetString ("before opening parenthesis"), simpleUsingStatement); - AddOption (whiteSpaceOptions, category, "WithinUsingParentheses", GettextCatalog.GetString ("within parenthesis"), simpleUsingStatement); - - - upperCategory = AddOption (whiteSpaceOptions, null, GettextCatalog.GetString ("Expressions"), null); - - example = @"class Example { - void Test () - { - Console.WriteLine(); - Console.WriteLine(""{0} {1}!"", ""Hello"", ""World""); - } -}"; - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("Method invocations"), example); - AddOption (whiteSpaceOptions, category, "BeforeMethodCallParentheses", GettextCatalog.GetString ("before opening parenthesis"), example); - AddOption (whiteSpaceOptions, category, "WithinMethodCallParentheses", GettextCatalog.GetString ("within parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BetweenEmptyMethodCallParentheses", GettextCatalog.GetString ("between empty parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BeforeMethodCallParameterComma", GettextCatalog.GetString ("before comma in parenthesis"), example); - AddOption (whiteSpaceOptions, category, "AfterMethodCallParameterComma", GettextCatalog.GetString ("after comma in parenthesis"), example); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("Object creation"), example); - example = @"partial class Example { - void Test () - { - var anExample = new Example (1, 2, 3); - var emptyExample = new Example (); - } -}"; - AddOption (whiteSpaceOptions, category, "NewParentheses", GettextCatalog.GetString ("before opening parenthesis"), example); - AddOption (whiteSpaceOptions, category, "WithinNewParentheses", GettextCatalog.GetString ("within parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BetweenEmptyNewParentheses", GettextCatalog.GetString ("between empty parenthesis"), example); - AddOption (whiteSpaceOptions, category, "BeforeNewParameterComma", GettextCatalog.GetString ("before comma in parenthesis"), example); - AddOption (whiteSpaceOptions, category, "AfterNewParameterComma", GettextCatalog.GetString ("after comma in parenthesis"), example); - - - example = @"class Example { - void Test () - { - a[1,2] = b[3]; - } -}"; - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("Element access"), example); - AddOption (whiteSpaceOptions, category, "SpacesBeforeBrackets", GettextCatalog.GetString ("before opening bracket"), example); - AddOption (whiteSpaceOptions, category, "SpacesWithinBrackets", GettextCatalog.GetString ("within brackets"), example); - AddOption (whiteSpaceOptions, category, "BeforeBracketComma", GettextCatalog.GetString ("before comma in brackets"), example); - AddOption (whiteSpaceOptions, category, "AfterBracketComma", GettextCatalog.GetString ("after comma in brackets"), example); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("Parentheses"), operatorExample); - AddOption (whiteSpaceOptions, category, "WithinParentheses", GettextCatalog.GetString ("within parenthesis"), operatorExample); - - example = @"class ClassDeclaration { - public void Test (object o) - { - int i = (int)o; - } - }"; - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("Type cast"), example); - AddOption (whiteSpaceOptions, category, "WithinCastParentheses", GettextCatalog.GetString ("within parenthesis"), example); - AddOption (whiteSpaceOptions, category, "SpacesAfterTypecast", GettextCatalog.GetString ("after type cast"), example); - - example = @"class ClassDeclaration { - public void Test () - { - int i = sizeof (ClassDeclaration); - } - }"; - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'sizeof'"), example); - AddOption (whiteSpaceOptions, category, "BeforeSizeOfParentheses", GettextCatalog.GetString ("before opening parenthesis"), example); - AddOption (whiteSpaceOptions, category, "WithinSizeOfParentheses", GettextCatalog.GetString ("within parenthesis"), example); - - example = @"class ClassDeclaration { - public void Test () - { - Type t = typeof (ClassDeclaration); - } - }"; - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("'typeof'"), example); - AddOption (whiteSpaceOptions, category, "BeforeTypeOfParentheses", GettextCatalog.GetString ("before opening parenthesis"), example); - AddOption (whiteSpaceOptions, category, "WithinTypeOfParentheses", GettextCatalog.GetString ("within parenthesis"), example); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("Around Operators"), operatorExample); - AddOption (whiteSpaceOptions, category, "AroundAssignmentParentheses", GettextCatalog.GetString ("Assignment (=, +=, -=, ...)"), operatorExample); - AddOption (whiteSpaceOptions, category, "AroundLogicalOperatorParentheses", GettextCatalog.GetString ("Logical (&&, ||) operators"), operatorExample); - AddOption (whiteSpaceOptions, category, "AroundEqualityOperatorParentheses", GettextCatalog.GetString ("Equality (==, !=) operators"), operatorExample); - AddOption (whiteSpaceOptions, category, "AroundRelationalOperatorParentheses", GettextCatalog.GetString ("Relational (<, >, <=, >=) operators"), operatorExample); - AddOption (whiteSpaceOptions, category, "AroundBitwiseOperatorParentheses", GettextCatalog.GetString ("Bitwise &, |, ^, ~() operators"), operatorExample); - AddOption (whiteSpaceOptions, category, "AroundAdditiveOperatorParentheses", GettextCatalog.GetString ("Additive (+, -) operators"), operatorExample); - AddOption (whiteSpaceOptions, category, "AroundMultiplicativeOperatorParentheses", GettextCatalog.GetString ("Multiplicative (*, /, %) operators"), operatorExample); - AddOption (whiteSpaceOptions, category, "AroundShiftOperatorParentheses", GettextCatalog.GetString ("Shift (<<, >>) operators"), operatorExample); - AddOption (whiteSpaceOptions, category, "AroundNullCoalescingOperator", GettextCatalog.GetString ("Null coalescing (??) operator"), operatorExample); - AddOption (whiteSpaceOptions, category, "SpaceAfterUnsafeAddressOfOperator", GettextCatalog.GetString ("Unsafe addressof operator (&)"), @"unsafe class ClassDeclaration { - public void TestMethod () - { - int* a = &x; - } -}"); - AddOption (whiteSpaceOptions, category, "SpaceAfterUnsafeAsteriskOfOperator", GettextCatalog.GetString ("Unsafe asterisk operator (*)"), @"unsafe class ClassDeclaration { - public void TestMethod () - { - int a = *x; - } -}"); - AddOption (whiteSpaceOptions, category, "SpaceAroundUnsafeArrowOperator", GettextCatalog.GetString ("Unsafe arrow operator (->)"), @"unsafe class ClassDeclaration { - public void TestMethod () - { - x->Foo(); - } -}"); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("Conditional Operator (?:)"), condOpExample); - AddOption (whiteSpaceOptions, category, "ConditionalOperatorBeforeConditionSpace", GettextCatalog.GetString ("before '?'"), condOpExample); - AddOption (whiteSpaceOptions, category, "ConditionalOperatorAfterConditionSpace", GettextCatalog.GetString ("after '?'"), condOpExample); - AddOption (whiteSpaceOptions, category, "ConditionalOperatorBeforeSeparatorSpace", GettextCatalog.GetString ("before ':'"), condOpExample); - AddOption (whiteSpaceOptions, category, "ConditionalOperatorAfterSeparatorSpace", GettextCatalog.GetString ("after ':'"), condOpExample); - - example = @"class ClassDeclaration { - string[][] field; - int[] test; - }"; - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("Array Declarations"), example); - AddOption (whiteSpaceOptions, category, "SpacesBeforeArrayDeclarationBrackets", GettextCatalog.GetString ("before opening bracket"), example); - - category = AddOption (whiteSpaceOptions, upperCategory, null, GettextCatalog.GetString ("Other"), example); - AddOption (whiteSpaceOptions, category, "SpaceBeforeSemicolon", GettextCatalog.GetString ("before semicolon"), example); - - /* - whiteSpaceOptions= new ListStore (typeof (Option), typeof (bool), typeof (bool)); - column = new TreeViewColumn (); - // text column - column.PackStart (cellRendererText, true); - column.SetCellDataFunc (cellRendererText, delegate (TreeViewColumn col, CellRenderer cell, TreeModel model, TreeIter iter) { - ((CellRendererText)cell).Text = ((Option)model.GetValue (iter, 0)).DisplayName; - }); - treeviewInsertWhiteSpaceOptions.AppendColumn (column); - - column = new TreeViewColumn (); - cellRendererCombo = new CellRendererCombo (); - cellRendererCombo.Ypad = 1; - cellRendererCombo.Mode = CellRendererMode.Editable; - cellRendererCombo.TextColumn = 1; - cellRendererCombo.Model = comboBoxStore; - cellRendererCombo.HasEntry = false; - cellRendererCombo.Editable = !profile.IsBuiltIn; - - cellRendererCombo.Edited += delegate(object o, EditedArgs args) { - TreeIter iter; - var model = whiteSpaceOptions; - if (model.GetIterFromString (out iter, args.Path)) { - var option = (Option)model.GetValue (iter, 0); - PropertyInfo info = GetPropertyByName (option.PropertyName); - if (info == null) - return; - var value = Enum.Parse (info.PropertyType, args.NewText); - info.SetValue (profile, value, null); - UpdateExample (texteditor.Document.Text); - } - }; - - column.PackStart (cellRendererCombo, false); - column.SetAttributes (cellRendererCombo, "visible", 2); - column.SetCellDataFunc (cellRendererCombo, delegate (TreeViewColumn col, CellRenderer cell, TreeModel model, TreeIter iter) { - ((CellRendererCombo)cell).Text = GetValue (((Option)model.GetValue (iter, 0)).PropertyName).ToString (); - }); - - cellRendererToggle = new CellRendererToggle (); - cellRendererToggle.Activatable = !profile.IsBuiltIn; - cellRendererToggle.Ypad = 1; - cellRendererToggle.Toggled += delegate(object o, ToggledArgs args) { - TreeIter iter; - var model = whiteSpaceOptions; - if (model.GetIterFromString (out iter, args.Path)) { - var option = (Option)model.GetValue (iter, 0); - PropertyInfo info = GetPropertyByName (option.PropertyName); - if (info == null || info.PropertyType != typeof(bool)) - return; - bool value = (bool)info.GetValue (this.profile, null); - info.SetValue (profile, !value, null); - UpdateExample (texteditor.Document.Text); - } - }; - - column.PackStart (cellRendererToggle, false); - column.SetAttributes (cellRendererToggle, "visible", 1); - column.SetCellDataFunc (cellRendererToggle, delegate (TreeViewColumn col, CellRenderer cell, TreeModel model, TreeIter iter) { - ((CellRendererToggle)cell).Active = (bool)GetValue (((Option)model.GetValue (iter, 0)).PropertyName); - }); - - treeviewInsertWhiteSpaceOptions.AppendColumn (column); - - treeviewInsertWhiteSpaceOptions.Model = whiteSpaceOptions;*/ - treeviewInsertWhiteSpaceCategory.ExpandAll (); - #endregion - - #region Blank line options - entryBeforUsings.Text = profile.BlankLinesBeforeUsings.ToString (); - entryAfterUsings.Text = profile.BlankLinesAfterUsings.ToString (); - - entryBeforeFirstDeclaration.Text = profile.BlankLinesBeforeFirstDeclaration.ToString (); - entryBetweenTypes.Text = profile.BlankLinesBetweenTypes.ToString (); - - entryBetweenFields.Text = profile.BlankLinesBetweenFields.ToString (); - entryBetweenEvents.Text = profile.BlankLinesBetweenEventFields.ToString (); - entryBetweenMembers.Text = profile.BlankLinesBetweenMembers.ToString (); - entryInsideRegion.Text = profile.BlankLinesInsideRegion.ToString (); - entryAroundRegion.Text = profile.BlankLinesAroundRegion.ToString (); - - entryBeforUsings.Changed += HandleEntryBeforUsingsChanged; - entryAfterUsings.Changed += HandleEntryBeforUsingsChanged; - entryBeforeFirstDeclaration.Changed += HandleEntryBeforUsingsChanged; - entryBetweenTypes.Changed += HandleEntryBeforUsingsChanged; - entryBetweenFields.Changed += HandleEntryBeforUsingsChanged; - entryBetweenEvents.Changed += HandleEntryBeforUsingsChanged; - entryBetweenMembers.Changed += HandleEntryBeforUsingsChanged; - entryAroundRegion.Changed += HandleEntryBeforUsingsChanged; - entryInsideRegion.Changed += HandleEntryBeforUsingsChanged; - #endregion - } - - static int SetFlag (Entry entry, int oldValue) - { - int newValue; - return int.TryParse (entry.Text, out newValue) ? newValue : oldValue; - } - - void HandleEntryBeforUsingsChanged (object sender, EventArgs e) - { - profile.BlankLinesBeforeUsings = SetFlag (entryBeforUsings, profile.BlankLinesBeforeUsings); - profile.BlankLinesAfterUsings = SetFlag (entryAfterUsings, profile.BlankLinesAfterUsings); - profile.BlankLinesBeforeFirstDeclaration = SetFlag (entryBeforeFirstDeclaration, profile.BlankLinesBeforeFirstDeclaration); - profile.BlankLinesBetweenTypes = SetFlag (entryBetweenTypes, profile.BlankLinesBetweenTypes); - profile.BlankLinesBetweenFields = SetFlag (entryBetweenFields, profile.BlankLinesBetweenFields); - profile.BlankLinesBetweenMembers = SetFlag (entryBetweenMembers, profile.BlankLinesBetweenMembers); - profile.BlankLinesBetweenEventFields = SetFlag (entryBetweenEvents, profile.BlankLinesBetweenMembers); - profile.BlankLinesAroundRegion = SetFlag (entryAroundRegion, profile.BlankLinesAroundRegion); - profile.BlankLinesInsideRegion = SetFlag (entryInsideRegion, profile.BlankLinesInsideRegion); - UpdateExample (blankLineExample); - } - - static PropertyInfo GetPropertyByName (string name) - { - PropertyInfo info = typeof(PlayScriptFormattingPolicy).GetProperty (name); - if (info == null) - throw new Exception (name + " property not found"); - return info; - } - - - static TreeIter AddOption (TreeStore model, string propertyName, string displayName, string example) - { - bool isBool = false; - if (!string.IsNullOrEmpty (propertyName)) { - PropertyInfo info = GetPropertyByName (propertyName); - isBool = info.PropertyType == typeof (bool); - } - - return model.AppendValues (propertyName, displayName, example, !string.IsNullOrEmpty (propertyName) && isBool, !string.IsNullOrEmpty (propertyName) && !isBool); - } - - static TreeIter AddOption (TreeStore model, TreeIter parent, string propertyName, string displayName, string example) - { - bool isBool = false; - if (!string.IsNullOrEmpty (propertyName)) { - PropertyInfo info = GetPropertyByName (propertyName); - isBool = info.PropertyType == typeof (bool); - } - - return model.AppendValues (parent, propertyName, displayName, example, !string.IsNullOrEmpty (propertyName) && isBool, !string.IsNullOrEmpty (propertyName) && !isBool); - } - - void TreeSelectionChanged (object sender, EventArgs e) - { - var treeSelection = (TreeSelection)sender; - TreeModel model; - TreeIter iter; - if (treeSelection.GetSelected (out model, out iter)) { - var info = GetProperty (model, iter); - if (info != null && info.PropertyType != typeof (bool)) { - ComboBoxStore.Clear (); - foreach (var v in Enum.GetValues (info.PropertyType)) { - ComboBoxStore.AppendValues (v.ToString (), TranslateValue (v)); - } - } - - UpdateExample (model, iter); - } - } - - - void UpdateExample (TreeModel model, TreeIter iter) - { - string example = (string)model.GetValue (iter, exampleTextColumn); - UpdateExample (example); - } - - void UpdateExample (string example) - { - string text; - if (!string.IsNullOrEmpty (example)) { - text = Environment.NewLine != "\n" ? example.Replace ("\n", Environment.NewLine) : example; - } else { - text = ""; - } - texteditor.Document.Text = CSharpFormatter.FormatText (profile, null, CSharpFormatter.MimeType, text, 0, text.Length); - } - - static PropertyInfo GetProperty (TreeModel model, TreeIter iter) - { - string propertyName = (string)model.GetValue (iter, propertyColumn); - if (string.IsNullOrEmpty (propertyName)) - return null; - return GetPropertyByName (propertyName); - } - - object GetValue (string propertyName) - { - var info = GetPropertyByName (propertyName); - return info.GetValue (profile, null); - } - - static void RenderIcon (TreeViewColumn col, CellRenderer cell, TreeModel model, TreeIter iter) - { - var pixbufCellRenderer = (CellRendererImage)cell; - if (model.IterHasChild (iter)) { - pixbufCellRenderer.Image = ImageService.GetIcon (((TreeView)col.TreeView).GetRowExpanded (model.GetPath (iter)) ? MonoDevelop.Ide.Gui.Stock.OpenFolder : MonoDevelop.Ide.Gui.Stock.ClosedFolder, IconSize.Menu); - } else { - pixbufCellRenderer.Image = ImageService.GetIcon (MonoDevelop.Ide.Gui.Stock.Property, IconSize.Menu); - } - } - - void ComboboxDataFunc (TreeViewColumn col, CellRenderer cell, TreeModel model, TreeIter iter) - { - var cellRenderer = (CellRendererCombo)cell; - var info = GetProperty (model, iter); - if (info == null) { - cellRenderer.Text = ""; - return; - } - object value = info.GetValue (profile, null); - - cellRenderer.Text = value is Enum ? TranslateValue (value) : value.ToString (); - } - - void ToggleDataFunc (TreeViewColumn col, CellRenderer cell, TreeModel model, TreeIter iter) - { - var cellRenderer = (CellRendererToggle)cell; - var info = GetProperty (model, iter); - if (info == null || info.PropertyType != typeof(bool)) - return; - bool value = (bool)info.GetValue (profile, null); - cellRenderer.Active = value; - } - - class CellRendererToggledHandler - { - readonly CSharpFormattingProfileDialog dialog; - readonly TreeStore model; - readonly TreeView treeView; - - public CellRendererToggledHandler (CSharpFormattingProfileDialog dialog, TreeView treeView, TreeStore model) - { - this.dialog = dialog; - this.model = model; - this.treeView = treeView; - } - - public void Toggled (object o, ToggledArgs args) - { - TreeIter iter; - if (model.GetIterFromString (out iter, args.Path)) { - var info = GetProperty (model, iter); - if (info == null || info.PropertyType != typeof(bool)) - return; - bool value = (bool)info.GetValue (dialog.profile, null); - info.SetValue (dialog.profile, !value, null); - dialog.UpdateExample (model, iter); - // When toggeling with the keyboard the tree view doesn't update automatically - // see 'Bug 188 - Pressing space to select does not update checkbox' - treeView.QueueDraw (); - } - } - } - - class ComboboxEditedHandler - { - readonly CSharpFormattingProfileDialog dialog; - readonly TreeStore model; - - public ComboboxEditedHandler (CSharpFormattingProfileDialog dialog, TreeStore model) - { - this.dialog = dialog; - this.model = model; - } - - public void ComboboxEdited (object o, EditedArgs args) - { - TreeIter iter; - if (model.GetIterFromString (out iter, args.Path)) { - var info = GetProperty (model, iter); - if (info == null) - return; - var value = ConvertProperty (info.PropertyType, args.NewText); - info.SetValue (dialog.profile, value, null); - dialog.UpdateExample (model, iter); - } - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpIndentVirtualSpaceManager.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpIndentVirtualSpaceManager.cs deleted file mode 100644 index 2d6f371..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpIndentVirtualSpaceManager.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -// CSharpIndentVirtualSpaceManager.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using Mono.TextEditor; -using System; -using MonoDevelop.Core; -using ICSharpCode.NRefactory.PlayScript; - -namespace MonoDevelop.PlayScript.Formatting -{ - class IndentVirtualSpaceManager : IIndentationTracker - { - readonly TextEditorData data; - readonly CacheIndentEngine stateTracker; - - public IndentVirtualSpaceManager(TextEditorData data, CacheIndentEngine stateTracker) - { - this.data = data; - this.stateTracker = stateTracker; - } - - string GetIndentationString (DocumentLocation loc) - { - var line = data.Document.GetLine (loc.Line); - if (line == null) - return ""; - // Get context to the end of the line w/o changing the main engine's state - var offset = line.Offset; - string curIndent = line.GetIndentation (data.Document); - try { - stateTracker.Update (Math.Min (data.Length, offset + Math.Min (line.Length, loc.Column - 1))); - int nlwsp = curIndent.Length; - if (!stateTracker.LineBeganInsideMultiLineComment || (nlwsp < line.LengthIncludingDelimiter && data.Document.GetCharAt (offset + nlwsp) == '*')) - return stateTracker.ThisLineIndent; - } catch (Exception e) { - LoggingService.LogError ("Error while indenting at "+ loc, e); - } - return curIndent; - } - - public string GetIndentationString (int lineNumber, int column) - { - return GetIndentationString (new DocumentLocation (lineNumber, column)); - } - - public string GetIndentationString (int offset) - { - return GetIndentationString (data.OffsetToLocation (offset)); - } - - public int GetVirtualIndentationColumn (int offset) - { - return 1 + GetIndentationString (offset).Length; - } - - public int GetVirtualIndentationColumn (int lineNumber, int column) - { - return 1 + GetIndentationString (lineNumber, column).Length; - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpTextEditorIndentation.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpTextEditorIndentation.cs deleted file mode 100644 index fbb3279..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/CSharpTextEditorIndentation.cs +++ /dev/null @@ -1,834 +0,0 @@ -// -// CSharpTextEditorIndentation.cs -// -// Author: -// Mike Krüger -// -// Copyright (C) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// -using System; -using System.Collections.Generic; -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui.Content; -using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.PlayScript.Formatting; -using MonoDevelop.PlayScript.Refactoring; -using Mono.TextEditor; -using MonoDevelop.Ide.CodeTemplates; -using MonoDevelop.SourceEditor; -using System.Linq; -using System.Text; -using MonoDevelop.Ide; -using ICSharpCode.NRefactory; -using ICSharpCode.NRefactory.Editor; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.PlayScript.Completion; - -namespace MonoDevelop.PlayScript.Formatting -{ - class CSharpTextEditorIndentation : TextEditorExtension - { - CacheIndentEngine stateTracker; - int cursorPositionBeforeKeyPress; - - TextEditorData textEditorData { - get { - return document.Editor; - } - } - - readonly IEnumerable types = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); - - PlayScriptFormattingPolicy Policy { - get { - if (Document != null && Document.Project != null && Document.Project.Policies != null) { - return Document.Project.Policies.Get (types); - } - return MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy (types); - } - } - - TextStylePolicy TextStylePolicy { - get { - if (Document != null && Document.Project != null && Document.Project.Policies != null) { - return Document.Project.Policies.Get (types); - } - return MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy (types); - } - } - - char lastCharInserted; - - static CSharpTextEditorIndentation () - { - CompletionWindowManager.WordCompleted += delegate(object sender, CodeCompletionContextEventArgs e) { - var editor = e.Widget as IExtensibleTextEditor; - if (editor == null) - return; - var textEditorExtension = editor.Extension; - while (textEditorExtension != null && !(textEditorExtension is CSharpTextEditorIndentation)) { - textEditorExtension = textEditorExtension.Next; - } - var extension = textEditorExtension as CSharpTextEditorIndentation; - if (extension == null) - return; - extension.SafeUpdateIndentEngine (extension.textEditorData.Caret.Offset); - if (extension.stateTracker.NeedsReindent) - extension.DoReSmartIndent (); - }; - } - - internal void SafeUpdateIndentEngine (int offset) - { - try { - stateTracker.Update (offset); - } catch (Exception e) { - LoggingService.LogError ("Error while updating the indentation engine", e); - } - } - - void HandleTextPaste (int insertionOffset, string text, int insertedChars) - { - if (document.Editor.Options.IndentStyle == IndentStyle.None || - document.Editor.Options.IndentStyle == IndentStyle.Auto) - return; - - // Just correct the start line of the paste operation - the text is already indented. - var curLine = Editor.GetLineByOffset (insertionOffset); - var curLineOffset = curLine.Offset; - SafeUpdateIndentEngine (curLineOffset); - if (!stateTracker.IsInsideOrdinaryCommentOrString) { - int pos = curLineOffset; - string curIndent = curLine.GetIndentation (textEditorData.Document); - int nlwsp = curIndent.Length; - - if (!stateTracker.LineBeganInsideMultiLineComment || (nlwsp < curLine.LengthIncludingDelimiter && textEditorData.Document.GetCharAt (curLineOffset + nlwsp) == '*')) { - // Possibly replace the indent - SafeUpdateIndentEngine (curLineOffset + curLine.Length); - string newIndent = stateTracker.ThisLineIndent; - if (newIndent != curIndent) { - if (CompletionWindowManager.IsVisible) { - if (pos < CompletionWindowManager.CodeCompletionContext.TriggerOffset) - CompletionWindowManager.CodeCompletionContext.TriggerOffset -= nlwsp; - } - textEditorData.Replace (pos, nlwsp, newIndent); - textEditorData.Document.CommitLineUpdate (textEditorData.Caret.Line); - } - } - } - textEditorData.FixVirtualIndentation (); - } - - public static bool OnTheFlyFormatting { - get { - return PropertyService.Get ("OnTheFlyFormatting", true); - } - set { - PropertyService.Set ("OnTheFlyFormatting", value); - } - } - - void RunFormatter (DocumentLocation location) - { - if (OnTheFlyFormatting && textEditorData != null && !(textEditorData.CurrentMode is TextLinkEditMode) && !(textEditorData.CurrentMode is InsertionCursorEditMode)) { - OnTheFlyFormatter.Format (Document, location); - } - } - - public override void Initialize () - { - base.Initialize (); - - - if (textEditorData != null) { - textEditorData.Options.Changed += HandleTextOptionsChanged; - HandleTextOptionsChanged (this, EventArgs.Empty); - textEditorData.Document.TextReplacing += HandleTextReplacing; - textEditorData.Document.TextReplaced += HandleTextReplaced; - textEditorData.Paste += HandleTextPaste; - } - if (IdeApp.Workspace != null) - IdeApp.Workspace.ActiveConfigurationChanged += HandleTextOptionsChanged; - } - - bool indentationDisabled; - - void HandleTextOptionsChanged (object sender, EventArgs e) - { - var policy = Policy.CreateOptions (); - var options = Editor.CreateNRefactoryTextEditorOptions (); - options.IndentBlankLines = true; - IStateMachineIndentEngine indentEngine; - try { - var csharpIndentEngine = new CSharpIndentEngine (textEditorData.Document, options, policy); - //csharpIndentEngine.EnableCustomIndentLevels = true; - foreach (var symbol in MonoDevelop.PlayScript.Highlighting.CSharpSyntaxMode.GetDefinedSymbols (document.Project)) { - csharpIndentEngine.DefineSymbol (symbol); - } - indentEngine = csharpIndentEngine; - } catch (Exception ex) { - LoggingService.LogError ("Error while creating the c# indentation engine", ex); - indentEngine = new NullIStateMachineIndentEngine (textEditorData.Document); - } - stateTracker = new CacheIndentEngine (indentEngine); - if (DefaultSourceEditorOptions.Instance.IndentStyle == IndentStyle.Auto) { - textEditorData.IndentationTracker = new DefaultIndentationTracker (textEditorData.Document); - } else { - textEditorData.IndentationTracker = new IndentVirtualSpaceManager (textEditorData, stateTracker); - } - - indentationDisabled = DefaultSourceEditorOptions.Instance.IndentStyle == IndentStyle.Auto || DefaultSourceEditorOptions.Instance.IndentStyle == IndentStyle.None; - if (indentationDisabled) { - textEditorData.TextPasteHandler = null; - } else { - textEditorData.TextPasteHandler = new TextPasteIndentEngine (stateTracker, options, policy); - } - } - - public override void Dispose () - { - if (textEditorData != null) { - textEditorData.TextPasteHandler = null; - textEditorData.Paste -= HandleTextPaste; - textEditorData.Options.Changed -= HandleTextOptionsChanged; - textEditorData.IndentationTracker = null; - textEditorData.Document.TextReplacing -= HandleTextReplacing; - textEditorData.Document.TextReplaced -= HandleTextReplaced; - } - IdeApp.Workspace.ActiveConfigurationChanged -= HandleTextOptionsChanged; - stateTracker = null; - base.Dispose (); - } - - bool? wasInVerbatimString; - - void HandleTextReplaced (object sender, DocumentChangeEventArgs e) - { - stateTracker.ResetEngineToPosition (e.Offset); - if (wasInVerbatimString == null) - return; - if (e.RemovalLength != 1 || textEditorData.Document.CurrentAtomicUndoOperationType == OperationType.Format) - return; - SafeUpdateIndentEngine (Math.Min (textEditorData.Document.TextLength, e.Offset + e.InsertionLength + 1)); - if (wasInVerbatimString == true && !stateTracker.IsInsideVerbatimString) { - textEditorData.Document.TextReplacing -= HandleTextReplacing; - textEditorData.Document.TextReplaced -= HandleTextReplaced; - ConvertVerbatimStringToNormal (textEditorData, e.Offset + e.InsertionLength + 1); - textEditorData.Document.TextReplacing += HandleTextReplacing; - textEditorData.Document.TextReplaced += HandleTextReplaced; - } - } - - void HandleTextReplacing (object sender, DocumentChangeEventArgs e) - { - wasInVerbatimString = null; - var o = e.Offset + e.RemovalLength; - if (o < 0 || o + 1 > textEditorData.Length || e.RemovalLength != 1 || textEditorData.Document.IsInUndo) { - return; - } - if (textEditorData.GetCharAt (o) != '"') - return; - SafeUpdateIndentEngine (o + 1); - wasInVerbatimString = stateTracker.IsInsideVerbatimString; - } - - internal static string ConvertToStringLiteral (string text) - { - var result = new StringBuilder (); - foreach (var ch in text) { - switch (ch) { - case '\t': - result.Append ("\\t"); - break; - case '"': - result.Append ("\\\""); - break; - case '\n': - result.Append ("\\n"); - break; - case '\r': - result.Append ("\\r"); - break; - case '\\': - result.Append ("\\\\"); - break; - default: - result.Append (ch); - break; - } - } - return result.ToString (); - } - - static void ConvertNormalToVerbatimString (TextEditorData textEditorData, int offset) - { - var endOffset = offset; - while (endOffset < textEditorData.Length) { - char ch = textEditorData.GetCharAt (endOffset); - if (ch == '\\') { - if (endOffset + 1 < textEditorData.Length && NewLine.IsNewLine (textEditorData.GetCharAt (endOffset + 1))) - return; - - endOffset += 2; - continue; - } - if (ch == '"') - break; - if (NewLine.IsNewLine (ch)) - return; - endOffset++; - } - if (offset > endOffset || endOffset == textEditorData.Length) - return; - var plainText = TextPasteUtils.StringLiteralPasteStrategy.Instance.Decode (textEditorData.GetTextAt (offset, endOffset - offset)); - var newText = TextPasteUtils.VerbatimStringStrategy.Encode (plainText); - textEditorData.Replace (offset, endOffset - offset, newText); - } - - static void ConvertVerbatimStringToNormal (TextEditorData textEditorData, int offset) - { - var endOffset = offset; - while (endOffset < textEditorData.Length) { - char ch = textEditorData.GetCharAt (endOffset); - if (ch == '"' && (endOffset + 1 < textEditorData.Length && textEditorData.GetCharAt (endOffset + 1) == '"')) { - endOffset += 2; - continue; - } - if (ch == '"') { - break; - } - endOffset++; - } - var plainText = TextPasteUtils.VerbatimStringStrategy.Decode (textEditorData.GetTextAt (offset, endOffset - offset)); - var newText = TextPasteUtils.StringLiteralPasteStrategy.Instance.Encode (plainText); - textEditorData.Replace (offset, endOffset - offset, newText); - } - - internal IStateMachineIndentEngine StateTracker { get { return stateTracker; } } - - public bool DoInsertTemplate () - { - string word = CodeTemplate.GetWordBeforeCaret (textEditorData); - foreach (CodeTemplate template in CodeTemplateService.GetCodeTemplates (CSharpFormatter.MimeType)) { - if (template.Shortcut == word) - return true; - } - return false; - } - - int lastInsertedSemicolon = -1; - - void CheckXmlCommentCloseTag (char keyChar) - { - if (keyChar == '>' && stateTracker.IsInsideDocLineComment) { - var location = Editor.Caret.Location; - string lineText = Editor.GetLineText (Editor.Caret.Line); - int startIndex = Math.Min (location.Column - 2, lineText.Length - 1); - while (startIndex >= 0 && lineText [startIndex] != '<') { - --startIndex; - if (lineText [startIndex] == '/') { - // already closed. - startIndex = -1; - break; - } - } - if (startIndex >= 0) { - int endIndex = startIndex + 1; - while (endIndex <= location.Column - 1 && endIndex < lineText.Length && Char.IsLetter (lineText [endIndex])) { - endIndex++; - } - string tag = endIndex - startIndex > 0 ? lineText.Substring (startIndex + 1, endIndex - startIndex - 1) : null; - if (!string.IsNullOrEmpty (tag) && CSharpCompletionEngine.CommentTags.Any (t => t == tag)) { - Editor.Document.Insert (Editor.Caret.Offset, "", AnchorMovementType.BeforeInsertion); - } - } - } - } - - internal void ReindentOnTab () - { - int cursor = textEditorData.Caret.Offset; - if (stateTracker.IsInsideVerbatimString && cursor > 0 && cursor < textEditorData.Document.TextLength && textEditorData.GetCharAt (cursor - 1) == '"') - SafeUpdateIndentEngine (cursor + 1); - if (stateTracker.IsInsideVerbatimString) { - // insert normal tab inside @" ... " - if (textEditorData.IsSomethingSelected) { - textEditorData.SelectedText = "\t"; - } - else { - textEditorData.Insert (cursor, "\t"); - } - textEditorData.Document.CommitLineUpdate (textEditorData.Caret.Line); - } - else if (cursor >= 1) { - if (textEditorData.Caret.Column > 1) { - int delta = cursor - cursorPositionBeforeKeyPress; - if (delta < 2 && delta > 0) { - textEditorData.Remove (cursor - delta, delta); - textEditorData.Caret.Offset = cursor - delta; - textEditorData.Document.CommitLineUpdate (textEditorData.Caret.Line); - } - } - SafeUpdateIndentEngine (textEditorData.Caret.Offset); - DoReSmartIndent (); - } - } - - public override bool KeyPress (Gdk.Key key, char keyChar, Gdk.ModifierType modifier) - { - bool skipFormatting = StateTracker.IsInsideOrdinaryCommentOrString || - StateTracker.IsInsidePreprocessorDirective; - - cursorPositionBeforeKeyPress = textEditorData.Caret.Offset; - bool isSomethingSelected = textEditorData.IsSomethingSelected; - if (key == Gdk.Key.BackSpace && textEditorData.Caret.Offset == lastInsertedSemicolon) { - textEditorData.Document.Undo (); - lastInsertedSemicolon = -1; - return false; - } - lastInsertedSemicolon = -1; - if (keyChar == ';' && !(textEditorData.CurrentMode is TextLinkEditMode) && !DoInsertTemplate () && !isSomethingSelected && PropertyService.Get ( - "SmartSemicolonPlacement", - false - ) && !(stateTracker.IsInsideComment || stateTracker.IsInsideString)) { - bool retval = base.KeyPress (key, keyChar, modifier); - DocumentLine curLine = textEditorData.Document.GetLine (textEditorData.Caret.Line); - string text = textEditorData.Document.GetTextAt (curLine); - if (!(text.EndsWith (";", StringComparison.Ordinal) || text.Trim ().StartsWith ("for", StringComparison.Ordinal))) { - int guessedOffset; - - if (GuessSemicolonInsertionOffset (textEditorData, curLine, textEditorData.Caret.Offset, out guessedOffset)) { - using (var undo = textEditorData.OpenUndoGroup ()) { - textEditorData.Remove (textEditorData.Caret.Offset - 1, 1); - textEditorData.Caret.Offset = guessedOffset; - lastInsertedSemicolon = textEditorData.Caret.Offset + 1; - retval = base.KeyPress (key, keyChar, modifier); - } - } - } - using (var undo = textEditorData.OpenUndoGroup ()) { - if (OnTheFlyFormatting && textEditorData != null && !(textEditorData.CurrentMode is TextLinkEditMode) && !(textEditorData.CurrentMode is InsertionCursorEditMode)) { - OnTheFlyFormatter.FormatStatmentAt (Document, textEditorData.Caret.Location); - } - } - return retval; - } - - if (key == Gdk.Key.Tab) { - SafeUpdateIndentEngine (textEditorData.Caret.Offset); - if (stateTracker.IsInsideStringLiteral && !textEditorData.IsSomethingSelected) { - var lexer = new CSharpCompletionEngineBase.MiniLexer (textEditorData.Document.GetTextAt (0, textEditorData.Caret.Offset)); - lexer.Parse (); - if (lexer.IsInString) { - textEditorData.InsertAtCaret ("\\t"); - return false; - } - } - } - - - if (key == Gdk.Key.Tab && DefaultSourceEditorOptions.Instance.TabIsReindent && !CompletionWindowManager.IsVisible && !(textEditorData.CurrentMode is TextLinkEditMode) && !DoInsertTemplate () && !isSomethingSelected) { - ReindentOnTab (); - - return false; - } - - SafeUpdateIndentEngine (textEditorData.Caret.Offset); - if (!stateTracker.IsInsideOrdinaryCommentOrString) { - if (keyChar == '@') { - var retval = base.KeyPress (key, keyChar, modifier); - int cursor = textEditorData.Caret.Offset; - if (cursor < textEditorData.Length && textEditorData.GetCharAt (cursor) == '"') - ConvertNormalToVerbatimString (textEditorData, cursor + 1); - return retval; - } - } - - - //do the smart indent - if (!indentationDisabled) { - bool retval; - //capture some of the current state - int oldBufLen = textEditorData.Length; - int oldLine = textEditorData.Caret.Line + 1; - bool reIndent = false; - - //pass through to the base class, which actually inserts the character - //and calls HandleCodeCompletion etc to handles completion - using (var undo = textEditorData.OpenUndoGroup ()) { - DoPreInsertionSmartIndent (key); - } - wasInStringLiteral = stateTracker.IsInsideStringLiteral; - bool automaticReindent; - // need to be outside of an undo group - otherwise it interferes with other text editor extension - // esp. the documentation insertion undo steps. - retval = base.KeyPress (key, keyChar, modifier); - //handle inserted characters - if (textEditorData.Caret.Offset <= 0 || textEditorData.IsSomethingSelected) - return retval; - - lastCharInserted = TranslateKeyCharForIndenter (key, keyChar, textEditorData.GetCharAt (textEditorData.Caret.Offset - 1)); - if (lastCharInserted == '\0') - return retval; - using (var undo = textEditorData.OpenUndoGroup ()) { - SafeUpdateIndentEngine (textEditorData.Caret.Offset); - - if (key == Gdk.Key.Return && modifier == Gdk.ModifierType.ControlMask) { - FixLineStart (textEditorData, stateTracker, textEditorData.Caret.Line + 1); - } else { - if (!(oldLine == textEditorData.Caret.Line + 1 && lastCharInserted == '\n') && (oldBufLen != textEditorData.Length || lastCharInserted != '\0')) { - DoPostInsertionSmartIndent (lastCharInserted, out reIndent); - } else { - reIndent = lastCharInserted == '\n'; - } - } - //reindent the line after the insertion, if needed - //N.B. if the engine says we need to reindent, make sure that it's because a char was - //inserted rather than just updating the stack due to moving around - - SafeUpdateIndentEngine (textEditorData.Caret.Offset); - // Automatically reindent in text link mode will cause the mode exiting, therefore we need to prevent that. - automaticReindent = (stateTracker.NeedsReindent && lastCharInserted != '\0') && !(textEditorData.CurrentMode is TextLinkEditMode); - if (key == Gdk.Key.Return && (reIndent || automaticReindent)) { - if (textEditorData.Options.IndentStyle == IndentStyle.Virtual) { - if (textEditorData.GetLine (textEditorData.Caret.Line).Length == 0) - textEditorData.Caret.Column = textEditorData.IndentationTracker.GetVirtualIndentationColumn (textEditorData.Caret.Location); - } else { - DoReSmartIndent (); - } - } - } - const string reindentChars = ";){}"; - if (reIndent || key != Gdk.Key.Return && key != Gdk.Key.Tab && automaticReindent && reindentChars.Contains (keyChar)) { - using (var undo = textEditorData.OpenUndoGroup ()) { - DoReSmartIndent (); - } - } - - if (!skipFormatting && !(stateTracker.IsInsideComment || stateTracker.IsInsideString)) { - if (keyChar == ';' || keyChar == '}') { - using (var undo = textEditorData.OpenUndoGroup ()) { - if (OnTheFlyFormatting && textEditorData != null && !(textEditorData.CurrentMode is TextLinkEditMode) && !(textEditorData.CurrentMode is InsertionCursorEditMode)) { - OnTheFlyFormatter.FormatStatmentAt (Document, textEditorData.Caret.Location); - } - } - } - } - - SafeUpdateIndentEngine (textEditorData.Caret.Offset); - lastCharInserted = '\0'; - CheckXmlCommentCloseTag (keyChar); - return retval; - } - - if (textEditorData.Options.IndentStyle == IndentStyle.Auto && DefaultSourceEditorOptions.Instance.TabIsReindent && key == Gdk.Key.Tab) { - bool retval = base.KeyPress (key, keyChar, modifier); - DoReSmartIndent (); - CheckXmlCommentCloseTag (keyChar); - return retval; - } - - //pass through to the base class, which actually inserts the character - //and calls HandleCodeCompletion etc to handles completion - var result = base.KeyPress (key, keyChar, modifier); - - if (!indentationDisabled && (key == Gdk.Key.Return || key == Gdk.Key.KP_Enter)) { - DoReSmartIndent (); - } - - CheckXmlCommentCloseTag (keyChar); - - if (!skipFormatting && keyChar == '}') - RunFormatter (new DocumentLocation (textEditorData.Caret.Location.Line, textEditorData.Caret.Location.Column)); - return result; - } - - static bool IsSemicolonalreadyPlaced (TextEditorData data, int caretOffset) - { - for (int pos2 = caretOffset - 1; pos2-- > 0;) { - var ch2 = data.Document.GetCharAt (pos2); - if (ch2 == ';') { - return true; - } - if (!char.IsWhiteSpace (ch2)) - return false; - } - return false; - } - - public static bool GuessSemicolonInsertionOffset (TextEditorData data, ISegment curLine, int caretOffset, out int outOffset) - { - int lastNonWsOffset = caretOffset; - char lastNonWsChar = '\0'; - outOffset = caretOffset; - - int max = curLine.EndOffset; - - int end = caretOffset; - while (end > 1 && char.IsWhiteSpace (data.GetCharAt (end))) - end--; - int end2 = end; - while (end2 > 1 && char.IsLetter (data.GetCharAt (end2 - 1))) - end2--; - if (end != end2) { - string token = data.GetTextBetween (end2, end + 1); - // guess property context - if (token == "get" || token == "set") - return false; - } - - var offset = curLine.Offset; - string lineText = data.GetTextAt (caretOffset, max - caretOffset); - var lexer = new CSharpCompletionEngineBase.MiniLexer (lineText); - lexer.Parse ((ch, i) => { - if (lexer.IsInSingleComment || lexer.IsInMultiLineComment) - return true; - if (ch == '}' && lexer.IsFistNonWs && !IsSemicolonalreadyPlaced (data, caretOffset)) { - lastNonWsChar = ';'; - return true; - } - if (!char.IsWhiteSpace (ch)) { - lastNonWsOffset = caretOffset + i; - lastNonWsChar = ch; - } - return false; - }); - // if the line ends with ';' the line end is not the correct place for a new semicolon. - if (lastNonWsChar == ';') - return false; - outOffset = lastNonWsOffset; - return true; - } - - static char TranslateKeyCharForIndenter (Gdk.Key key, char keyChar, char docChar) - { - switch (key) { - case Gdk.Key.Return: - case Gdk.Key.KP_Enter: - return '\n'; - case Gdk.Key.Tab: - return '\t'; - default: - if (docChar == keyChar) - return keyChar; - break; - } - return '\0'; - } - // removes "\s*\+\s*" patterns (used for special behaviour inside strings) - void HandleStringConcatinationDeletion (int start, int end) - { - if (start < 0 || end >= textEditorData.Length || textEditorData.IsSomethingSelected) - return; - char ch = textEditorData.GetCharAt (start); - if (ch == '"') { - int sgn = Math.Sign (end - start); - bool foundPlus = false; - for (int max = start + sgn; max != end && max >= 0 && max < textEditorData.Length; max += sgn) { - ch = textEditorData.GetCharAt (max); - if (Char.IsWhiteSpace (ch)) - continue; - if (ch == '+') { - if (foundPlus) - break; - foundPlus = true; - } else if (ch == '"') { - if (!foundPlus) - break; - if (sgn < 0) { - textEditorData.Remove (max, start - max); - textEditorData.Caret.Offset = max + 1; - } else { - textEditorData.Remove (start + sgn, max - start); - textEditorData.Caret.Offset = start; - } - break; - } else { - break; - } - } - } - } - - void DoPreInsertionSmartIndent (Gdk.Key key) - { - switch (key) { - case Gdk.Key.BackSpace: - SafeUpdateIndentEngine (textEditorData.Caret.Offset); - HandleStringConcatinationDeletion (textEditorData.Caret.Offset - 1, 0); - break; - case Gdk.Key.Delete: - SafeUpdateIndentEngine (textEditorData.Caret.Offset); - HandleStringConcatinationDeletion (textEditorData.Caret.Offset, textEditorData.Length); - break; - } - } - //special handling for certain characters just inserted , for comments etc - void DoPostInsertionSmartIndent (char charInserted, out bool reIndent) - { - SafeUpdateIndentEngine (textEditorData.Caret.Offset); - reIndent = false; - switch (charInserted) { - case '}': - case ';': - reIndent = true; - break; - case '\n': - if (FixLineStart (textEditorData, stateTracker, stateTracker.Location.Line)) - return; - //newline always reindents unless it's had special handling - reIndent = true; - break; - } - } - - internal bool wasInStringLiteral; - - public bool FixLineStart (TextEditorData textEditorData, IStateMachineIndentEngine stateTracker, int lineNumber) - { - if (lineNumber > DocumentLocation.MinLine) { - DocumentLine line = textEditorData.Document.GetLine (lineNumber); - if (line == null) - return false; - - DocumentLine prevLine = textEditorData.Document.GetLine (lineNumber - 1); - if (prevLine == null) - return false; - string trimmedPreviousLine = textEditorData.Document.GetTextAt (prevLine).TrimStart (); - - //xml doc comments - //check previous line was a doc comment - //check there's a following line? - if (trimmedPreviousLine.StartsWith ("///", StringComparison.Ordinal)) { - if (textEditorData.GetTextAt (line.Offset, line.Length).TrimStart ().StartsWith ("///", StringComparison.Ordinal)) - return false; - //check that the newline command actually inserted a newline - textEditorData.EnsureCaretIsNotVirtual (); - var nextLineSegment = textEditorData.Document.GetLine (lineNumber + 1); - string nextLine = nextLineSegment != null ? textEditorData.Document.GetTextAt (nextLineSegment).TrimStart () : ""; - - if (trimmedPreviousLine.Length > "///".Length || nextLine.StartsWith ("///", StringComparison.Ordinal)) { - var insertionPoint = textEditorData.Caret.Offset; - int inserted = textEditorData.Insert (insertionPoint, "/// "); - textEditorData.Caret.Offset = insertionPoint + inserted; - return true; - } - //multi-line comments - } else if (stateTracker.IsInsideMultiLineComment) { - if (textEditorData.GetTextAt (line.Offset, line.Length).TrimStart ().StartsWith ("*", StringComparison.Ordinal)) - return false; - textEditorData.EnsureCaretIsNotVirtual (); - string commentPrefix = string.Empty; - if (trimmedPreviousLine.StartsWith ("* ", StringComparison.Ordinal)) { - commentPrefix = "* "; - } else if (trimmedPreviousLine.StartsWith ("/**", StringComparison.Ordinal) || trimmedPreviousLine.StartsWith ("/*", StringComparison.Ordinal)) { - commentPrefix = " * "; - } else if (trimmedPreviousLine.StartsWith ("*", StringComparison.Ordinal)) { - commentPrefix = "*"; - } - - int indentSize = line.GetIndentation (textEditorData.Document).Length; - var insertedText = prevLine.GetIndentation (textEditorData.Document) + commentPrefix; - textEditorData.Replace (line.Offset, indentSize, insertedText); - textEditorData.Caret.Offset = line.Offset + insertedText.Length; - return true; - } else if (wasInStringLiteral) { - var lexer = new CSharpCompletionEngineBase.MiniLexer (textEditorData.Document.GetTextAt (0, prevLine.EndOffset).TrimEnd ()); - lexer.Parse (); - if (!lexer.IsInString) - return false; - textEditorData.EnsureCaretIsNotVirtual (); - textEditorData.Insert (prevLine.Offset + prevLine.Length, "\" +"); - - int indentSize = textEditorData.Caret.Offset - line.Offset; - var insertedText = prevLine.GetIndentation (textEditorData.Document) + (trimmedPreviousLine.StartsWith ("\"", StringComparison.Ordinal) ? "" : "\t") + "\""; - textEditorData.Replace (line.Offset, indentSize, insertedText); - return true; - } - } - return false; - } - //does re-indenting and cursor positioning - void DoReSmartIndent () - { - DoReSmartIndent (textEditorData.Caret.Offset); - } - - void DoReSmartIndent (int cursor) - { - SafeUpdateIndentEngine (cursor); - if (stateTracker.LineBeganInsideVerbatimString || stateTracker.LineBeganInsideMultiLineComment) - return; - if (DefaultSourceEditorOptions.Instance.IndentStyle == IndentStyle.Auto) { - textEditorData.FixVirtualIndentation (); - return; - } - var line = textEditorData.Document.GetLineByOffset (cursor); - - // Get context to the end of the line w/o changing the main engine's state - var curTracker = stateTracker.Clone (); - try { - for (int max = cursor; max < line.EndOffset; max++) { - curTracker.Push (textEditorData.Document.GetCharAt (max)); - } - } catch (Exception e) { - LoggingService.LogError ("Exception during indentation", e); - } - - int pos = line.Offset; - string curIndent = line.GetIndentation (textEditorData.Document); - int nlwsp = curIndent.Length; - int offset = cursor > pos + nlwsp ? cursor - (pos + nlwsp) : 0; - if (!stateTracker.LineBeganInsideMultiLineComment || (nlwsp < line.LengthIncludingDelimiter && textEditorData.Document.GetCharAt (line.Offset + nlwsp) == '*')) { - // Possibly replace the indent - string newIndent = curTracker.ThisLineIndent; - int newIndentLength = newIndent.Length; - if (newIndent != curIndent) { - if (CompletionWindowManager.IsVisible) { - if (pos < CompletionWindowManager.CodeCompletionContext.TriggerOffset) - CompletionWindowManager.CodeCompletionContext.TriggerOffset -= nlwsp; - } - - newIndentLength = textEditorData.Replace (pos, nlwsp, newIndent); - textEditorData.Document.CommitLineUpdate (textEditorData.Caret.Line); - CompletionWindowManager.HideWindow (); - } - pos += newIndentLength; - } else { - pos += curIndent.Length; - } - - pos += offset; - - textEditorData.FixVirtualIndentation (); - } - - /* - [MonoDevelop.Components.Commands.CommandHandler (MonoDevelop.Ide.CodeFormatting.CodeFormattingCommands.FormatBuffer)] - public void FormatBuffer () - { - Console.WriteLine ("format buffer!"); - ITypeResolveContext dom = TypeSystemService.GetProjectDom (Document.Project); - OnTheFlyFormatter.Format (this.textEditorData, dom); - }*/ - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/Indent.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/Indent.cs deleted file mode 100644 index cb5c4d2..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/Indent.cs +++ /dev/null @@ -1,88 +0,0 @@ -// -// Indent.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -namespace MonoDevelop.PlayScript.Formatting -{ - class Indent - { - public int Level { - get; - set; - } - - public int ExtraSpaces { - get; - set; - } - - public bool TabsToSpaces { - get; - set; - } - - public int TabSize { - get; - set; - } - - public Indent () - { - } - - public Indent (int level, int extraSpaces) - { - this.Level = level; - this.ExtraSpaces = extraSpaces; - } - - public static Indent operator+(Indent left, Indent right) - { - return new Indent (left.Level + right.Level, left.ExtraSpaces + right.ExtraSpaces); - } - - public static Indent operator-(Indent left, Indent right) - { - return new Indent (left.Level - right.Level, left.ExtraSpaces - right.ExtraSpaces); - } - - public string IndentString { - get { - return (TabsToSpaces ? new string (' ', Level * TabSize) : new string ('\t', Level)) + new string (' ', ExtraSpaces); - } - } - - public string SingleIndent { - get { - return TabsToSpaces ? new string (' ', TabSize) : "\t"; - } - } - - public override string ToString () - { - return string.Format ("[Indent: Level={0}, ExtraSpaces={1}]", Level, ExtraSpaces); - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/NewFormattingProfileDialog.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/NewFormattingProfileDialog.cs deleted file mode 100644 index 6f91b04..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/NewFormattingProfileDialog.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -// NewFormattingProfileDialog.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System.Collections.Generic; -using System.Linq; - -namespace MonoDevelop.PlayScript.Formatting -{ - partial class NewFormattingProfileDialog : Gtk.Dialog - { - public string NewProfileName { - get; - private set; - } - - - public PlayScriptFormattingPolicy InitializeFrom { - get { - return policies[comboboxInitFrom.Active]; - } - } - - readonly List policies; - public NewFormattingProfileDialog (List policies) - { - // ReSharper disable once DoNotCallOverridableMethodsInConstructor - this.Build (); - this.policies = policies; - this.entryProfileName.Changed += delegate { - NewProfileName = entryProfileName.Text; - buttonOk.Sensitive = !string.IsNullOrEmpty (NewProfileName) && !this.policies.Any (p => p.Name == NewProfileName); - }; - - var model = new Gtk.ListStore (typeof(string)); - foreach (var p in policies) { - model.AppendValues (p.Name); - } - comboboxInitFrom.Model = model; - comboboxInitFrom.Active = 0; - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/OnTheFlyFormatter.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/OnTheFlyFormatter.cs deleted file mode 100644 index 711e497..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/OnTheFlyFormatter.cs +++ /dev/null @@ -1,267 +0,0 @@ -// -// OnTheFlyFormatter.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using Mono.TextEditor; -using MonoDevelop.Ide; -using System; -using System.Collections.Generic; -using MonoDevelop.Projects.Policies; -using System.Text; -using MonoDevelop.PlayScript.Completion; -using MonoDevelop.PlayScript.Refactoring; -using MonoDevelop.Core; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.PlayScript.Completion; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; -using ICSharpCode.NRefactory; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.PlayScript.Parser; -using Mono.PlayScript; - -namespace MonoDevelop.PlayScript.Formatting -{ - static class OnTheFlyFormatter - { - public static void Format (MonoDevelop.Ide.Gui.Document data) - { - Format (data, 0, data.Editor.Length); - } - - public static void Format (MonoDevelop.Ide.Gui.Document data, TextLocation location) - { - Format (data, location, location, false); - } - - public static void Format (MonoDevelop.Ide.Gui.Document data, TextLocation startLocation, TextLocation endLocation, bool exact = true) - { - Format (data, data.Editor.LocationToOffset (startLocation), data.Editor.LocationToOffset (endLocation), exact); - } - - public static void Format (MonoDevelop.Ide.Gui.Document data, int startOffset, int endOffset, bool exact = true) - { - var policyParent = data.Project != null ? data.Project.Policies : PolicyService.DefaultPolicies; - var mimeTypeChain = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); - Format (policyParent, mimeTypeChain, data, startOffset, endOffset, exact); - } - - public static void FormatStatmentAt (MonoDevelop.Ide.Gui.Document data, DocumentLocation location) - { - var offset = data.Editor.LocationToOffset (location); - var policyParent = data.Project != null ? data.Project.Policies : PolicyService.DefaultPolicies; - var mimeTypeChain = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); - Format (policyParent, mimeTypeChain, data, offset, offset, false, true); - } - - static string BuildStub (MonoDevelop.Ide.Gui.Document data, CSharpCompletionTextEditorExtension.TypeSystemTreeSegment seg, int endOffset, out int memberStartOffset) - { - var pf = data.ParsedDocument.ParsedFile as CSharpUnresolvedFile; - if (pf == null) { - memberStartOffset = 0; - return null; - } - - var sb = new StringBuilder (); - - int closingBrackets = 0; - // use the member start location to determine the using scope, because this information is in sync, the position in - // the file may have changed since last parse run (we have up 2 date locations from the type segment tree). - var scope = pf.GetUsingScope (seg.Entity.Region.Begin); - - while (scope != null && !string.IsNullOrEmpty (scope.NamespaceName)) { - // Hack: some syntax errors lead to invalid namespace names. - if (scope.NamespaceName.EndsWith ("", StringComparison.Ordinal)) { - scope = scope.Parent; - continue; - } - sb.Append ("namespace Stub {"); - sb.Append (data.Editor.EolMarker); - closingBrackets++; - while (scope.Parent != null && scope.Parent.Region == scope.Region) - scope = scope.Parent; - scope = scope.Parent; - } - - var parent = seg.Entity.DeclaringTypeDefinition; - while (parent != null) { - sb.Append ("class " + parent.Name + " {"); - sb.Append (data.Editor.EolMarker); - closingBrackets++; - parent = parent.DeclaringTypeDefinition; - } - - var segmentLine = data.Editor.GetLineByOffset (seg.Offset); - memberStartOffset = sb.Length + seg.Offset - segmentLine.Offset; - var text = data.Editor.GetTextBetween (Math.Max (0, segmentLine.Offset), endOffset); - sb.Append (text); - var lex = new CSharpCompletionEngineBase.MiniLexer (text); - lex.Parse ((ch,i) => { - if (lex.IsInString || lex.IsInChar || lex.IsInVerbatimString || lex.IsInSingleComment || lex.IsInMultiLineComment || lex.IsInPreprocessorDirective) - return false; - if (ch =='{') { - closingBrackets++; - } else if (ch =='}') { - closingBrackets--; - } - return false; - }); - - - // Insert at least caret column eol markers otherwise the reindent of the generated closing bracket - // could interfere with the current indentation. - var endLocation = data.Editor.OffsetToLocation (endOffset); - for (int i = 0; i <= endLocation.Column; i++) { - sb.Append (data.Editor.EolMarker); - } - sb.Append (data.Editor.EolMarker); - sb.Append (new string ('}', closingBrackets)); - return sb.ToString (); - } - - static FormattingChanges GetFormattingChanges (PolicyContainer policyParent, IEnumerable mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input, DomRegion formattingRegion, ref int formatStartOffset, ref int formatLength, bool formatLastStatementOnly) - { - using (var stubData = TextEditorData.CreateImmutable (input)) { - stubData.Document.FileName = document.FileName; - //var parser = document.HasProject ? new CSharpParser (TypeSystemParser.GetCompilerArguments (document.Project)) : new CSharpParser (); - var parser = document.HasProject ? new ICSharpCode.NRefactory.PlayScript.PlayScriptParser (TypeSystemParser.GetCompilerArguments (document.Project)) : new ICSharpCode.NRefactory.PlayScript.PlayScriptParser (); - var compilationUnit = parser.Parse (stubData); - bool hadErrors = parser.HasErrors; - if (hadErrors) { - using (var stubData2 = TextEditorData.CreateImmutable (input + "}")) { - compilationUnit = parser.Parse (stubData2); - hadErrors = parser.HasErrors; - } - } - // try it out, if the behavior is better when working only with correct code. - if (hadErrors) { - return null; - } - - var policy = policyParent.Get (mimeTypeChain); - - var formattingVisitor = new ICSharpCode.NRefactory.PlayScript.CSharpFormatter (policy.CreateOptions (), document.Editor.CreateNRefactoryTextEditorOptions ()); - formattingVisitor.FormattingMode = FormattingMode.Intrusive; - formattingVisitor.AddFormattingRegion (formattingRegion); - - - var changes = formattingVisitor.AnalyzeFormatting (stubData.Document, compilationUnit); - - if (formatLastStatementOnly) { - AstNode node = compilationUnit.GetAdjacentNodeAt (stubData.OffsetToLocation (formatStartOffset + formatLength - 1)); - if (node != null) { - while (node.Role == Roles.EmbeddedStatement || node.Role == IfElseStatement.TrueRole || node.Role == IfElseStatement.FalseRole) - node = node.Parent; - // include indentation if node starts in new line - var formatNode = node.GetPrevNode (); - if (formatNode.Role != Roles.NewLine) - formatNode = node; - var start = stubData.LocationToOffset (formatNode.StartLocation); - if (start > formatStartOffset) { - var end = stubData.LocationToOffset (node.EndLocation); - formatStartOffset = start; - formatLength = end - start; - } - } - } - return changes; - } - } - - public static void Format (PolicyContainer policyParent, IEnumerable mimeTypeChain, MonoDevelop.Ide.Gui.Document data, int startOffset, int endOffset, bool exact, bool formatLastStatementOnly = false) - { - if (data.ParsedDocument == null) - return; - var ext = data.GetContent (); - if (ext == null) - return; - string text; - int formatStartOffset, formatLength, realTextDelta; - DomRegion formattingRegion; - int startDelta = 1; - if (exact) { - text = data.Editor.Text; - var seg = ext.GetMemberSegmentAt (startOffset); - var seg2 = ext.GetMemberSegmentAt (endOffset); - if (seg != null && seg == seg2) { - var member = seg.Entity; - if (member == null || member.Region.IsEmpty || member.BodyRegion.End.IsEmpty) - return; - - text = BuildStub (data, seg, endOffset, out formatStartOffset); - startDelta = startOffset - seg.Offset; - formatLength = endOffset - startOffset + startDelta; - realTextDelta = seg.Offset - formatStartOffset; - formattingRegion = new DomRegion (data.Editor.OffsetToLocation (formatStartOffset), data.Editor.OffsetToLocation (endOffset)); - } else { - formatStartOffset = startOffset; - formatLength = endOffset - startOffset; - realTextDelta = 0; - formattingRegion = new DomRegion (data.Editor.OffsetToLocation (startOffset), data.Editor.OffsetToLocation (endOffset)); - } - } else { - var seg = ext.GetMemberSegmentAt (startOffset - 1); - if (seg == null) { - return; - } - var member = seg.Entity; - if (member == null) - return; - - // Build stub - text = BuildStub (data, seg, startOffset, out formatStartOffset); - formattingRegion = new DomRegion (data.Editor.OffsetToLocation (formatStartOffset), data.Editor.OffsetToLocation (endOffset)); - - formatLength = endOffset - seg.Offset; - realTextDelta = seg.Offset - formatStartOffset; - } - // Get changes from formatting visitor - var changes = GetFormattingChanges (policyParent, mimeTypeChain, data, text, formattingRegion, ref formatStartOffset, ref formatLength, formatLastStatementOnly); - if (changes == null) - return; - - // Do the actual formatting -// var originalVersion = data.Editor.Document.Version; - - using (var undo = data.Editor.OpenUndoGroup (OperationType.Format)) { - try { - changes.ApplyChanges (formatStartOffset + startDelta, Math.Max (0, formatLength - startDelta - 1), delegate (int replaceOffset, int replaceLength, string insertText) { - int translatedOffset = realTextDelta + replaceOffset; - data.Editor.Document.CommitLineUpdate (data.Editor.OffsetToLineNumber (translatedOffset)); - data.Editor.Replace (translatedOffset, replaceLength, insertText); - }, (replaceOffset, replaceLength, insertText) => { - int translatedOffset = realTextDelta + replaceOffset; - if (translatedOffset < 0 || translatedOffset + replaceLength > data.Editor.Length || replaceLength < 0) - return true; - return data.Editor.GetTextAt (translatedOffset, replaceLength) == insertText; - }); - } catch (Exception e) { - LoggingService.LogError ("Error in on the fly formatter", e); - } - -// var currentVersion = data.Editor.Document.Version; -// data.Editor.Caret.Offset = originalVersion.MoveOffsetTo (currentVersion, caretOffset, ICSharpCode.NRefactory.Editor.AnchorMovementType.Default); - } - } - } -} \ No newline at end of file diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsAllmanCSharpPolicy.xml b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsAllmanCSharpPolicy.xml deleted file mode 100644 index 866d51f..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsAllmanCSharpPolicy.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - - True - True - True - True - True - True - True - True - True - True - True - True - True - AllowOneLine - AllowOneLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - AllowOneLine - AllowOneLine - NextLine - NextLine - NextLine - True - True - NextLine - False - NewLine - SameLine - NewLine - NewLine - DoNotCare - DoNotChange - NextLine - True - False - False - False - True - False - False - False - False - True - False - False - True - False - True - False - False - False - True - False - NewLine - SameLine - True - False - False - True - False - False - False - False - False - False - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - True - False - False - True - True - True - True - False - False - False - True - False - True - False - False - 0 - 1 - 0 - 1 - 0 - 0 - 1 - 1 - 1 - True - True - \ No newline at end of file diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsGNUCSharpPolicy.xml b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsGNUCSharpPolicy.xml deleted file mode 100644 index 843cad6..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsGNUCSharpPolicy.xml +++ /dev/null @@ -1,163 +0,0 @@ - - - - - True - True - True - True - True - True - True - True - True - True - True - True - True - AllowOneLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - EndOfLine - NextLine - NextLine - EndOfLine - EndOfLine - EndOfLine - AllowOneLine - AllowOneLine - EndOfLine - EndOfLine - EndOfLine - True - True - NextLineShifted2 - False - SameLine - SameLine - SameLine - SameLine - SameLine - WrapIfTooLong - EndOfLine - True - False - False - False - True - False - False - False - False - True - False - False - True - False - True - False - False - False - True - False - NewLine - SameLine - True - False - False - True - False - False - False - False - False - False - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - True - False - False - True - True - True - True - False - False - False - True - False - True - False - False - 0 - 1 - 0 - 1 - 0 - 0 - 1 - 1 - 1 - False - \ No newline at end of file diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsGNUTextStylePolicy.xml b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsGNUTextStylePolicy.xml deleted file mode 100644 index acdbba8..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsGNUTextStylePolicy.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - 120 - 4 - 2 - True - False - True - Unix - \ No newline at end of file diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsInvariantTextStylePolicy.xml b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsInvariantTextStylePolicy.xml deleted file mode 100644 index 449b97f..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsInvariantTextStylePolicy.xml +++ /dev/null @@ -1,9 +0,0 @@ - - 120 - 4 - 4 - False - False - True - Unix - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsKRCSharpPolicy.xml b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsKRCSharpPolicy.xml deleted file mode 100644 index c83369f..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsKRCSharpPolicy.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - - True - True - True - True - True - True - True - True - True - True - True - True - True - AllowOneLine - AllowOneLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - EndOfLine - NextLine - NextLine - EndOfLine - EndOfLine - EndOfLine - AllowOneLine - AllowOneLine - EndOfLine - EndOfLine - EndOfLine - True - True - EndOfLine - False - SameLine - SameLine - SameLine - SameLine - SameLine - WrapIfTooLong - EndOfLine - True - False - False - False - True - False - False - False - False - True - False - False - True - False - True - False - False - False - True - False - NewLine - SameLine - True - False - False - True - False - False - False - False - False - False - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - True - False - False - True - True - True - True - False - False - False - True - False - True - False - False - 0 - 1 - 0 - 1 - 0 - 0 - 1 - 1 - 1 - True - False - \ No newline at end of file diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsMonoCSharpPolicy.xml b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsMonoCSharpPolicy.xml deleted file mode 100644 index 99bbf1b..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsMonoCSharpPolicy.xml +++ /dev/null @@ -1,166 +0,0 @@ - - - - True - True - True - True - True - True - True - True - True - False - True - True - True - AllowOneLine - AllowOneLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - EndOfLine - NextLine - NextLine - EndOfLine - EndOfLine - EndOfLine - AllowOneLine - AllowOneLine - EndOfLine - EndOfLine - EndOfLine - True - True - EndOfLine - False - SameLine - SameLine - SameLine - SameLine - SameLine - WrapIfTooLong - EndOfLine - True - True - False - False - True - False - True - False - False - True - False - False - True - False - True - True - False - False - True - False - DoNotCare - DoNotCare - True - False - False - True - True - False - False - False - False - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - True - False - False - True - True - True - True - False - True - False - True - False - True - False - False - 0 - 1 - 0 - 1 - 0 - 0 - 1 - 1 - 1 - True - False - False - False - \ No newline at end of file diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsSharpDevelopCSharpPolicy.xml b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsSharpDevelopCSharpPolicy.xml deleted file mode 100644 index 719bad7..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsSharpDevelopCSharpPolicy.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - - True - True - True - True - True - True - True - True - True - True - True - True - True - AllowOneLine - AllowOneLine - NextLine - NextLine - NextLine - NextLine - NextLine - NextLine - EndOfLine - NextLine - NextLine - EndOfLine - EndOfLine - EndOfLine - AllowOneLine - AllowOneLine - EndOfLine - EndOfLine - EndOfLine - True - True - EndOfLine - False - SameLine - SameLine - SameLine - SameLine - SameLine - WrapIfTooLong - EndOfLine - True - False - False - False - True - False - False - False - False - True - False - False - True - False - True - False - False - False - True - False - NewLine - SameLine - True - False - False - True - False - False - False - False - False - False - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - True - False - False - True - True - True - True - False - False - False - True - False - True - False - False - 0 - 1 - 0 - 1 - 0 - 0 - 1 - 1 - 1 - True - False - \ No newline at end of file diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsWhitesmithsCSharpPolicy.xml b/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsWhitesmithsCSharpPolicy.xml deleted file mode 100644 index ebecece..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Formatting/policies/PsWhitesmithsCSharpPolicy.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - - True - True - True - True - True - True - True - True - True - True - True - True - True - AllowOneLine - AllowOneLine - NextLineShifted - NextLineShifted - NextLineShifted - NextLineShifted - NextLineShifted - NextLineShifted - NextLineShifted - NextLineShifted - NextLineShifted - NextLineShifted - NextLineShifted - NextLineShifted - AllowOneLine - AllowOneLine - NextLineShifted - NextLineShifted - NextLineShifted - True - True - NextLineShifted - False - SameLine - SameLine - SameLine - SameLine - SameLine - WrapIfTooLong - EndOfLine - True - False - False - False - True - False - False - False - False - True - False - False - True - False - True - False - False - False - True - False - NewLine - SameLine - True - False - False - True - False - False - False - False - False - False - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - True - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - False - True - False - False - True - True - True - True - False - False - False - True - False - True - False - False - 0 - 1 - 0 - 1 - 0 - 0 - 1 - 1 - 1 - True - True - \ No newline at end of file diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/CSharpSelectionSurroundingProvider.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/CSharpSelectionSurroundingProvider.cs deleted file mode 100644 index 11f7e45..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/CSharpSelectionSurroundingProvider.cs +++ /dev/null @@ -1,101 +0,0 @@ -// -// CSharpSelectionSurroundingProvider.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using Mono.TextEditor; -using MonoDevelop.PlayScript.Formatting; - -namespace MonoDevelop.PlayScript.Highlighting -{ - class CSharpSelectionSurroundingProvider : DefaultSelectionSurroundingProvider - { - MonoDevelop.Ide.Gui.Document document; - - public CSharpSelectionSurroundingProvider (MonoDevelop.Ide.Gui.Document document) - { - this.document = document; - } - - public override bool GetSelectionSurroundings (TextEditorData textEditorData, uint unicodeKey, out string start, out string end) - { - if (unicodeKey == '/') { - start = "/*"; - end = "*/"; - return true; - } - - if (unicodeKey == '"') { - start = textEditorData.MainSelection.Anchor.Line != textEditorData.MainSelection.Lead.Line ? "@\"" : "\""; - end = "\""; - return true; - } - return base.GetSelectionSurroundings (textEditorData, unicodeKey, out start, out end); - } - - public override void HandleSpecialSelectionKey (TextEditorData textEditorData,uint unicodeKey) - { - string start, end; - GetSelectionSurroundings (textEditorData, unicodeKey, out start, out end); - var selection = textEditorData.MainSelection; - - if (textEditorData.MainSelection.SelectionMode == SelectionMode.Block) { - int startCol = System.Math.Min (selection.Anchor.Column, selection.Lead.Column) - 1; - int endCol = System.Math.Max (selection.Anchor.Column, selection.Lead.Column); - for (int lineNumber = selection.MinLine; lineNumber <= selection.MaxLine; lineNumber++) { - DocumentLine lineSegment = textEditorData.GetLine (lineNumber); - - if (lineSegment.Offset + startCol < lineSegment.EndOffset) - textEditorData.Insert (lineSegment.Offset + startCol, start); - if (lineSegment.Offset + endCol < lineSegment.EndOffset) - textEditorData.Insert (lineSegment.Offset + endCol, end); - } - - textEditorData.MainSelection = new Selection ( - new DocumentLocation (selection.Anchor.Line, endCol == selection.Anchor.Column ? endCol + start.Length : startCol + 1 + start.Length), - new DocumentLocation (selection.Lead.Line, endCol == selection.Anchor.Column ? startCol + 1 + start.Length : endCol + start.Length), - Mono.TextEditor.SelectionMode.Block); - textEditorData.Document.CommitMultipleLineUpdate (textEditorData.MainSelection.MinLine, textEditorData.MainSelection.MaxLine); - } else { - int anchorOffset = selection.GetAnchorOffset (textEditorData); - int leadOffset = selection.GetLeadOffset (textEditorData); - if (leadOffset < anchorOffset) { - int tmp = anchorOffset; - anchorOffset = leadOffset; - leadOffset = tmp; - } - textEditorData.Insert (anchorOffset, start); - textEditorData.Insert (leadOffset >= anchorOffset ? leadOffset + start.Length : leadOffset, end); - // textEditorData.SetSelection (anchorOffset + start.Length, leadOffset + start.Length); - if (CSharpTextEditorIndentation.OnTheFlyFormatting) { - var l1 = textEditorData.GetLineByOffset (anchorOffset); - var l2 = textEditorData.GetLineByOffset (leadOffset); - OnTheFlyFormatter.Format (document, l1.Offset, l2.EndOffsetIncludingDelimiter); - } - } - } - - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/CSharpSyntaxMode.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/CSharpSyntaxMode.cs deleted file mode 100644 index bd406bf..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/CSharpSyntaxMode.cs +++ /dev/null @@ -1,694 +0,0 @@ -// -// SyntaxMode.cs -// -// Author: -// Mike Krüger -// -// Copyright (C) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using System.Linq; -using System.Collections.Generic; -using Mono.TextEditor.Highlighting; -using Mono.TextEditor; -using System.Xml; -using MonoDevelop.Projects; -using MonoDevelop.PlayScript.Project; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide; -using MonoDevelop.Ide.Tasks; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using ICSharpCode.NRefactory.Semantics; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; -using MonoDevelop.SourceEditor.QuickTasks; -using System.Threading; -using System.Diagnostics; -using MonoDevelop.Core; -using ICSharpCode.NRefactory.PlayScript.Analysis; -using ICSharpCode.NRefactory; -using MonoDevelop.Refactoring; -using ICSharpCode.NRefactory.Refactoring; - -namespace MonoDevelop.PlayScript.Highlighting -{ - static class StringHelper - { - public static bool IsAt (this string str, int idx, string pattern) - { - if (idx + pattern.Length > str.Length) - return false; - - for (int i = 0; i < pattern.Length; i++) - if (pattern [i] != str [idx + i]) - return false; - return true; - } - } - - class CSharpSyntaxMode : SyntaxMode, IQuickTaskProvider, IDisposable - { - readonly Document guiDocument; - - CSharpAstResolver resolver; - CancellationTokenSource src; - - public bool SemanticHighlightingEnabled { - get { - return true; - } - } - - internal class StyledTreeSegment : TreeSegment - { - public string Style { - get; - private set; - } - - public StyledTreeSegment (int offset, int length, string style) : base (offset, length) - { - Style = style; - } - } - - class HighlightingSegmentTree : SegmentTree - { - public bool GetStyle (Chunk chunk, ref int endOffset, out string style) - { - var segment = GetSegmentsAt (chunk.Offset).FirstOrDefault (); - if (segment == null) { - style = null; - return false; - } - endOffset = segment.EndOffset; - style = segment.Style; - return true; - } - - public void AddStyle (int startOffset, int endOffset, string style) - { - if (IsDirty) - return; - Add (new StyledTreeSegment (startOffset, endOffset - startOffset, style)); - } - } - - Dictionary lineSegments = new Dictionary (); - - public bool DisableConditionalHighlighting { - get; - set; - } - - public static IEnumerable GetDefinedSymbols (MonoDevelop.Projects.Project project) - { - var workspace = IdeApp.Workspace; - if (workspace == null || project == null) - yield break; - var configuration = project.GetConfiguration (workspace.ActiveConfiguration) as DotNetProjectConfiguration; - if (configuration != null) { - foreach (string s in configuration.GetDefineSymbols ()) - yield return s; - // Workaround for mcs defined symbol - if (configuration.TargetRuntime.RuntimeId == "Mono") - yield return "__MonoCS__"; - } - } - - void HandleDocumentParsed (object sender, EventArgs e) - { - if (src != null) - src.Cancel (); - resolver = null; - if (guiDocument.IsProjectContextInUpdate) { - return; - } - if (guiDocument != null && SemanticHighlightingEnabled) { - var parsedDocument = guiDocument.ParsedDocument; - if (parsedDocument != null) { - if (guiDocument.Project != null && guiDocument.IsCompileableInProject) { - src = new CancellationTokenSource (); - //var newResolverTask = guiDocument.GetSharedResolver (); - var newResolverTask = guiDocument.GetPlayScriptSharedResolver(); - var cancellationToken = src.Token; - System.Threading.Tasks.Task.Factory.StartNew (delegate { - if (newResolverTask == null) - return; - var newResolver = newResolverTask.Result; - if (newResolver == null) - return; - var visitor = new QuickTaskVisitor (newResolver, cancellationToken); - try { - newResolver.RootNode.AcceptVisitor (visitor); - } catch (Exception ex) { - LoggingService.LogError ("Error while analyzing the file for the semantic highlighting.", ex); - return; - } - if (!cancellationToken.IsCancellationRequested) { - Gtk.Application.Invoke (delegate { - if (cancellationToken.IsCancellationRequested) - return; - var editorData = guiDocument.Editor; - if (editorData == null) - return; -// compilation = newResolver.Compilation; - resolver = newResolver; - quickTasks = visitor.QuickTasks; - OnTasksUpdated (EventArgs.Empty); - foreach (var kv in lineSegments) { - try { - kv.Value.tree.RemoveListener (); - } catch (Exception) { - } - } - lineSegments.Clear (); - var textEditor = editorData.Parent; - if (textEditor != null) { - if (!parsedDocument.HasErrors) { - var margin = textEditor.TextViewMargin; - margin.PurgeLayoutCache (); - textEditor.QueueDraw (); - } - } - }); - } - }, cancellationToken); - } - } - } - } - - class HighlightingVisitior : SemanticHighlightingVisitor - { - readonly int lineNumber; - readonly int lineOffset; - readonly int lineLength; - internal HighlightingSegmentTree tree = new HighlightingSegmentTree (); - - public HighlightingVisitior (CSharpAstResolver resolver, CancellationToken cancellationToken, int lineNumber, int lineOffset, int lineLength) - { - if (resolver == null) - throw new ArgumentNullException ("resolver"); - this.resolver = resolver; - this.cancellationToken = cancellationToken; - this.lineNumber = lineNumber; - this.lineOffset = lineOffset; - this.lineLength = lineLength; - regionStart = new TextLocation (lineNumber, 1); - regionEnd = new TextLocation (lineNumber, lineLength); - - Setup (); - } - - void Setup () - { - defaultTextColor = "Plain Text"; - referenceTypeColor = "User Types"; - valueTypeColor = "User Types(Value types)"; - interfaceTypeColor = "User Types(Interfaces)"; - enumerationTypeColor = "User Types(Enums)"; - typeParameterTypeColor = "User Types(Type parameters)"; - delegateTypeColor = "User Types(Delegates)"; - - methodCallColor = "User Method Usage"; - methodDeclarationColor = "User Method Declaration"; - - eventDeclarationColor = "User Event Declaration"; - eventAccessColor = "User Event Usage"; - - fieldDeclarationColor ="User Field Declaration"; - fieldAccessColor = "User Field Usage"; - - propertyDeclarationColor = "User Property Declaration"; - propertyAccessColor = "User Property Usage"; - - variableDeclarationColor = "User Variable Declaration"; - variableAccessColor = "User Variable Usage"; - - parameterDeclarationColor = "User Parameter Declaration"; - parameterAccessColor = "User Parameter Usage"; - - valueKeywordColor = "Keyword(Context)"; - externAliasKeywordColor = "Keyword(Namespace)"; - varKeywordTypeColor = "Keyword(Type)"; - - parameterModifierColor = "Keyword(Parameter)"; - inactiveCodeColor = "Excluded Code"; - syntaxErrorColor = "Syntax Error"; - - stringFormatItemColor = "String Format Items"; - } - - protected override void Colorize(TextLocation start, TextLocation end, string color) - { - int startOffset; - if (start.Line == lineNumber) { - startOffset = lineOffset + start.Column - 1; - } else { - if (start.Line > lineNumber) - return; - startOffset = lineOffset; - } - int endOffset; - if (end.Line == lineNumber) { - endOffset = lineOffset +end.Column - 1; - } else { - if (end.Line < lineNumber) - return; - endOffset = lineOffset + lineLength; - } - tree.AddStyle (startOffset, endOffset, color); - } - - public override void VisitSimpleType (SimpleType simpleType) - { - var identifierToken = simpleType.IdentifierToken; - VisitChildrenUntil(simpleType, identifierToken); - var resolveResult = resolver.Resolve (simpleType, cancellationToken); - if (resolveResult.Type.Namespace == "System") { - switch (resolveResult.Type.Name) { - case "nfloat": - case "nint": - case "nuint": - Colorize(identifierToken, "Keyword(Type)"); - break; - default: - Colorize (identifierToken, resolveResult); - break; - } - } else { - Colorize (identifierToken, resolveResult); - } - VisitChildrenAfter(simpleType, identifierToken); - } - - public override void VisitIdentifierExpression (IdentifierExpression identifierExpression) - { - var identifier = identifierExpression.IdentifierToken; - VisitChildrenUntil(identifierExpression, identifier); - if (isInAccessorContainingValueParameter && identifierExpression.Identifier == "value") { - Colorize(identifier, valueKeywordColor); - } else { - var resolveResult = resolver.Resolve (identifierExpression, cancellationToken); - Colorize (identifier, resolveResult); - } - VisitChildrenAfter(identifierExpression, identifier); - } - } - - class QuickTaskVisitor : DepthFirstAstVisitor - { - internal List QuickTasks = new List (); - readonly CSharpAstResolver resolver; - readonly CancellationToken cancellationToken; - - public QuickTaskVisitor (CSharpAstResolver resolver, CancellationToken cancellationToken) - { - this.resolver = resolver; - this.cancellationToken = cancellationToken; - } - - protected override void VisitChildren (AstNode node) - { - if (cancellationToken.IsCancellationRequested) - return; - base.VisitChildren (node); - } - - public override void VisitIdentifierExpression (IdentifierExpression identifierExpression) - { - base.VisitIdentifierExpression (identifierExpression); - var result = resolver.Resolve (identifierExpression, cancellationToken); - if (result.IsError) { - QuickTasks.Add (new QuickTask (() => string.Format ("error CS0103: The name `{0}' does not exist in the current context", identifierExpression.Identifier), identifierExpression.StartLocation, Severity.Error)); - } - } - - public override void VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression) - { - base.VisitMemberReferenceExpression (memberReferenceExpression); - var result = resolver.Resolve (memberReferenceExpression, cancellationToken) as UnknownMemberResolveResult; - if (result != null && result.TargetType.Kind != TypeKind.Unknown) { - QuickTasks.Add (new QuickTask (string.Format ("error CS0117: `{0}' does not contain a definition for `{1}'", result.TargetType.FullName, memberReferenceExpression.MemberName), memberReferenceExpression.MemberNameToken.StartLocation, Severity.Error)); - } - } - - public override void VisitSimpleType (SimpleType simpleType) - { - base.VisitSimpleType (simpleType); - var result = resolver.Resolve (simpleType, cancellationToken); - if (result.IsError) { - QuickTasks.Add (new QuickTask (string.Format ("error CS0246: The type or namespace name `{0}' could not be found. Are you missing an assembly reference?", simpleType.Identifier), simpleType.StartLocation, Severity.Error)); - } - } - - public override void VisitMemberType (MemberType memberType) - { - base.VisitMemberType (memberType); - var result = resolver.Resolve (memberType, cancellationToken); - if (result.IsError) { - QuickTasks.Add (new QuickTask (string.Format ("error CS0246: The type or namespace name `{0}' could not be found. Are you missing an assembly reference?", memberType.MemberName), memberType.StartLocation, Severity.Error)); - } - } - - public override void VisitComment (ICSharpCode.NRefactory.PlayScript.Comment comment) - { - } - } - - static CSharpSyntaxMode () - { - MonoDevelop.Debugger.DebuggingService.DisableConditionalCompilation += DispatchService.GuiDispatch (new EventHandler (OnDisableConditionalCompilation)); - if (IdeApp.Workspace != null) { - IdeApp.Workspace.ActiveConfigurationChanged += delegate { - foreach (var doc in IdeApp.Workbench.Documents) { - TextEditorData data = doc.Editor; - if (data == null) - continue; - // Force syntax mode reparse (required for #if directives) - var editor = doc.Editor; - if (editor != null) { - if (data.Document.SyntaxMode is SyntaxMode) { - ((SyntaxMode)data.Document.SyntaxMode).UpdateDocumentHighlighting (); - SyntaxModeService.WaitUpdate (data.Document); - } - editor.Parent.TextViewMargin.PurgeLayoutCache (); - doc.ReparseDocument (); - editor.Parent.QueueDraw (); - } - } - }; - } - CommentTag.SpecialCommentTagsChanged += (sender, e) => { - UpdateCommentRule (); - var actDoc = IdeApp.Workbench.ActiveDocument; - if (actDoc != null && actDoc.Editor != null) { - actDoc.UpdateParseDocument (); - actDoc.Editor.Parent.TextViewMargin.PurgeLayoutCache (); - actDoc.Editor.Parent.QueueDraw (); - } - }; - } - - static void OnDisableConditionalCompilation (object s, DocumentEventArgs e) - { - var mode = e.Document.Editor.Document.SyntaxMode as CSharpSyntaxMode; - if (mode == null) - return; - mode.DisableConditionalHighlighting = true; - e.Document.Editor.Document.CommitUpdateAll (); - } - - static Dictionary contextualHighlightKeywords; - static readonly string[] ContextualKeywords = new string[] { - "value" -/* "async", - "await", - , //* - "get", "set", "add", "remove", //* - "var", //* - "global", - "partial", //* - "where", //* - "select", - "group", - "by", - "into", - "from", - "ascending", - "descending", - "orderby", - "let", - "join", - "on", - "equals"*/ - }; - - #region Syntax mode rule cache - static List _rules; - static List _keywords; - static Span[] _spans; - static Match[] _matches; - static Marker[] _prevMarker; - static List _SemanticRules; - static Rule _commentRule; - static Dictionary _keywordTable; - static Dictionary _keywordTableIgnoreCase; - static Dictionary> _properties; - #endregion - - static void UpdateCommentRule () - { - if (_commentRule == null) - return; - var joinedTasks = string.Join ("", CommentTag.SpecialCommentTags.Select (t => t.Tag)); - _commentRule.SetDelimiter (new string ("&()<>{}[]~!%^*-+=|\\#/:;\"' ,\t.?".Where (c => joinedTasks.IndexOf (c) < 0).ToArray ())); - _commentRule.Keywords = new[] { - new Keywords { - Color = "Comment Tag", - Words = CommentTag.SpecialCommentTags.Select (t => t.Tag) - } - }; - } - - public CSharpSyntaxMode (Document document) - { -// var foo = System.Reflection.Assembly.GetCallingAssembly (); -// var resourceNames = foo.GetManifestResourceNames ().Where (s => s.Contains ("Policy.xml")); -// foreach(string resourceName in resourceNames) -// { -// Console.WriteLine(resourceName); -// } -// resourceNames = foo.GetManifestResourceNames ().Where (s => !s.Contains ("Policy.xml")); -// foreach(string resourceName in resourceNames) -// { -// Console.WriteLine(resourceName); -// } - - this.guiDocument = document; - guiDocument.DocumentParsed += HandleDocumentParsed; - if (guiDocument.ParsedDocument != null) - HandleDocumentParsed (this, EventArgs.Empty); - - bool loadRules = _rules == null; - - if (loadRules) { - var thisAssembly = System.Reflection.Assembly.GetCallingAssembly (); - var resourceName = thisAssembly.GetManifestResourceNames ().First (s => s.Contains ("PlayScriptSyntaxMode")); - Console.WriteLine(resourceName); - var provider = new ResourceStreamProvider (thisAssembly, resourceName); -// var provider = new ResourceStreamProvider (typeof(ResourceStreamProvider).Assembly, typeof(ResourceStreamProvider).Assembly.GetManifestResourceNames ().First (s => s.Contains ("PlayScriptSyntaxMode"))); - using (var reader = provider.Open ()) { - SyntaxMode baseMode = SyntaxMode.Read (reader); - _rules = new List (baseMode.Rules.Where (r => r.Name != "Comment")); - _rules.Add (new Rule { - Name = "PreProcessorComment" - }); - - _commentRule = new Rule { - Name = "Comment", - IgnoreCase = true - }; - UpdateCommentRule (); - - _rules.Add (_commentRule); - _keywords = new List (baseMode.Keywords); - _spans = new List (baseMode.Spans.Where (span => span.Begin.Pattern != "#")).ToArray (); - _matches = baseMode.Matches; - _prevMarker = baseMode.PrevMarker; - _SemanticRules = new List (baseMode.SemanticRules); - _keywordTable = baseMode.keywordTable; - _keywordTableIgnoreCase = baseMode.keywordTableIgnoreCase; - _properties = baseMode.Properties; - } - - contextualHighlightKeywords = new Dictionary (); - foreach (var word in ContextualKeywords) { - if (_keywordTable.ContainsKey (word)) { - contextualHighlightKeywords[word] = _keywordTable[word].Color; - } else { - Console.WriteLine ("missing keyword:"+word); - } - } - - foreach (var word in ContextualKeywords) { - _keywordTable.Remove (word); - } - } - - rules = _rules; - keywords = _keywords; - spans = _spans; - matches = _matches; - prevMarker = _prevMarker; - SemanticRules = _SemanticRules; - keywordTable = _keywordTable; - keywordTableIgnoreCase = _keywordTableIgnoreCase; - properties = _properties; - - if (loadRules) { - AddSemanticRule ("Comment", new HighlightUrlSemanticRule ("Comment(Line)")); - AddSemanticRule ("XmlDocumentation", new HighlightUrlSemanticRule ("Comment(Doc)")); - AddSemanticRule ("String", new HighlightUrlSemanticRule ("String")); - } - } - - #region IDisposable implementation - - public void Dispose () - { - if (src != null) - src.Cancel (); - guiDocument.DocumentParsed -= HandleDocumentParsed; - } - - #endregion - - -// public override SpanParser CreateSpanParser (DocumentLine line, CloneableStack spanStack) -// { -// return new CSharpSpanParser (this, spanStack ?? line.StartSpan.Clone ()); -// } - - public override ChunkParser CreateChunkParser (SpanParser spanParser, ColorScheme style, DocumentLine line) - { - return new CSharpChunkParser (this, spanParser, style, line); - } - - protected class CSharpChunkParser : ChunkParser, IResolveVisitorNavigator - { - - HashSet tags = new HashSet (); - - CSharpSyntaxMode csharpSyntaxMode; - int lineNumber; - public CSharpChunkParser (CSharpSyntaxMode csharpSyntaxMode, SpanParser spanParser, ColorScheme style, DocumentLine line) : base (csharpSyntaxMode, spanParser, style, line) - { - lineNumber = line.LineNumber; - this.csharpSyntaxMode = csharpSyntaxMode; - foreach (var tag in CommentTag.SpecialCommentTags) { - tags.Add (tag.Tag); - } - - } - - #region IResolveVisitorNavigator implementation - ResolveVisitorNavigationMode IResolveVisitorNavigator.Scan(AstNode node) - { - if (node is SimpleType || node is MemberType - || node is IdentifierExpression || node is MemberReferenceExpression - || node is InvocationExpression) { - return ResolveVisitorNavigationMode.Resolve; - } - return ResolveVisitorNavigationMode.Scan; - } - - void IResolveVisitorNavigator.Resolved(AstNode node, ResolveResult result) - { - } - - void IResolveVisitorNavigator.ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType) - { - } - #endregion - static int TokenLength (AstNode node) - { - Debug.Assert (node.StartLocation.Line == node.EndLocation.Line); - return node.EndLocation.Column - node.StartLocation.Column; - } - - protected override void AddRealChunk (Chunk chunk) - { - var document = csharpSyntaxMode.guiDocument; - var parsedDocument = document != null ? document.ParsedDocument : null; - if (parsedDocument != null && csharpSyntaxMode.SemanticHighlightingEnabled && csharpSyntaxMode.resolver != null) { - int endLoc = -1; - string semanticStyle = null; - if (spanParser.CurSpan != null && (spanParser.CurSpan.Rule == "Comment" || spanParser.CurSpan.Rule == "PreProcessorComment")) { - base.AddRealChunk (chunk); - return; - } - - try { - HighlightingVisitior visitor; - if (!csharpSyntaxMode.lineSegments.TryGetValue (line, out visitor)) { - var resolver = csharpSyntaxMode.resolver; - visitor = new HighlightingVisitior (resolver, default (CancellationToken), lineNumber, base.line.Offset, line.Length); - visitor.tree.InstallListener (doc); - resolver.RootNode.AcceptVisitor (visitor); - csharpSyntaxMode.lineSegments[line] = visitor; - } - string style; - if (visitor.tree.GetStyle (chunk, ref endLoc, out style)) { - semanticStyle = style; - } - } catch (Exception e) { - Console.WriteLine ("Error in semantic highlighting: " + e); - } - if (semanticStyle != null) { - if (endLoc < chunk.EndOffset) { - base.AddRealChunk (new Chunk (chunk.Offset, endLoc - chunk.Offset, semanticStyle)); - base.AddRealChunk (new Chunk (endLoc, chunk.EndOffset - endLoc, chunk.Style)); - return; - } - chunk.Style = semanticStyle; - } - } - - base.AddRealChunk (chunk); - } - - protected override string GetStyle (Chunk chunk) - { - if (spanParser.CurRule.Name == "Comment") { - if (tags.Contains (doc.GetTextAt (chunk))) - return "Comment Tag"; - } - return base.GetStyle (chunk); - } - } - - - #region IQuickTaskProvider implementation - public event EventHandler TasksUpdated; - - protected virtual void OnTasksUpdated (EventArgs e) - { - var handler = TasksUpdated; - if (handler != null) - handler (this, e); - } - - List quickTasks; - public IEnumerable QuickTasks { - get { - return quickTasks; - } - } - #endregion - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/HighlightUsagesExtension.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/HighlightUsagesExtension.cs deleted file mode 100644 index 7601f95..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/HighlightUsagesExtension.cs +++ /dev/null @@ -1,103 +0,0 @@ -// -// HighlightUsagesExtension.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; -using MonoDevelop.Core; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using MonoDevelop.Ide.FindInFiles; -using ICSharpCode.NRefactory.Semantics; -using ICSharpCode.NRefactory.PlayScript; -using System.Threading; -using MonoDevelop.SourceEditor; - -namespace MonoDevelop.PlayScript.Highlighting -{ - public class HighlightUsagesExtension : AbstractUsagesExtension - { - CSharpSyntaxMode syntaxMode; - - public override void Initialize () - { - base.Initialize (); - - TextEditorData.SelectionSurroundingProvider = new CSharpSelectionSurroundingProvider (Document); - syntaxMode = new CSharpSyntaxMode (Document); - TextEditorData.Document.SyntaxMode = syntaxMode; - } - - public override void Dispose () - { - if (syntaxMode != null) { - TextEditorData.Document.SyntaxMode = null; - syntaxMode.Dispose (); - syntaxMode = null; - } - base.Dispose (); - } - - protected override bool TryResolve (out ResolveResult resolveResult) - { - AstNode node; - resolveResult = null; - if (!Document.TryResolveAt (Document.Editor.Caret.Location, out resolveResult, out node)) { - return false; - } - if (node is PrimitiveType) { - return false; - } - return true; - } - - - protected override IEnumerable GetReferences (ResolveResult resolveResult, CancellationToken token) - { - var finder = new MonoDevelop.PlayScript.Refactoring.CSharpReferenceFinder (); - if (resolveResult is MemberResolveResult) { - finder.SetSearchedMembers (new [] { ((MemberResolveResult)resolveResult).Member }); - } else if (resolveResult is TypeResolveResult) { - finder.SetSearchedMembers (new [] { resolveResult.Type }); - } else if (resolveResult is MethodGroupResolveResult) { - finder.SetSearchedMembers (((MethodGroupResolveResult)resolveResult).Methods); - } else if (resolveResult is NamespaceResolveResult) { - finder.SetSearchedMembers (new [] { ((NamespaceResolveResult)resolveResult).Namespace }); - } else if (resolveResult is LocalResolveResult) { - finder.SetSearchedMembers (new [] { ((LocalResolveResult)resolveResult).Variable }); - } else if (resolveResult is NamedArgumentResolveResult) { - finder.SetSearchedMembers (new [] { ((NamedArgumentResolveResult)resolveResult).Parameter }); - } else { - return EmptyList; - } - - try { - return new List (finder.FindInDocument (Document, token)); - } catch (Exception e) { - LoggingService.LogError ("Error in highlight usages extension.", e); - } - return EmptyList; - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/MoveToUsagesHandler.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/MoveToUsagesHandler.cs deleted file mode 100644 index e306d6d..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Highlighting/MoveToUsagesHandler.cs +++ /dev/null @@ -1,119 +0,0 @@ -// -// MoveToUsagesHandler.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using MonoDevelop.Components.Commands; -using System.Linq; -using MonoDevelop.Ide; -using MonoDevelop.Ide.Gui.Content; -using Mono.TextEditor; - -namespace MonoDevelop.PlayScript.Highlighting -{ - enum MoveToUsagesCommand { - PrevUsage, - NextUsage - } - - class MoveToPrevUsageHandler : CommandHandler - { - protected override void Update (CommandInfo info) - { - MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument; - if (doc == null || doc.Editor == null) { - info.Visible = info.Enabled = false; - return; - } - - info.Visible = info.Enabled = true; - } - - internal static HighlightUsagesExtension GetHighlightUsageExtension (MonoDevelop.Ide.Gui.Document doc) - { - return doc.GetContent (); - } - protected override void Run () - { - MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument; - HighlightUsagesExtension ext = GetHighlightUsageExtension (doc); - if (ext == null) - return; - if (ext.IsTimerOnQueue) - ext.ForceUpdate (); - - var caretOffset = doc.Editor.Caret.Offset; - for (int i = 0; i < ext.UsagesSegments.Count; i++) { - if (ext.UsagesSegments [i].TextSegment.Contains (caretOffset)) - MoveToNextUsageHandler.MoveToSegment (doc, ext.UsagesSegments [(i + ext.UsagesSegments.Count - 1) % ext.UsagesSegments.Count]); - } - } - } - - class MoveToNextUsageHandler : CommandHandler - { - protected override void Update (CommandInfo info) - { - MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument; - if (doc == null || doc.Editor == null) { - info.Visible = info.Enabled = false; - return; - } - - info.Visible = info.Enabled = true; - } - - protected override void Run () - { - MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument; - HighlightUsagesExtension ext = MoveToPrevUsageHandler.GetHighlightUsageExtension (doc); - if (ext == null) - return; - if (ext.IsTimerOnQueue) - ext.ForceUpdate (); - if (ext == null || ext.Markers.Count == 0) - return; - - var caretOffset = doc.Editor.Caret.Offset; - for (int i = 0; i < ext.UsagesSegments.Count; i++) { - if (ext.UsagesSegments [i].TextSegment.Contains (caretOffset)) - MoveToNextUsageHandler.MoveToSegment (doc, ext.UsagesSegments [(i + 1) % ext.UsagesSegments.Count]); - } - } - - public static void MoveToSegment (MonoDevelop.Ide.Gui.Document doc, TextSegment segment) - { - if (segment.IsInvalid || segment.IsEmpty) - return; - TextEditorData data = doc.Editor; - data.Caret.Offset = segment.Offset; - data.Parent.ScrollTo (segment.EndOffset); - - var loc = data.Document.OffsetToLocation (segment.EndOffset); - if (data.Parent.TextViewMargin.ColumnToX (data.Document.GetLine (loc.Line), loc.Column) < data.HAdjustment.PageSize) - data.HAdjustment.Value = 0; - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Parser/CSharpFoldingParser.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Parser/CSharpFoldingParser.cs deleted file mode 100644 index 66a9bdd..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Parser/CSharpFoldingParser.cs +++ /dev/null @@ -1,265 +0,0 @@ -// -// CSharpFoldingParser.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2012 Xamarin Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory; -using ICSharpCode.NRefactory.TypeSystem; -using ICSharpCode.NRefactory.PlayScript; - -namespace MonoDevelop.PlayScript.Parser -{ - unsafe class CSharpFoldingParser : IFoldingParser - { - #region IFoldingParser implementation - - static unsafe bool StartsIdentifier (char* ptr, char* endPtr, string identifier) - { - fixed (char* startId = identifier) { - char* idPtr = startId; - char* endId = startId + identifier.Length; - while (idPtr < endId) { - if (ptr >= endPtr) - return false; - if (*idPtr != *ptr) - return false; - idPtr++; - ptr++; - } - return true; - } - } - - static unsafe void SkipWhitespaces (ref char* ptr, char* endPtr, ref int column) - { - while (ptr < endPtr) { - char ch = *ptr; - if (ch != ' ' && ch != '\t') - return; - column++; - ptr++; - } - } - - static unsafe string ReadToEol (string content, ref char* ptr, char* endPtr, ref int line, ref int column) - { - char* lineBeginPtr = ptr; - char* lineEndPtr = lineBeginPtr; - - while (ptr < endPtr) { - switch (*ptr) { - case '\n': - if (lineEndPtr == lineBeginPtr) - lineEndPtr = ptr; - line++; - column = 1; - ptr++; - fixed (char* startPtr = content) { - return content.Substring ((int)(lineBeginPtr - startPtr), (int)(lineEndPtr - lineBeginPtr)); - } - case '\r': - lineEndPtr = ptr; - if (ptr + 1 < endPtr && *(ptr + 1) == '\n') - ptr++; - goto case '\n'; - } - column++; - ptr++; - } - return ""; - } - - public unsafe ParsedDocument Parse (string fileName, string content) - { - var regionStack = new Stack> (); - var result = new DefaultParsedDocument (fileName); - bool inSingleComment = false, inMultiLineComment = false; - bool inString = false, inVerbatimString = false; - bool inChar = false; - bool inLineStart = true, hasStartedAtLine = false; - int line = 1, column = 1; - var startLoc = TextLocation.Empty; - - fixed (char* startPtr = content) { - char* endPtr = startPtr + content.Length; - char* ptr = startPtr; - char* beginPtr = ptr; - while (ptr < endPtr) { - switch (*ptr) { - case '#': - if (!inLineStart) - break; - inLineStart = false; - ptr++; - - if (StartsIdentifier (ptr, endPtr, "region")) { - var regionLocation = new TextLocation (line, column); - column++; - ptr += "region".Length; - column += "region".Length; - SkipWhitespaces (ref ptr, endPtr, ref column); - regionStack.Push (Tuple.Create (ReadToEol (content, ref ptr, endPtr, ref line, ref column), regionLocation)); - continue; - } else if (StartsIdentifier (ptr, endPtr, "endregion")) { - column++; - ptr += "endregion".Length; - column += "endregion".Length; - if (regionStack.Count > 0) { - var beginRegion = regionStack.Pop (); - result.Add (new FoldingRegion ( - beginRegion.Item1, - new DomRegion (beginRegion.Item2.Line, beginRegion.Item2.Column, line, column), - FoldType.UserRegion, - true)); - } - continue; - } else { - column++; - } - break; - case '/': - if (inString || inChar || inVerbatimString || inMultiLineComment || inSingleComment) { - inLineStart = false; - break; - } - if (ptr + 1 < endPtr) { - char nextCh = *(ptr + 1); - if (nextCh == '/') { - hasStartedAtLine = inLineStart; - beginPtr = ptr + 2; - startLoc = new TextLocation (line, column); - ptr++; - column++; - inSingleComment = true; - } else if (nextCh == '*') { - hasStartedAtLine = inLineStart; - beginPtr = ptr + 2; - startLoc = new TextLocation (line, column); - ptr++; - column++; - inMultiLineComment = true; - } - } - inLineStart = false; - break; - case '*': - inLineStart = false; - if (inString || inChar || inVerbatimString || inSingleComment) - break; - if (inMultiLineComment && ptr + 1 < endPtr) { - if (ptr + 1 < endPtr && *(ptr + 1) == '/') { - ptr += 2; - column += 2; - inMultiLineComment = false; - result.Add (new MonoDevelop.Ide.TypeSystem.Comment () { - Region = new DomRegion (startLoc, new TextLocation (line, column)), - OpenTag = "/*", - CommentType = MonoDevelop.Ide.TypeSystem.CommentType.Block, - Text = content.Substring ((int)(beginPtr - startPtr), (int)(ptr - beginPtr)), - CommentStartsLine = hasStartedAtLine - }); - continue; - } - } - break; - case '@': - inLineStart = false; - if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment) - break; - if (ptr + 1 < endPtr && *(ptr + 1) == '"') { - ptr++; - column++; - inVerbatimString = true; - } - break; - case '\n': - if (inSingleComment && hasStartedAtLine) { - bool isDocumentation = *beginPtr == '/'; - if (isDocumentation) - beginPtr++; - - result.Add (new MonoDevelop.Ide.TypeSystem.Comment () { - Region = new DomRegion (startLoc, new TextLocation (line, column)), - CommentType = MonoDevelop.Ide.TypeSystem.CommentType.SingleLine, - OpenTag = "//", - Text = content.Substring ((int)(beginPtr - startPtr), (int)(ptr - beginPtr)), - CommentStartsLine = hasStartedAtLine, - IsDocumentation = isDocumentation - }); - inSingleComment = false; - } - inString = false; - inChar = false; - inLineStart = true; - line++; - column = 1; - ptr++; - continue; - case '\r': - if (ptr + 1 < endPtr && *(ptr + 1) == '\n') - ptr++; - goto case '\n'; - case '\\': - if (inString || inChar) - ptr++; - break; - case '"': - if (inSingleComment || inMultiLineComment || inChar) - break; - if (inVerbatimString) { - if (ptr + 1 < endPtr && *(ptr + 1) == '"') { - ptr++; - column++; - break; - } - inVerbatimString = false; - break; - } - inString = !inString; - break; - case '\'': - if (inSingleComment || inMultiLineComment || inString || inVerbatimString) - break; - inChar = !inChar; - break; - default: - inLineStart &= *ptr == ' ' || *ptr == '\t'; - break; - } - - column++; - ptr++; - } - } - foreach (var fold in result.Comments.ToFolds ()) { - result.Add (fold); - } - return result; - } - #endregion - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Parser/McsParser.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Parser/McsParser.cs deleted file mode 100644 index d80b551..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Parser/McsParser.cs +++ /dev/null @@ -1,1171 +0,0 @@ -// -// McsParser.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.CodeDom; -using System.Collections.Generic; -using System.IO; -using System.Text; -using Mono.CSharp; -using MonoDevelop.CSharp.Project; -using MonoDevelop.CSharp.Resolver; -using MonoDevelop.Projects; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; -using System.Linq; - -namespace MonoDevelop.CSharp.Parser -{ - public class McsParser : AbstractParser - { - public override IExpressionFinder CreateExpressionFinder (ProjectDom dom) - { - return new NewCSharpExpressionFinder (dom); - } - - public override IResolver CreateResolver (ProjectDom dom, object editor, string fileName) - { - MonoDevelop.Ide.Gui.Document doc = (MonoDevelop.Ide.Gui.Document)editor; - if (doc.Editor == null) - return null; - - return new NRefactoryResolver (dom, doc.CompilationUnit, ICSharpCode.OldNRefactory.SupportedLanguage.CSharp, doc.Editor, fileName); - } - - public class ErrorReportPrinter : ReportPrinter - { - public readonly List Errors = new List (); - - public override void Print (AbstractMessage msg) - { - base.Print (msg); - Error newError = new Error (msg.IsWarning ? ErrorType.Warning : ErrorType.Error, msg.Location.Row, msg.Location.Column, msg.Text); - Errors.Add (newError); - } - } - - static string GetLangString (LangVersion ver) - { - switch (ver) { - case LangVersion.Default: - return "Default"; - case LangVersion.ISO_1: - return "ISO-1"; - case LangVersion.ISO_2: - return "ISO-2"; - } - return "Default"; - } - - public override ParsedDocument Parse (ProjectDom dom, string fileName, string content) - { - var result = new ParsedDocument (fileName); - var unit = new MonoDevelop.Projects.Dom.CompilationUnit (fileName); - result.CompilationUnit = unit; - - if (string.IsNullOrEmpty (content)) - return result; - - lock (CompilerCallableEntryPoint.parseLock) { - var tagComments = ProjectDomService.SpecialCommentTags.GetNames (); - List compilerArguments = new List (); - if (dom != null && dom.Project != null && MonoDevelop.Ide.IdeApp.Workspace != null) { - DotNetProjectConfiguration configuration = dom.Project.GetConfiguration (MonoDevelop.Ide.IdeApp.Workspace.ActiveConfiguration) as DotNetProjectConfiguration; - CSharpCompilerParameters par = configuration != null ? configuration.CompilationParameters as CSharpCompilerParameters : null; - if (par != null) { - foreach (var define in configuration.GetDefineSymbols ()) { - compilerArguments.Add ("-define:" + define); - } - if (par.UnsafeCode) - compilerArguments.Add ("-unsafe"); - if (par.TreatWarningsAsErrors) - compilerArguments.Add ("-warnaserror"); - if (!string.IsNullOrEmpty (par.NoWarnings)) - compilerArguments.Add ("-nowarn:" + string.Join (",", par.NoWarnings.Split (';', ',', ' ', '\t'))); - compilerArguments.Add ("-warn:" + par.WarningLevel); - compilerArguments.Add ("-langversion:" + GetLangString (par.LangVersion)); - if (par.GenerateOverflowChecks) - compilerArguments.Add ("-checked"); - } - } - - - CompilerCompilationUnit top; - ErrorReportPrinter errorReportPrinter = new ErrorReportPrinter (); - using (var stream = new MemoryStream (Encoding.UTF8.GetBytes (content))) { - top = CompilerCallableEntryPoint.ParseFile (compilerArguments.ToArray (), stream, fileName, errorReportPrinter); - } - if (top == null) - return null; - foreach (var special in top.SpecialsBag.Specials) { - var comment = special as SpecialsBag.Comment; - if (comment != null) { - VisitComment (result, comment, tagComments); - } else { - VisitPreprocessorDirective (result, special as SpecialsBag.PreProcessorDirective); - } - } - // convert DOM - var conversionVisitor = new ConversionVisitor (top.LocationsBag); - try { - conversionVisitor.Dom = dom; - conversionVisitor.ParsedDocument = result; - conversionVisitor.Unit = unit; - top.UsingsBag.Global.Accept (conversionVisitor); - top.ModuleCompiled.Accept (conversionVisitor); - } catch (Exception ex) { - System.Console.WriteLine (ex); - } - result.LanguageAST = new ICSharpCode.NRefactory.PlayScript.CSharpParser().Parse (top, 0); - // parser errorse - errorReportPrinter.Errors.ForEach (e => conversionVisitor.ParsedDocument.Add (e)); - return result; - } - } - - void VisitComment (ParsedDocument result, SpecialsBag.Comment comment, string[] tagComments) - { - var cmt = new MonoDevelop.Projects.Dom.Comment (comment.Content); - cmt.CommentStartsLine = comment.StartsLine; - switch (comment.CommentType) { - case SpecialsBag.CommentType.Multi: - cmt.CommentType = MonoDevelop.Projects.Dom.CommentType.MultiLine; - cmt.OpenTag = "/*"; - cmt.ClosingTag = "*/"; - break; - case SpecialsBag.CommentType.Single: - cmt.CommentType = MonoDevelop.Projects.Dom.CommentType.SingleLine; - cmt.OpenTag = "//"; - break; - case SpecialsBag.CommentType.Documentation: - cmt.CommentType = MonoDevelop.Projects.Dom.CommentType.SingleLine; - cmt.IsDocumentation = true; - cmt.OpenTag = "///"; - break; - } - cmt.Region = new DomRegion (comment.Line, comment.Col, comment.EndLine, comment.EndCol); - result.Comments.Add (cmt); - foreach (string tag in tagComments) { - int idx = comment.Content.IndexOf (tag); - if (idx < 0) - continue; - result.Add (new Tag (tag, comment.Content, cmt.Region)); - } - } - - Stack regions = new Stack (); - Stack ifBlocks = new Stack (); - List elifBlocks = new List (); - SpecialsBag.PreProcessorDirective elseBlock = null; - - Stack conditionalRegions = new Stack (); - ConditionalRegion ConditionalRegion { - get { - return conditionalRegions.Count > 0 ? conditionalRegions.Peek () : null; - } - } - - void CloseConditionBlock (DomLocation loc) - { - if (ConditionalRegion == null || ConditionalRegion.ConditionBlocks.Count == 0 || !ConditionalRegion.ConditionBlocks[ConditionalRegion.ConditionBlocks.Count - 1].End.IsEmpty) - return; - ConditionalRegion.ConditionBlocks[ConditionalRegion.ConditionBlocks.Count - 1].End = loc; - } - - void AddCurRegion (ParsedDocument result, int line, int col) - { - if (ConditionalRegion == null) - return; - ConditionalRegion.End = new DomLocation (line, col); - result.Add (ConditionalRegion); - conditionalRegions.Pop (); - } - - static ICSharpCode.OldNRefactory.PrettyPrinter.CSharpOutputVisitor visitor = new ICSharpCode.OldNRefactory.PrettyPrinter.CSharpOutputVisitor (); - - void VisitPreprocessorDirective (ParsedDocument result, SpecialsBag.PreProcessorDirective directive) - { - DomLocation loc = new DomLocation (directive.Line, directive.Col); - switch (directive.Cmd) { - case Tokenizer.PreprocessorDirective.If: - conditionalRegions.Push (new ConditionalRegion (visitor.Text)); - ifBlocks.Push (directive); - ConditionalRegion.Start = loc; - break; - case Tokenizer.PreprocessorDirective.Elif: - CloseConditionBlock (new DomLocation (directive.EndLine, directive.EndCol)); - if (ConditionalRegion != null) - ConditionalRegion.ConditionBlocks.Add (new ConditionBlock (visitor.Text, loc)); - break; - case Tokenizer.PreprocessorDirective.Else: - CloseConditionBlock (new DomLocation (directive.EndLine, directive.EndCol)); - if (ConditionalRegion != null) - ConditionalRegion.ElseBlock = new DomRegion (loc, DomLocation.Empty); - break; - case Tokenizer.PreprocessorDirective.Endif: - DomLocation endLoc = new DomLocation (directive.EndLine, directive.EndCol); - CloseConditionBlock (endLoc); - if (ConditionalRegion != null && !ConditionalRegion.ElseBlock.Start.IsEmpty) - ConditionalRegion.ElseBlock = new DomRegion (ConditionalRegion.ElseBlock.Start, endLoc); - AddCurRegion (result, directive.EndLine, directive.EndCol); - if (ifBlocks.Count > 0) { - var ifBlock = ifBlocks.Pop (); - DomRegion dr = new DomRegion (ifBlock.Line, ifBlock.Col, directive.EndLine, directive.EndCol); - result.Add (new FoldingRegion ("#if " + ifBlock.Arg.Trim (), dr, FoldType.UserRegion, false)); - foreach (var d in elifBlocks) { - dr.Start = new DomLocation (d.Line, d.Col); - result.Add (new FoldingRegion ("#elif " + ifBlock.Arg.Trim (), dr, FoldType.UserRegion, false)); - } - if (elseBlock != null) { - dr.Start = new DomLocation (elseBlock.Line, elseBlock.Col); - result.Add (new FoldingRegion ("#else", dr, FoldType.UserRegion, false)); - } - } - elseBlock = null; - break; - case Tokenizer.PreprocessorDirective.Define: - result.Add (new PreProcessorDefine (directive.Arg, loc)); - break; - case Tokenizer.PreprocessorDirective.Region: - regions.Push (directive); - break; - case Tokenizer.PreprocessorDirective.Endregion: - if (regions.Count > 0) { - var start = regions.Pop (); - DomRegion dr = new DomRegion (start.Line, start.Col, directive.EndLine, directive.EndCol); - result.Add (new FoldingRegion (start.Arg, dr, FoldType.UserRegion, true)); - } - break; - } - } - - class ConversionVisitor : StructuralVisitor - { - public ProjectDom Dom { - get; - set; - } - - public ParsedDocument ParsedDocument { - get; - set; - } - - public LocationsBag LocationsBag { - get; - private set; - } - - public MonoDevelop.Projects.Dom.CompilationUnit Unit { - get; - set; - } - static string[] keywordTable; - static ConversionVisitor () - { - keywordTable = new string[255]; - for (int i = 0; i < 255; i++) - keywordTable [i] = DomReturnType.Void.FullName; - - keywordTable [(int)BuiltinTypeSpec.Type.Other] = DomReturnType.Void.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.String] = DomReturnType.String.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Int] = DomReturnType.Int32.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.UInt] = DomReturnType.UInt32.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Long] = DomReturnType.Int64.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.ULong] = DomReturnType.UInt64.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Object] = DomReturnType.Object.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Float] = DomReturnType.Float.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Double] = DomReturnType.Double.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Byte] = DomReturnType.Byte.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.SByte] = DomReturnType.SByte.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Short] = DomReturnType.Int16.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.UShort] = DomReturnType.UInt16.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Decimal] = DomReturnType.Decimal.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Char] = DomReturnType.Char.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.Bool] = DomReturnType.Bool.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.IntPtr] = DomReturnType.IntPtr.FullName; - keywordTable [(int)BuiltinTypeSpec.Type.UIntPtr] = DomReturnType.UIntPtr.FullName; - } - - public ConversionVisitor (LocationsBag locationsBag) - { - this.LocationsBag = locationsBag; - } - - int lastComment = 0; - string RetrieveDocumentation (int upToLine) - { - StringBuilder result = null; - while (lastComment < ParsedDocument.Comments.Count) { - var cur = ParsedDocument.Comments[lastComment]; - if (cur.Region.Start.Line >= upToLine) - break; - if (cur.IsDocumentation) { - if (result == null) - result = new StringBuilder (); - result.Append (cur.Text); - } - lastComment++; - } - return result == null ? null : result.ToString (); - } - - public static DomLocation Convert (Mono.CSharp.Location loc) - { - return new DomLocation (loc.Row, loc.Column); - } - - public DomRegion ConvertRegion (Mono.CSharp.Location start, Mono.CSharp.Location end) - { - DomLocation startLoc = Convert (start); - var endLoc = Convert (end); - endLoc.Column++; - return new DomRegion (startLoc, endLoc); - } - - static MonoDevelop.Projects.Dom.Modifiers ConvertModifiers (Mono.CSharp.Modifiers modifiers) - { - MonoDevelop.Projects.Dom.Modifiers result = MonoDevelop.Projects.Dom.Modifiers.None; - - if ((modifiers & Mono.CSharp.Modifiers.PUBLIC) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Public; - if ((modifiers & Mono.CSharp.Modifiers.PRIVATE) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Private; - if ((modifiers & Mono.CSharp.Modifiers.PROTECTED) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Protected; - if ((modifiers & Mono.CSharp.Modifiers.INTERNAL) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Internal; - - if ((modifiers & Mono.CSharp.Modifiers.ABSTRACT) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Abstract; - if ((modifiers & Mono.CSharp.Modifiers.NEW) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.New; - if ((modifiers & Mono.CSharp.Modifiers.SEALED) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Sealed; - if ((modifiers & Mono.CSharp.Modifiers.READONLY) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Readonly; - if ((modifiers & Mono.CSharp.Modifiers.VIRTUAL) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Virtual; - if ((modifiers & Mono.CSharp.Modifiers.OVERRIDE) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Override; - if ((modifiers & Mono.CSharp.Modifiers.EXTERN) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Extern; - if ((modifiers & Mono.CSharp.Modifiers.VOLATILE) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Volatile; - if ((modifiers & Mono.CSharp.Modifiers.UNSAFE) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Unsafe; - - if ((modifiers & Mono.CSharp.Modifiers.STATIC) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Static; - - if ((modifiers & Mono.CSharp.Modifiers.PARTIAL) != 0) - result |= MonoDevelop.Projects.Dom.Modifiers.Partial; - return result; - } - - void AddType (IType child) - { - if (typeStack.Count > 0) { - typeStack.Peek ().Add (child); - } else { - Unit.Add (child); - } - } - - - void AddTypeArguments (ATypeNameExpression texpr, DomReturnType result) - { - if (!texpr.HasTypeArguments) - return; - foreach (var arg in texpr.TypeArguments.Args) { - result.AddTypeParameter (ConvertReturnType (arg)); - } - } - - IReturnType ConvertReturnType (Mono.CSharp.Expression typeName) - { - if (typeName is TypeExpression) { - var typeExpr = (Mono.CSharp.TypeExpression)typeName; - return new DomReturnType (keywordTable [(int)typeExpr.Type.BuiltinType]); - } - - if (typeName is Mono.CSharp.QualifiedAliasMember) { - var qam = (Mono.CSharp.QualifiedAliasMember)typeName; - // TODO: Overwork the return type model - atm we don't have a good representation - // for qualified alias members. - return new DomReturnType (qam.Name); - } - - if (typeName is MemberAccess) { - MemberAccess ma = (MemberAccess)typeName; - var baseType = (DomReturnType)ConvertReturnType (ma.LeftExpression); - baseType.Parts.Add (new ReturnTypePart (ma.Name)); - AddTypeArguments (ma, baseType); - return baseType; - } - - if (typeName is SimpleName) { - var sn = (SimpleName)typeName; - var result = new DomReturnType (sn.Name); - AddTypeArguments (sn, result); - return result; - } - - if (typeName is ComposedCast) { - var cc = (ComposedCast)typeName; - var baseType = (DomReturnType)ConvertReturnType (cc.Left); - if (cc.Spec.IsNullable) { - return new DomReturnType ("System.Nullable", true, new IReturnType[] { baseType }); - } else if (cc.Spec.IsPointer) { - baseType.PointerNestingLevel++; - } else { - baseType.ArrayDimensions++; - baseType.SetDimension (baseType.ArrayDimensions - 1, cc.Spec.Dimension - 1); - } - return baseType; - } - MonoDevelop.Core.LoggingService.LogError ("Error while converting :" + typeName + " - unknown type name"); - return new DomReturnType (DomReturnType.Void.FullName); - } - - - IReturnType ConvertReturnType (MemberName name) - { - return ConvertReturnType (name.GetTypeExpression ()); - } - - #region Global - string currentNamespaceName = ""; - Stack currentNamespace = new Stack (); - - string ConvertToString (MemberName name) - { - if (name == null) - return ""; - - return name.Left != null ? ConvertToString (name.Left) + "." + name.Name : name.Name; - } - - public override void Visit (ModuleContainer mc) - { - foreach (var at in ConvertAttributes (mc.OptAttributes, mc)) - Unit.Add (at); - } - - public override void Visit (UsingsBag.Namespace nspace) - { - string oldNamespace = currentNamespaceName; - currentNamespace.Push (nspace); - if (nspace.Name != null) { // no need to push the global namespace - string name = ConvertToString (nspace.Name); - string[] splittedNamespace = name.Split ('.'); - for (int i = splittedNamespace.Length; i > 0; i--) { - DomUsing domUsing = new DomUsing (); - domUsing.IsFromNamespace = true; - domUsing.Region = domUsing.ValidRegion = ConvertRegion (nspace.OpenBrace, nspace.CloseBrace); - domUsing.Add (string.Join (".", splittedNamespace, 0, i)); - Unit.Add (domUsing); - } - currentNamespaceName = string.IsNullOrEmpty (currentNamespaceName) ? name : currentNamespaceName + "." + name; - } - - VisitNamespaceUsings (nspace); - VisitNamespaceBody (nspace); - currentNamespace.Pop (); - currentNamespaceName = oldNamespace; - } - - public override void Visit (UsingsBag.Using u) - { - if (!string.IsNullOrEmpty (currentNamespaceName)) { - DomUsing relativeNamespaceUsing = new DomUsing (); - relativeNamespaceUsing.Region = ConvertRegion (u.UsingLocation, u.SemicolonLocation); - relativeNamespaceUsing.ValidRegion = ConvertRegion (currentNamespace.Peek ().OpenBrace, currentNamespace.Peek ().CloseBrace); - relativeNamespaceUsing.Add (currentNamespaceName + "." + ConvertToString (u.NSpace)); - Unit.Add (relativeNamespaceUsing); - } - DomUsing domUsing = new DomUsing (); - domUsing.Region = ConvertRegion (u.UsingLocation, u.SemicolonLocation); - domUsing.ValidRegion = ConvertRegion (currentNamespace.Peek ().OpenBrace, currentNamespace.Peek ().CloseBrace); - domUsing.Add (ConvertToString (u.NSpace)); - Unit.Add (domUsing); - } - - public override void Visit (UsingsBag.AliasUsing u) - { - DomUsing domUsing = new DomUsing (); - domUsing.Region = ConvertRegion (u.UsingLocation, u.SemicolonLocation); - domUsing.ValidRegion = ConvertRegion (currentNamespace.Peek ().OpenBrace, currentNamespace.Peek ().CloseBrace); - domUsing.Add (u.Identifier.Value, new DomReturnType (ConvertToString (u.Nspace))); - Unit.Add (domUsing); - } - - public override void Visit (MemberCore member) - { - Console.WriteLine ("Unknown member:"); - Console.WriteLine (member.GetType () + "-> Member {0}", member.GetSignatureForError ()); - } - - Stack typeStack = new Stack (); - - void VisitType (TypeContainer c, ClassType classType) - { - DomType newType = new DomType (); - newType.SourceProjectDom = Dom; - newType.CompilationUnit = Unit; - if (typeStack.Count == 0 && !string.IsNullOrEmpty (currentNamespaceName)) - newType.Namespace = currentNamespaceName; - - newType.Name = ConvertQuoted (c.MemberName.Name); - newType.Location = Convert (c.MemberName.Location); - newType.ClassType = classType; - var location = LocationsBag.GetMemberLocation (c); - - if (location != null && location.Count > 1) { - var region = ConvertRegion (c.MemberName.Location, location[location.Count - 1]); - region.Start = new DomLocation (region.Start.Line, region.Start.Column + c.MemberName.Name.Length); - newType.BodyRegion = region; - } else { - var region = ConvertRegion (c.MemberName.Location, c.MemberName.Location); - region.Start = new DomLocation (region.Start.Line, region.Start.Column + c.MemberName.Name.Length); - region.End = new DomLocation (int.MaxValue, int.MaxValue); - newType.BodyRegion = region; - } - - newType.Modifiers = ConvertModifiers (c.ModFlags); - AddAttributes (newType, c.OptAttributes, c); - AddTypeParameter (newType, c); - - if (c.TypeBaseExpressions != null) { - foreach (var type in c.TypeBaseExpressions) { - var baseType = ConvertReturnType (type); - // Console.WriteLine (newType.Name + " -- " + baseType); - if (newType.BaseType == null) { - newType.BaseType = baseType; - } else { - newType.AddInterfaceImplementation (baseType); - } - } - } - - AddType (newType); - // visit members - typeStack.Push (newType); - foreach (MemberCore member in c.OrderedAllMembers) { - member.Accept (this); - } - typeStack.Pop (); - } - - public override void Visit (Class c) - { - VisitType (c, ClassType.Class); - } - - public override void Visit (Struct s) - { - VisitType (s, ClassType.Struct); - } - - public override void Visit (Interface i) - { - VisitType (i, ClassType.Interface); - } - - public override void Visit (Mono.CSharp.Enum e) - { - VisitType (e, ClassType.Enum); - } - - class CodeAstVisitor : StructuralVisitor - { - public override object Visit (Constant constant) - { - return new CodePrimitiveExpression (constant.GetValue ()); - } - - public override object Visit (Unary unaryExpression) - { - var exprResult = (CodeExpression)unaryExpression.Expr.Accept (this); - - switch (unaryExpression.Oper) { - case Unary.Operator.UnaryPlus: - return exprResult; - case Unary.Operator.UnaryNegation: // -a => 0 - a - return new CodeBinaryOperatorExpression (new CodePrimitiveExpression (0), CodeBinaryOperatorType.Subtract, exprResult); - case Unary.Operator.LogicalNot: // !a => a == false - return new CodeBinaryOperatorExpression (exprResult, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (false)); - } - return exprResult; - } - static CodeBinaryOperatorType Convert (Binary.Operator o) - { - switch (o) { - case Binary.Operator.Multiply: - return CodeBinaryOperatorType.Multiply; - case Binary.Operator.Division: - return CodeBinaryOperatorType.Divide; - case Binary.Operator.Modulus: - return CodeBinaryOperatorType.Modulus; - case Binary.Operator.Addition: - return CodeBinaryOperatorType.Add; - case Binary.Operator.Subtraction: - return CodeBinaryOperatorType.Subtract; - case Binary.Operator.LeftShift: - case Binary.Operator.RightShift: - return CodeBinaryOperatorType.Multiply; // unsupported - case Binary.Operator.LessThan: - return CodeBinaryOperatorType.LessThan; - case Binary.Operator.GreaterThan: - return CodeBinaryOperatorType.GreaterThan; - case Binary.Operator.LessThanOrEqual: - return CodeBinaryOperatorType.LessThanOrEqual; - case Binary.Operator.GreaterThanOrEqual: - return CodeBinaryOperatorType.GreaterThanOrEqual; - case Binary.Operator.Equality: - return CodeBinaryOperatorType.IdentityEquality; - case Binary.Operator.Inequality: - return CodeBinaryOperatorType.IdentityInequality; - case Binary.Operator.BitwiseAnd: - return CodeBinaryOperatorType.BitwiseAnd; - case Binary.Operator.ExclusiveOr: - return CodeBinaryOperatorType.BitwiseOr; // unsupported - case Binary.Operator.BitwiseOr: - return CodeBinaryOperatorType.BitwiseOr; - case Binary.Operator.LogicalAnd: - return CodeBinaryOperatorType.BooleanAnd; - case Binary.Operator.LogicalOr: - return CodeBinaryOperatorType.BooleanOr; - - } - return CodeBinaryOperatorType.Add; - } - - public override object Visit (Binary binaryExpression) - { - return new CodeBinaryOperatorExpression ( - (CodeExpression)binaryExpression.Left.Accept (this), - Convert (binaryExpression.Oper), - (CodeExpression)binaryExpression.Right.Accept (this)); - } - } - - - System.CodeDom.CodeExpression ResolveMemberAccessExpression (Mono.CSharp.Expression expr) - { - if (expr is MemberAccess) { - var ma = (MemberAccess)expr; - return new CodeFieldReferenceExpression (ResolveMemberAccessExpression (ma.LeftExpression), ma.Name); - } - if (expr is SimpleName) - return new CodeTypeReferenceExpression (((SimpleName)expr).Name); - return null; - } - - IEnumerable ConvertAttributes (Attributes optAttributes, IMemberContext mc) - { - List atts = new List (); - - if (optAttributes == null || optAttributes.Attrs == null) - return atts; - ResolveContext ctx = new ResolveContext (mc); - foreach (var section in optAttributes.Sections) { - - foreach (var attr in section) { - DomAttribute domAttribute = new DomAttribute (); - domAttribute.Name = ConvertQuoted (attr.Name); - domAttribute.Region = ConvertRegion (attr.Location, attr.Location); - domAttribute.AttributeType = ConvertReturnType (attr.TypeNameExpression); - if (attr.PosArguments != null) { - for (int i = 0; i < attr.PosArguments.Count; i++) { - CodeExpression domExp; - var exp = attr.PosArguments [i].Expr; - - if (exp is TypeOf) { - TypeOf tof = (TypeOf)exp; - IReturnType rt = ConvertReturnType (tof.TypeExpression); - domExp = new CodeTypeOfExpression (rt.FullName); - } else if (exp is Binary) { - // Currently unsupported in the old dom (will be in the new dom) - continue; - } else if (exp is Constant) { - try { - var res = exp.Resolve (ctx); - var val = res as Constant; - if (val == null) - continue; - domExp = new CodePrimitiveExpression (val.GetValue ()); - } catch { - continue; - } - } else { - try { - domExp = ResolveMemberAccessExpression (exp); - } catch { - continue; - } - } - if (domExp != null) - domAttribute.AddPositionalArgument (domExp); - } - } - if (attr.NamedArguments != null) { - for (int i = 0; i < attr.NamedArguments.Count; i++) { - var val = attr.NamedArguments [i].Expr as Constant; - if (val == null) - continue; - domAttribute.AddNamedArgument (((NamedArgument)attr.NamedArguments [i]).Name, new CodePrimitiveExpression (val.GetValue ())); - } - } - - atts.Add (domAttribute); - } - } - return atts; - } - - public void AddAttributes (MonoDevelop.Projects.Dom.AbstractMember member, Attributes optAttributes, IMemberContext mc) - { - foreach (var attr in ConvertAttributes (optAttributes, mc)) - member.Add (attr); - } - - MonoDevelop.Projects.Dom.TypeParameter ConvertTemplateDefinition (Mono.CSharp.TypeParameter parameter) - { - var result = new MonoDevelop.Projects.Dom.TypeParameter (parameter.Name); - if (parameter.Constraints != null) { - foreach (var constraintExpr in parameter.Constraints.ConstraintExpressions) { - if (constraintExpr is SpecialContraintExpr) { - var sce = (SpecialContraintExpr)constraintExpr; - if (sce.Constraint == SpecialConstraint.Struct) - result.AddConstraint (DomReturnType.ValueType); - if (sce.Constraint == SpecialConstraint.Class) - result.AddConstraint (DomReturnType.Object); - if (sce.Constraint == SpecialConstraint.Constructor) - result.TypeParameterModifier |= TypeParameterModifier.HasDefaultConstructorConstraint; - } else { - result.AddConstraint (ConvertReturnType (constraintExpr)); - } - } - } - return result; - } - - public void AddTypeParameter (AbstractTypeParameterMember member, DeclSpace decl) - { - if (!decl.IsGeneric || decl.CurrentTypeParameters == null) - return; - - foreach (var typeParameter in decl.CurrentTypeParameters) { - var par = ConvertTemplateDefinition (typeParameter); - member.AddTypeParameter (par); - } - } - - public override void Visit (Mono.CSharp.Delegate d) - { - DomType delegateType = DomType.CreateDelegate (Unit, d.MemberName.Name, Convert (d.MemberName.Location), ConvertReturnType (d.ReturnType), null); - delegateType.SourceProjectDom = Dom; - delegateType.Location = Convert (d.MemberName.Location); - delegateType.Documentation = RetrieveDocumentation (d.MemberName.Location.Row); - delegateType.Modifiers = ConvertModifiers (d.ModFlags); - AddAttributes (delegateType, d.OptAttributes, d); - - AddParameter ((MonoDevelop.Projects.Dom.AbstractMember)delegateType.Methods.First (), d.Parameters); - AddTypeParameter (delegateType, d); - AddType (delegateType); - - } - #endregion - - #region Type members - - - public override void Visit (FixedField f) - { - DomField field = new DomField (); - field.Name = ConvertQuoted (f.MemberName.Name); - field.Documentation = RetrieveDocumentation (f.Location.Row); - field.Location = Convert (f.MemberName.Location); - field.Modifiers = ConvertModifiers (f.ModFlags) | MonoDevelop.Projects.Dom.Modifiers.Fixed; - field.ReturnType = ConvertReturnType (f.TypeName); - AddAttributes (field, f.OptAttributes, f); - field.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (field); - if (f.Declarators != null) { - foreach (var decl in f.Declarators) { - field = new DomField (); - field.Name = ConvertQuoted (decl.Name.Value); - field.Location = Convert (decl.Name.Location); - field.Modifiers = ConvertModifiers (f.ModFlags) | MonoDevelop.Projects.Dom.Modifiers.Fixed; - field.ReturnType = ConvertReturnType (f.TypeName); - AddAttributes (field, f.OptAttributes, f); - field.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (field); - } - } - } - - public override void Visit (Field f) - { - var field = new DomField (); - field.Name = ConvertQuoted (f.MemberName.Name); - field.Documentation = RetrieveDocumentation (f.Location.Row); - field.Location = Convert (f.MemberName.Location); - field.Modifiers = ConvertModifiers (f.ModFlags); - field.ReturnType = ConvertReturnType (f.TypeName); - AddAttributes (field, f.OptAttributes, f); - field.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (field); - - if (f.Declarators != null) { - foreach (var decl in f.Declarators) { - field = new DomField (); - field.Name = ConvertQuoted (decl.Name.Value); - field.Location = Convert (decl.Name.Location); - field.Modifiers = ConvertModifiers (f.ModFlags); - field.ReturnType = ConvertReturnType (f.TypeName); - AddAttributes (field, f.OptAttributes, f); - field.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (field); - } - } - } - - public override void Visit (Const f) - { - DomField field = new DomField (); - field.Name = ConvertQuoted (f.MemberName.Name); - field.Documentation = RetrieveDocumentation (f.Location.Row); - field.Location = Convert (f.MemberName.Location); - field.Modifiers = ConvertModifiers (f.ModFlags) | MonoDevelop.Projects.Dom.Modifiers.Const; - field.ReturnType = ConvertReturnType (f.TypeName); - AddAttributes (field, f.OptAttributes, f); - field.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (field); - if (f.Declarators != null) { - foreach (var decl in f.Declarators) { - field = new DomField (); - field.Name = ConvertQuoted (decl.Name.Value); - field.Location = Convert (decl.Name.Location); - field.Modifiers = ConvertModifiers (f.ModFlags) | MonoDevelop.Projects.Dom.Modifiers.Const; - field.ReturnType = ConvertReturnType (f.TypeName); - AddAttributes (field, f.OptAttributes, f); - field.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (field); - } - } - } - - void AddExplicitInterfaces (MonoDevelop.Projects.Dom.AbstractMember member, InterfaceMemberBase mcsMember) - { - if (!mcsMember.IsExplicitImpl) - return; - member.AddExplicitInterface (ConvertReturnType (mcsMember.MemberName.Left)); - } - - public override void Visit (EventField e) - { - var evt = new DomEvent (); - evt.Name = ConvertQuoted (e.MemberName.Name); - evt.Documentation = RetrieveDocumentation (e.Location.Row); - evt.Location = Convert (e.MemberName.Location); - evt.Modifiers = ConvertModifiers (e.ModFlags); - evt.ReturnType = ConvertReturnType (e.TypeName); - AddAttributes (evt, e.OptAttributes, e); - AddExplicitInterfaces (evt, e); - evt.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (evt); - if (e.Declarators != null) { - foreach (var decl in e.Declarators) { - evt = new DomEvent (); - evt.Name = ConvertQuoted (decl.Name.Value); - evt.Location = Convert (decl.Name.Location); - evt.Modifiers = ConvertModifiers (e.ModFlags); - evt.ReturnType = ConvertReturnType (e.TypeName); - AddAttributes (evt, e.OptAttributes, e); - evt.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (evt); - } - } - } - - public override void Visit (EventProperty e) - { - DomEvent evt = new DomEvent (); - evt.Name = ConvertQuoted (e.MemberName.Name); - evt.Documentation = RetrieveDocumentation (e.Location.Row); - evt.Location = Convert (e.MemberName.Location); - evt.Modifiers = ConvertModifiers (e.ModFlags); - evt.ReturnType = ConvertReturnType (e.TypeName); - var location = LocationsBag.GetMemberLocation (e); - if (location != null) - evt.BodyRegion = ConvertRegion (location[1], location[location.Count - 1]); - - AddAttributes (evt, e.OptAttributes, e); - AddExplicitInterfaces (evt, e); - - evt.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (evt); - } - - public override void Visit (Property p) - { - DomProperty property = new DomProperty (); - property.Name = ConvertQuoted (p.MemberName.Name); - property.Documentation = RetrieveDocumentation (p.Location.Row); - property.Location = Convert (p.MemberName.Location); - property.GetterModifier = property.SetterModifier = ConvertModifiers (p.ModFlags); - - var location = LocationsBag.GetMemberLocation (p); - if (location != null && location.Count >= 1) { - var endLoc = location.Count == 1 ? location[0] : location[location.Count - 1]; - property.BodyRegion = ConvertRegion (location[0], endLoc); - } else { - property.BodyRegion = DomRegion.Empty; - } - property.ReturnType = ConvertReturnType (p.TypeName); - - AddAttributes (property, p.OptAttributes, p); - AddExplicitInterfaces (property, p); - - if (p.Get != null) { - property.PropertyModifier |= PropertyModifier.HasGet; - if ((p.Get.ModFlags & Mono.CSharp.Modifiers.AccessibilityMask) != 0) - property.GetterModifier = ConvertModifiers (p.Get.ModFlags); - if (p.Get.Block != null) { - property.GetRegion = ConvertRegion (p.Get.Location, p.Get.Block.EndLocation); - } else { - var getLocation = LocationsBag.GetMemberLocation (p.Get); - property.GetRegion = ConvertRegion (p.Get.Location, getLocation.Count > 0 ? getLocation[0] : p.Get.Location); - } - } - - if (p.Set != null) { - property.PropertyModifier |= PropertyModifier.HasSet; - if ((p.Set.ModFlags & Mono.CSharp.Modifiers.AccessibilityMask) != 0) - property.SetterModifier = ConvertModifiers (p.Set.ModFlags); - if (p.Set.Block != null) { - property.SetRegion = ConvertRegion (p.Set.Location, p.Set.Block.EndLocation); - } else { - var setLocation = LocationsBag.GetMemberLocation (p.Set); - property.SetRegion = ConvertRegion (p.Set.Location, setLocation.Count > 0 ? setLocation[0] : p.Set.Location); - } - } - property.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (property); - } - - static string ConvertQuoted (string name) - { - if (name == null) - return null; - return name.StartsWith ("@") ? name.Substring (1) : name; - } - - public void AddParameter (MonoDevelop.Projects.Dom.AbstractMember member, AParametersCollection parameters) - { - for (int i = 0; i < parameters.Count; i++) { - var p = (Parameter)parameters.FixedParameters[i]; - DomParameter parameter = new DomParameter (); - parameter.Name = ConvertQuoted (p.Name); - parameter.Location = Convert (p.Location); - parameter.ReturnType = ConvertReturnType (p.TypeExpression); - var modifiers = MonoDevelop.Projects.Dom.ParameterModifiers.None; - if ((p.ParameterModifier & Parameter.Modifier.OUT) == Parameter.Modifier.OUT) - modifiers |= MonoDevelop.Projects.Dom.ParameterModifiers.Out; - if ((p.ParameterModifier & Parameter.Modifier.REF) == Parameter.Modifier.REF) - modifiers |= MonoDevelop.Projects.Dom.ParameterModifiers.Ref; - if ((p.ParameterModifier & Parameter.Modifier.PARAMS) == Parameter.Modifier.PARAMS) - modifiers |= MonoDevelop.Projects.Dom.ParameterModifiers.Params; - if ((p.ParameterModifier & Parameter.Modifier.This) == Parameter.Modifier.This) - modifiers |= MonoDevelop.Projects.Dom.ParameterModifiers.This; - parameter.ParameterModifiers = modifiers; - member.Add (parameter); - } - } - - public override void Visit (Indexer i) - { - DomProperty indexer = new DomProperty (); - indexer.PropertyModifier |= PropertyModifier.IsIndexer; - indexer.Name = "this"; - indexer.Documentation = RetrieveDocumentation (i.Location.Row); - indexer.Location = Convert (i.Location); - indexer.GetterModifier = indexer.SetterModifier = ConvertModifiers (i.ModFlags); - var location = LocationsBag.GetMemberLocation (i); - if (location != null && location.Count >= 1) { - var endLoc = location.Count == 1 ? location[0] : location[location.Count - 1]; - indexer.BodyRegion = ConvertRegion (location[0], endLoc); - } else { - indexer.BodyRegion = DomRegion.Empty; - } - - indexer.ReturnType = ConvertReturnType (i.TypeName); - AddParameter (indexer, i.ParameterInfo); - - AddAttributes (indexer, i.OptAttributes, i); - AddExplicitInterfaces (indexer, i); - - if (i.Get != null) { - indexer.PropertyModifier |= PropertyModifier.HasGet; - if ((i.Get.ModFlags & Mono.CSharp.Modifiers.AccessibilityMask) != 0) - indexer.GetterModifier = ConvertModifiers (i.Get.ModFlags); - if (i.Get.Block != null) { - indexer.GetRegion = ConvertRegion (i.Get.Location, i.Get.Block.EndLocation); - } else { - var getLocation = LocationsBag.GetMemberLocation (i.Get); - indexer.GetRegion = ConvertRegion (i.Get.Location, getLocation.Count > 0 ? getLocation[0] : i.Get.Location); - } - } - - if (i.Set != null) { - indexer.PropertyModifier |= PropertyModifier.HasSet; - if ((i.Set.ModFlags & Mono.CSharp.Modifiers.AccessibilityMask) != 0) - indexer.SetterModifier = ConvertModifiers (i.Set.ModFlags); - if (i.Set.Block != null) { - indexer.SetRegion = ConvertRegion (i.Set.Location, i.Set.Block.EndLocation); - } else { - var setLocation = LocationsBag.GetMemberLocation (i.Set); - indexer.SetRegion = ConvertRegion (i.Set.Location, setLocation.Count > 0 ? setLocation[0] : i.Set.Location); - } - } - indexer.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (indexer); - } - - public override void Visit (Method m) - { - DomMethod method = new DomMethod (); - method.Name = ConvertQuoted (m.MemberName.Name); - method.Documentation = RetrieveDocumentation (m.Location.Row); - method.Location = Convert (m.MemberName.Location); - method.Modifiers = ConvertModifiers (m.ModFlags); - if (m.Block != null) { - var location = LocationsBag.GetMemberLocation (m); - var region = ConvertRegion (location != null ? location[1] : m.Block.StartLocation, m.Block.EndLocation); - if (location != null) - region.Start = new DomLocation (region.Start.Line, region.Start.Column + 1); - method.BodyRegion = region; - } - - method.ReturnType = ConvertReturnType (m.TypeName); - AddAttributes (method, m.OptAttributes, m); - AddParameter (method, m.ParameterInfo); - AddExplicitInterfaces (method, m); - method.Modifiers = ConvertModifiers (m.ModFlags); - if (method.IsStatic && method.Parameters.Count > 0 && method.Parameters[0].ParameterModifiers == ParameterModifiers.This) - method.MethodModifier |= MethodModifier.IsExtension; - if (m.GenericMethod != null) - AddTypeParameter (method, m.GenericMethod); - method.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (method); - } - - public override void Visit (Operator o) - { - DomMethod method = new DomMethod (); - method.Name = ConvertQuoted (o.MemberName.Name); - method.Documentation = RetrieveDocumentation (o.Location.Row); - method.Location = Convert (o.MemberName.Location); - method.Modifiers = ConvertModifiers (o.ModFlags); - if (o.Block != null) { - var location = LocationsBag.GetMemberLocation (o); - var region = ConvertRegion (location != null ? location[1] : o.Block.StartLocation, o.Block.EndLocation); - if (location != null) - region.Start = new DomLocation (region.Start.Line, region.Start.Column + 1); - method.BodyRegion = region; - } - method.Modifiers = ConvertModifiers (o.ModFlags) | MonoDevelop.Projects.Dom.Modifiers.SpecialName; - method.ReturnType = ConvertReturnType (o.TypeName); - AddAttributes (method, o.OptAttributes, o); - AddParameter (method, o.ParameterInfo); - AddExplicitInterfaces (method, o); - - method.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (method); - } - - public override void Visit (Constructor c) - { - DomMethod method = new DomMethod (); - method.Name = ".ctor"; - method.Documentation = RetrieveDocumentation (c.Location.Row); - method.Location = Convert (c.MemberName.Location); - method.Modifiers = ConvertModifiers (c.ModFlags); - if (c.Block != null) { - var location = LocationsBag.GetMemberLocation (c); - var region = ConvertRegion (location != null ? location[1] : c.Block.StartLocation, c.Block.EndLocation); - if (location != null) - region.Start = new DomLocation (region.Start.Line, region.Start.Column + 1); - method.BodyRegion = region; - } - method.Modifiers = ConvertModifiers (c.ModFlags) | MonoDevelop.Projects.Dom.Modifiers.SpecialName; - method.MethodModifier |= MethodModifier.IsConstructor; - AddAttributes (method, c.OptAttributes, c); - AddParameter (method, c.ParameterInfo); - AddExplicitInterfaces (method, c); - method.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (method); - } - - public override void Visit (Destructor d) - { - DomMethod method = new DomMethod (); - method.Name = ".dtor"; - method.Documentation = RetrieveDocumentation (d.Location.Row); - method.Location = Convert (d.MemberName.Location); - if (d.Block != null) { - var location = LocationsBag.GetMemberLocation (d); - var region = ConvertRegion (location != null ? location[1] : d.Block.StartLocation, d.Block.EndLocation); - if (location != null) - region.Start = new DomLocation (region.Start.Line, region.Start.Column + 1); - method.BodyRegion = region; - } - method.Modifiers = ConvertModifiers (d.ModFlags) | MonoDevelop.Projects.Dom.Modifiers.SpecialName; - method.MethodModifier |= MethodModifier.IsFinalizer; - AddAttributes (method, d.OptAttributes, d); - AddExplicitInterfaces (method, d); - method.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (method); - } - - public override void Visit (EnumMember f) - { - DomField field = new DomField (); - field.Name = ConvertQuoted (f.MemberName.Name); - field.Documentation = RetrieveDocumentation (f.Location.Row); - // return types for enum fields are == null - field.Location = Convert (f.MemberName.Location); - field.Modifiers = MonoDevelop.Projects.Dom.Modifiers.Const | MonoDevelop.Projects.Dom.Modifiers.SpecialName| MonoDevelop.Projects.Dom.Modifiers.Public; - AddAttributes (field, f.OptAttributes, f); - field.DeclaringType = typeStack.Peek (); - typeStack.Peek ().Add (field); - } - #endregion - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Parser/TypeSystemProvider.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Parser/TypeSystemProvider.cs deleted file mode 100644 index 516549f..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Parser/TypeSystemProvider.cs +++ /dev/null @@ -1,469 +0,0 @@ -// -// TypeSystemParser.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2011 Mike Krüger -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.TypeSystem; -using System.Collections.Generic; -using MonoDevelop.Projects; -using MonoDevelop.PlayScript.Project; -using MonoDevelop.Ide.Tasks; -using System.Linq; -using ICSharpCode.NRefactory; -using MonoDevelop.PlayScript.Refactoring.CodeActions; -using MonoDevelop.Core; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using ICSharpCode.NRefactory.MonoPlayScript; -using MonoDevelop.PlayScript.Parser; - -namespace MonoDevelop.PlayScript.Parser -{ - public class TypeSystemParser : MonoDevelop.Ide.TypeSystem.TypeSystemParser - { - public override ParsedDocument Parse (bool storeAst, string fileName, System.IO.TextReader content, MonoDevelop.Projects.Project project = null) - { - var parser = new ICSharpCode.NRefactory.PlayScript.PlayScriptParser (GetCompilerArguments (project)); - parser.GenerateTypeSystemMode = !storeAst; - var result = new ParsedDocumentDecorator (); - - if (project != null) { - var projectFile = project.Files.GetFile (fileName); - if (projectFile != null && !TypeSystemParserNode.IsCompileBuildAction (projectFile.BuildAction)) - result.Flags |= ParsedDocumentFlags.NonSerializable; - } - - var tagComments = CommentTag.SpecialCommentTags.Select (t => t.Tag).ToArray (); - - parser.CompilationUnitCallback = delegate (CompilerCompilationUnit top) { - foreach (var special in top.SpecialsBag.Specials) { - var comment = special as SpecialsBag.Comment; - if (comment != null) { - VisitComment (result, comment, tagComments); - } else { - if (storeAst) { - var ppd = special as SpecialsBag.PreProcessorDirective; - if (ppd != null) - VisitPreprocessorDirective (result, ppd); - } - } - } - }; - - var unit = parser.Parse (content, fileName); - unit.Freeze (); - var pf = unit.ToTypeSystem (); - try { - pf.LastWriteTime = System.IO.File.GetLastWriteTimeUtc (fileName); - } catch (Exception) { - pf.LastWriteTime = DateTime.UtcNow; - } - - result.LastWriteTimeUtc = pf.LastWriteTime.Value; - result.ParsedFile = pf; - result.Add (GetSemanticTags (unit)); - - result.CreateRefactoringContext = delegate (MonoDevelop.Ide.Gui.Document doc, System.Threading.CancellationToken token) { - var task = MDRefactoringContext.Create (doc, doc.Editor.Caret.Location, token); - try { - task.Wait (5000, token); - } catch (AggregateException ae) { - ae.Flatten ().Handle (aex => aex is OperationCanceledException); - return null; - } catch (OperationCanceledException) { - return null; - } - if (!task.IsCompleted) - return null; - return task.Result; - }; - result.CreateRefactoringContextWithEditor = (data, resolver, token) => new MDRefactoringContext ((DotNetProject)project, data, result, (CSharpAstResolver)resolver, TextLocation.Empty, token); - - if (storeAst) { - result.Ast = unit; - result.Add (GenerateFoldings (unit, result)); - } - return result; - } - - IEnumerable GenerateFoldings (SyntaxTree unit, ParsedDocument doc) - { - foreach (var fold in doc.ConditionalRegions.ToFolds ()) - yield return fold; - - foreach (var fold in doc.Comments.ToFolds ()) - yield return fold; - - var visitor = new FoldingVisitor (); - unit.AcceptVisitor (visitor, null); - foreach (var fold in visitor.Foldings) - yield return fold; - } - - class FoldingVisitor : DepthFirstAstVisitor - { - public readonly List Foldings = new List (); - - void AddUsings (AstNode parent) - { - var firstChild = parent.Children.FirstOrDefault (child => child is UsingDeclaration || child is UsingAliasDeclaration); - var node = firstChild; - while (node != null) { - var next = node.GetNextNode (); - if (next is UsingDeclaration || next is UsingAliasDeclaration) { - node = next; - } else { - break; - } - } - if (firstChild != node) { - Foldings.Add (new FoldingRegion (new DomRegion (firstChild.StartLocation, node.EndLocation), FoldType.Undefined)); - } - } - public override object VisitSyntaxTree (SyntaxTree unit, object data) - { - AddUsings (unit); - return base.VisitSyntaxTree (unit, data); - } - - static TextLocation CorrectEnd (AstNode token) - { - return new TextLocation (token.EndLocation.Line, token.EndLocation.Column + 1); - } - - static bool LastToken(AstNode arg) - { - return !(arg.Role == Roles.NewLine || arg.Role == Roles.Whitespace || arg.Role == Roles.Comment); - } - - public override object VisitNamespaceDeclaration (NamespaceDeclaration namespaceDeclaration, object data) - { - AddUsings (namespaceDeclaration); - if (!namespaceDeclaration.RBraceToken.IsNull && namespaceDeclaration.LBraceToken.StartLocation.Line != namespaceDeclaration.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (namespaceDeclaration.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (namespaceDeclaration.RBraceToken)), FoldType.Undefined)); - return base.VisitNamespaceDeclaration (namespaceDeclaration, data); - } - - public override object VisitTypeDeclaration (TypeDeclaration typeDeclaration, object data) - { - if (!typeDeclaration.RBraceToken.IsNull && typeDeclaration.LBraceToken.StartLocation.Line != typeDeclaration.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (typeDeclaration.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (typeDeclaration.RBraceToken)), FoldType.Type)); - return base.VisitTypeDeclaration (typeDeclaration, data); - } - - public override object VisitMethodDeclaration (MethodDeclaration methodDeclaration, object data) - { - if (!methodDeclaration.Body.IsNull && methodDeclaration.Body.LBraceToken.StartLocation.Line != methodDeclaration.Body.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (methodDeclaration.Body.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (methodDeclaration.Body.RBraceToken)), FoldType.Member)); - return base.VisitMethodDeclaration (methodDeclaration, data); - } - - public override object VisitConstructorDeclaration (ConstructorDeclaration constructorDeclaration, object data) - { - if (!constructorDeclaration.Body.IsNull && constructorDeclaration.Body.LBraceToken.StartLocation.Line != constructorDeclaration.Body.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (constructorDeclaration.Body.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (constructorDeclaration.Body.RBraceToken)), FoldType.Member)); - return base.VisitConstructorDeclaration (constructorDeclaration, data); - } - - public override object VisitDestructorDeclaration (DestructorDeclaration destructorDeclaration, object data) - { - if (!destructorDeclaration.Body.IsNull && destructorDeclaration.Body.LBraceToken.StartLocation.Line != destructorDeclaration.Body.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (destructorDeclaration.Body.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (destructorDeclaration.Body.RBraceToken)), FoldType.Member)); - return base.VisitDestructorDeclaration (destructorDeclaration, data); - } - - public override object VisitOperatorDeclaration (OperatorDeclaration operatorDeclaration, object data) - { - if (!operatorDeclaration.Body.IsNull && operatorDeclaration.Body.LBraceToken.StartLocation.Line != operatorDeclaration.Body.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (operatorDeclaration.Body.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (operatorDeclaration.Body.RBraceToken)), FoldType.Member)); - return base.VisitOperatorDeclaration (operatorDeclaration, data); - } - - public override object VisitPropertyDeclaration (PropertyDeclaration propertyDeclaration, object data) - { - if (!propertyDeclaration.LBraceToken.IsNull && propertyDeclaration.LBraceToken.StartLocation.Line != propertyDeclaration.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (propertyDeclaration.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (propertyDeclaration.RBraceToken)), FoldType.Member)); - return base.VisitPropertyDeclaration (propertyDeclaration, data); - } - - public override object VisitIndexerDeclaration (IndexerDeclaration indexerDeclaration, object data) - { - if (!indexerDeclaration.LBraceToken.IsNull && indexerDeclaration.LBraceToken.StartLocation.Line != indexerDeclaration.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (indexerDeclaration.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (indexerDeclaration.RBraceToken)), FoldType.Member)); - return base.VisitIndexerDeclaration (indexerDeclaration, data); - } - - public override object VisitCustomEventDeclaration (CustomEventDeclaration eventDeclaration, object data) - { - if (!eventDeclaration.LBraceToken.IsNull && eventDeclaration.LBraceToken.StartLocation.Line != eventDeclaration.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (eventDeclaration.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (eventDeclaration.RBraceToken)), FoldType.Member)); - return base.VisitCustomEventDeclaration (eventDeclaration, data); - } - - public override object VisitSwitchStatement (SwitchStatement switchStatement, object data) - { - if (!switchStatement.RBraceToken.IsNull && switchStatement.LBraceToken.StartLocation.Line != switchStatement.RBraceToken.StartLocation.Line) - Foldings.Add (new FoldingRegion (new DomRegion (switchStatement.LBraceToken.GetPrevNode (LastToken).EndLocation, CorrectEnd (switchStatement.RBraceToken)), FoldType.Member)); - return base.VisitSwitchStatement (switchStatement, data); - } - - public override object VisitBlockStatement (BlockStatement blockStatement, object data) - { - if (!(blockStatement.Parent is EntityDeclaration) && blockStatement.EndLocation.Line - blockStatement.StartLocation.Line > 2) { - Foldings.Add (new FoldingRegion (new DomRegion (blockStatement.GetPrevNode (LastToken).EndLocation, CorrectEnd (blockStatement.RBraceToken)), FoldType.Undefined)); - } - - return base.VisitBlockStatement (blockStatement, data); - } - } - - static IEnumerable GetSemanticTags (SyntaxTree unit) - { - var visitor = new SemanticTagVisitor (); - unit.AcceptVisitor (visitor); - foreach (var fold in visitor.Tags) - yield return fold; - } - - public class SemanticTagVisitor : DepthFirstAstVisitor - { - public List Tags = new List (); - - public override void VisitThrowStatement (ThrowStatement throwStatement) - { - var createExpression = throwStatement.Expression as ObjectCreateExpression; - if (createExpression == null) - return; - var st = createExpression.Type as SimpleType; - var mt = createExpression.Type as MemberType; - if (st != null && st.Identifier == "NotImplementedException" || - mt != null && mt.MemberName == "NotImplementedException" && mt.Target.ToString () == "System") { - - if (createExpression.Arguments.Any ()) { - Tags.Add (new Tag ("High", GettextCatalog.GetString ("NotImplementedException({0}) thrown.", createExpression.Arguments.First ().ToString ()), new DomRegion (throwStatement.StartLocation, throwStatement.EndLocation))); - } else { - Tags.Add (new Tag ("High", GettextCatalog.GetString ("NotImplementedException thrown."), new DomRegion (throwStatement.StartLocation, throwStatement.EndLocation))); - } - } - } - } - - void VisitMcsUnit () - { - } - - void VisitComment (ParsedDocument result, SpecialsBag.Comment comment, string[] tagComments) - { - var cmt = new MonoDevelop.Ide.TypeSystem.Comment (comment.Content); - cmt.CommentStartsLine = comment.StartsLine; - switch (comment.CommentType) { - case SpecialsBag.CommentType.Multi: - cmt.CommentType = MonoDevelop.Ide.TypeSystem.CommentType.Block; - cmt.OpenTag = "/*"; - cmt.ClosingTag = "*/"; - break; - case SpecialsBag.CommentType.Single: - cmt.CommentType = MonoDevelop.Ide.TypeSystem.CommentType.SingleLine; - cmt.OpenTag = "//"; - break; - case SpecialsBag.CommentType.Documentation: - cmt.CommentType = MonoDevelop.Ide.TypeSystem.CommentType.Documentation; - cmt.IsDocumentation = true; - cmt.OpenTag = "///"; - break; - } - cmt.Region = new DomRegion (comment.Line, comment.Col, comment.EndLine, comment.EndCol); - result.Comments.Add (cmt); - var trimmedContent = comment.Content.TrimStart (); - foreach (string tag in tagComments) { - if (!trimmedContent.StartsWith (tag)) - continue; - result.Add (new Tag (tag, comment.Content, cmt.Region)); - } - } - - Stack regions = new Stack (); - Stack ifBlocks = new Stack (); - List elifBlocks = new List (); - SpecialsBag.PreProcessorDirective elseBlock = null; - - Stack conditionalRegions = new Stack (); - ConditionalRegion ConditionalRegion { - get { - return conditionalRegions.Count > 0 ? conditionalRegions.Peek () : null; - } - } - - void CloseConditionBlock (TextLocation loc) - { - if (ConditionalRegion == null || ConditionalRegion.ConditionBlocks.Count == 0 || !ConditionalRegion.ConditionBlocks[ConditionalRegion.ConditionBlocks.Count - 1].End.IsEmpty) - return; - ConditionalRegion.ConditionBlocks[ConditionalRegion.ConditionBlocks.Count - 1].End = loc; - } - - void AddCurRegion (ParsedDocument result, int line, int col) - { - if (ConditionalRegion == null) - return; - ConditionalRegion.End = new TextLocation (line, col); - result.Add (ConditionalRegion); - conditionalRegions.Pop (); - } - - void VisitPreprocessorDirective (ParsedDocument result, SpecialsBag.PreProcessorDirective directive) - { - TextLocation loc = new TextLocation (directive.Line, directive.Col); - switch (directive.Cmd) { - case Tokenizer.PreprocessorDirective.If: - conditionalRegions.Push (new ConditionalRegion (directive.Arg)); - ifBlocks.Push (directive); - ConditionalRegion.Start = loc; - break; - case Tokenizer.PreprocessorDirective.Elif: - CloseConditionBlock (new TextLocation (directive.EndLine, directive.EndCol)); - if (ConditionalRegion != null) - ConditionalRegion.ConditionBlocks.Add (new ConditionBlock (directive.Arg, loc)); - break; - case Tokenizer.PreprocessorDirective.Else: - CloseConditionBlock (new TextLocation (directive.EndLine, directive.EndCol)); - if (ConditionalRegion != null) - ConditionalRegion.ElseBlock = new DomRegion (loc, TextLocation.Empty); - break; - case Tokenizer.PreprocessorDirective.Endif: - TextLocation endLoc = new TextLocation (directive.EndLine, directive.EndCol); - CloseConditionBlock (endLoc); - if (ConditionalRegion != null && !ConditionalRegion.ElseBlock.Begin.IsEmpty) - ConditionalRegion.ElseBlock = new DomRegion (ConditionalRegion.ElseBlock.Begin, endLoc); - AddCurRegion (result, directive.EndLine, directive.EndCol); - if (ifBlocks.Count > 0) { - var ifBlock = ifBlocks.Pop (); - var ifRegion = new DomRegion (ifBlock.Line, ifBlock.Col, directive.EndLine, directive.EndCol); - result.Add (new FoldingRegion ("#if " + ifBlock.Arg.Trim (), ifRegion, FoldType.UserRegion, false)); - foreach (var d in elifBlocks) { - var elIlfRegion = new DomRegion (d.Line, d.Col, directive.EndLine, directive.EndCol); - result.Add (new FoldingRegion ("#elif " + ifBlock.Arg.Trim (), elIlfRegion, FoldType.UserRegion, false)); - } - if (elseBlock != null) { - var elseBlockRegion = new DomRegion (elseBlock.Line, elseBlock.Col, elseBlock.Line, elseBlock.Col); - result.Add (new FoldingRegion ("#else", elseBlockRegion, FoldType.UserRegion, false)); - } - } - elseBlock = null; - break; - case Tokenizer.PreprocessorDirective.Define: - result.Add (new PreProcessorDefine (directive.Arg, loc)); - break; - case Tokenizer.PreprocessorDirective.Region: - regions.Push (directive); - break; - case Tokenizer.PreprocessorDirective.Endregion: - if (regions.Count > 0) { - var start = regions.Pop (); - DomRegion dr = new DomRegion (start.Line, start.Col, directive.EndLine, directive.EndCol); - result.Add (new FoldingRegion (start.Arg, dr, FoldType.UserRegion, true)); - } - break; - } - } - - public static ICSharpCode.NRefactory.PlayScript.CompilerSettings GetCompilerArguments (MonoDevelop.Projects.Project project) - { - var compilerArguments = new ICSharpCode.NRefactory.PlayScript.CompilerSettings (); - - if (project == null || MonoDevelop.Ide.IdeApp.Workspace == null) { - compilerArguments.AllowUnsafeBlocks = true; - return compilerArguments; - } - - var configuration = project.GetConfiguration (MonoDevelop.Ide.IdeApp.Workspace.ActiveConfiguration) as DotNetProjectConfiguration; - if (configuration == null) - return compilerArguments; - - foreach (var sym in configuration.GetDefineSymbols ()) - compilerArguments.ConditionalSymbols.Add (sym); - - var par = configuration.CompilationParameters as PlayScriptCompilerParameters; - if (par == null) - return compilerArguments; - - compilerArguments.AllowUnsafeBlocks = par.UnsafeCode; - compilerArguments.LanguageVersion = ConvertLanguageVersion (par.LangVersion); - compilerArguments.CheckForOverflow = par.GenerateOverflowChecks; - compilerArguments.WarningLevel = par.WarningLevel; - compilerArguments.TreatWarningsAsErrors = par.TreatWarningsAsErrors; - if (!string.IsNullOrEmpty (par.NoWarnings)) { - foreach (var warning in par.NoWarnings.Split (';', ',', ' ', '\t')) { - int w; - try { - w = int.Parse (warning); - } catch (Exception) { - continue; - } - compilerArguments.DisabledWarnings.Add (w); - } - } - - return compilerArguments; - } - - internal static Version ConvertLanguageVersion (LangVersion ver) - { - switch (ver) { - case LangVersion.ISO_1: - return new Version (1, 0, 0, 0); - case LangVersion.ISO_2: - return new Version (2, 0, 0, 0); - case LangVersion.Version3: - return new Version (3, 0, 0, 0); - case LangVersion.Version4: - return new Version (4, 0, 0, 0); - case LangVersion.Version5: - return new Version (5, 0, 0, 0); - case LangVersion.Version6: - return new Version (6, 0, 0, 0); - case LangVersion.Default: - break; - } - return new Version (6, 0, 0, 0);; - } - } - - static class FoldingUtils - { - public static IEnumerable ToFolds (this IEnumerable conditionalRegions) - { - foreach (ConditionalRegion region in conditionalRegions) { - yield return new FoldingRegion ("#if " + region.Flag, region.Region, FoldType.ConditionalDefine); - foreach (ConditionBlock block in region.ConditionBlocks) { - yield return new FoldingRegion ("#elif " + block.Flag, block.Region, - FoldType.ConditionalDefine); - } - if (!region.ElseBlock.IsEmpty) - yield return new FoldingRegion ("#else", region.ElseBlock, FoldType.ConditionalDefine); - } - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CSharpCompilerParameters.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Project/CSharpCompilerParameters.cs deleted file mode 100644 index 7ccbfee..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CSharpCompilerParameters.cs +++ /dev/null @@ -1,333 +0,0 @@ -// -// CSharpCompilerParameters.cs -// -// Author: -// Mike Krüger -// -// Copyright (C) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// -using System; -using System.Collections.Generic; - -using MonoDevelop.Projects; -using MonoDevelop.Core.Serialization; -using MonoDevelop.Core; -using System.Linq; - -namespace MonoDevelop.PlayScript.Project -{ - public enum LangVersion { - Default = 0, - ISO_1 = 1, - ISO_2 = 2, - Version3 = 3, - Version4 = 4, - Version5 = 5, - Version6 = 6 - } - - /// - /// This class handles project specific compiler parameters - /// - public class PlayScriptCompilerParameters: DotNetConfigurationParameters - { - // Configuration parameters - - [ItemProperty ("WarningLevel")] - int warninglevel = 4; - - [ItemProperty ("NoWarn", DefaultValue = "")] - string noWarnings = String.Empty; - - [ItemProperty ("Optimize")] - bool optimize; - - [ItemProperty ("AllowUnsafeBlocks", DefaultValue = false)] - bool unsafecode = false; - - [ItemProperty ("CheckForOverflowUnderflow", DefaultValue = false)] - bool generateOverflowChecks; - - [ItemProperty ("DefineConstants", DefaultValue = "")] - string definesymbols = String.Empty; - - [ProjectPathItemProperty ("DocumentationFile")] - FilePath documentationFile; - - [ItemProperty ("LangVersion", DefaultValue = "Default")] - string langVersion = "Default"; - - [ItemProperty ("NoStdLib", DefaultValue = false)] - bool noStdLib; - - [ItemProperty ("TreatWarningsAsErrors", DefaultValue = false)] - bool treatWarningsAsErrors; - - [ItemProperty("PlatformTarget", DefaultValue="anycpu")] - string platformTarget = "anycpu"; - - [ItemProperty("WarningsNotAsErrors", DefaultValue="")] - string warningsNotAsErrors = ""; - - [ItemProperty("DebugType", DefaultValue="")] - string debugType = ""; - - #region Members required for backwards compatibility. Not used for anything else. - - [ItemProperty ("StartupObject", DefaultValue = null)] - internal string mainclass; - - [ProjectPathItemProperty ("ApplicationIcon", DefaultValue = null)] - internal string win32Icon; - - [ProjectPathItemProperty ("Win32Resource", DefaultValue = null)] - internal string win32Resource; - - [ItemProperty ("CodePage", DefaultValue = null)] - internal string codePage; - - [ItemProperty ("GenerateDocumentation", DefaultValue = null)] - bool? generateXmlDocumentation = null; - - #endregion - - - protected override void OnEndLoad () - { - base.OnEndLoad (); - -// // Backwards compatibility. Move parameters to the project parameters object -// if (ParentConfiguration != null && ParentConfiguration.ProjectParameters != null) { -// var cparams = (PlayScriptProjectParameters) ParentConfiguration.ProjectParameters; -// if (win32Icon != null) { -// cparams.Win32Icon = win32Icon; -// win32Icon = null; -// } -// if (win32Resource != null) { -// cparams.Win32Resource = win32Resource; -// win32Resource = null; -// } -// if (mainclass != null) { -// cparams.MainClass = mainclass; -// mainclass = null; -// } -// if (!string.IsNullOrEmpty (codePage)) { -// cparams.CodePage = int.Parse (codePage); -// codePage = null; -// } -// } - - if (generateXmlDocumentation.HasValue && ParentConfiguration != null) { - if (generateXmlDocumentation.Value) - documentationFile = ParentConfiguration.CompiledOutputName.ChangeExtension (".xml"); - else - documentationFile = null; - generateXmlDocumentation = null; - } - } - - - public LangVersion LangVersion { - get { - var val = TryLangVersionFromString (langVersion); - if (val == null) { - throw new Exception ("Unknown LangVersion string '" + val + "'"); - } - return val.Value; - } - set { - var v = TryLangVersionToString (value); - if (v == null) { - throw new ArgumentOutOfRangeException ("Unknown LangVersion enum value '" + value + "'"); - } - langVersion = v; - } - } - -#region Code Generation - - [Obsolete] - public override void AddDefineSymbol (string symbol) - { - var symbols = new List (GetDefineSymbols ()); - symbols.Add (symbol); - definesymbols = string.Join (";", symbols) + ";"; - } - - public override IEnumerable GetDefineSymbols () - { - return definesymbols.Split (';', ',', ' ', '\t').Where (s => !string.IsNullOrWhiteSpace (s)); - } - - [Obsolete] - public override void RemoveDefineSymbol (string symbol) - { - var symbols = new List (GetDefineSymbols ()); - symbols.Remove (symbol); - - if (symbols.Count > 0) - definesymbols = string.Join (";", symbols) + ";"; - else - definesymbols = string.Empty; - } - - public string DefineSymbols { - get { - return definesymbols; - } - set { - definesymbols = value ?? string.Empty; - } - } - - public bool Optimize { - get { - return optimize; - } - set { - optimize = value; - } - } - - public bool UnsafeCode { - get { - return unsafecode; - } - set { - unsafecode = value; - } - } - - public bool GenerateOverflowChecks { - get { - return generateOverflowChecks; - } - set { - generateOverflowChecks = value; - } - } - - public FilePath DocumentationFile { - get { - return documentationFile; - } - set { - documentationFile = value; - } - } - - public string PlatformTarget { - get { - return platformTarget; - } - set { - platformTarget = value ?? string.Empty; - } - } - - public override string DebugType { - get { - return debugType; - } - set { - debugType = value; - } - } - -#endregion - -#region Errors and Warnings - public int WarningLevel { - get { - return warninglevel; - } - set { - warninglevel = value; - } - } - - public string NoWarnings { - get { - return noWarnings; - } - set { - noWarnings = value; - } - } - - public override bool NoStdLib { - get { - return noStdLib; - } - set { - noStdLib = value; - } - } - - public bool TreatWarningsAsErrors { - get { - return treatWarningsAsErrors; - } - set { - treatWarningsAsErrors = value; - } - } - - public string WarningsNotAsErrors { - get { - return warningsNotAsErrors; - } - set { - warningsNotAsErrors = value; - } - } -#endregion - - static LangVersion? TryLangVersionFromString (string value) - { - switch (value) { - case "Default": return LangVersion.Default; - case "ISO-1": return LangVersion.ISO_1; - case "ISO-2": return LangVersion.ISO_2; - case "3": return LangVersion.Version3; - case "4": return LangVersion.Version4; - case "5": return LangVersion.Version5; - case "6": return LangVersion.Version6; - default: return null; - } - } - - internal static string TryLangVersionToString (LangVersion value) - { - switch (value) { - case LangVersion.Default: return "Default"; - case LangVersion.ISO_1: return "ISO-1"; - case LangVersion.ISO_2: return "ISO-2"; - case LangVersion.Version3: return "3"; - case LangVersion.Version4: return "4"; - case LangVersion.Version5: return "5"; - case LangVersion.Version6: return "6"; - default: return null; - } - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CSharpProjectParameters.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Project/CSharpProjectParameters.cs deleted file mode 100644 index 790d686..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CSharpProjectParameters.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// ProjectParameters.cs -// -// Author: -// Lluis Sanchez Gual -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using MonoDevelop.Core.Serialization; -using MonoDevelop.Projects; - -namespace MonoDevelop.PlayScript.Project -{ - public class PlayScriptProjectParameters: ProjectParameters - { - [ItemProperty ("StartupObject", DefaultValue = "")] - string mainclass = string.Empty; - - [ProjectPathItemProperty ("ApplicationIcon", DefaultValue = "")] - string win32Icon = String.Empty; - - [ProjectPathItemProperty ("Win32Resource", DefaultValue = "")] - string win32Resource = String.Empty; - - [ItemProperty ("CodePage", DefaultValue = 0)] - int codePage; - - public string MainClass { - get { - return mainclass; - } - set { - mainclass = value ?? string.Empty; - } - } - - public int CodePage { - get { - return codePage; - } - set { - codePage = value; - } - } - - public string Win32Icon { - get { - return win32Icon; - } - set { - win32Icon = value ?? string.Empty; - } - } - - public string Win32Resource { - get { - return win32Resource; - } - set { - win32Resource = value ?? string.Empty; - } - } - - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CSharpResourceIdBuilder.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Project/CSharpResourceIdBuilder.cs deleted file mode 100644 index 5f6e063..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CSharpResourceIdBuilder.cs +++ /dev/null @@ -1,192 +0,0 @@ -// -// CSharpResourceIdBuilder.cs -// -// Author: -// Ankit Jain -// -// Copyright (C) 2006 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using MonoDevelop.Core; -using MonoDevelop.Projects; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text; -using MonoDevelop.Projects.Extensions; -using MonoDevelop.Projects.Formats.MSBuild; - -namespace MonoDevelop.PlayScript.Project -{ - class CSharpResourceIdBuilder : MSBuildResourceHandler - { - public override string GetDefaultResourceId (ProjectFile pf) - { - if (String.IsNullOrEmpty (pf.DependsOn) || !File.Exists (pf.DependsOn) || Path.GetExtension (pf.DependsOn).ToLower () != ".cs") - return base.GetDefaultResourceId (pf); - - string ns = null; - string classname = null; - - using (StreamReader rdr = new StreamReader (pf.DependsOn)) { - int numopen = 0; - while (true) { - string tok = GetNextToken (rdr); - if (tok == null) - break; - - if (tok == "@") { - //Handle @namespace, @class - GetNextToken (rdr); - continue; - } - - if (String.Compare (tok, "namespace", false) == 0) - ns = GetNextToken (rdr); - - if (tok == "{") - numopen ++; - - if (tok == "}") { - numopen --; - if (numopen == 0) - ns = String.Empty; - } - - if (tok == "class") { - classname = GetNextToken (rdr); - break; - } - } - - if (classname == null) - return base.GetDefaultResourceId (pf); - - string culture, extn, only_filename; - if (MSBuildProjectService.TrySplitResourceName (pf.ProjectVirtualPath, out only_filename, out culture, out extn)) - extn = "." + culture + ".resources"; - else - extn = ".resources"; - - if (ns == null) - return classname + extn; - else - return ns + '.' + classname + extn; - } - } - - /* Special parser for C# files - * Assumes that the file is compilable - * skips comments, - * skips strings "foo", - * skips anything after a # , eg. #region, #if - * Won't handle #if false etc kinda blocks*/ - string GetNextToken (StreamReader sr) - { - StringBuilder sb = new StringBuilder (); - - while (true) { - int c = sr.Peek (); - if (c == -1) - return null; - - if (c == '\r' || c == '\n') { - sr.ReadLine (); - if (sb.Length > 0) - break; - - continue; - } - - if (c == '/') { - sr.Read (); - - if (sr.Peek () == '*') { - /* multi-line comment */ - sr.Read (); - - while (true) { - int n = sr.Read (); - if (n == -1) - break; - if (n != '*') - continue; - - if (sr.Peek () == '/') { - /* End of multi-line comment */ - if (sb.Length > 0) { - sr.Read (); - return sb.ToString (); - } - break; - } - } - } else if (sr.Peek () == '/') { - //Single line comment, skip the rest of the line - sr.ReadLine (); - continue; - } - } else if (c == '"') { - /* String "foo" */ - sr.Read (); - while (true) { - int n = sr.Peek (); - if (n == -1) - throw new Exception ("String literal not closed"); - - if (n == '"') { - /* end of string */ - if (sb.Length > 0) { - sr.Read (); - return sb.ToString (); - } - - break; - } - sr.Read (); - } - } else if (c == '#') { - //skip rest of the line - sr.ReadLine (); - } else { - if (Char.IsLetterOrDigit ((char) c) || c == '_' || c == '.') { - sb.Append ((char) c); - } else { - if (sb.Length > 0) - break; - - if (c != ' ' && c != '\t') { - sr.Read (); - return ((char) c).ToString (); - } - } - } - - sr.Read (); - } - - return sb.ToString (); - } - - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CodeGenerationPanel.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Project/CodeGenerationPanel.cs deleted file mode 100644 index a58cc00..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CodeGenerationPanel.cs +++ /dev/null @@ -1,136 +0,0 @@ -// -// CodeGenerationPanel.cs -// -// Author: -// Mike Krüger -// -// Copyright (C) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using MonoDevelop.Projects; -using Gtk; -using MonoDevelop.Ide.Gui.Dialogs; - -namespace MonoDevelop.PlayScript.Project -{ - partial class CodeGenerationPanelWidget : Gtk.Bin - { - const int DEBUG_FULL = 0; - const int DEBUG_PDB_ONLY = 1; - const int DEBUG_NONE = 2; - - DotNetProjectConfiguration configuration; - PlayScriptCompilerParameters compilerParameters = null; - - public CodeGenerationPanelWidget () - { - Build (); -// xmlDocsEntry.DisplayAsRelativePath = true; - } - - public void Load (DotNetProjectConfiguration configuration) - { - this.configuration = configuration; - compilerParameters = (PlayScriptCompilerParameters) configuration.CompilationParameters; - - symbolsEntry.Text = compilerParameters.DefineSymbols; - generateXmlOutputCheckButton.Active = !string.IsNullOrEmpty (compilerParameters.DocumentationFile); - enableOptimizationCheckButton.Active = compilerParameters.Optimize; - generateOverflowChecksCheckButton.Active = compilerParameters.GenerateOverflowChecks; - warningsAsErrorsCheckButton.Active = compilerParameters.TreatWarningsAsErrors; - warningLevelSpinButton.Value = compilerParameters.WarningLevel; - ignoreWarningsEntry.Text = compilerParameters.NoWarnings; - - int i = PlayScriptLanguageBinding.SupportedPlatforms.IndexOf (compilerParameters.PlatformTarget); - comboPlatforms.Active = i != -1 ? i : 0; - - if (!configuration.DebugMode || string.Equals ("none", compilerParameters.DebugType, StringComparison.OrdinalIgnoreCase)) { - comboDebug.Active = DEBUG_NONE; - } else if (string.Equals ("pdbonly", compilerParameters.DebugType, StringComparison.OrdinalIgnoreCase)) { - comboDebug.Active = DEBUG_PDB_ONLY; - } else { - comboDebug.Active = DEBUG_FULL; - } - -// xmlDocsEntry.DefaultPath = configuration.OutputDirectory; -// -// xmlDocsEntry.Path = string.IsNullOrEmpty (compilerParameters.DocumentationFile) -// ? configuration.CompiledOutputName.ChangeExtension (".xml") -// : compilerParameters.DocumentationFile; - } - - public void Store () - { - if (compilerParameters == null) - throw new ApplicationException ("Code generation panel wasn't loaded !"); - - compilerParameters.DefineSymbols = symbolsEntry.Text; -// compilerParameters.DocumentationFile = generateXmlOutputCheckButton.Active? xmlDocsEntry.Path : null; - compilerParameters.Optimize = enableOptimizationCheckButton.Active; - compilerParameters.GenerateOverflowChecks = generateOverflowChecksCheckButton.Active; - compilerParameters.TreatWarningsAsErrors = warningsAsErrorsCheckButton.Active; - compilerParameters.WarningLevel = warningLevelSpinButton.ValueAsInt; - compilerParameters.NoWarnings = ignoreWarningsEntry.Text; - compilerParameters.PlatformTarget = PlayScriptLanguageBinding.SupportedPlatforms [comboPlatforms.Active]; - - switch (comboDebug.Active) { - case DEBUG_FULL: - configuration.DebugMode = true; - if (!string.Equals (compilerParameters.DebugType, "full", StringComparison.OrdinalIgnoreCase)) { - compilerParameters.DebugType = ""; - } - break; - case DEBUG_PDB_ONLY: - configuration.DebugMode = true; - compilerParameters.DebugType = "pdbonly"; - break; - case DEBUG_NONE: - configuration.DebugMode = false; - if (!string.Equals (compilerParameters.DebugType, "none", StringComparison.OrdinalIgnoreCase)) { - compilerParameters.DebugType = ""; - } - break; - } - } - } - - class CodeGenerationPanel : MultiConfigItemOptionsPanel - { - CodeGenerationPanelWidget widget; - - public override Widget CreatePanelWidget() - { - return widget = new CodeGenerationPanelWidget (); - } - - public override void LoadConfigData () - { - widget.Load ((DotNetProjectConfiguration) CurrentConfiguration); - } - - public override void ApplyChanges () - { - widget.Store (); - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CodeGenerationPanel.cs.org b/PlayScript.Addin/MonoDevelop.PlayScript.Project/CodeGenerationPanel.cs.org deleted file mode 100644 index 6de75cf..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CodeGenerationPanel.cs.org +++ /dev/null @@ -1,136 +0,0 @@ -// -// CodeGenerationPanel.cs -// -// Author: -// Mike Krüger -// -// Copyright (C) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using MonoDevelop.Projects; -using Gtk; -using MonoDevelop.Ide.Gui.Dialogs; - -namespace MonoDevelop.PlayScript.Project -{ - partial class CodeGenerationPanelWidget : Gtk.Bin - { - const int DEBUG_FULL = 0; - const int DEBUG_PDB_ONLY = 1; - const int DEBUG_NONE = 2; - - DotNetProjectConfiguration configuration; - PlayScriptCompilerParameters compilerParameters = null; - - public CodeGenerationPanelWidget () - { - Build (); - xmlDocsEntry.DisplayAsRelativePath = true; - } - - public void Load (DotNetProjectConfiguration configuration) - { - this.configuration = configuration; - compilerParameters = (PlayScriptCompilerParameters) configuration.CompilationParameters; - - symbolsEntry.Text = compilerParameters.DefineSymbols; - generateXmlOutputCheckButton.Active = !string.IsNullOrEmpty (compilerParameters.DocumentationFile); - enableOptimizationCheckButton.Active = compilerParameters.Optimize; - generateOverflowChecksCheckButton.Active = compilerParameters.GenerateOverflowChecks; - warningsAsErrorsCheckButton.Active = compilerParameters.TreatWarningsAsErrors; - warningLevelSpinButton.Value = compilerParameters.WarningLevel; - ignoreWarningsEntry.Text = compilerParameters.NoWarnings; - - int i = PlayScriptLanguageBinding.SupportedPlatforms.IndexOf (compilerParameters.PlatformTarget); - comboPlatforms.Active = i != -1 ? i : 0; - - if (!configuration.DebugMode || string.Equals ("none", compilerParameters.DebugType, StringComparison.OrdinalIgnoreCase)) { - comboDebug.Active = DEBUG_NONE; - } else if (string.Equals ("pdbonly", compilerParameters.DebugType, StringComparison.OrdinalIgnoreCase)) { - comboDebug.Active = DEBUG_PDB_ONLY; - } else { - comboDebug.Active = DEBUG_FULL; - } - - xmlDocsEntry.DefaultPath = configuration.OutputDirectory; - - xmlDocsEntry.Path = string.IsNullOrEmpty (compilerParameters.DocumentationFile) - ? configuration.CompiledOutputName.ChangeExtension (".xml") - : compilerParameters.DocumentationFile; - } - - public void Store () - { - if (compilerParameters == null) - throw new ApplicationException ("Code generation panel wasn't loaded !"); - - compilerParameters.DefineSymbols = symbolsEntry.Text; - compilerParameters.DocumentationFile = generateXmlOutputCheckButton.Active? xmlDocsEntry.Path : null; - compilerParameters.Optimize = enableOptimizationCheckButton.Active; - compilerParameters.GenerateOverflowChecks = generateOverflowChecksCheckButton.Active; - compilerParameters.TreatWarningsAsErrors = warningsAsErrorsCheckButton.Active; - compilerParameters.WarningLevel = warningLevelSpinButton.ValueAsInt; - compilerParameters.NoWarnings = ignoreWarningsEntry.Text; - compilerParameters.PlatformTarget = PlayScriptLanguageBinding.SupportedPlatforms [comboPlatforms.Active]; - - switch (comboDebug.Active) { - case DEBUG_FULL: - configuration.DebugMode = true; - if (!string.Equals (compilerParameters.DebugType, "full", StringComparison.OrdinalIgnoreCase)) { - compilerParameters.DebugType = ""; - } - break; - case DEBUG_PDB_ONLY: - configuration.DebugMode = true; - compilerParameters.DebugType = "pdbonly"; - break; - case DEBUG_NONE: - configuration.DebugMode = false; - if (!string.Equals (compilerParameters.DebugType, "none", StringComparison.OrdinalIgnoreCase)) { - compilerParameters.DebugType = ""; - } - break; - } - } - } - - class CodeGenerationPanel : MultiConfigItemOptionsPanel - { - CodeGenerationPanelWidget widget; - - public override Widget CreatePanelWidget() - { - return widget = new CodeGenerationPanelWidget (); - } - - public override void LoadConfigData () - { - widget.Load ((DotNetProjectConfiguration) CurrentConfiguration); - } - - public override void ApplyChanges () - { - widget.Store (); - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CompilerOptionsPanelWidget.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Project/CompilerOptionsPanelWidget.cs deleted file mode 100644 index 253bde0..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CompilerOptionsPanelWidget.cs +++ /dev/null @@ -1,250 +0,0 @@ -// -// CompilerOptionsPanelWidget.cs -// -// Author: -// Michael Hutchinson -// Mike Krüger -// -// Copyright (C) 2007, 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using Gtk; - -using MonoDevelop.Core; -using MonoDevelop.Projects; -using MonoDevelop.Projects.Text; -using MonoDevelop.Ide.Gui.Dialogs; -using MonoDevelop.Ide; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Ide.TypeSystem; - -namespace MonoDevelop.PlayScript.Project -{ - - partial class CompilerOptionsPanelWidget : Gtk.Bin - { - DotNetProject project; - ListStore classListStore; - bool classListFilled; - - public CompilerOptionsPanelWidget (DotNetProject project) - { - this.Build(); - this.project = project; - var configuration = (DotNetProjectConfiguration) project.GetConfiguration (IdeApp.Workspace.ActiveConfiguration); - var compilerParameters = (PlayScriptCompilerParameters) configuration.CompilationParameters; - var projectParameters = (PlayScriptProjectParameters) configuration.ProjectParameters; - - ListStore store = new ListStore (typeof (string)); - store.AppendValues (GettextCatalog.GetString ("Executable")); - store.AppendValues (GettextCatalog.GetString ("Library")); - store.AppendValues (GettextCatalog.GetString ("Executable with GUI")); - compileTargetCombo.Model = store; - CellRendererText cr = new CellRendererText (); - compileTargetCombo.PackStart (cr, true); - compileTargetCombo.AddAttribute (cr, "text", 0); - compileTargetCombo.Active = (int) configuration.CompileTarget; - compileTargetCombo.Changed += new EventHandler (OnTargetChanged); - - if (project.IsLibraryBasedProjectType) { - //fixme: should we totally hide these? - compileTargetCombo.Sensitive = false; - mainClassEntry.Sensitive = false; - } else { - classListStore = new ListStore (typeof(string)); - mainClassEntry.Model = classListStore; - mainClassEntry.TextColumn = 0; - ((Entry)mainClassEntry.Child).Text = projectParameters.MainClass ?? string.Empty; - - UpdateTarget (); - } - - // Load the codepage. If it matches any of the supported encodigs, use the encoding name - string foundEncoding = null; - foreach (TextEncoding e in TextEncoding.SupportedEncodings) { - if (e.CodePage == -1) - continue; - if (e.CodePage == projectParameters.CodePage) - foundEncoding = e.Id; - codepageEntry.AppendText (e.Id); - } - if (foundEncoding != null) - codepageEntry.Entry.Text = foundEncoding; - else if (projectParameters.CodePage != 0) - codepageEntry.Entry.Text = projectParameters.CodePage.ToString (); - -// iconEntry.Path = projectParameters.Win32Icon; -// iconEntry.DefaultPath = project.BaseDirectory; - allowUnsafeCodeCheckButton.Active = compilerParameters.UnsafeCode; - noStdLibCheckButton.Active = compilerParameters.NoStdLib; - - ListStore langVerStore = new ListStore (typeof (string)); - langVerStore.AppendValues (GettextCatalog.GetString ("Default")); - langVerStore.AppendValues ("ISO-1"); - langVerStore.AppendValues ("ISO-2"); - langVerStore.AppendValues ("Version 3"); - langVerStore.AppendValues ("Version 4"); - langVerStore.AppendValues ("Version 5"); - langVerStore.AppendValues ("Version 6"); - langVerCombo.Model = langVerStore; - langVerCombo.Active = (int) compilerParameters.LangVersion; - } - - protected override void OnDestroyed () - { - if (classListStore != null) { - classListStore.Dispose (); - classListStore = null; - } - base.OnDestroyed (); - } - - public bool ValidateChanges () - { - if (codepageEntry.Entry.Text.Length > 0) { - // Get the codepage. If the user specified an encoding name, find it. - int trialCodePage = -1; - foreach (TextEncoding e in TextEncoding.SupportedEncodings) { - if (e.Id == codepageEntry.Entry.Text) { - trialCodePage = e.CodePage; - break; - } - } - - if (trialCodePage == -1) { - if (!int.TryParse (codepageEntry.Entry.Text, out trialCodePage)) { - MessageService.ShowError (GettextCatalog.GetString ("Invalid code page number.")); - return false; - } - } - } - return true; - } - - public void Store (ItemConfigurationCollection configs) - { - int codePage; - CompileTarget compileTarget = (CompileTarget) compileTargetCombo.Active; - LangVersion langVersion = (LangVersion) langVerCombo.Active; - - - if (codepageEntry.Entry.Text.Length > 0) { - // Get the codepage. If the user specified an encoding name, find it. - int trialCodePage = -1; - foreach (TextEncoding e in TextEncoding.SupportedEncodings) { - if (e.Id == codepageEntry.Entry.Text) { - trialCodePage = e.CodePage; - break; - } - } - - if (trialCodePage != -1) - codePage = trialCodePage; - else { - if (!int.TryParse (codepageEntry.Entry.Text, out trialCodePage)) { - return; - } - codePage = trialCodePage; - } - } else - codePage = 0; - - project.CompileTarget = compileTarget; - - var projectParameters = (PlayScriptProjectParameters) project.LanguageParameters; - - projectParameters.CodePage = codePage; - -// if (iconEntry.Sensitive) -// projectParameters.Win32Icon = iconEntry.Path; - - if (mainClassEntry.Sensitive) - projectParameters.MainClass = mainClassEntry.Entry.Text; - - foreach (DotNetProjectConfiguration configuration in configs) { - var compilerParameters = (PlayScriptCompilerParameters) configuration.CompilationParameters; - compilerParameters.UnsafeCode = allowUnsafeCodeCheckButton.Active; - compilerParameters.NoStdLib = noStdLibCheckButton.Active; - compilerParameters.LangVersion = langVersion; - } - } - - void OnTargetChanged (object s, EventArgs a) - { - UpdateTarget (); - } - - void UpdateTarget () - { -// if ((CompileTarget) compileTargetCombo.Active == CompileTarget.Library) { -// iconEntry.Sensitive = false; -// } else { -// iconEntry.Sensitive = true; -// if (!classListFilled) -// FillClasses (); -// } - } - - void FillClasses () - { - try { - var ctx = TypeSystemService.GetCompilation (project); - if (ctx == null) - // Project not found in parser database - return; - foreach (var c in ctx.GetAllTypeDefinitions ()) { - if (c.Methods != null) { - foreach (var m in c.Methods) { - if (m.IsStatic && m.Name == "Main") - classListStore.AppendValues (c.FullName); - } - } - } - classListFilled = true; - } catch (InvalidOperationException) { - // Project not found in parser database - } - } - } - - class CompilerOptionsPanel : ItemOptionsPanel - { - CompilerOptionsPanelWidget widget; - - public override Widget CreatePanelWidget () - { - return (widget = new CompilerOptionsPanelWidget ((DotNetProject) ConfiguredProject)); - } - - public override bool ValidateChanges () - { - return widget.ValidateChanges (); - } - - public override void ApplyChanges () - { - MultiConfigItemOptionsDialog dlg = (MultiConfigItemOptionsDialog) ParentDialog; - widget.Store (dlg.Configurations); - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CompilerOptionsPanelWidget.cs.org b/PlayScript.Addin/MonoDevelop.PlayScript.Project/CompilerOptionsPanelWidget.cs.org deleted file mode 100644 index 7e195a2..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Project/CompilerOptionsPanelWidget.cs.org +++ /dev/null @@ -1,251 +0,0 @@ -// -// CompilerOptionsPanelWidget.cs -// -// Author: -// Michael Hutchinson -// Mike Krüger -// -// Copyright (C) 2007, 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using Gtk; - -using MonoDevelop.Core; -using MonoDevelop.Projects; -using MonoDevelop.Projects.Text; -using MonoDevelop.Ide.Gui.Dialogs; -using MonoDevelop.Ide; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Ide.TypeSystem; - -namespace MonoDevelop.PlayScript.Project -{ - - partial class CompilerOptionsPanelWidget : Gtk.Bin - { - DotNetProject project; - ListStore classListStore; - bool classListFilled; - - public CompilerOptionsPanelWidget (DotNetProject project) - { - this.Build(); - this.project = project; - var configuration = (DotNetProjectConfiguration) project.GetConfiguration (IdeApp.Workspace.ActiveConfiguration); - var compilerParameters = (PlayScriptCompilerParameters) configuration.CompilationParameters; - var projectParameters = (PlayScriptProjectParameters) configuration.ProjectParameters; - - ListStore store = new ListStore (typeof (string)); - store.AppendValues (GettextCatalog.GetString ("Executable")); - store.AppendValues (GettextCatalog.GetString ("Library")); - store.AppendValues (GettextCatalog.GetString ("Executable with GUI")); - store.AppendValues (GettextCatalog.GetString ("Module")); - compileTargetCombo.Model = store; - CellRendererText cr = new CellRendererText (); - compileTargetCombo.PackStart (cr, true); - compileTargetCombo.AddAttribute (cr, "text", 0); - compileTargetCombo.Active = (int) configuration.CompileTarget; - compileTargetCombo.Changed += new EventHandler (OnTargetChanged); - - if (project.IsLibraryBasedProjectType) { - //fixme: should we totally hide these? - compileTargetCombo.Sensitive = false; - mainClassEntry.Sensitive = false; - } else { - classListStore = new ListStore (typeof(string)); - mainClassEntry.Model = classListStore; - mainClassEntry.TextColumn = 0; - ((Entry)mainClassEntry.Child).Text = projectParameters.MainClass ?? string.Empty; - - UpdateTarget (); - } - - // Load the codepage. If it matches any of the supported encodigs, use the encoding name - string foundEncoding = null; - foreach (TextEncoding e in TextEncoding.SupportedEncodings) { - if (e.CodePage == -1) - continue; - if (e.CodePage == projectParameters.CodePage) - foundEncoding = e.Id; - codepageEntry.AppendText (e.Id); - } - if (foundEncoding != null) - codepageEntry.Entry.Text = foundEncoding; - else if (projectParameters.CodePage != 0) - codepageEntry.Entry.Text = projectParameters.CodePage.ToString (); - - iconEntry.Path = projectParameters.Win32Icon; - iconEntry.DefaultPath = project.BaseDirectory; - allowUnsafeCodeCheckButton.Active = compilerParameters.UnsafeCode; - noStdLibCheckButton.Active = compilerParameters.NoStdLib; - - ListStore langVerStore = new ListStore (typeof (string)); - langVerStore.AppendValues (GettextCatalog.GetString ("Default")); - langVerStore.AppendValues ("ISO-1"); - langVerStore.AppendValues ("ISO-2"); - langVerStore.AppendValues ("Version 3"); - langVerStore.AppendValues ("Version 4"); - langVerStore.AppendValues ("Version 5"); - langVerStore.AppendValues ("Version 6"); - langVerCombo.Model = langVerStore; - langVerCombo.Active = (int) compilerParameters.LangVersion; - } - - protected override void OnDestroyed () - { - if (classListStore != null) { - classListStore.Dispose (); - classListStore = null; - } - base.OnDestroyed (); - } - - public bool ValidateChanges () - { - if (codepageEntry.Entry.Text.Length > 0) { - // Get the codepage. If the user specified an encoding name, find it. - int trialCodePage = -1; - foreach (TextEncoding e in TextEncoding.SupportedEncodings) { - if (e.Id == codepageEntry.Entry.Text) { - trialCodePage = e.CodePage; - break; - } - } - - if (trialCodePage == -1) { - if (!int.TryParse (codepageEntry.Entry.Text, out trialCodePage)) { - MessageService.ShowError (GettextCatalog.GetString ("Invalid code page number.")); - return false; - } - } - } - return true; - } - - public void Store (ItemConfigurationCollection configs) - { - int codePage; - CompileTarget compileTarget = (CompileTarget) compileTargetCombo.Active; - LangVersion langVersion = (LangVersion) langVerCombo.Active; - - - if (codepageEntry.Entry.Text.Length > 0) { - // Get the codepage. If the user specified an encoding name, find it. - int trialCodePage = -1; - foreach (TextEncoding e in TextEncoding.SupportedEncodings) { - if (e.Id == codepageEntry.Entry.Text) { - trialCodePage = e.CodePage; - break; - } - } - - if (trialCodePage != -1) - codePage = trialCodePage; - else { - if (!int.TryParse (codepageEntry.Entry.Text, out trialCodePage)) { - return; - } - codePage = trialCodePage; - } - } else - codePage = 0; - - project.CompileTarget = compileTarget; - - var projectParameters = (PlayScriptProjectParameters) project.LanguageParameters; - - projectParameters.CodePage = codePage; - - if (iconEntry.Sensitive) - projectParameters.Win32Icon = iconEntry.Path; - - if (mainClassEntry.Sensitive) - projectParameters.MainClass = mainClassEntry.Entry.Text; - - foreach (DotNetProjectConfiguration configuration in configs) { - var compilerParameters = (PlayScriptCompilerParameters) configuration.CompilationParameters; - compilerParameters.UnsafeCode = allowUnsafeCodeCheckButton.Active; - compilerParameters.NoStdLib = noStdLibCheckButton.Active; - compilerParameters.LangVersion = langVersion; - } - } - - void OnTargetChanged (object s, EventArgs a) - { - UpdateTarget (); - } - - void UpdateTarget () - { - if ((CompileTarget) compileTargetCombo.Active == CompileTarget.Library) { - iconEntry.Sensitive = false; - } else { - iconEntry.Sensitive = true; - if (!classListFilled) - FillClasses (); - } - } - - void FillClasses () - { - try { - var ctx = TypeSystemService.GetCompilation (project); - if (ctx == null) - // Project not found in parser database - return; - foreach (var c in ctx.GetAllTypeDefinitions ()) { - if (c.Methods != null) { - foreach (var m in c.Methods) { - if (m.IsStatic && m.Name == "Main") - classListStore.AppendValues (c.FullName); - } - } - } - classListFilled = true; - } catch (InvalidOperationException) { - // Project not found in parser database - } - } - } - - class CompilerOptionsPanel : ItemOptionsPanel - { - CompilerOptionsPanelWidget widget; - - public override Widget CreatePanelWidget () - { - return (widget = new CompilerOptionsPanelWidget ((DotNetProject) ConfiguredProject)); - } - - public override bool ValidateChanges () - { - return widget.ValidateChanges (); - } - - public override void ApplyChanges () - { - MultiConfigItemOptionsDialog dlg = (MultiConfigItemOptionsDialog) ParentDialog; - widget.Store (dlg.Configurations); - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/Actions/ConvertToEnumAction.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/Actions/ConvertToEnumAction.cs deleted file mode 100644 index c4cf970..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/Actions/ConvertToEnumAction.cs +++ /dev/null @@ -1,503 +0,0 @@ -// -// Author: -// Luís Reis -// -// Copyright (c) 2013 Luís Reis -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Linq; -using ICSharpCode.NRefactory.Semantics; -using ICSharpCode.NRefactory.TypeSystem; -using ICSharpCode.NRefactory.TypeSystem.Implementation; -using ICSharpCode.NRefactory.PatternMatching; -using MonoDevelop.CodeActions; -using ICSharpCode.NRefactory; -using System.Threading; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.PlayScript.Refactoring; -using ICSharpCode.Decompiler.ILAst; -using MonoDevelop.Core; - -namespace MonoDevelop.PlayScript.Refactoring.CodeActions -{ - /// - /// Generates an enumeration from const fields - /// - class ConvertToEnumAction : MonoDevelop.CodeActions.CodeActionProvider - { - public override IEnumerable GetActions(MonoDevelop.Ide.Gui.Document document, object refactoringContext, TextLocation loc, CancellationToken cancellationToken) - { - var context = refactoringContext as MDRefactoringContext; - - if (context == null || context.IsInvalid) - yield break; - - VariableInitializer currentVariable = context.GetNode(); - if (currentVariable == null) { - yield break; - } - - FieldDeclaration currentField = currentVariable.Parent as FieldDeclaration; - if (currentField == null) { - yield break; - } - - if (!currentField.Modifiers.HasFlag(Modifiers.Const)) { - yield break; - } - - PrimitiveType baseType = TypeToIntegerPrimitive(context, currentField.ReturnType); - if (baseType == null) { - //Can't make enums of these types - yield break; - } - - TypeDeclaration containerType = currentVariable.GetParent(); - - //Get all the fields/variables that the enum can possibly cover - //Don't check the name just yet. That'll come later. - - var constFields = containerType.Members.OfType() - .Where(field => field.GetParent() == containerType && field.HasModifier(Modifiers.Const)).ToList(); - - var constVariables = constFields.SelectMany(field => field.Variables).ToList(); - - //Now, it's time to check the name of the selected variable - //We'll use this to search for prefixes later - - var names = constVariables.Select(variable => variable.Name).ToList(); - string currentName = currentVariable.Name; - - //Now, find the common name prefixes - //If the variable is called 'A_B_C_D', then 'A', 'A_B' and 'A_B_C' are - //the potentially available prefixes. - //Note that the common prefixes are the ones that more than one variable - //has. - //Each prefix has an associated action. - - foreach (var prefix in GetCommonPrefixes (currentName, names)) { - string title = string.Format(GettextCatalog.GetString("Create enum '{0}'"), prefix); - - yield return new DefaultCodeAction(title, (ctx, script) => { - PrepareToRunAction (prefix, baseType, containerType, constVariables, cancellationToken, ctx, script); - }); - } - } - - void PrepareToRunAction (string prefix, PrimitiveType baseType, TypeDeclaration containerType, List variables, CancellationToken cancellationToken, RefactoringContext context, Script script) - { - List names = variables.Select(variable => variable.Name).ToList(); - Dictionary newNames = names.ToDictionary(originalName => originalName, originalName => { - if (!originalName.StartsWith(prefix)) { - return originalName; - } - int startName = prefix.Length; - while (startName < originalName.Length - 1 && originalName[startName] == '_') { - ++startName; - } - return originalName.Substring(startName); - }); - - string enumName; - using (var dialog = new ConvertToEnumDialog (prefix, variables, variables.Where(variable => variable.Name.StartsWith(prefix, StringComparison.InvariantCulture) - && VariableHasSpecifiedIntegerType(context, variable, baseType)).ToList(), newNames)) - { - if (dialog.Run (/*MonoDevelop.Ide.IdeApp.Workbench.RootWindow*/) != Xwt.Command.Ok) { - return; - } - enumName = dialog.EnumName; - variables = dialog.SelectedVariables; - newNames = dialog.NewNames; - } - - RunAction (context, baseType, enumName, newNames, containerType, variables, script); - - } - - void RunAction(RefactoringContext context, AstType baseType, string enumName, Dictionary newNames, TypeDeclaration containerTypeDeclaration, List variables, Script script) - { - var names = variables.Select (variable => variable.Name).ToList (); - var containerType = (context.Resolve(containerTypeDeclaration) as TypeResolveResult).Type; - - var fields = containerTypeDeclaration.Members.OfType().Where(field => field.Modifiers.HasFlag(Modifiers.Const)).ToList(); - List variableUnitsToRemove = new List(variables); - List fieldsToRemove = new List(); - - foreach (var field in fields) { - if (field.Variables.All(variableUnitsToRemove.Contains)) { - fieldsToRemove.Add(field); - - variableUnitsToRemove.RemoveAll(field.Variables.Contains); - } - } - - var generatedEnum = CreateEnumDeclaration(baseType, enumName, variables, names, newNames); - - AstNode root = GetRootNodeOf(containerTypeDeclaration); - var newRoot = root.Clone(); - - FixIdentifiers(context, enumName, variables, containerType, baseType, names, newNames, root, newRoot); - foreach (var member in root.Descendants.OfType().Where (member => names.Contains (member.MemberName))) { - if (variables.Any(variable => variable.Descendants.Contains(member))) { - //Already handled - continue; - } - - var resolvedIdentifier = context.Resolve(member) as MemberResolveResult; - if (resolvedIdentifier == null) { - continue; - } - - if (resolvedIdentifier.Type.Equals(containerType)) { - continue; - } - - var equivalentMember = GetEquivalentNodeFor(root, newRoot, member); - MemberReferenceExpression memberToReplace = (MemberReferenceExpression)equivalentMember; - - var replacement = CreateReplacementMemberReference(enumName, baseType, newNames, memberToReplace); - memberToReplace.ReplaceWith(replacement); - } - - //Fix the file - InsertAfterEquivalent(root, newRoot, containerTypeDeclaration.LBraceToken, generatedEnum, Roles.TypeMemberRole); - - foreach (var variableToRemove in variableUnitsToRemove) { - GetEquivalentNodeFor(root, newRoot, variableToRemove).Remove(); - } - foreach (var fieldToRemove in fieldsToRemove) { - GetEquivalentNodeFor(root, newRoot, fieldToRemove).Remove(); - } - - script.Replace(root, newRoot); - - ReplaceVariableReferences(context, root, baseType, enumName, script, newNames, variables); - } - - static void ReplaceVariableReferences(RefactoringContext context, AstNode root, AstType baseType, string enumName, Script script, Dictionary newNames, IEnumerable variables) - { - var resolveResults = variables.Select(variable => (MemberResolveResult)context.Resolve(variable)); - var resolvedFields = resolveResults.Select(resolveResult => resolveResult.Member); - script.DoGlobalOperationOn(resolvedFields, (newCtx, newScript, foundNodes) => { - foreach (var foundNode in foundNodes) { - TypeDeclaration newContainerType = foundNode.GetParent(); - if (root.Descendants.OfType().Select(type => ((TypeResolveResult)context.Resolve(type)).Type.FullName).ToList().Contains(((TypeResolveResult)newCtx.Resolve(newContainerType)).Type.FullName)) { - //This file has already been fixed - return; - } - var identifierExpr = foundNode as IdentifierExpression; - if (identifierExpr != null) { - newScript.Replace(identifierExpr, CreateIdentifierReplacement(enumName, baseType, newNames, identifierExpr)); - continue; - } - var memberRef = foundNode as MemberReferenceExpression; - if (memberRef != null) { - var replacement = CreateReplacementMemberReference(enumName, baseType, newNames, memberRef); - newScript.Replace(memberRef, replacement); - } - } - }); - } - - TypeDeclaration CreateEnumDeclaration(AstType baseType, string enumName, List variables, List names, Dictionary newNames) - { - TypeDeclaration generatedEnum = new TypeDeclaration(); - generatedEnum.ClassType = ClassType.Enum; - generatedEnum.BaseTypes.Add(baseType.Clone()); - generatedEnum.Name = enumName; - generatedEnum.Modifiers = GetCombinedModifier((Modifiers)variables.Select(variable => ((FieldDeclaration)variable.Parent).Modifiers).Aggregate(0, (prev, newModifier) => prev | (int)newModifier)); - foreach (var variable in variables) { - var generatedMember = new EnumMemberDeclaration(); - generatedMember.Name = newNames[variable.Name]; - var value = variable.Initializer.Clone(); - foreach (var identifier in value.DescendantsAndSelf.OfType().Where(identifier => names.Contains(identifier.Identifier))) { - var newIdentifier = new IdentifierExpression(newNames[identifier.Identifier]); - if (identifier == value) { - value = newIdentifier; - break; - } - identifier.ReplaceWith(newIdentifier); - } - generatedMember.Initializer = value; - generatedEnum.Members.Add(generatedMember); - } - return generatedEnum; - } - - /// - /// Determines whether the initialized variable has the specified primitive integer type - /// - /// true if the initialized variable has the specified type; otherwise, false. - /// The context to use. - /// The variable initializer to check. - /// The type to compare with. - bool VariableHasSpecifiedIntegerType(RefactoringContext context, VariableInitializer variable, AstType type) - { - return TypeToIntegerPrimitive(context, variable.GetParent().ReturnType).Match(type).Success; - } - - static Dictionary primitiveTypes = new Dictionary(); - - static ConvertToEnumAction() - { - primitiveTypes.Add(typeof(byte).FullName, new PrimitiveType("byte")); - primitiveTypes.Add(typeof(sbyte).FullName, new PrimitiveType("sbyte")); - - primitiveTypes.Add(typeof(short).FullName, new PrimitiveType("short")); - primitiveTypes.Add(typeof(int).FullName, new PrimitiveType("int")); - primitiveTypes.Add(typeof(long).FullName, new PrimitiveType("long")); - - primitiveTypes.Add(typeof(ushort).FullName, new PrimitiveType("ushort")); - primitiveTypes.Add(typeof(uint).FullName, new PrimitiveType("uint")); - primitiveTypes.Add(typeof(ulong).FullName, new PrimitiveType("ulong")); - } - - /// - /// Gets a PrimitiveType instance from an AstType. - /// Only returns integer types (and never the char type) - /// - /// The integer primitive. - /// The context to use. - /// The AstType to get the primitive from. - PrimitiveType TypeToIntegerPrimitive(RefactoringContext context, AstType type) - { - var resolvedType = context.ResolveType(type) as DefaultResolvedTypeDefinition; - - PrimitiveType primitiveType; - if (!primitiveTypes.TryGetValue(resolvedType.FullName, out primitiveType)) { - return null; - } - - return primitiveType; - } - - static Expression CreateReplacementMemberReference(string enumName, AstType baseType, Dictionary newNames, MemberReferenceExpression memberToReplace) - { - return new ParenthesizedExpression(new CastExpression(baseType.Clone(), new MemberReferenceExpression(new MemberReferenceExpression(memberToReplace.Target.Clone(), enumName), newNames [memberToReplace.MemberName]))); - } - - void FixIdentifiers(RefactoringContext context, string enumName, List variables, IType containerType, AstType baseType, List names, Dictionary newNames, AstNode root, AstNode newRoot) - { - foreach (var identifier in root.Descendants.OfType ().Where (identifier => names.Contains (identifier.Identifier))) { - if (variables.Any(variable => variable.Descendants.Contains(identifier))) { - //Already handled - continue; - } - var resolvedIdentifier = context.Resolve(identifier) as MemberResolveResult; - if (resolvedIdentifier == null) { - continue; - } - if (resolvedIdentifier.Type.Equals(containerType)) { - continue; - } - var replacement = CreateIdentifierReplacement(enumName, baseType, newNames, identifier); - GetEquivalentNodeFor(root, newRoot, identifier).ReplaceWith(replacement); - } - } - - static ParenthesizedExpression CreateIdentifierReplacement(string enumName, AstType baseType, Dictionary newNames, IdentifierExpression identifier) - { - var replacement = new ParenthesizedExpression(new CastExpression(baseType.Clone(), new MemberReferenceExpression(new IdentifierExpression(enumName), newNames [identifier.Identifier]))); - return replacement; - } - - /// - /// Finds the corresponding node in another ("new") AST. - /// Assumes entities have not been renamed and no statements have been removed. - /// - /// The equivalent node in the new AST. - /// The root of the first ("old") AST. - /// The root of the new AST. - /// Node (from the old AST) to find in the new one. - AstNode GetEquivalentNodeFor(AstNode root, AstNode newRoot, AstNode nodeToFind) - { - if (nodeToFind == null) { - throw new ArgumentNullException("nodeToFind"); - } - - if (nodeToFind.Parent != root) { - AstNode foundRoot = GetEquivalentNodeFor(root, newRoot, nodeToFind.Parent); - if (foundRoot == null) { - //If the equivalent of the parent does not exist in the new AST, - //then neither does this node. - return null; - } - newRoot = foundRoot; - root = nodeToFind.Parent; - } - - //At this point, the roots are the parents of the nodes to check - //root is the parent of the nodeToFind, and newRoot is the parent of the node to return - - var block = root as BlockStatement; - if (block != null && nodeToFind.Role == BlockStatement.StatementRole) { - //This could be a problem if statements were removed in the new AST, - //but fortunately that's not the problem we're trying to solve. - return ((BlockStatement)newRoot).Statements.ElementAt(block.TakeWhile(statement => statement != nodeToFind).Count()); - } - - //First, we'll narrow down the search - the equivalent node *always* has the same type and role as nodeToFind - //The Role check will help e.g. in binary expressions (where there is a 'Left' and a 'Right' role) - var candidates = newRoot.Children.Where(child => child.GetType() == nodeToFind.GetType() && child.Role == nodeToFind.Role); - var entity = nodeToFind as EntityDeclaration; - if (entity != null) { - var field = nodeToFind as FieldDeclaration; - if (field != null) { - //Fields have to be treated separately because fields have no names - candidates = candidates.Where(candidate => IsEquivalentField((FieldDeclaration) candidate, field)); - } - else { - //Some entities can be distinguished by name. - candidates = candidates.Where(candidate => ((EntityDeclaration)candidate).Name == entity.Name); - - var method = nodeToFind as MethodDeclaration; - if (method != null) { - //Methods, however, can be overloaded - so their names aren't enough. - candidates = candidates.Where(candidate => CheckIfMethodsHaveSameParameters((MethodDeclaration) candidate, method)); - } - } - } - - var ns = nodeToFind as NamespaceDeclaration; - if (ns != null) { - candidates = candidates.Where(candidate => ((NamespaceDeclaration)candidate).Name == ns.Name).ToList(); - if (candidates.Count() > 1) { - throw new NotImplementedException("Two or more namespace declarations with the same name are siblings. This case is not currently supported by this action."); - } - } - - var initializer = nodeToFind as VariableInitializer; - if (initializer != null) { - candidates = candidates.Where(candidate => ((VariableInitializer)candidate).Name == initializer.Name); - } - - var equivalentNode = candidates.SingleOrDefault(); - return equivalentNode; - } - - bool IsEquivalentField(FieldDeclaration field1, FieldDeclaration field2) { - return field1.Variables.Any(variable1 => { - return field2.Variables.Any(variable2 => variable1.Name == variable2.Name); - }); - } - - bool CheckIfMethodsHaveSameParameters(MethodDeclaration methodDeclaration, MethodDeclaration comparedMethod) - { - if (methodDeclaration.Parameters.Count != comparedMethod.Parameters.Count) { - return false; - } - - ParameterDeclaration param1 = methodDeclaration.Parameters.FirstOrDefault(); - ParameterDeclaration param2 = comparedMethod.Parameters.FirstOrDefault(); - - while (param1 != null) { - //If the names or initializers are different, this will still match. - //But if the type or order changes, this will complain - if (!param1.Type.Match(param2.Type).Success) { - return false; - } - - param1 = (ParameterDeclaration) param1.GetNextSibling(node => node is ParameterDeclaration); - param2 = (ParameterDeclaration) param2.GetNextSibling(node => node is ParameterDeclaration); - } - - return true; - } - - void InsertAfterEquivalent(AstNode root, AstNode newRoot, AstNode prevNode, T newNode, Role role) - where T : AstNode - { - AstNode equivalentPrevNode = GetEquivalentNodeFor(root, newRoot, prevNode); - equivalentPrevNode.Parent.InsertChildAfter(equivalentPrevNode, newNode, role); - } - - /// - /// Gets the least permissive access modifier that still allows access to - /// fields or methods with the specified modifiers. - /// This will ignore all modifiers unrelated to access - such as const and readonly - /// - /// A modifier that is at least as permissive as all provided modifiers. - /// The modifiers to use. - Modifiers GetCombinedModifier(Modifiers modifiers) - { - if (modifiers.HasFlag(Modifiers.Public)) - return Modifiers.Public; - - Modifiers combinedModifier = 0; - if (modifiers.HasFlag(Modifiers.Protected)) { - combinedModifier |= Modifiers.Protected; - } - if (modifiers.HasFlag(Modifiers.Internal)) { - combinedModifier |= Modifiers.Internal; - } - - //No modifier if the fields are all private. - return combinedModifier; - } - - /// - /// Gets all prefixes that more than one name have. - /// - /// The common prefixes. - /// The name to use. - /// The names to check. - IEnumerable GetCommonPrefixes(string currentName, IEnumerable names) - { - //Find the indexes that 'split' words in the variable name - var boundariesForCurrentWord = GetWordsBoundaries(currentName); - - //Get the candidate prefixes - List proposedPrefixes = boundariesForCurrentWord.Select(boundary => currentName.Substring(0, boundary)).ToList(); - - //Return only the prefixes that more than one variable has. - return proposedPrefixes.Where(prefix => names.Count(name => name.StartsWith(prefix, StringComparison.InvariantCulture)) > 1); - } - - List GetWordsBoundaries(string name) - { - List foundBoundaries = new List(); - for (int i = 1; i < name.Length - 1; ++i) { - char chr = name [i]; - if (chr == '_') { - foundBoundaries.Add(i); - continue; - } - - if (char.IsUpper(chr) && char.IsLower(name [i - 1])) { - foundBoundaries.Add(i); - continue; - } - } - - return foundBoundaries; - } - - AstNode GetRootNodeOf(AstNode node) - { - while (node.Parent != null) { - node = node.Parent; - } - - return node; - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/Actions/ConvertToEnumDialog.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/Actions/ConvertToEnumDialog.cs deleted file mode 100644 index eb4dd61..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/Actions/ConvertToEnumDialog.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -// ConvertToEnumDialog.cs -// -// Author: -// Luís Reis -// -// Copyright (c) 2013 Luís Reis -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Linq; -using MonoDevelop.Core; -using System.Collections.Generic; -using ICSharpCode.NRefactory.PlayScript; - -namespace MonoDevelop.PlayScript.Refactoring.CodeActions -{ - class ConvertToEnumDialog : Xwt.Dialog - { - Xwt.TextEntry enumNameEntry; - Xwt.ListView variableList; - Xwt.ListStore variableStore; - Xwt.DataField enabledField; - Xwt.ListViewColumn enabledColumn; - Xwt.DataField oldNameField; - Xwt.ListViewColumn oldNameColumn; - Xwt.DataField newNameField; - Xwt.ListViewColumn newNameColumn; - List variables; - - public ConvertToEnumDialog(string proposedEnumName, List variables, List defaultActiveVariables, Dictionary newNames) { - this.variables = variables; - - Title = GettextCatalog.GetString("Convert fields to enumeration"); - - Xwt.VBox vbox = new Xwt.VBox (); - - vbox.PackStart(new Xwt.Label(GettextCatalog.GetString("Name of enum"))); - - enumNameEntry = new Xwt.TextEntry (); - enumNameEntry.Text = proposedEnumName; - vbox.PackStart (enumNameEntry); - - vbox.PackStart (new Xwt.Label (GettextCatalog.GetString ("Variables to include"))); - - variableList = new Xwt.ListView (); - enabledField = new Xwt.DataField (); - oldNameField = new Xwt.DataField (); - newNameField = new Xwt.DataField (); - - variableStore = new Xwt.ListStore (enabledField, oldNameField, newNameField); - variableList.DataSource = variableStore; - - enabledColumn = new Xwt.ListViewColumn (GettextCatalog.GetString ("Included"), new Xwt.CheckBoxCellView(enabledField) { Editable = true }); - variableList.Columns.Add (enabledColumn); - oldNameColumn = new Xwt.ListViewColumn(GettextCatalog.GetString("Field name"), new Xwt.TextCellView(oldNameField) { Editable = false }); - variableList.Columns.Add (oldNameColumn); - newNameColumn = new Xwt.ListViewColumn(GettextCatalog.GetString("Enum name"), new Xwt.TextCellView(newNameField) { Editable = true, }); - variableList.Columns.Add (newNameColumn); - - for (int i = 0; i < variables.Count; ++i) { - var variable = variables[i]; - - variableStore.AddRow (); - variableStore.SetValue (i, enabledField, defaultActiveVariables.Contains(variable)); - variableStore.SetValue (i, oldNameField, variable.Name); - - variableStore.SetValue (i, newNameField, newNames [variable.Name]); - } - - vbox.PackStart (variableList, true, true); - - vbox.PackStart (new Xwt.Label (GettextCatalog.GetString ("Warning: This may take a while..."))); - - Content = vbox; - - Buttons.Add (new Xwt.DialogButton(Xwt.Command.Ok)); - Buttons.Add (new Xwt.DialogButton(Xwt.Command.Cancel)); - } - - public string EnumName { - get { return enumNameEntry.Text; } - } - - public List SelectedVariables - { - get { - return variables.Where((variable, idx) => variableStore.GetValue(idx, enabledField)).ToList(); - } - } - - public Dictionary NewNames - { - get { - var newNames = new Dictionary (); - - for (int i = 0; i < variableStore.RowCount; ++i) { - newNames[variableStore.GetValue(i, oldNameField)] = variableStore.GetValue(i, newNameField); - } - - return newNames; - } - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/Actions/MoveTypeToFile.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/Actions/MoveTypeToFile.cs deleted file mode 100644 index 6d847cc..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/Actions/MoveTypeToFile.cs +++ /dev/null @@ -1,167 +0,0 @@ -// -// MoveTypeToFile.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2011 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using ICSharpCode.NRefactory.PlayScript; -using ICSharpCode.NRefactory.PatternMatching; -using MonoDevelop.Core; -using System.Collections.Generic; -using Mono.TextEditor; -using System.Linq; -using MonoDevelop.Refactoring; -using System.IO; -using System.Text; -using MonoDevelop.Ide.StandardHeader; -using MonoDevelop.Core.ProgressMonitoring; -using ICSharpCode.NRefactory; -using System.Threading; -using ICSharpCode.NRefactory.PlayScript.Refactoring; - -namespace MonoDevelop.PlayScript.Refactoring.CodeActions -{ - class MoveTypeToFile : MonoDevelop.CodeActions.CodeActionProvider - { - public override IEnumerable GetActions (MonoDevelop.Ide.Gui.Document document, object refactoringContext, TextLocation loc, CancellationToken cancellationToken) - { - var context = refactoringContext as MDRefactoringContext; - if (context == null) - return Enumerable.Empty (); - return GetActions (context); - } - protected IEnumerable GetActions (MDRefactoringContext context) - { - if (context.IsInvalid) - yield break; - var type = GetTypeDeclaration (context); - if (type == null) - yield break; - if (Path.GetFileNameWithoutExtension (context.TextEditor.FileName) == type.Name) - yield break; - string title; - if (IsSingleType (context)) { - title = String.Format (GettextCatalog.GetString ("Rename file to '{0}'"), Path.GetFileName (GetCorrectFileName (context, type))); - } else { - title = String.Format (GettextCatalog.GetString ("Move type to file '{0}'"), Path.GetFileName (GetCorrectFileName (context, type))); - } - yield return new MonoDevelop.CodeActions.DefaultCodeAction (title, (c, s) => { - var ctx = (MDRefactoringContext) c; - var script = (Script) s; - string correctFileName = GetCorrectFileName (ctx, type); - if (IsSingleType (ctx)) { - FileService.RenameFile (ctx.TextEditor.FileName, correctFileName); - if (ctx.FileContainerProject != null) - ctx.FileContainerProject.Save (new NullProgressMonitor ()); - return; - } - - CreateNewFile (ctx, type, correctFileName); - script.Remove (type); - }); - } - - static void CreateNewFile (MDRefactoringContext context, TypeDeclaration type, string correctFileName) - { - var content = context.TextEditor.Text; - - var types = new List (context.Unit.GetTypes ().Where (t => t.StartLocation != type.StartLocation)); - types.Sort ((x, y) => y.StartLocation.CompareTo (x.StartLocation)); - - foreach (var removeType in types) { - var start = context.GetOffset (removeType.StartLocation); - var end = context.GetOffset (removeType.EndLocation); - content = content.Remove (start, end - start); - } - - if (context.FileContainerProject != null) { - string header = StandardHeaderService.GetHeader (context.FileContainerProject, correctFileName, true); - if (!string.IsNullOrEmpty (header)) - content = header + context.TextEditor.EolMarker + StripHeader (content); - } - content = StripDoubleBlankLines (content); - - File.WriteAllText (correctFileName, content); - context.FileContainerProject.AddFile (correctFileName); - MonoDevelop.Ide.IdeApp.ProjectOperations.Save (context.FileContainerProject); - } - - static bool IsBlankLine (TextDocument doc, int i) - { - var line = doc.GetLine (i); - return line.Length == line.GetIndentation (doc).Length; - } - - static string StripDoubleBlankLines (string content) - { - var doc = new Mono.TextEditor.TextDocument (content); - for (int i = 1; i + 1 <= doc.LineCount; i++) { - if (IsBlankLine (doc, i) && IsBlankLine (doc, i + 1)) { - doc.Remove (doc.GetLine (i).SegmentIncludingDelimiter); - i--; - continue; - } - } - return doc.Text; - } - - static string StripHeader (string content) - { - var doc = new Mono.TextEditor.TextDocument (content); - while (true) { - string lineText = doc.GetLineText (1); - if (lineText == null) - break; - if (lineText.StartsWith ("//")) { - doc.Remove (doc.GetLine (1).SegmentIncludingDelimiter); - continue; - } - break; - } - return doc.Text; - } - - bool IsSingleType (MDRefactoringContext context) - { - return context.Unit.GetTypes ().Count () == 1; - } - - TypeDeclaration GetTypeDeclaration (MDRefactoringContext context) - { - var result = context.GetNode (); - if (result == null || result.Parent is TypeDeclaration) - return null; - if (result != null && result.NameToken.Contains (context.Location)) - return result; - return null; - } - - internal static string GetCorrectFileName (MDRefactoringContext context, EntityDeclaration type) - { - if (type == null) - return context.TextEditor.FileName; - return Path.Combine (Path.GetDirectoryName (context.TextEditor.FileName), type.Name + Path.GetExtension (context.TextEditor.FileName)); - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/ContextActionExtensions.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/ContextActionExtensions.cs deleted file mode 100644 index 66c341d..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/ContextActionExtensions.cs +++ /dev/null @@ -1,69 +0,0 @@ -// -// ContextActionExtensions.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2011 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using Mono.TextEditor; -using ICSharpCode.NRefactory.PlayScript; -//using MonoDevelop.PlayScript.Resolver; -using ICSharpCode.NRefactory.PlayScript.Resolver; - -namespace MonoDevelop.PlayScript.Refactoring.CodeActions -{ - static class ContextActionExtensions - { - public static int CalcIndentLevel (this MonoDevelop.Ide.Gui.Document doc, string indent) - { - int col = GetColumn (indent, 0, doc.Editor.Options.TabSize); - return System.Math.Max (0, col / doc.Editor.Options.TabSize); - } - - public static int GetColumn (string wrapper, int i, int tabSize) - { - int j = i; - int col = 0; - for (; j < wrapper.Length && (wrapper[j] == ' ' || wrapper[j] == '\t'); j++) { - if (wrapper[j] == ' ') { - col++; - } else { - col = GetNextTabstop (col, tabSize); - } - } - return col; - } - - static int GetNextTabstop (int currentColumn, int tabSize) - { - int result = currentColumn + tabSize; - return (result / tabSize) * tabSize; - } - - public static void FormatText (this AstNode node, MonoDevelop.Ide.Gui.Document doc) - { - doc.UpdateParseDocument (); - MonoDevelop.PlayScript.Formatting.OnTheFlyFormatter.Format (doc, node.StartLocation); - } - } -} - diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/MDRefactoringContext.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/MDRefactoringContext.cs deleted file mode 100644 index e2fabb6..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/MDRefactoringContext.cs +++ /dev/null @@ -1,276 +0,0 @@ -// -// MDRefactoringContext.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2011 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Linq; -using ICSharpCode.NRefactory.PlayScript; -using MonoDevelop.Projects; -using MonoDevelop.Core; -using MonoDevelop.Refactoring; -using ICSharpCode.NRefactory.PlayScript.Refactoring; -using MonoDevelop.Ide.TypeSystem; -using ICSharpCode.NRefactory; -using System.Threading; -using MonoDevelop.Ide.Gui; -using System.Diagnostics; -using MonoDevelop.PlayScript.Refactoring.CodeIssues; -using Mono.TextEditor; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using MonoDevelop.PlayScript.Formatting; -using System.Threading.Tasks; - -using MonoDevelop.Components; -using MonoDevelop.Ide; - -namespace MonoDevelop.PlayScript.Refactoring.CodeActions -{ - public class MDRefactoringContext : RefactoringContext, IRefactoringContext - { - MonoDevelop.Projects.Project fileContainerProject; - - public TextEditorData TextEditor { - get; - private set; - } - - public DotNetProject Project { - get; - private set; - } - - public MonoDevelop.Projects.Project FileContainerProject { - get { - if (fileContainerProject == null) - fileContainerProject = FindProjectContainingFile () ?? Project; - return fileContainerProject; - } - } - - MonoDevelop.Projects.Project FindProjectContainingFile () - { - var file = TextEditor.FileName; - if (string.IsNullOrEmpty (file) || Project == null) - return null; - - var pf = Project.GetProjectFile (file); - if (pf != null && (pf.Flags & ProjectItemFlags.Hidden) != 0) { - // The file is hidden in this project, so it may also be part of another project. - // Try to find a project in which this file is not hidden - foreach (var p in Project.ParentSolution.GetAllProjects ()) { - pf = p.GetProjectFile (file); - if (pf != null && (pf.Flags & ProjectItemFlags.Hidden) == 0) - return p; - } - } - return null; - } - - public bool IsInvalid { - get { - if (Resolver == null || TextEditor == null) - return true; - return ParsedDocument == null; - } - } - - public ParsedDocument ParsedDocument { - get; - private set; - } - - public SyntaxTree Unit { - get { - Debug.Assert (!IsInvalid); - return Resolver.RootNode as SyntaxTree; - } - } - - public override string DefaultNamespace { - get { - var p = FileContainerProject as IDotNetFileContainer; - if (p == null || TextEditor == null || string.IsNullOrEmpty (TextEditor.FileName)) - return null; - return p.GetDefaultNamespace (TextEditor.FileName); - } - } - - public override bool Supports (Version version) - { - var project = Project; - if (project == null) - return true; - switch (project.TargetFramework.ClrVersion) { - case ClrVersion.Net_1_1: - return version.Major > 1 || version.Major == 1 && version.Minor >= 1; - case ClrVersion.Net_2_0: - return version.Major >= 2; - case ClrVersion.Clr_2_1: - return version.Major > 2 || version.Major == 2 && version.Minor >= 1; - default: - return true; - } - } - - public override ICSharpCode.NRefactory.PlayScript.TextEditorOptions TextEditorOptions { - get { - return TextEditor.CreateNRefactoryTextEditorOptions (); - } - } - - public override bool IsSomethingSelected { - get { - return TextEditor.IsSomethingSelected; - } - } - - public override string SelectedText { - get { - return TextEditor.SelectedText; - } - } - - public override TextLocation SelectionStart { - get { - return TextEditor.MainSelection.Start; - } - } - - public override TextLocation SelectionEnd { - get { - return TextEditor.MainSelection.End; - } - } - - public override int GetOffset (TextLocation location) - { - return TextEditor.LocationToOffset (location); - } - - public override TextLocation GetLocation (int offset) - { - return TextEditor.OffsetToLocation (offset); - } - - public override string GetText (int offset, int length) - { - return TextEditor.GetTextAt (offset, length); - } - - public override string GetText (ICSharpCode.NRefactory.Editor.ISegment segment) - { - return TextEditor.GetTextAt (segment.Offset, segment.Length); - } - - public override ICSharpCode.NRefactory.Editor.IDocumentLine GetLineByOffset (int offset) - { - return TextEditor.GetLineByOffset (offset); - } - - readonly Document document; - TextLocation location; - - public override TextLocation Location { - get { - return location; - } - } - - internal void SetLocation (TextLocation loc) - { - if (document != null) - location = RefactoringService.GetCorrectResolveLocation (document, loc); - else - location = loc; - } - - readonly CSharpFormattingOptions formattingOptions; - - public CSharpFormattingOptions FormattingOptions { - get { - return formattingOptions; - } - } - - public Script StartScript () - { - return new MDRefactoringScript (this, formattingOptions); - } - - public IDisposable CreateScript () - { - return StartScript (); - } - - internal static Task Create (Document document, TextLocation loc, CancellationToken cancellationToken = default (CancellationToken)) - { - var shared = document.GetSharedResolver (); - if (shared == null) { - var tcs = new TaskCompletionSource (); - tcs.SetResult (null); - return tcs.Task; - } -// TODO: Fix me - throw new NotImplementedException("PlayScript TODO MDRefactoringContext create"); - return null; -// return shared.ContinueWith (t => { -// var sharedResolver = t.Result; -// if (sharedResolver == null) -// return null; -// return new MDRefactoringContext (document, sharedResolver, loc, cancellationToken); -// // Do not add TaskContinuationOptions.ExecuteSynchronously -// // https://bugzilla.xamarin.com/show_bug.cgi?id=25065 -// // adding ExecuteSynchronously appears to create a deadlock situtation in TypeSystemParser.Parse() -// }); - } - - internal MDRefactoringContext (Document document, CSharpAstResolver resolver, TextLocation loc, CancellationToken cancellationToken = default (CancellationToken)) : base (resolver, cancellationToken) - { - if (document == null) - throw new ArgumentNullException ("document"); - this.document = document; - this.TextEditor = document.Editor; - this.ParsedDocument = document.ParsedDocument; - this.Project = document.Project as DotNetProject; - this.formattingOptions = document.GetFormattingOptions (); - this.location = loc; - var policy = document.HasProject ? document.Project.Policies.Get () : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy (); - Services.AddService (typeof(NamingConventionService), policy.CreateNRefactoryService ()); - Services.AddService (typeof(DefaultCodeGenerationService), new CSharpCodeGenerationService()); - } - - public MDRefactoringContext (DotNetProject project, TextEditorData data, ParsedDocument parsedDocument, CSharpAstResolver resolver, TextLocation loc, CancellationToken cancellationToken = default (CancellationToken)) : base (resolver, cancellationToken) - { - this.TextEditor = data; - this.ParsedDocument = parsedDocument; - this.Project = project; - var policy = Project.Policies.Get (); - this.formattingOptions = policy.CreateOptions (); - this.location = loc; - var namingPolicy = Project.Policies.Get (); - Services.AddService (typeof(NamingConventionService), namingPolicy.CreateNRefactoryService ()); - } - } -} diff --git a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/MDRefactoringScript.cs b/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/MDRefactoringScript.cs deleted file mode 100644 index 7ea235a..0000000 --- a/PlayScript.Addin/MonoDevelop.PlayScript.Refactoring.CodeActions/MDRefactoringScript.cs +++ /dev/null @@ -1,379 +0,0 @@ -// -// MDRefactoringScript.cs -// -// Author: -// Mike Krüger -// -// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Linq; -using ICSharpCode.NRefactory.PlayScript.Refactoring; -using ICSharpCode.NRefactory.PlayScript; -using Mono.TextEditor; -using MonoDevelop.Core; -using System.Collections.Generic; -using ICSharpCode.NRefactory.TypeSystem; -using MonoDevelop.Refactoring.Rename; -using ICSharpCode.NRefactory.PlayScript.Resolver; -using System.IO; -using MonoDevelop.PlayScript.Formatting; -using System.Threading.Tasks; -using MonoDevelop.Ide; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide.FindInFiles; -using MonoDevelop.Ide.TypeSystem; -using MonoDevelop.Ide.Gui.Content; -using MonoDevelop.Projects; -using ICSharpCode.NRefactory.PlayScript.TypeSystem; - -namespace MonoDevelop.PlayScript.Refactoring.CodeActions -{ - class MDRefactoringScript : DocumentScript - { - readonly MDRefactoringContext context; - readonly IDisposable undoGroup; - readonly ICSharpCode.NRefactory.Editor.ITextSourceVersion startVersion; - int operationsRunning; - - public MDRefactoringScript (MDRefactoringContext context, CSharpFormattingOptions formattingOptions) : base(context.TextEditor.Document, formattingOptions, context.TextEditor.CreateNRefactoryTextEditorOptions ()) - { - this.context = context; - undoGroup = this.context.TextEditor.OpenUndoGroup (); - this.startVersion = this.context.TextEditor.Version; - - } - - void Rollback () - { - DisposeOnClose (true); - foreach (var ver in context.TextEditor.Version.GetChangesTo (startVersion)) { - context.TextEditor.Document.Replace (ver.Offset, ver.RemovalLength, ver.InsertedText.Text); - } - } - - public override void Select (AstNode node) - { - var seg = GetSegment (node); - var startOffset = seg.Offset; - var endOffset = seg.EndOffset; - while (startOffset < endOffset) { - char ch = context.TextEditor.GetCharAt (startOffset); - if (!char.IsWhiteSpace (ch)) - break; - startOffset++; - } - while (startOffset < endOffset && endOffset > 0) { - char ch = context.TextEditor.GetCharAt (endOffset - 1); - if (!char.IsWhiteSpace (ch)) - break; - endOffset--; - } - - context.TextEditor.Caret.Offset = endOffset; - context.TextEditor.SelectionRange = new TextSegment (startOffset, endOffset - startOffset); - } - - public override Task