├── .gitattributes
├── .gitignore
├── .gitmirrorall
├── CodeGenerators
├── ControlAndDataFlowGraph
│ ├── ControlAndDataFlowGraph.csproj
│ ├── ControlFlowInferencer.cs
│ ├── ControlFlowQueries.cs
│ ├── DataFlowInferencer.cs
│ ├── Graph.cs
│ ├── HandlerInferencer.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── TypeInferencer.cs
├── Optimization
│ ├── ILGeneration.cs
│ ├── Inlining.cs
│ ├── LocalMinimizer.cs
│ ├── Merger.cs
│ ├── MultipleAssignment.cs
│ ├── OptimizationUtilities.csproj
│ ├── PartialEvaluation.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── StackEliminator.cs
└── OptimizationUtilities
│ ├── AbstractDomains
│ └── Intervals.cs
│ ├── AbstractInterpretation.cs
│ ├── AnalysisUtilities.csproj
│ ├── Evaluator.cs
│ ├── ExpressionCanonicalizer.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── Purger.cs
│ ├── SatSolver.cs
│ ├── Simplifier.cs
│ ├── SingleAssignment.cs
│ └── ValueMappings.cs
├── Common
├── Include
│ ├── CCIEventSource.cs
│ ├── DietCollection.cs
│ ├── PortingHelpers.cs
│ └── Version.cs
└── InterimKey.snk
├── Converters
├── CodeModelToIL
│ ├── CodeModelToIL.csproj
│ ├── Helpers.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── Visitor.cs
├── ContractExtractor
│ ├── ContractChecker.cs
│ ├── ContractExtractor.cs
│ ├── ContractExtractor.csproj
│ ├── ContractHelper.cs
│ ├── ContractProviders.cs
│ ├── MoveNext.cs
│ └── Properties
│ │ └── AssemblyInfo.cs
├── ILGenerator
│ ├── ILGenerator.cs
│ ├── ILGenerator.csproj
│ ├── ILRewriter.cs
│ ├── MethodBody.cs
│ └── Properties
│ │ └── AssemblyInfo.cs
├── NewILToCodeModel
│ ├── AnonymousDelegateCachingRemover.cs
│ ├── AnonymousDelegateInserter.cs
│ ├── ClosureFinder.cs
│ ├── ClosureRemover.cs
│ ├── Decompiler.cs
│ ├── ForEachLoopReplacer.cs
│ ├── ForLoopReplacer.cs
│ ├── HelperObjects.cs
│ ├── IfThenElseReplacer.cs
│ ├── InstructionParser.cs
│ ├── LexicalScopes.cs
│ ├── LockReplacer.cs
│ ├── NewILToCodeModel.csproj
│ ├── Patterns.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── RemoveCompilationArtifacts.cs
│ ├── ResourceUseReplacer.cs
│ ├── SourceMethodBody.cs
│ ├── SwitchReplacer.cs
│ ├── TryCatchReplacer.cs
│ ├── TypeInferencer.cs
│ ├── Unstacker.cs
│ └── WhileLoopReplacer.cs
├── ReflectionEmitter
│ ├── Emitter.cs
│ ├── Mapper.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── ReflectionEmitter.csproj
└── ReflectionImporter
│ ├── Mapper.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── ReflectionImporter.csproj
│ └── Wrapper.cs
├── CoreObjectModel
├── AstsProjectedAsCodeModel
│ ├── AstsProjectedAsCodeModel.csproj
│ ├── Contracts.cs
│ ├── Core.cs
│ ├── Error.cs
│ ├── ErrorMessages.resx
│ ├── Expressions.cs
│ ├── MemberDeclarationInterfaces.cs
│ ├── MemberDeclarations.cs
│ ├── Members.cs
│ ├── Miscellaneous.cs
│ ├── NamespaceDeclarationInterfaces.cs
│ ├── NamespaceDeclarations.cs
│ ├── Namespaces.cs
│ ├── Options.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Statements.cs
│ ├── TypeDeclarationInterfaces.cs
│ ├── TypeDeclarations.cs
│ ├── Types.cs
│ └── Units.cs
├── CodeModel
│ ├── CodeModel.csproj
│ ├── Contracts.cs
│ ├── DummyObjects.cs
│ ├── ExpressionHelper.cs
│ ├── Expressions.cs
│ ├── Members.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Statements.cs
│ └── Visitors.cs
├── MetadataHelper
│ ├── AttributeHelper.cs
│ ├── CommandLineOptions.cs
│ ├── Core.cs
│ ├── ErrorMessages.resx
│ ├── ExpressionHelper.cs
│ ├── GlobalAssemblyCache.cs
│ ├── MemberHelper.cs
│ ├── Members.cs
│ ├── MetadataHelper.csproj
│ ├── PlatformTypes.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── TypeHelper.cs
│ ├── Types.cs
│ ├── UnitHelper.cs
│ ├── UnmanagedFileIO.cs
│ ├── UtilityDataStructures.cs
│ ├── Validator.cs
│ └── Visitors.cs
├── MetadataModel
│ ├── CachingInternFactory.cs
│ ├── Core.cs
│ ├── DummyObjects.cs
│ ├── Expressions.cs
│ ├── Members.cs
│ ├── MetadataModel.csproj
│ ├── Miscellaneous.cs
│ ├── NameScope.cs
│ ├── Namespaces.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Types.cs
│ └── Units.cs
├── MutableCodeModel
│ ├── Contracts.cs
│ ├── Copier.cs
│ ├── Expressions.cs
│ ├── Members.cs
│ ├── MutableCodeModel.csproj
│ ├── Mutator.cs
│ ├── Normalizer
│ │ ├── AnonymousDelegateRemover.cs
│ │ ├── CapturedLocalOrArgumentFinder.cs
│ │ ├── Duplicator.cs
│ │ ├── ForEachRemover.cs
│ │ ├── Helpers.cs
│ │ └── Normalizer.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── Statements.cs
├── MutableMetadataModel
│ ├── Copier.cs
│ ├── Expressions.cs
│ ├── Members.cs
│ ├── Miscellaneous.cs
│ ├── MutableMetadataModel.csproj
│ ├── Mutator.cs
│ ├── Namespaces.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Types.cs
│ └── Units.cs
└── SourceModel
│ ├── DummyObjects.cs
│ ├── Implementations.cs
│ ├── Interfaces.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── SourceModel.csproj
│ └── SourceModelHelper.cs
├── LICENSE
├── Microsoft.Cci.Sources.targets
├── Microsoft.Cci.csproj
├── Microsoft.Cci.sln
├── Microsoft.Cci_NetCore.csproj
├── PDBReaderAndWriter
├── PdbReader
│ ├── BitAccess.cs
│ ├── BitSet.cs
│ ├── CvInfo.cs
│ ├── DataStream.cs
│ ├── DbiDbgHdr.cs
│ ├── DbiHeader.cs
│ ├── DbiModuleInfo.cs
│ ├── DbiSecCon.cs
│ ├── IntHashTable.cs
│ ├── MsfDirectory.cs
│ ├── PdbConstant.cs
│ ├── PdbDebugException.cs
│ ├── PdbException.cs
│ ├── PdbFile.cs
│ ├── PdbFileHeader.cs
│ ├── PdbFormatProvider.cs
│ ├── PdbFunction.cs
│ ├── PdbInfo.cs
│ ├── PdbLine.cs
│ ├── PdbLines.cs
│ ├── PdbReader.cs
│ ├── PdbReader.csproj
│ ├── PdbScope.cs
│ ├── PdbSlot.cs
│ ├── PdbSource.cs
│ ├── PdbTokenLine.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── SourceLocationProvider.cs
└── PdbWriter
│ ├── ISymbolWriter.cs
│ ├── PdbWriter.csproj
│ ├── Properties
│ └── AssemblyInfo.cs
│ └── Writer.cs
├── PEReaderAndWriter
├── PEReader
│ ├── AliasForTypeExtensions.cs
│ ├── Attributes.cs
│ ├── BinaryObjectModel.cs
│ ├── CoreTypes.cs
│ ├── Errors.cs
│ ├── ILReader.cs
│ ├── ModuleExtensions.cs
│ ├── ModuleReadWriteFactory.cs
│ ├── PEFileReader.cs
│ ├── PEFileStructures.cs
│ ├── PEFileToObjectModel.cs
│ ├── PeReader.csproj
│ ├── PeReaderErrorMessages.resx
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Types.cs
│ ├── UnmanagedReadWrite.cs
│ ├── UtilityDataStructures.cs
│ └── WindowsRuntimeHost.cs
└── PEWriter
│ ├── BinaryWriter.cs
│ ├── IMetadata.cs
│ ├── MemoryStream.cs
│ ├── PdbWriterInterface.cs
│ ├── PeWriter.cs
│ ├── PeWriter.csproj
│ └── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Samples
├── AsmMeta
│ ├── AsmMeta.cs
│ ├── AsmMeta.csproj
│ ├── CCRefGenTask.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── RemoveMethodBodies.cs
│ ├── Rewriter.cs
│ └── app.config
├── ILMerge
│ ├── ILMerge.csproj
│ ├── Program.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── README.md
├── PeToPe
│ ├── PeToPe.csproj
│ ├── Program.cs
│ └── Properties
│ │ └── AssemblyInfo.cs
└── PeToText
│ ├── PeToText.csproj
│ ├── Program.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ └── SourceEmitter.cs
├── SourceEmitters
├── CSharpSourceEmitter
│ ├── AttributeSourceEmitter.cs
│ ├── BaseSourceEmitter.cs
│ ├── BaseTypeOrInterfaceSourceEmitter.cs
│ ├── BaseTypesAndInterfacesListSourceEmitter.cs
│ ├── CSharp3.0.Felt.Annotated.language
│ ├── CSharp3.0.Felt.language
│ ├── CSharpSourceEmitter.csproj
│ ├── EventSourceEmitter.cs
│ ├── ExpressionSourceEmitter.cs
│ ├── FieldSourceEmitter.cs
│ ├── GenericTypeParameterSourceEmitter.cs
│ ├── GenericTypeParametersListSourceEmitter.cs
│ ├── ICSharpSourceEmitter.cs
│ ├── ISourceEmitterOutput.cs
│ ├── MemberBaseSourceEmitter.cs
│ ├── MethodSourceEmitter.cs
│ ├── NamespaceSourceEmitter.cs
│ ├── ParameterListSourceEmitter.cs
│ ├── ParameterSourceEmitter.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── PropertySourceEmitter.cs
│ ├── SourceEmitterOutputString.cs
│ ├── SourceEmitterOutputTextWriter.cs
│ ├── StatementSourceEmitter.cs
│ ├── TypeDefinitionSourceEmitter.cs
│ ├── TypeReferenceSourceEmitter.cs
│ ├── TypeSourceEmitter.cs
│ └── Utils.cs
├── SourceEmitter
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── SourceEmitter.cs
│ └── SourceEmitter.csproj
└── VB
│ └── VBSourceEmitter
│ ├── AttributeSourceEmitter.cs
│ ├── BaseSourceEmitter.cs
│ ├── BaseTypeOrInterfaceSourceEmitter.cs
│ ├── BaseTypesAndInterfacesListSourceEmitter.cs
│ ├── EventSourceEmitter.cs
│ ├── ExpressionSourceEmitter.cs
│ ├── FieldSourceEmitter.cs
│ ├── GenericTypeParameterSourceEmitter.cs
│ ├── GenericTypeParametersListSourceEmitter.cs
│ ├── ISourceEmitterOutput.cs
│ ├── IVBSourceEmitter.cs
│ ├── MemberBaseSourceEmitter.cs
│ ├── MethodSourceEmitter.cs
│ ├── NamespaceSourceEmitter.cs
│ ├── ParameterListSourceEmitter.cs
│ ├── ParameterSourceEmitter.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── PropertySourceEmitter.cs
│ ├── SourceEmitterOutputString.cs
│ ├── SourceEmitterOutputTextWriter.cs
│ ├── StatementSourceEmitter.cs
│ ├── TypeDefinitionSourceEmitter.cs
│ ├── TypeReferenceSourceEmitter.cs
│ ├── TypeSourceEmitter.cs
│ ├── Utils.cs
│ └── VBSourceEmitter.csproj
└── project.json
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
65 | # Force bash scripts to always use lf line endings so that if a repo is accessed
66 | # in Unix via a file share from Windows, the scripts will work.
67 | *.sh text eol=lf
68 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | syntax: glob
2 |
3 | ### VisualStudio ###
4 |
5 | # Tool Runtime Dir
6 | /[Tt]ools/
7 |
8 | # User-specific files
9 | *.suo
10 | *.user
11 | *.userosscache
12 | *.sln.docstates
13 |
14 | # Build results
15 | [Dd]ebug/
16 | [Dd]ebugPublic/
17 | [Rr]elease/
18 | [Rr]eleases/
19 | x64/
20 | x86/
21 | build/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | msbuild.log
26 |
27 | # Cross building rootfs
28 | cross/rootfs/
29 |
30 | # Visual Studio 2015
31 | .vs/
32 |
33 | # Visual Studio 2015 Pre-CTP6
34 | *.sln.ide
35 | *.ide/
36 |
37 | # MSTest test Results
38 | [Tt]est[Rr]esult*/
39 | [Bb]uild[Ll]og.*
40 |
41 | #NUNIT
42 | *.VisualState.xml
43 | TestResult.xml
44 |
45 | # Build Results of an ATL Project
46 | [Dd]ebugPS/
47 | [Rr]eleasePS/
48 | dlldata.c
49 |
50 | *_i.c
51 | *_p.c
52 | *_i.h
53 | *.ilk
54 | *.meta
55 | *.obj
56 | *.pch
57 | *.pdb
58 | *.pgc
59 | *.pgd
60 | *.rsp
61 | *.sbr
62 | *.tlb
63 | *.tli
64 | *.tlh
65 | *.tmp
66 | *.tmp_proj
67 | *.log
68 | *.vspscc
69 | *.vssscc
70 | .builds
71 | *.pidb
72 | *.svclog
73 | *.scc
74 |
75 | # Chutzpah Test files
76 | _Chutzpah*
77 |
78 | # Visual C++ cache files
79 | ipch/
80 | *.aps
81 | *.ncb
82 | *.opendb
83 | *.opensdf
84 | *.sdf
85 | *.cachefile
86 | *.VC.db
87 |
88 | # Visual Studio profiler
89 | *.psess
90 | *.vsp
91 | *.vspx
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding addin-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 |
117 | # MightyMoose
118 | *.mm.*
119 | AutoTest.Net/
120 |
121 | # Web workbench (sass)
122 | .sass-cache/
123 |
124 | # Installshield output folder
125 | [Ee]xpress/
126 |
127 | # DocProject is a documentation generator add-in
128 | DocProject/buildhelp/
129 | DocProject/Help/*.HxT
130 | DocProject/Help/*.HxC
131 | DocProject/Help/*.hhc
132 | DocProject/Help/*.hhk
133 | DocProject/Help/*.hhp
134 | DocProject/Help/Html2
135 | DocProject/Help/html
136 |
137 | # Click-Once directory
138 | publish/
139 |
140 | # Publish Web Output
141 | *.[Pp]ublish.xml
142 | *.azurePubxml
143 | *.pubxml
144 | *.publishproj
145 |
146 | # NuGet Packages
147 | *.nuget.props
148 | *.nuget.targets
149 | *.nupkg
150 | **/packages/*
151 |
152 | # NuGet package restore lockfiles
153 | project.lock.json
154 |
155 | # Windows Azure Build Output
156 | csx/
157 | *.build.csdef
158 |
159 | # Windows Store app package directory
160 | AppPackages/
161 |
162 | # Others
163 | *.Cache
164 | ClientBin/
165 | [Ss]tyle[Cc]op.*
166 | ~$*
167 | *.dbmdl
168 | *.dbproj.schemaview
169 | *.pfx
170 | *.publishsettings
171 | node_modules/
172 | *.metaproj
173 | *.metaproj.tmp
174 |
175 | # RIA/Silverlight projects
176 | Generated_Code/
177 |
178 | # Backup & report files from converting an old project file
179 | # to a newer Visual Studio version. Backup files are not needed,
180 | # because we have git ;-)
181 | _UpgradeReport_Files/
182 | Backup*/
183 | UpgradeLog*.XML
184 | UpgradeLog*.htm
185 |
186 | # SQL Server files
187 | *.mdf
188 | *.ldf
189 |
190 | # Business Intelligence projects
191 | *.rdl.data
192 | *.bim.layout
193 | *.bim_*.settings
194 |
195 | # Microsoft Fakes
196 | FakesAssemblies/
197 |
198 | ### MonoDevelop ###
199 |
200 | *.pidb
201 | *.userprefs
202 |
203 | ### Windows ###
204 |
205 | # Windows image file caches
206 | Thumbs.db
207 | ehthumbs.db
208 |
209 | # Folder config file
210 | Desktop.ini
211 |
212 | # Recycle Bin used on file shares
213 | $RECYCLE.BIN/
214 |
215 | # Windows Installer files
216 | *.cab
217 | *.msi
218 | *.msm
219 | *.msp
220 |
221 | # Windows shortcuts
222 | *.lnk
223 |
224 | ### Linux ###
225 |
226 | *~
227 |
228 | # KDE directory preferences
229 | .directory
230 |
231 | ### OSX ###
232 |
233 | .DS_Store
234 | .AppleDouble
235 | .LSOverride
236 |
237 | # Icon must end with two \r
238 | Icon
239 |
240 | # Thumbnails
241 | ._*
242 |
243 | # Files that might appear on external disk
244 | .Spotlight-V100
245 | .Trashes
246 |
247 | # Directories potentially created on remote AFP share
248 | .AppleDB
249 | .AppleDesktop
250 | Network Trash Folder
251 | Temporary Items
252 | .apdisk
253 |
254 | # vim temporary files
255 | [._]*.s[a-w][a-z]
256 | [._]s[a-w][a-z]
257 | *.un~
258 | Session.vim
259 | .netrwhist
260 | *~
261 |
--------------------------------------------------------------------------------
/.gitmirrorall:
--------------------------------------------------------------------------------
1 | This folder will be mirrored by the Git-TFS Mirror recursively.
--------------------------------------------------------------------------------
/CodeGenerators/ControlAndDataFlowGraph/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("CFG and DFG")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("29c3269c-6c6e-49fc-b471-181bb71ec938")]
24 |
--------------------------------------------------------------------------------
/CodeGenerators/Optimization/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("Optimization")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyCulture("")]
14 |
15 | // Setting ComVisible to false makes the types in this assembly not visible
16 | // to COM components. If you need to access a type in this assembly from
17 | // COM, set the ComVisible attribute to true on that type.
18 | [assembly: ComVisible(false)]
19 |
20 | // The following GUID is for the ID of the typelib if this project is exposed to COM
21 | [assembly: Guid("9a1c684f-4070-4fa3-af2d-c33b1c7f6fd7")]
22 |
--------------------------------------------------------------------------------
/CodeGenerators/OptimizationUtilities/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("Microsoft.Cci.Analysis.AnalysisUtilities")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyCulture("")]
14 |
15 | // Setting ComVisible to false makes the types in this assembly not visible
16 | // to COM components. If you need to access a type in this assembly from
17 | // COM, set the ComVisible attribute to true on that type.
18 | [assembly: ComVisible(false)]
19 |
20 | // The following GUID is for the ID of the typelib if this project is exposed to COM
21 | [assembly: Guid("c7078b32-c394-49a1-9946-c0306c238aa8")]
22 |
--------------------------------------------------------------------------------
/Common/Include/CCIEventSource.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Diagnostics.Tracing;
6 | using Microsoft.Cci;
7 |
8 | ///
9 | /// This eventSource can be used for Telemetry/tracing of the CCI assembly.
10 | /// PerfView /Providers=*Microsoft-CCI collect
11 | /// turns it on.
12 | ///
13 | [EventSource(Name = "Microsoft-CCI")]
14 | internal class CciEventSource : EventSource
15 | {
16 | static public CciEventSource Log = new CciEventSource();
17 |
18 | // Used to specify which events to turn on.
19 | public class Keywords
20 | {
21 | ///
22 | /// Events associated with reading IL DLLs
23 | ///
24 | public const EventKeywords PERead = (EventKeywords)1;
25 | public const EventKeywords PEReadDetailed = (EventKeywords)2;
26 | ///
27 | /// Events associated with writing IL DLLs
28 | ///
29 | public const EventKeywords PEWrite = (EventKeywords)4;
30 | public const EventKeywords PEWriteDetailed = (EventKeywords)8;
31 | }
32 |
33 | // Generally useful
34 | [Event(1)]
35 | public void Message(string Message) { WriteEvent(1, Message); }
36 |
37 | // Write Instrumentation
38 | [Event(2, Keywords = Keywords.PEWrite | Keywords.PEWriteDetailed)]
39 | public void ModuleWritten(string Name, int ModuleId, string FileName) { WriteEvent(2, Name, ModuleId, FileName); }
40 | [Event(3, Keywords = Keywords.PEWrite | Keywords.PEWriteDetailed)]
41 | public void ModuleWrittenSize(string Name, int ModuleId, string FileName, int Size) { WriteEvent(3, Name, ModuleId, FileName, Size); }
42 | [Event(4, Keywords = Keywords.PEWriteDetailed)]
43 | public void TypeWritten(string Name, int TypeId, int ModuleId) { WriteEvent(4, Name, TypeId, ModuleId); }
44 | [Event(5, Keywords = Keywords.PEWriteDetailed)]
45 | public void MethodWritten(string Name, int TypeId, int Size) { WriteEvent(5, Name, TypeId, Size); }
46 |
47 | // Read Instrumentation
48 | [Event(6, Keywords = Keywords.PERead | Keywords.PEReadDetailed)]
49 | private void ModuleOpened(string Name, string FileName, int ModuleId, int Size) { WriteEvent(6, Name, FileName, ModuleId, Size); }
50 | [NonEvent]
51 | public void ModuleOpened(IModule module, ModuleIdentity moduleIdentity, uint size)
52 | {
53 | ModuleOpened(module.Name.Value, moduleIdentity == null ? "" : moduleIdentity.Location, module.GetHashCode(), (int) size);
54 | }
55 | }
56 |
57 |
58 |
--------------------------------------------------------------------------------
/Common/Include/PortingHelpers.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Runtime.InteropServices;
6 | using System.Diagnostics;
7 |
8 | // Set of helper extension methods and types to unify the full .NET and Core .NET surface areas
9 |
10 | namespace System.Runtime.InteropServices
11 | {
12 | // UnmanagedType.CustomMarshaler got removed from Core FX - define the old value here
13 | static class UnmanagedTypeEx
14 | {
15 | public const UnmanagedType CustomMarshaler = (UnmanagedType)44;
16 | }
17 | }
18 |
19 | namespace Microsoft.Cci
20 | {
21 | static class ConvertExtensions
22 | {
23 | // Convert.GetTypeCode was removed from CoreFX - have an extension method
24 | public static TypeCode ConvertGetTypeCode(this object value)
25 | {
26 | if (value == null) return TypeCode.Empty;
27 | IConvertible temp = value as IConvertible;
28 | if (temp != null)
29 | {
30 | return temp.GetTypeCode();
31 | }
32 | return TypeCode.Object;
33 | }
34 | }
35 | }
36 |
37 | #if COREFX_CONTRACTS
38 |
39 | // These are constants/attributes that got removed from Core FX, but the CCI code refers to them
40 |
41 | namespace System.Collections.Generic
42 | {
43 | static class MyExtensions
44 | {
45 | public static IReadOnlyList AsReadOnly(this List This) { return new System.Collections.ObjectModel.ReadOnlyCollection(This); }
46 | }
47 | }
48 |
49 | namespace System.Security
50 | {
51 | class SuppressUnmanagedCodeSecurityAttribute : Attribute { }
52 | }
53 |
54 | #endif
55 |
--------------------------------------------------------------------------------
/Common/Include/Version.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | [assembly: AssemblyVersion("0.0.0.2")]
6 | [assembly: AssemblyFileVersion("0.0.0.2")]
7 | [assembly: AssemblyCompany("Microsoft Corporation")]
8 | [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")]
9 |
10 |
--------------------------------------------------------------------------------
/Common/InterimKey.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/cci/659f31f9736a1e8ded870ee2132d91f87505148e/Common/InterimKey.snk
--------------------------------------------------------------------------------
/Converters/CodeModelToIL/Helpers.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Collections.Generic;
5 | using System.Diagnostics.Contracts;
6 |
7 | namespace Microsoft.Cci.CodeModelToIL {
8 |
9 | internal sealed class ExpressionSourceLocation : IExpressionSourceLocation {
10 |
11 | internal ExpressionSourceLocation(IPrimarySourceLocation primarySourceLocation) {
12 | Contract.Requires(primarySourceLocation != null);
13 | this.primarySourceLocation = primarySourceLocation;
14 | }
15 |
16 | [ContractInvariantMethod]
17 | private void ObjectInvariant() {
18 | Contract.Invariant(this.primarySourceLocation != null);
19 | }
20 |
21 | public IPrimarySourceLocation PrimarySourceLocation {
22 | get { return this.primarySourceLocation; }
23 | }
24 | IPrimarySourceLocation primarySourceLocation;
25 |
26 | public IDocument Document {
27 | get { return this.PrimarySourceLocation.Document; }
28 | }
29 | }
30 |
31 | internal sealed class TemporaryVariable : ILocalDefinition {
32 |
33 | internal TemporaryVariable(ITypeReference type, IMethodDefinition containingMethod) {
34 | this.type = type;
35 | this.methodDefinition = containingMethod;
36 | }
37 |
38 | public IMetadataConstant CompileTimeValue {
39 | get { return Dummy.Constant; }
40 | }
41 |
42 | public IEnumerable CustomModifiers {
43 | get { return Enumerable.Empty; }
44 | }
45 |
46 | public bool IsConstant {
47 | get { return false; }
48 | }
49 |
50 | public bool IsModified {
51 | get { return false; }
52 | }
53 |
54 | public bool IsPinned {
55 | get { return false; }
56 | }
57 |
58 | public bool IsReference {
59 | get { return false; }
60 | }
61 |
62 | public IName Name {
63 | get { return Dummy.Name; }
64 | }
65 |
66 | public IEnumerable Locations {
67 | get { return Enumerable.Empty; }
68 | }
69 |
70 | public IMethodDefinition MethodDefinition {
71 | get { return this.methodDefinition; }
72 | }
73 | IMethodDefinition methodDefinition;
74 |
75 |
76 | public ITypeReference Type {
77 | get { return this.type; }
78 | }
79 | ITypeReference type;
80 |
81 |
82 | }
83 |
84 | }
--------------------------------------------------------------------------------
/Converters/CodeModelToIL/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("CodeModelToIL")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("d7c9cef7-550e-4c11-a8b0-ea4e6c288442")]
25 |
26 |
--------------------------------------------------------------------------------
/Converters/ContractExtractor/ContractChecker.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Diagnostics.Contracts;
7 | using System.IO;
8 | using Microsoft.Cci;
9 | using Microsoft.Cci.MutableContracts;
10 |
11 | namespace Microsoft.Cci.Contracts {
12 |
13 | internal class Visibility : CodeTraverser {
14 |
15 | private IMetadataHost host;
16 | private TypeMemberVisibility currentVisibility = TypeMemberVisibility.Public;
17 |
18 | private Visibility(IMetadataHost host) {
19 | this.host = host;
20 | }
21 |
22 | ///
23 | /// Returns the most restrictive visibility of any member mentioned within the expression.
24 | /// I.e., if a private member is referenced within the expression, then TypeMemberVisibility.Private
25 | /// is returned. If TypeMemberVisibility.Public is returned, then all referenced members are public.
26 | ///
27 | public static TypeMemberVisibility MostRestrictiveVisibility(IMetadataHost host, IExpression expression) {
28 | var v = new Visibility(host);
29 | v.Traverse(expression);
30 | return v.currentVisibility;
31 | }
32 |
33 | public override void TraverseChildren(IBoundExpression boundExpression) {
34 | var tm = boundExpression.Definition as ITypeMemberReference;
35 | if (tm != null) {
36 | var resolvedMember = tm.ResolvedTypeDefinitionMember;
37 | string propertyName = ContractHelper.GetStringArgumentFromAttribute(resolvedMember.Attributes, "System.Diagnostics.Contracts.ContractPublicPropertyNameAttribute");
38 | // we don't care what it is, it just means it has a public property that represents it
39 | // so if it is null, then it is *not* a field that has a [ContractPublicPropertyName] marking
40 | // and so its visibility counts. If it *is* such a field, then it is considered to be public.
41 | // (TODO: checker should make sure that the property it names is public.)
42 | if (propertyName == null) {
43 | this.currentVisibility = TypeHelper.VisibilityIntersection(this.currentVisibility, resolvedMember.Visibility);
44 | }
45 | }
46 | base.TraverseChildren(boundExpression);
47 | }
48 |
49 | }
50 |
51 | ///
52 | ///
53 | ///
54 | public class ContractChecker {
55 |
56 | private ContractChecker() { }
57 |
58 | ///
59 | /// Mutates the by removing any contracts that violate any of the rules
60 | /// about contracts, e.g., preconditions mentioning a member that is more restrictive than the method containing
61 | /// the precondition.
62 | /// TODO: Return a list of errors.
63 | ///
64 | public static void CheckMethodContract(IMetadataHost host, IMethodDefinition method, MethodContract methodContract) {
65 | var reqs = methodContract.Preconditions;
66 | var newReqs = new List(methodContract.Preconditions.Count);
67 | foreach (var p in reqs) {
68 | var contractExpression = p.Condition;
69 | var v = Visibility.MostRestrictiveVisibility(host, contractExpression);
70 | var currentVisibility = method.Visibility;
71 | var intersection = TypeHelper.VisibilityIntersection(v, currentVisibility);
72 | if (intersection == currentVisibility) {
73 | newReqs.Add(p);
74 | } else {
75 | // TODO!! BUGBUG!! Need to signal an error, not just silently not add the precondition!
76 | }
77 | }
78 | methodContract.Preconditions = newReqs;
79 | }
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/Converters/ContractExtractor/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("ContractExtractor")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("83382330-db16-4afc-9f17-3b620f6030e7")]
25 |
26 |
--------------------------------------------------------------------------------
/Converters/ILGenerator/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("ILGenerator")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("64b687bd-39ec-4270-9ecf-6bfa09db035d")]
25 |
26 |
--------------------------------------------------------------------------------
/Converters/NewILToCodeModel/AnonymousDelegateCachingRemover.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Diagnostics.Contracts;
5 | using Microsoft.Cci.MutableCodeModel;
6 | using System.Collections.Generic;
7 | using Microsoft.Cci.UtilityDataStructures;
8 |
9 | namespace Microsoft.Cci.ILToCodeModel {
10 | internal class AnonymousDelegateCachingRemover : CodeRewriter {
11 |
12 | internal AnonymousDelegateCachingRemover(IMetadataHost host, Hashtable/*?*/ delegatesCachedInFields,
13 | Hashtable/*?*/ delegatesCachedInLocals)
14 | : base(host) {
15 | Contract.Requires(host != null);
16 | this.delegatesCachedInFields = delegatesCachedInFields;
17 | this.delegatesCachedInLocals = delegatesCachedInLocals;
18 | }
19 |
20 | Hashtable/*?*/ delegatesCachedInFields;
21 | Hashtable/*?*/ delegatesCachedInLocals;
22 |
23 | public override IExpression Rewrite(IAnonymousDelegate anonymousDelegate) {
24 | return anonymousDelegate;
25 | }
26 |
27 | public override IExpression Rewrite(IBoundExpression boundExpression) {
28 | var fieldReference = boundExpression.Definition as IFieldReference;
29 | if (fieldReference != null) {
30 | if (this.delegatesCachedInFields != null) {
31 | var cachedDelegate = this.delegatesCachedInFields.Find(fieldReference.InternedKey);
32 | if (cachedDelegate != null) return cachedDelegate;
33 | }
34 | } else if (this.delegatesCachedInLocals != null) {
35 | var local = boundExpression.Definition as LocalDefinition;
36 | if (local != null) {
37 | AnonymousDelegate cachedDelegate;
38 | if (this.delegatesCachedInLocals.TryGetValue(local, out cachedDelegate)) {
39 | Contract.Assume(cachedDelegate != null);
40 | return cachedDelegate;
41 | }
42 | }
43 | }
44 | return base.Rewrite(boundExpression);
45 | }
46 |
47 | public override IStatement Rewrite(IConditionalStatement conditionalStatement) {
48 | var condition = conditionalStatement.Condition;
49 | var logicalNot = condition as ILogicalNot;
50 | if (logicalNot != null) condition = logicalNot.Operand;
51 | var equal = condition as IEquality;
52 | if (equal != null && equal.RightOperand is IDefaultValue) condition = equal.LeftOperand;
53 | var boundExpression = condition as IBoundExpression;
54 | if (boundExpression != null) {
55 | var locations = conditionalStatement.Locations;
56 | var fieldReference = boundExpression.Definition as IFieldReference;
57 | if (fieldReference != null) {
58 | if (this.delegatesCachedInFields != null && this.delegatesCachedInFields.Find(fieldReference.InternedKey) != null)
59 | return CodeDummy.Block;
60 | } else if (this.delegatesCachedInLocals != null) {
61 | var local = boundExpression.Definition as LocalDefinition;
62 | if (local != null && this.delegatesCachedInLocals.ContainsKey(local))
63 | return CodeDummy.Block;
64 | }
65 | }
66 | return base.Rewrite(conditionalStatement);
67 | }
68 |
69 | public override IStatement Rewrite(IExpressionStatement expressionStatement) {
70 | var assignment = expressionStatement.Expression as Assignment;
71 | if (assignment != null) {
72 | var local = assignment.Target.Definition as LocalDefinition;
73 | if (local != null && this.delegatesCachedInLocals != null && this.delegatesCachedInLocals.ContainsKey(local))
74 | return CodeDummy.Block;
75 | }
76 | return base.Rewrite(expressionStatement);
77 | }
78 |
79 | public override IStatement Rewrite(ILocalDeclarationStatement localDeclarationStatement) {
80 | var local = localDeclarationStatement.LocalVariable as LocalDefinition;
81 | if (local != null && this.delegatesCachedInLocals != null && this.delegatesCachedInLocals.ContainsKey(local))
82 | return CodeDummy.Block;
83 | return base.Rewrite(localDeclarationStatement);
84 | }
85 |
86 |
87 | }
88 |
89 | }
--------------------------------------------------------------------------------
/Converters/NewILToCodeModel/ForLoopReplacer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Collections.Generic;
5 | using Microsoft.Cci.MutableCodeModel;
6 | using System.Diagnostics.Contracts;
7 | using Microsoft.Cci.UtilityDataStructures;
8 | using System;
9 |
10 | namespace Microsoft.Cci.ILToCodeModel {
11 |
12 | internal class ForLoopReplacer : CodeTraverser {
13 |
14 | internal ForLoopReplacer(SourceMethodBody sourceMethodBody) {
15 | Contract.Requires(sourceMethodBody != null);
16 | this.host = sourceMethodBody.host; Contract.Assume(sourceMethodBody.host != null);
17 | this.gotosThatTarget = sourceMethodBody.gotosThatTarget; Contract.Assume(this.gotosThatTarget != null);
18 | }
19 |
20 | IMetadataHost host;
21 | Hashtable> gotosThatTarget;
22 |
23 | [ContractInvariantMethod]
24 | private void ObjectInvariant() {
25 | Contract.Invariant(this.host != null);
26 | Contract.Invariant(this.gotosThatTarget != null);
27 | }
28 |
29 | public override void TraverseChildren(IBlockStatement block) {
30 | Contract.Assume(block is BlockStatement);
31 | var decompiledBlock = (BlockStatement)block;
32 | var statements = decompiledBlock.Statements;
33 | for (int i = 0; i < statements.Count-1; i++) {
34 | IStatement initializer = null;
35 | var initializerAssignStat = statements[i] as IExpressionStatement;
36 | if (initializerAssignStat != null) {
37 | if (!(initializerAssignStat.Expression is IAssignment)) continue;
38 | initializer = initializerAssignStat;
39 | } else {
40 | var initialDecl = statements[i] as ILocalDeclarationStatement;
41 | if (initialDecl == null || initialDecl.InitialValue == null) continue;
42 | initializer = initialDecl;
43 | }
44 | var whileLoop = statements[i+1] as IWhileDoStatement;
45 | if (whileLoop == null) continue;
46 | var loopBody = whileLoop.Body as BlockStatement;
47 | if (loopBody == null) continue;
48 | var incrementer = FindLastStatement(loopBody) as IExpressionStatement;
49 | if (incrementer == null) continue;
50 | var incrementAssignment = incrementer.Expression as IAssignment;
51 | if (incrementAssignment == null || !(incrementAssignment.Source is IAddition || incrementAssignment.Source is ISubtraction)) continue;
52 | var forLoop = new ForStatement() { Condition = whileLoop.Condition, Body = loopBody };
53 | if (initializer != null) {
54 | statements.RemoveAt(i--);
55 | forLoop.InitStatements.Add(initializer);
56 | }
57 | RemoveLastStatement(loopBody, incrementer);
58 | forLoop.IncrementStatements.Add(incrementer);
59 | statements[i + 1] = forLoop;
60 | }
61 | base.TraverseChildren(block);
62 | }
63 |
64 | static bool RemoveLastStatement(BlockStatement block, IStatement statement) {
65 | while (block != null) {
66 | var i = block.Statements.Count-1;
67 | if (i < 0) return false;
68 | if (block.Statements[i] == statement) {
69 | block.Statements.RemoveAt(i);
70 | return true;
71 | }
72 | block = block.Statements[i] as BlockStatement;
73 | }
74 | return false;
75 | }
76 |
77 | static IStatement FindLastStatement(BlockStatement block) {
78 | IStatement result = null;
79 | while (block != null) {
80 | var i = block.Statements.Count-1;
81 | if (i < 0) return result;
82 | var nextBlock = block.Statements[i] as BlockStatement;
83 | if (nextBlock == null) return block.Statements[i];
84 | if (i > 0) result = block.Statements[i-1];
85 | block = nextBlock;
86 | }
87 | return null;
88 | }
89 |
90 | }
91 |
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/Converters/NewILToCodeModel/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("NewILToCodeModel")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("edc44e58-27cf-4041-841e-08213c6e9d40")]
25 |
--------------------------------------------------------------------------------
/Converters/NewILToCodeModel/SwitchReplacer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Collections.Generic;
5 | using Microsoft.Cci.MutableCodeModel;
6 | using System.Diagnostics.Contracts;
7 | using Microsoft.Cci.UtilityDataStructures;
8 | using System;
9 |
10 | namespace Microsoft.Cci.ILToCodeModel {
11 |
12 | internal class SwitchReplacer : CodeTraverser {
13 |
14 | IMetadataHost host;
15 | Hashtable> gotosThatTarget;
16 |
17 | internal SwitchReplacer(SourceMethodBody sourceMethodBody) {
18 | Contract.Requires(sourceMethodBody != null);
19 | this.host = sourceMethodBody.host; Contract.Assume(sourceMethodBody.host != null);
20 | this.gotosThatTarget = sourceMethodBody.gotosThatTarget; Contract.Assume(this.gotosThatTarget != null);
21 | }
22 |
23 | [ContractInvariantMethod]
24 | private void ObjectInvariant() {
25 | Contract.Invariant(this.host != null);
26 | Contract.Invariant(this.gotosThatTarget != null);
27 | }
28 |
29 | public override void TraverseChildren(IBlockStatement block) {
30 | base.TraverseChildren(block);
31 | Contract.Assume(block is BlockStatement);
32 | var decompiledBlock = (BlockStatement)block;
33 | var statements = decompiledBlock.Statements;
34 | for (int i = 0; i < statements.Count-1; i++) {
35 | var switchInstruction = statements[i] as SwitchInstruction;
36 | if (switchInstruction == null) continue;
37 | SwitchStatement result = new SwitchStatement();
38 | result.Expression = switchInstruction.switchExpression;
39 | statements[i] = result;
40 | for (int j = 0, n = switchInstruction.SwitchCases.Count; j < n; j++) {
41 | CompileTimeConstant caseLabel = new CompileTimeConstant() { Value = j, Type = this.host.PlatformType.SystemInt32 };
42 | var gotoCaseBody = switchInstruction.SwitchCases[j];
43 | Contract.Assume(gotoCaseBody != null);
44 | SwitchCase currentCase = new SwitchCase() { Expression = caseLabel };
45 | result.Cases.Add(currentCase);
46 | if (j < n-1) {
47 | Contract.Assume(switchInstruction.SwitchCases[j+1] != null);
48 | if (gotoCaseBody.TargetStatement == switchInstruction.SwitchCases[j+1].TargetStatement) continue;
49 | }
50 | currentCase.Body.Add(gotoCaseBody);
51 | }
52 | if (i == statements.Count-1) return;
53 | Contract.Assert(i+1 <= statements.Count);
54 | var gotoStatement = statements[i+1] as IGotoStatement;
55 | if (gotoStatement != null) {
56 | SwitchCase defaultCase = new SwitchCase() { }; // Default case is represented by a dummy Expression.
57 | defaultCase.Body.Add(statements[i + 1]);
58 | statements.RemoveAt(i + 1);
59 | result.Cases.Add(defaultCase);
60 | }
61 | }
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Converters/NewILToCodeModel/WhileLoopReplacer.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Collections.Generic;
5 | using Microsoft.Cci.MutableCodeModel;
6 | using System.Diagnostics.Contracts;
7 | using Microsoft.Cci.UtilityDataStructures;
8 | using System;
9 |
10 | namespace Microsoft.Cci.ILToCodeModel {
11 |
12 | internal class WhileLoopReplacer : CodeTraverser {
13 |
14 | internal WhileLoopReplacer(SourceMethodBody sourceMethodBody) {
15 | Contract.Requires(sourceMethodBody != null);
16 | this.host = sourceMethodBody.host; Contract.Assume(sourceMethodBody.host != null);
17 | this.gotosThatTarget = sourceMethodBody.gotosThatTarget; Contract.Assume(this.gotosThatTarget != null);
18 | }
19 |
20 | IMetadataHost host;
21 | Hashtable> gotosThatTarget;
22 |
23 | [ContractInvariantMethod]
24 | private void ObjectInvariant() {
25 | Contract.Invariant(this.host != null);
26 | Contract.Invariant(this.gotosThatTarget != null);
27 | }
28 |
29 | public override void TraverseChildren(IBlockStatement block) {
30 | Contract.Assume(block is BlockStatement);
31 | var decompiledBlock = (BlockStatement)block;
32 | var statements = decompiledBlock.Statements;
33 | for (int i = 0; i < statements.Count-3; i++) {
34 | var gotoCondition = statements[i] as GotoStatement;
35 | if (gotoCondition == null) continue;
36 | var gotosThatTarget = this.gotosThatTarget[(uint)gotoCondition.TargetStatement.Label.UniqueKey];
37 | Contract.Assume(gotosThatTarget != null && gotosThatTarget.Count >= 1);
38 | if (gotosThatTarget.Count != 1) continue;
39 | var conditionalGotoBody = LookForCondition(statements, i+1, gotoCondition.TargetStatement);
40 | if (conditionalGotoBody == null || !(conditionalGotoBody.FalseBranch is EmptyStatement)) continue;
41 | var gotoBody = conditionalGotoBody.TrueBranch as GotoStatement;
42 | if (gotoBody == null) continue;
43 | Contract.Assume(i < statements.Count-3);
44 | if (!IsOrContainsAsFirstStatement(statements[i+1], gotoBody.TargetStatement)) continue;
45 | gotosThatTarget.Remove(gotoCondition);
46 | gotosThatTarget = this.gotosThatTarget[(uint)gotoBody.TargetStatement.Label.UniqueKey];
47 | Contract.Assume(gotosThatTarget != null && gotosThatTarget.Count >= 1);
48 | gotosThatTarget.Remove(gotoBody);
49 | var loopBody = ExtractBlock(statements, i+1, gotoCondition.TargetStatement);
50 | var whileLoop = new WhileDoStatement() { Body = loopBody, Condition = conditionalGotoBody.Condition };
51 | Contract.Assume(i < statements.Count);
52 | statements[i] = whileLoop;
53 | }
54 | base.TraverseChildren(block);
55 | }
56 |
57 | private static bool IsOrContainsAsFirstStatement(IStatement statement, ILabeledStatement labeledStatement) {
58 | if (statement == labeledStatement) return true;
59 | var block = statement as BlockStatement;
60 | while (block != null) {
61 | var statements = block.Statements;
62 | var n = statements.Count;
63 | if (n == 0) return false;
64 | for (int i = 0; i < n; i++) {
65 | var s = statements[i];
66 | var locDecl = s as LocalDeclarationStatement;
67 | if (locDecl != null) {
68 | if (locDecl.InitialValue == null) continue;
69 | return false;
70 | }
71 | if (s == labeledStatement) return true;
72 | block = s as BlockStatement;
73 | }
74 | }
75 | return false;
76 | }
77 |
78 | private ConditionalStatement/*?*/ LookForCondition(List statements, int i, ILabeledStatement potentialLabel) {
79 | Contract.Requires(statements != null);
80 | Contract.Requires(i >= 0);
81 | Contract.Requires(potentialLabel != null);
82 |
83 | for (; i < statements.Count-1; i++) {
84 | if (statements[i] != potentialLabel) continue;
85 | return statements[i+1] as ConditionalStatement;
86 | }
87 | return null;
88 | }
89 |
90 | private static IStatement ExtractBlock(List statements, int first, ILabeledStatement labelOfSubsequentCode) {
91 | Contract.Requires(statements != null);
92 | Contract.Requires(first > 0);
93 | Contract.Ensures(Contract.Result() != null);
94 |
95 | var last = first;
96 | var n = statements.Count;
97 | while (last < n) {
98 | var statement = statements[last];
99 | if (statement == labelOfSubsequentCode) {
100 | statements.RemoveRange(last, 2);
101 | break;
102 | }
103 | last++;
104 | }
105 | if (last == n) return new EmptyStatement();
106 | Contract.Assume(last <= statements.Count);
107 | if (first == last) return new EmptyStatement();
108 | if (first == last-1) {
109 | var firstBlock = statements[first] as BlockStatement;
110 | if (firstBlock != null) {
111 | statements.RemoveAt(first);
112 | return firstBlock;
113 | }
114 | }
115 | var newStatements = statements.GetRange(first, last-first);
116 | statements.RemoveRange(first, last-first);
117 | return new BlockStatement() { Statements = newStatements };
118 | }
119 |
120 | }
121 |
122 | }
123 |
--------------------------------------------------------------------------------
/Converters/ReflectionEmitter/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("ReflectionEmitter")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a typeBuilder in this assembly from
20 | // COM, set the ComVisible attribute to true on that typeBuilder.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("dd06ef47-5c16-488c-be84-25c516cf10ee")]
25 |
--------------------------------------------------------------------------------
/Converters/ReflectionImporter/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("ReflectionImporter")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("714e31c1-398b-4c5b-abec-ee04ba09e132")]
25 |
--------------------------------------------------------------------------------
/Converters/ReflectionImporter/ReflectionImporter.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 8.0.30703
7 | 2.0
8 | {86E871EE-47CF-4473-BDF1-6EB13250F6E9}
9 | Library
10 | Properties
11 | Microsoft.Cci
12 | Microsoft.Cci.ReflectionImporter
13 | v4.5
14 | 512
15 | SAK
16 | SAK
17 | SAK
18 | SAK
19 | 0
20 |
21 |
22 | true
23 | full
24 | false
25 | bin\Debug\
26 | DEBUG;TRACE
27 | prompt
28 | 4
29 | bin\Debug\Microsoft.Cci.ReflectionImporter.XML
30 | True
31 | False
32 | True
33 | False
34 | True
35 | False
36 | True
37 | True
38 | True
39 | True
40 | False
41 | True
42 | True
43 | True
44 | True
45 | False
46 | False
47 | False
48 | False
49 | True
50 | True
51 | True
52 | False
53 | True
54 |
55 |
56 |
57 |
58 | -show unreached
59 |
60 | True
61 | Full
62 | Build
63 | 2
64 |
65 |
66 | pdbonly
67 | true
68 | bin\Release\
69 | TRACE
70 | prompt
71 | 4
72 | bin\Release\Microsoft.Cci.ReflectionImporter.XML
73 |
74 |
75 |
76 | Build\Version.cs
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | {4A34A3C5-6176-49D7-A4C5-B2B671247F8F}
85 | MetadataHelper
86 |
87 |
88 | {33CAB640-0D03-43DF-81BD-22CDC6C0A597}
89 | MetadataModel
90 |
91 |
92 |
93 |
100 |
--------------------------------------------------------------------------------
/CoreObjectModel/AstsProjectedAsCodeModel/MemberDeclarationInterfaces.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Collections.Generic;
5 |
6 | //^ using Microsoft.Contracts;
7 |
8 | namespace Microsoft.Cci.Ast {
9 | ///
10 | /// The parameters and return type that makes up a method or property signature.
11 | /// This interface models the source representation of a signature.
12 | ///
13 | public interface ISignatureDeclaration : ISourceItem {
14 | ///
15 | /// The parameters forming part of this signature.
16 | ///
17 | IEnumerable Parameters { get; }
18 |
19 | ///
20 | /// An expression that denotes the return type of the method or type of the property.
21 | ///
22 | TypeExpression Type { get; }
23 |
24 | ///
25 | /// The symbol table object that represents the metadata for this signature.
26 | ///
27 | ISignature SignatureDefinition { get; }
28 | }
29 |
30 | ///
31 | /// A member of a type declaration, such as a field or a method.
32 | /// This interface models the source representation of a type member.
33 | ///
34 | public interface ITypeDeclarationMember : IContainerMember, IDeclaration, IErrorCheckable {
35 |
36 | ///
37 | /// The type declaration that contains this member.
38 | ///
39 | TypeDeclaration ContainingTypeDeclaration { get; }
40 |
41 | /////
42 | ///// Calls the visitor.Visit(T) method where T is the most derived object model node interface type implemented by the concrete type
43 | ///// of the object implementing ITypeDeclarationMember. The dispatch method does not invoke Dispatch on any child objects. If child traversal
44 | ///// is desired, the implementations of the Visit methods should do the subsequent dispatching.
45 | /////
46 | //void Dispatch(IMetadataVisitor visitor);
47 |
48 | ///
49 | /// Returns the visibility that applies by default to this member if no visibility was supplied in the source code.
50 | ///
51 | TypeMemberVisibility GetDefaultVisibility();
52 |
53 | ///
54 | /// Indicates that this member is intended to hide the name of an inherited member.
55 | ///
56 | bool IsNew { get; }
57 |
58 | ///
59 | /// True if the member exposes an unsafe type, such as a pointer.
60 | ///
61 | bool IsUnsafe { get; }
62 |
63 | ///
64 | /// The name of the member.
65 | ///
66 | new NameDeclaration Name {
67 | get;
68 | }
69 |
70 | ///
71 | /// Makes a shallow copy of this member that can be added to the member list of the given target type declaration.
72 | /// The shallow copy may share child objects with this instance, but should never expose such child objects except through
73 | /// wrappers (or shallow copies made on demand). If this instance is already a member of the target type declaration it
74 | /// returns itself.
75 | ///
76 | ITypeDeclarationMember MakeShallowCopyFor(TypeDeclaration targetTypeDeclaration);
77 | //^ requires targetTypeDeclaration.GetType() == this.ContainingTypeDeclaration.GetType();
78 | //^ ensures result.GetType() == this.GetType();
79 | //^ ensures result.ContainingTypeDeclaration == targetTypeDeclaration;
80 |
81 | ///
82 | /// The symbol table object that represents the metadata for this member. May be null if this member does not generate metadata.
83 | ///
84 | ITypeDefinitionMember/*?*/ TypeDefinitionMember { get; }
85 |
86 | ///
87 | /// Indicates if the member is public or confined to its containing type, derived types and/or declaring assembly.
88 | ///
89 | TypeMemberVisibility Visibility { get; }
90 | }
91 |
92 | }
--------------------------------------------------------------------------------
/CoreObjectModel/AstsProjectedAsCodeModel/NamespaceDeclarationInterfaces.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | //^ using Microsoft.Contracts;
5 |
6 | //TODO: get rid of these interfaces
7 |
8 | namespace Microsoft.Cci.Ast {
9 |
10 | ///
11 | /// Implemented by constructs that can be nested inside namespaces, such as types, nested namespaces, alias declarations, and so on.
12 | ///
13 | public interface INamespaceDeclarationMember : IContainerMember, ISourceItem, IErrorCheckable {
14 |
15 | ///
16 | /// The namespace declaration in which this nested namespace declaration is nested.
17 | ///
18 | NamespaceDeclaration ContainingNamespaceDeclaration {
19 | get;
20 | // ^ ensures exists{INamespaceDeclarationMember member in result.Members; member == this};
21 | }
22 |
23 | /////
24 | ///// Calls the visitor.Visit(T) method where T is the most derived object model node interface type implemented by the concrete type
25 | ///// of the object implementing INamespaceDeclarationMember. The dispatch method does not invoke Dispatch on any child objects. If child traversal
26 | ///// is desired, the implementations of the Visit methods should do the subsequent dispatching.
27 | /////
28 | //void Dispatch(IMetadataVisitor visitor);
29 |
30 | ///
31 | /// Makes a shallow copy of this member that can be added to the member list of the given target namespace declaration.
32 | /// The shallow copy may share child objects with this instance, but should never expose such child objects except through
33 | /// wrappers (or shallow copies made on demand). If this instance is already a member of the target namespace declaration it
34 | /// returns itself.
35 | ///
36 | INamespaceDeclarationMember MakeShallowCopyFor(NamespaceDeclaration targetNamespaceDeclaration);
37 | //^ requires targetNamespaceDeclaration.GetType() == this.ContainingNamespaceDeclaration.GetType();
38 | //^ ensures result.GetType() == this.GetType();
39 | //^ ensures result.ContainingNamespaceDeclaration == targetNamespaceDeclaration;
40 |
41 | ///
42 | /// The name of the member. For example the alias of an alias declaration, the name of nested namespace and so on.
43 | /// Can be the empty name, for example if the construct is a namespace import.
44 | ///
45 | new NameDeclaration Name {
46 | get;
47 | }
48 |
49 | }
50 |
51 | }
52 |
53 |
--------------------------------------------------------------------------------
/CoreObjectModel/AstsProjectedAsCodeModel/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("Microsoft.Cci.Ast")]
12 | [assembly: AssemblyDescription(@"A set of base classes that provide common implementations of the functionality
13 | required by the Microsoft.Cci object model.")]
14 | [assembly: AssemblyConfiguration("")]
15 | [assembly: AssemblyProduct("CCI")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | // Setting ComVisible to false makes the types in this assembly not visible
20 | // to COM componenets. If you need to access a type in this assembly from
21 | // COM, set the ComVisible attribute to true on that type.
22 | [assembly: ComVisible(false)]
23 |
24 | // The following GUID is for the ID of the typelib if this project is exposed to COM
25 | [assembly: Guid("f18a5287-3f3b-4816-8ce7-08651d2aa927")]
26 |
27 |
--------------------------------------------------------------------------------
/CoreObjectModel/AstsProjectedAsCodeModel/TypeDeclarationInterfaces.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | //^ using Microsoft.Contracts;
5 |
6 | //TODO: get rid of these interfaces
7 |
8 | namespace Microsoft.Cci.Ast {
9 | ///
10 | /// Corresponds to a source construct that declares a class.
11 | ///
12 | public interface IClassDeclaration {
13 | ///
14 | /// A static class can not have instance members. A static class is sealed.
15 | ///
16 | bool IsStatic { get; }
17 | }
18 |
19 | ///
20 | /// Corresponds to a source construct that declares a delegate.
21 | ///
22 | public interface IDelegateDeclaration {
23 | ///
24 | /// The signature of the Invoke method.
25 | ///
26 | ISignatureDeclaration Signature { get; }
27 |
28 | }
29 |
30 | ///
31 | /// Corresponds to a source construct that declares an enumerated scalar type.
32 | ///
33 | public interface IEnumDeclaration {
34 |
35 | ///
36 | /// The primitive integral type that will be used to represent the values of enumeration. May be null.
37 | ///
38 | TypeExpression/*?*/ UnderlyingType { get; }
39 | }
40 |
41 | ///
42 | /// Corresponds to a source construct that declares an interface.
43 | ///
44 | public interface IInterfaceDeclaration {
45 | }
46 |
47 | ///
48 | /// Corresponds to a source construct that declares a value type (struct).
49 | ///
50 | public interface IStructDeclaration {
51 | }
52 |
53 | }
--------------------------------------------------------------------------------
/CoreObjectModel/CodeModel/Members.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using Microsoft.Cci.Contracts;
7 |
8 | //^ using Microsoft.Contracts;
9 |
10 | namespace Microsoft.Cci {
11 |
12 | ///
13 | /// A metadata (IL) representation along with a source level representation of the body of a method or of a property/event accessor.
14 | ///
15 | public interface ISourceMethodBody : IMethodBody {
16 |
17 | ///
18 | /// The collection of statements making up the body.
19 | /// This is produced by either language parser or through decompilation of the Instructions.
20 | ///
21 | IBlockStatement Block {
22 | get;
23 | //^ requires !this.MethodDefinition.IsAbstract;
24 | }
25 | }
26 |
27 | ///
28 | /// An object that can visit a source method body Block and produce the corresponding IL.
29 | ///
30 | public interface ISourceToILConverter {
31 |
32 | ///
33 | /// Traverses the given block of statements in the context of the given method to produce a list of
34 | /// IL operations, exception information blocks (the locations of handlers, filters and finallies) and any private helper
35 | /// types (for example closure classes) that represent the semantics of the given block of statements.
36 | /// The results of the traversal can be retrieved via the GetOperations, GetOperationExceptionInformation
37 | /// and GetPrivateHelperTypes methods.
38 | /// It is assumed that any implementation of this interface will already have a reference to the method the body is
39 | /// contained in before this method is called.
40 | ///
41 | /// A block of statements that are to be converted to IL.
42 | void ConvertToIL(IBlockStatement body);
43 |
44 | ///
45 | /// Returns all of the local variables (including compiler generated temporary variables) that are local to the block
46 | /// of statements translated by this converter.
47 | ///
48 | IEnumerable GetLocalVariables();
49 |
50 | ///
51 | /// Returns the IL operations that correspond to the statements that have been converted to IL by this converter.
52 | ///
53 | IEnumerable GetOperations();
54 |
55 | ///
56 | /// Returns zero or more exception exception information blocks (information about handlers, filters and finally blocks)
57 | /// that correspond to try-catch-finally constructs that appear in the statements that have been converted to IL by this converter.
58 | ///
59 | IEnumerable GetOperationExceptionInformation();
60 |
61 | ///
62 | /// Returns zero or more types that are used to keep track of information needed to implement
63 | /// the statements that have been converted to IL by this converter. For example, any closure classes
64 | /// needed to compile anonymous delegate expressions (lambdas) will be returned by this method.
65 | ///
66 | IEnumerable GetPrivateHelperTypes();
67 |
68 | ///
69 | /// The maximum number of stack slots that will be needed by an interpreter of the IL produced by this converter.
70 | ///
71 | ushort MaximumStackSizeNeeded { get; }
72 |
73 | }
74 |
75 | }
--------------------------------------------------------------------------------
/CoreObjectModel/CodeModel/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("SourceObjectModel")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("fe42d275-bcf4-4be3-986b-755ae58bfdfd")]
25 |
--------------------------------------------------------------------------------
/CoreObjectModel/MetadataHelper/AttributeHelper.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using System.Diagnostics.Contracts;
8 |
9 | //^ using Microsoft.Contracts;
10 |
11 | namespace Microsoft.Cci {
12 | ///
13 | /// Class containing helper routines for Attributes
14 | ///
15 | public static class AttributeHelper {
16 | ///
17 | /// Returns true if the type definition is an attribute. Typedefinition is said to be attribute when it inherits from [mscorlib]System.Attribute
18 | ///
19 | public static bool IsAttributeType(ITypeDefinition typeDefinition) {
20 | Contract.Requires(typeDefinition != null);
21 |
22 | return TypeHelper.Type1DerivesFromType2(typeDefinition, typeDefinition.PlatformType.SystemAttribute);
23 | }
24 |
25 | ///
26 | /// Returns true if the given collection of attributes contains an attribute of the given type.
27 | ///
28 | public static bool Contains(IEnumerable attributes, ITypeReference attributeType) {
29 | Contract.Requires(attributes != null);
30 | Contract.Requires(attributeType != null);
31 |
32 | foreach (ICustomAttribute attribute in attributes) {
33 | if (attribute == null) continue;
34 | if (TypeHelper.TypesAreEquivalent(attribute.Type, attributeType)) return true;
35 | }
36 | return false;
37 | }
38 |
39 | ///
40 | /// Specifies whether more than one instance of this type of attribute is allowed on same element.
41 | /// This information is obtained from an attribute on the attribute type definition.
42 | ///
43 | public static bool AllowMultiple(ITypeDefinition attributeType, INameTable nameTable) {
44 | Contract.Requires(attributeType != null);
45 | Contract.Requires(nameTable != null);
46 |
47 | foreach (ICustomAttribute ca in attributeType.Attributes) {
48 | if (!TypeHelper.TypesAreEquivalent(ca.Type, attributeType.PlatformType.SystemAttributeUsageAttribute))
49 | continue;
50 | foreach (IMetadataNamedArgument namedArgument in ca.NamedArguments) {
51 | if (namedArgument.ArgumentName.UniqueKey == nameTable.AllowMultiple.UniqueKey) {
52 | IMetadataConstant/*?*/ compileTimeConst = namedArgument.ArgumentValue as IMetadataConstant;
53 | if (compileTimeConst == null || compileTimeConst.Value == null || !(compileTimeConst.Value is bool))
54 | continue;
55 | //^ assume false; //Unboxing cast might fail
56 | return (bool)compileTimeConst.Value;
57 | }
58 | }
59 | }
60 | return false;
61 | }
62 |
63 | ///
64 | /// Specifies whether this attribute applies to derived types and/or overridden methods.
65 | /// This information is obtained from an attribute on the attribute type definition.
66 | ///
67 | public static bool Inherited(ITypeDefinition attributeType, INameTable nameTable) {
68 | Contract.Requires(attributeType != null);
69 | Contract.Requires(nameTable != null);
70 |
71 | foreach (ICustomAttribute ca in attributeType.Attributes) {
72 | if (!TypeHelper.TypesAreEquivalent(ca.Type, attributeType.PlatformType.SystemAttributeUsageAttribute))
73 | continue;
74 | foreach (IMetadataNamedArgument namedArgument in ca.NamedArguments) {
75 | if (namedArgument.ArgumentName.UniqueKey == nameTable.AllowMultiple.UniqueKey) {
76 | IMetadataConstant/*?*/ compileTimeConst = namedArgument.ArgumentValue as IMetadataConstant;
77 | if (compileTimeConst == null || compileTimeConst.Value == null || !(compileTimeConst.Value is bool))
78 | continue;
79 | //^ assume false; //Unboxing cast might fail
80 | return (bool)compileTimeConst.Value;
81 | }
82 | }
83 | }
84 | return false;
85 | }
86 |
87 | ///
88 | /// Specifies the symbol table elements on which it is valid to apply this attribute.
89 | /// This information is obtained from an attribute on the attribute type definition.
90 | ///
91 | public static AttributeTargets ValidOn(ITypeDefinition attributeType) {
92 | Contract.Requires(attributeType != null);
93 |
94 | foreach (ICustomAttribute ca in attributeType.Attributes) {
95 | if (!TypeHelper.TypesAreEquivalent(ca.Type, attributeType.PlatformType.SystemAttributeUsageAttribute))
96 | continue;
97 | foreach (IMetadataExpression expr in ca.Arguments) {
98 | IMetadataConstant/*?*/ ctorParam = expr as IMetadataConstant;
99 | if (ctorParam == null || ctorParam.Value == null || !(ctorParam.Value is int))
100 | break;
101 | //^ assume false; //Unboxing cast might fail
102 | int val = (int)ctorParam.Value;
103 | return (AttributeTargets)val;
104 | }
105 | }
106 | return AttributeTargets.All;
107 | }
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/CoreObjectModel/MetadataHelper/ExpressionHelper.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using Microsoft.Cci;
5 | using System;
6 | using System.Diagnostics.Contracts;
7 |
8 | ///
9 | /// Class containing helper routines for IMetadataExpression expressions.
10 | ///
11 | public static class MetadataExpressionHelper {
12 |
13 | ///
14 | /// Returns true if the given constant expression contains a finite numeric value. In other words, infinities and NaN are excluded.
15 | ///
16 | ///
17 | ///
18 | public static bool IsFiniteNumeric(IMetadataConstant constExpression) {
19 | IConvertible/*?*/ ic = constExpression.Value as IConvertible;
20 | if (ic == null) return false;
21 | switch (ic.GetTypeCode()) {
22 | case System.TypeCode.SByte:
23 | case System.TypeCode.Int16:
24 | case System.TypeCode.Int32:
25 | case System.TypeCode.Int64:
26 | case System.TypeCode.Byte:
27 | case System.TypeCode.UInt16:
28 | case System.TypeCode.UInt32:
29 | case System.TypeCode.UInt64:
30 | return true;
31 | case System.TypeCode.Double:
32 | var d = ic.ToDouble(null);
33 | return !(Double.IsNaN(d) || Double.IsInfinity(d));
34 | case System.TypeCode.Single:
35 | var s = ic.ToSingle(null);
36 | return !(Single.IsNaN(s) || Single.IsInfinity(s));
37 | }
38 | return false;
39 | }
40 |
41 | ///
42 | /// True if the value is a boxed -1 of type byte, int, long, sbyte, short, uint, ulong or ushort.
43 | ///
44 | [Pure]
45 | public static bool IsIntegralMinusOne(IMetadataConstant constExpression) {
46 | IConvertible/*?*/ ic = constExpression.Value as IConvertible;
47 | if (ic == null) return false;
48 | switch (ic.GetTypeCode()) {
49 | case System.TypeCode.SByte: return ic.ToSByte(null) == -1;
50 | case System.TypeCode.Int16: return ic.ToInt16(null) == -1;
51 | case System.TypeCode.Int32: return ic.ToInt32(null) == -1;
52 | case System.TypeCode.Int64: return ic.ToInt64(null) == -1;
53 | case System.TypeCode.Byte: return ic.ToByte(null) == byte.MaxValue;
54 | case System.TypeCode.UInt16: return ic.ToUInt16(null) == ushort.MaxValue;
55 | case System.TypeCode.UInt32: return ic.ToUInt32(null) == uint.MaxValue;
56 | case System.TypeCode.UInt64: return ic.ToUInt64(null) == ulong.MaxValue;
57 | }
58 | return false;
59 | }
60 |
61 | ///
62 | /// True if the value is a boxed zero of type byte, int, long, sbyte, short, uint, ulong, ushort or bool that is not equal to 0.
63 | ///
64 | [Pure]
65 | public static bool IsIntegralNonzero(IMetadataConstant constExpression) {
66 | IConvertible/*?*/ ic = constExpression.Value as IConvertible;
67 | if (ic == null) return false;
68 | switch (ic.GetTypeCode()) {
69 | case System.TypeCode.SByte: return ic.ToSByte(null) != 0;
70 | case System.TypeCode.Int16: return ic.ToInt16(null) != 0;
71 | case System.TypeCode.Int32: return ic.ToInt32(null) != 0;
72 | case System.TypeCode.Int64: return ic.ToInt64(null) != 0;
73 | case System.TypeCode.Byte: return ic.ToByte(null) != 0;
74 | case System.TypeCode.UInt16: return ic.ToUInt16(null) != 0;
75 | case System.TypeCode.UInt32: return ic.ToUInt32(null) != 0;
76 | case System.TypeCode.UInt64: return ic.ToUInt64(null) != 0;
77 | case System.TypeCode.Boolean: return ic.ToBoolean(null);
78 | }
79 | return false;
80 | }
81 |
82 | ///
83 | /// True if the value is a boxed 1 of type byte, int, long, sbyte, short, uint, ulong, ushort or bool.
84 | ///
85 | [Pure]
86 | public static bool IsIntegralOne(IMetadataConstant constExpression) {
87 | IConvertible/*?*/ ic = constExpression.Value as IConvertible;
88 | if (ic == null) return false;
89 | switch (ic.GetTypeCode()) {
90 | case System.TypeCode.SByte: return ic.ToSByte(null) == 1;
91 | case System.TypeCode.Int16: return ic.ToInt16(null) == 1;
92 | case System.TypeCode.Int32: return ic.ToInt32(null) == 1;
93 | case System.TypeCode.Int64: return ic.ToInt64(null) == 1;
94 | case System.TypeCode.Byte: return ic.ToByte(null) == 1;
95 | case System.TypeCode.UInt16: return ic.ToUInt16(null) == 1;
96 | case System.TypeCode.UInt32: return ic.ToUInt32(null) == 1;
97 | case System.TypeCode.UInt64: return ic.ToUInt64(null) == 1;
98 | case System.TypeCode.Boolean: return ic.ToBoolean(null);
99 | }
100 | return false;
101 | }
102 |
103 | ///
104 | /// True if the value is a boxed zero of type byte, int, long, sbyte, short, uint, ulong, ushort or bool.
105 | ///
106 | [Pure]
107 | public static bool IsIntegralZero(IMetadataConstant constExpression) {
108 | IConvertible/*?*/ ic = constExpression.Value as IConvertible;
109 | if (ic == null) return false;
110 | switch (ic.GetTypeCode()) {
111 | case System.TypeCode.SByte: return ic.ToSByte(null) == 0;
112 | case System.TypeCode.Int16: return ic.ToInt16(null) == 0;
113 | case System.TypeCode.Int32: return ic.ToInt32(null) == 0;
114 | case System.TypeCode.Int64: return ic.ToInt64(null) == 0;
115 | case System.TypeCode.Byte: return ic.ToByte(null) == 0;
116 | case System.TypeCode.UInt16: return ic.ToUInt16(null) == 0;
117 | case System.TypeCode.UInt32: return ic.ToUInt32(null) == 0;
118 | case System.TypeCode.UInt64: return ic.ToUInt64(null) == 0;
119 | case System.TypeCode.Boolean: return !ic.ToBoolean(null);
120 | }
121 | return false;
122 | }
123 |
124 | }
--------------------------------------------------------------------------------
/CoreObjectModel/MetadataHelper/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Diagnostics.Contracts;
5 | using System.Reflection;
6 | using System.Runtime.CompilerServices;
7 | using System.Runtime.InteropServices;
8 |
9 | // General Information about an assembly is controlled through the following
10 | // set of attributes. Change these attribute values to modify the information
11 | // associated with an assembly.
12 | [assembly: AssemblyTitle("MetadataHelper")]
13 | [assembly: AssemblyDescription("A collection of convenience methods that are implemented solely in terms of the metadata object model.")]
14 | [assembly: AssemblyConfiguration("")]
15 | [assembly: AssemblyProduct("CCI")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | // Setting ComVisible to false makes the types in this assembly not visible
20 | // to COM components. If you need to access a type in this assembly from
21 | // COM, set the ComVisible attribute to true on that type.
22 | [assembly: ComVisible(false)]
23 |
24 | // The following GUID is for the ID of the typelib if this project is exposed to COM
25 | [assembly: Guid("e18a577e-4477-4fbd-ae4f-5f1116791fcf")]
26 |
27 | [assembly: ContractVerification(false)]
28 |
--------------------------------------------------------------------------------
/CoreObjectModel/MetadataModel/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Reflection;
6 | using System.Runtime.CompilerServices;
7 | using System.Runtime.InteropServices;
8 |
9 | // General Information about an assembly is controlled through the following
10 | // set of attributes. Change these attribute values to modify the information
11 | // associated with an assembly.
12 | [assembly: AssemblyTitle("Microsoft.Cci.MetadataModel")]
13 | [assembly: AssemblyDescription("An object model for CLR metadata and IL")]
14 | [assembly: AssemblyConfiguration("")]
15 | [assembly: AssemblyProduct("CCI")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | // Setting ComVisible to false makes the types in this assembly not visible
20 | // to COM components. If you need to access a type in this assembly from
21 | // COM, set the ComVisible attribute to true on that type.
22 | [assembly: ComVisible(false)]
23 |
24 | // The following GUID is for the ID of the typelib if this project is exposed to COM
25 | [assembly: Guid("62878a7b-9cd8-48f0-af78-02b7583ab03d")]
26 |
--------------------------------------------------------------------------------
/CoreObjectModel/MutableCodeModel/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("Microsoft.Cci.MutableCodeModel")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("b7dccfcd-96b3-499e-ba5f-1f1ba7b09978")]
25 |
--------------------------------------------------------------------------------
/CoreObjectModel/MutableMetadataModel/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 | using System.Diagnostics.Contracts;
8 |
9 | // General Information about an assembly is controlled through the following
10 | // set of attributes. Change these attribute values to modify the information
11 | // associated with an assembly.
12 | [assembly: AssemblyTitle("Microsoft.Cci.MutableMetadataModel")]
13 | [assembly: AssemblyDescription("")]
14 | [assembly: AssemblyConfiguration("")]
15 | [assembly: AssemblyProduct("CCI")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | // Setting ComVisible to false makes the types in this assembly not visible
20 | // to COM components. If you need to access a type in this assembly from
21 | // COM, set the ComVisible attribute to true on that type.
22 | [assembly: ComVisible(false)]
23 |
24 | // The following GUID is for the ID of the typelib if this project is exposed to COM
25 | [assembly: Guid("b7dccfcd-96b3-499e-ba5f-1f1ba7b09978")]
26 |
27 | [assembly: ContractVerification(false)]
28 |
--------------------------------------------------------------------------------
/CoreObjectModel/SourceModel/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("Microsoft.Cci.SourceModel")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("f0b0c0f2-4aa5-4a2e-a2bb-12dfadea90d0")]
25 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) Microsoft
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/BitSet.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal struct BitSet {
8 | internal BitSet(BitAccess bits) {
9 | bits.ReadInt32(out size); // 0..3 : Number of words
10 | words = new uint[size];
11 | bits.ReadUInt32(words);
12 | }
13 |
14 | //internal BitSet(int size) {
15 | // this.size = size;
16 | // words = new uint[size];
17 | //}
18 |
19 | internal bool IsSet(int index) {
20 | int word = index / 32;
21 | if (word >= this.size) return false;
22 | return ((words[word] & GetBit(index)) != 0);
23 | }
24 |
25 | //internal void Set(int index) {
26 | // int word = index / 32;
27 | // if (word >= this.size) return;
28 | // words[word] |= GetBit(index);
29 | //}
30 |
31 | //internal void Clear(int index) {
32 | // int word = index / 32;
33 | // if (word >= this.size) return;
34 | // words[word] &= ~GetBit(index);
35 | //}
36 |
37 | private static uint GetBit(int index) {
38 | return ((uint)1 << (index % 32));
39 | }
40 |
41 | //private static uint ReverseBits(uint value) {
42 | // uint o = 0;
43 | // for (int i = 0; i < 32; i++) {
44 | // o = (o << 1) | (value & 1);
45 | // value >>= 1;
46 | // }
47 | // return o;
48 | //}
49 |
50 | internal bool IsEmpty {
51 | get { return size == 0; }
52 | }
53 |
54 | //internal bool GetWord(int index, out uint word) {
55 | // if (index < size) {
56 | // word = ReverseBits(words[index]);
57 | // return true;
58 | // }
59 | // word = 0;
60 | // return false;
61 | //}
62 |
63 | private int size;
64 | private uint[] words;
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/DataStream.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.IO;
6 |
7 | namespace Microsoft.Cci.Pdb {
8 | internal class DataStream {
9 | internal DataStream() {
10 | }
11 |
12 | internal DataStream(int contentSize, BitAccess bits, int count) {
13 | this.contentSize = contentSize;
14 | if (count > 0) {
15 | this.pages = new int[count];
16 | bits.ReadInt32(this.pages);
17 | }
18 | }
19 |
20 | internal void Read(PdbReader reader, BitAccess bits) {
21 | bits.MinCapacity(contentSize);
22 | Read(reader, 0, bits.Buffer, 0, contentSize);
23 | }
24 |
25 | internal void Read(PdbReader reader, int position,
26 | byte[] bytes, int offset, int data) {
27 | if (position + data > contentSize) {
28 | throw new PdbException("DataStream can't read off end of stream. " +
29 | "(pos={0},siz={1})",
30 | position, data);
31 | }
32 | if (position == contentSize) {
33 | return;
34 | }
35 |
36 | int left = data;
37 | int page = position / reader.pageSize;
38 | int rema = position % reader.pageSize;
39 |
40 | // First get remained of first page.
41 | if (rema != 0) {
42 | int todo = reader.pageSize - rema;
43 | if (todo > left) {
44 | todo = left;
45 | }
46 |
47 | reader.Seek(pages[page], rema);
48 | reader.Read(bytes, offset, todo);
49 |
50 | offset += todo;
51 | left -= todo;
52 | page++;
53 | }
54 |
55 | // Now get the remaining pages.
56 | while (left > 0) {
57 | int todo = reader.pageSize;
58 | if (todo > left) {
59 | todo = left;
60 | }
61 |
62 | reader.Seek(pages[page], 0);
63 | reader.Read(bytes, offset, todo);
64 |
65 | offset += todo;
66 | left -= todo;
67 | page++;
68 | }
69 | }
70 |
71 | //private void AddPages(int page0, int count) {
72 | // if (pages == null) {
73 | // pages = new int[count];
74 | // for (int i = 0; i < count; i++) {
75 | // pages[i] = page0 + i;
76 | // }
77 | // } else {
78 | // int[] old = pages;
79 | // int used = old.Length;
80 |
81 | // pages = new int[used + count];
82 | // Array.Copy(old, pages, used);
83 | // for (int i = 0; i < count; i++) {
84 | // pages[used + i] = page0 + i;
85 | // }
86 | // }
87 | //}
88 |
89 | //internal int Pages {
90 | // get { return pages == null ? 0 : pages.Length; }
91 | //}
92 |
93 | internal int Length {
94 | get { return contentSize; }
95 | }
96 |
97 | //internal int GetPage(int index) {
98 | // return pages[index];
99 | //}
100 |
101 | internal int contentSize;
102 | internal int[] pages;
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/DbiDbgHdr.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal struct DbiDbgHdr {
8 | internal DbiDbgHdr(BitAccess bits) {
9 | bits.ReadUInt16(out snFPO);
10 | bits.ReadUInt16(out snException);
11 | bits.ReadUInt16(out snFixup);
12 | bits.ReadUInt16(out snOmapToSrc);
13 | bits.ReadUInt16(out snOmapFromSrc);
14 | bits.ReadUInt16(out snSectionHdr);
15 | bits.ReadUInt16(out snTokenRidMap);
16 | bits.ReadUInt16(out snXdata);
17 | bits.ReadUInt16(out snPdata);
18 | bits.ReadUInt16(out snNewFPO);
19 | bits.ReadUInt16(out snSectionHdrOrig);
20 | }
21 |
22 | internal ushort snFPO; // 0..1
23 | internal ushort snException; // 2..3 (deprecated)
24 | internal ushort snFixup; // 4..5
25 | internal ushort snOmapToSrc; // 6..7
26 | internal ushort snOmapFromSrc; // 8..9
27 | internal ushort snSectionHdr; // 10..11
28 | internal ushort snTokenRidMap; // 12..13
29 | internal ushort snXdata; // 14..15
30 | internal ushort snPdata; // 16..17
31 | internal ushort snNewFPO; // 18..19
32 | internal ushort snSectionHdrOrig; // 20..21
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/DbiHeader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal struct DbiHeader {
8 | internal DbiHeader(BitAccess bits) {
9 | bits.ReadInt32(out sig);
10 | bits.ReadInt32(out ver);
11 | bits.ReadInt32(out age);
12 | bits.ReadInt16(out gssymStream);
13 | bits.ReadUInt16(out vers);
14 | bits.ReadInt16(out pssymStream);
15 | bits.ReadUInt16(out pdbver);
16 | bits.ReadInt16(out symrecStream);
17 | bits.ReadUInt16(out pdbver2);
18 | bits.ReadInt32(out gpmodiSize);
19 | bits.ReadInt32(out secconSize);
20 | bits.ReadInt32(out secmapSize);
21 | bits.ReadInt32(out filinfSize);
22 | bits.ReadInt32(out tsmapSize);
23 | bits.ReadInt32(out mfcIndex);
24 | bits.ReadInt32(out dbghdrSize);
25 | bits.ReadInt32(out ecinfoSize);
26 | bits.ReadUInt16(out flags);
27 | bits.ReadUInt16(out machine);
28 | bits.ReadInt32(out reserved);
29 | }
30 |
31 | internal int sig; // 0..3
32 | internal int ver; // 4..7
33 | internal int age; // 8..11
34 | internal short gssymStream; // 12..13
35 | internal ushort vers; // 14..15
36 | internal short pssymStream; // 16..17
37 | internal ushort pdbver; // 18..19
38 | internal short symrecStream; // 20..21
39 | internal ushort pdbver2; // 22..23
40 | internal int gpmodiSize; // 24..27
41 | internal int secconSize; // 28..31
42 | internal int secmapSize; // 32..35
43 | internal int filinfSize; // 36..39
44 | internal int tsmapSize; // 40..43
45 | internal int mfcIndex; // 44..47
46 | internal int dbghdrSize; // 48..51
47 | internal int ecinfoSize; // 52..55
48 | internal ushort flags; // 56..57
49 | internal ushort machine; // 58..59
50 | internal int reserved; // 60..63
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/DbiModuleInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal class DbiModuleInfo {
8 | internal DbiModuleInfo(BitAccess bits, bool readStrings) {
9 | bits.ReadInt32(out opened);
10 | new DbiSecCon(bits);
11 | bits.ReadUInt16(out flags);
12 | bits.ReadInt16(out stream);
13 | bits.ReadInt32(out cbSyms);
14 | bits.ReadInt32(out cbOldLines);
15 | bits.ReadInt32(out cbLines);
16 | bits.ReadInt16(out files);
17 | bits.ReadInt16(out pad1);
18 | bits.ReadUInt32(out offsets);
19 | bits.ReadInt32(out niSource);
20 | bits.ReadInt32(out niCompiler);
21 | if (readStrings) {
22 | bits.ReadCString(out moduleName);
23 | bits.ReadCString(out objectName);
24 | } else {
25 | bits.SkipCString(out moduleName);
26 | bits.SkipCString(out objectName);
27 | }
28 | bits.Align(4);
29 | //if (opened != 0 || pad1 != 0) {
30 | // throw new PdbException("Invalid DBI module. "+
31 | // "(opened={0}, pad={1})", opened, pad1);
32 | //}
33 | }
34 |
35 | internal int opened; // 0..3
36 | //internal DbiSecCon section; // 4..31
37 | internal ushort flags; // 32..33
38 | internal short stream; // 34..35
39 | internal int cbSyms; // 36..39
40 | internal int cbOldLines; // 40..43
41 | internal int cbLines; // 44..57
42 | internal short files; // 48..49
43 | internal short pad1; // 50..51
44 | internal uint offsets;
45 | internal int niSource;
46 | internal int niCompiler;
47 | internal string moduleName;
48 | internal string objectName;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/DbiSecCon.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal struct DbiSecCon {
8 | internal DbiSecCon(BitAccess bits) {
9 | bits.ReadInt16(out section);
10 | bits.ReadInt16(out pad1);
11 | bits.ReadInt32(out offset);
12 | bits.ReadInt32(out size);
13 | bits.ReadUInt32(out flags);
14 | bits.ReadInt16(out module);
15 | bits.ReadInt16(out pad2);
16 | bits.ReadUInt32(out dataCrc);
17 | bits.ReadUInt32(out relocCrc);
18 | //if (pad1 != 0 || pad2 != 0) {
19 | // throw new PdbException("Invalid DBI section. "+
20 | // "(pad1={0}, pad2={1})",
21 | // pad1, pad2);
22 | //}
23 | }
24 |
25 | internal short section; // 0..1
26 | internal short pad1; // 2..3
27 | internal int offset; // 4..7
28 | internal int size; // 8..11
29 | internal uint flags; // 12..15
30 | internal short module; // 16..17
31 | internal short pad2; // 18..19
32 | internal uint dataCrc; // 20..23
33 | internal uint relocCrc; // 24..27
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/IntHashTable.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/cci/659f31f9736a1e8ded870ee2132d91f87505148e/PDBReaderAndWriter/PdbReader/IntHashTable.cs
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/MsfDirectory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal class MsfDirectory {
8 | internal MsfDirectory(PdbReader reader, PdbFileHeader head, BitAccess bits) {
9 | int pages = reader.PagesFromSize(head.directorySize);
10 |
11 | // 0..n in page of directory pages.
12 | bits.MinCapacity(head.directorySize);
13 | int directoryRootPages = head.directoryRoot.Length;
14 | int pagesPerPage = head.pageSize / 4;
15 | int pagesToGo = pages;
16 | for (int i = 0; i < directoryRootPages; i++) {
17 | int pagesInThisPage = pagesToGo <= pagesPerPage ? pagesToGo : pagesPerPage;
18 | reader.Seek(head.directoryRoot[i], 0);
19 | bits.Append(reader.reader, pagesInThisPage * 4);
20 | pagesToGo -= pagesInThisPage;
21 | }
22 | bits.Position = 0;
23 |
24 | DataStream stream = new DataStream(head.directorySize, bits, pages);
25 | bits.MinCapacity(head.directorySize);
26 | stream.Read(reader, bits);
27 |
28 | // 0..3 in directory pages
29 | int count;
30 | bits.ReadInt32(out count);
31 |
32 | // 4..n
33 | int[] sizes = new int[count];
34 | bits.ReadInt32(sizes);
35 |
36 | // n..m
37 | streams = new DataStream[count];
38 | for (int i = 0; i < count; i++) {
39 | if (sizes[i] <= 0) {
40 | streams[i] = new DataStream();
41 | } else {
42 | streams[i] = new DataStream(sizes[i], bits,
43 | reader.PagesFromSize(sizes[i]));
44 | }
45 | }
46 | }
47 |
48 | internal DataStream[] streams;
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbConstant.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Runtime.InteropServices;
6 |
7 | namespace Microsoft.Cci.Pdb {
8 | ///
9 | public class PdbConstant {
10 | internal string name;
11 | internal uint token;
12 | internal object value;
13 |
14 | internal PdbConstant(string name, uint token, object value) {
15 | this.name = name;
16 | this.token = token;
17 | this.value = value;
18 | }
19 |
20 | internal PdbConstant(BitAccess bits) {
21 | bits.ReadUInt32(out this.token);
22 | byte tag1;
23 | bits.ReadUInt8(out tag1);
24 | byte tag2;
25 | bits.ReadUInt8(out tag2);
26 | if (tag2 == 0) {
27 | this.value = tag1;
28 | } else if (tag2 == 0x80) {
29 | switch (tag1) {
30 | case 0x00: //sbyte
31 | sbyte sb;
32 | bits.ReadInt8(out sb);
33 | this.value = sb;
34 | break;
35 | case 0x01: //short
36 | short s;
37 | bits.ReadInt16(out s);
38 | this.value = s;
39 | break;
40 | case 0x02: //ushort
41 | ushort us;
42 | bits.ReadUInt16(out us);
43 | this.value = us;
44 | break;
45 | case 0x03: //int
46 | int i;
47 | bits.ReadInt32(out i);
48 | this.value = i;
49 | break;
50 | case 0x04: //uint
51 | uint ui;
52 | bits.ReadUInt32(out ui);
53 | this.value = ui;
54 | break;
55 | case 0x05: //float
56 | this.value = bits.ReadFloat();
57 | break;
58 | case 0x06: //double
59 | this.value = bits.ReadDouble();
60 | break;
61 | case 0x09: //long
62 | long sl;
63 | bits.ReadInt64(out sl);
64 | this.value = sl;
65 | break;
66 | case 0x0a: //ulong
67 | ulong ul;
68 | bits.ReadUInt64(out ul);
69 | this.value = ul;
70 | break;
71 | case 0x10: //string
72 | string str;
73 | bits.ReadBString(out str);
74 | this.value = str;
75 | break;
76 | case 0x19: //decimal
77 | this.value = bits.ReadDecimal();
78 | break;
79 | default:
80 | //TODO: error
81 | break;
82 | }
83 | } else {
84 | //TODO: error
85 | }
86 | bits.ReadCString(out name);
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbDebugException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.IO;
6 |
7 | namespace Microsoft.Cci.Pdb {
8 | internal class PdbDebugException : IOException {
9 | internal PdbDebugException(String format, params object[] args)
10 | : base(String.Format(format, args)) {
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.IO;
6 |
7 | namespace Microsoft.Cci.Pdb {
8 | internal class PdbException : IOException {
9 | internal PdbException(String format, params object[] args)
10 | : base(String.Format(format, args)) {
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbFileHeader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.IO;
6 | using System.Linq;
7 | using System.Text;
8 |
9 | namespace Microsoft.Cci.Pdb {
10 | internal class PdbFileHeader {
11 | private readonly byte[] windowsPdbMagic = new byte[32] {
12 | 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, // "Microsof"
13 | 0x74, 0x20, 0x43, 0x2F, 0x43, 0x2B, 0x2B, 0x20, // "t C/C++ "
14 | 0x4D, 0x53, 0x46, 0x20, 0x37, 0x2E, 0x30, 0x30, // "MSF 7.00"
15 | 0x0D, 0x0A, 0x1A, 0x44, 0x53, 0x00, 0x00, 0x00 // "^^^DS^^^"
16 | };
17 |
18 | //internal PdbFileHeader(int pageSize) {
19 | // this.magic = new byte[32] {
20 | // 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, // "Microsof"
21 | // 0x74, 0x20, 0x43, 0x2F, 0x43, 0x2B, 0x2B, 0x20, // "t C/C++ "
22 | // 0x4D, 0x53, 0x46, 0x20, 0x37, 0x2E, 0x30, 0x30, // "MSF 7.00"
23 | // 0x0D, 0x0A, 0x1A, 0x44, 0x53, 0x00, 0x00, 0x00 // "^^^DS^^^"
24 | // };
25 | // this.pageSize = pageSize;
26 | //}
27 |
28 | internal PdbFileHeader(Stream reader, BitAccess bits) {
29 | bits.MinCapacity(56);
30 | reader.Seek(0, SeekOrigin.Begin);
31 | bits.FillBuffer(reader, 52);
32 |
33 | this.magic = new byte[32];
34 | bits.ReadBytes(this.magic); // 0..31
35 | bits.ReadInt32(out this.pageSize); // 32..35
36 | bits.ReadInt32(out this.freePageMap); // 36..39
37 | bits.ReadInt32(out this.pagesUsed); // 40..43
38 | bits.ReadInt32(out this.directorySize); // 44..47
39 | bits.ReadInt32(out this.zero); // 48..51
40 |
41 | if (!this.magic.SequenceEqual(windowsPdbMagic))
42 | {
43 | throw new PdbException("The PDB file is not recognized as a Windows PDB file");
44 | }
45 |
46 | int directoryPages = ((((directorySize + pageSize - 1) / pageSize) * 4) + pageSize - 1) / pageSize;
47 | this.directoryRoot = new int[directoryPages];
48 | bits.FillBuffer(reader, directoryPages * 4);
49 | bits.ReadInt32(this.directoryRoot);
50 | }
51 |
52 | //internal string Magic {
53 | // get { return StringFromBytesUTF8(magic); }
54 | //}
55 |
56 | //internal void Write(Stream writer, BitAccess bits) {
57 | // bits.MinCapacity(pageSize);
58 | // bits.WriteBytes(magic); // 0..31
59 | // bits.WriteInt32(pageSize); // 32..35
60 | // bits.WriteInt32(freePageMap); // 36..39
61 | // bits.WriteInt32(pagesUsed); // 40..43
62 | // bits.WriteInt32(directorySize); // 44..47
63 | // bits.WriteInt32(zero); // 48..51
64 | // bits.WriteInt32(directoryRoot); // 52..55
65 |
66 | // writer.Seek(0, SeekOrigin.Begin);
67 | // bits.WriteBuffer(writer, pageSize);
68 | //}
69 |
70 | //////////////////////////////////////////////////// Helper Functions.
71 | //
72 | //internal static string StringFromBytesUTF8(byte[] bytes) {
73 | // return StringFromBytesUTF8(bytes, 0, bytes.Length);
74 | //}
75 |
76 | //internal static string StringFromBytesUTF8(byte[] bytes, int offset, int length) {
77 | // for (int i = 0; i < length; i++) {
78 | // if (bytes[offset + i] < ' ') {
79 | // length = i;
80 | // }
81 | // }
82 | // return Encoding.UTF8.GetString(bytes, offset, length);
83 | //}
84 |
85 | ////////////////////////////////////////////////////////////// Fields.
86 | //
87 | internal readonly byte[] magic;
88 | internal readonly int pageSize;
89 | internal int freePageMap;
90 | internal int pagesUsed;
91 | internal int directorySize;
92 | internal readonly int zero;
93 | internal int[] directoryRoot;
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 |
7 | using Microsoft.Cci.Pdb;
8 |
9 | namespace Microsoft.Cci {
10 |
11 | ///
12 | /// This class represents the information read from a PDB file (both legacy Windows and Portable).
13 | ///
14 | internal class PdbInfo {
15 | ///
16 | /// Enumeration of per-function information contained in the PDB file.
17 | ///
18 | public IEnumerable Functions;
19 |
20 | ///
21 | /// Mapping from tokens to source files and line numbers.
22 | ///
23 | public Dictionary TokenToSourceMapping;
24 |
25 | ///
26 | /// Source server data information.
27 | ///
28 | public string SourceServerData;
29 |
30 | ///
31 | /// Age of the PDB file is used to match the PDB against the PE binary.
32 | ///
33 | public int Age;
34 |
35 | ///
36 | /// GUID of the PDB file is used to match the PDB against the PE binary.
37 | ///
38 | public Guid Guid;
39 |
40 | ///
41 | /// Source link data information.
42 | ///
43 | public byte[] SourceLinkData;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbLine.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal struct PdbLine {
8 | internal uint offset;
9 | internal uint lineBegin;
10 | internal uint lineEnd;
11 | internal ushort colBegin;
12 | internal ushort colEnd;
13 |
14 | internal PdbLine(uint offset, uint lineBegin, ushort colBegin, uint lineEnd, ushort colEnd) {
15 | this.offset = offset;
16 | this.lineBegin = lineBegin;
17 | this.colBegin = colBegin;
18 | this.lineEnd = lineEnd;
19 | this.colEnd = colEnd;
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbLines.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal class PdbLines {
8 | internal PdbSource file;
9 | internal PdbLine[] lines;
10 |
11 | internal PdbLines(PdbSource file, uint count) {
12 | this.file = file;
13 | this.lines = new PdbLine[count];
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbReader.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.IO;
6 |
7 | namespace Microsoft.Cci.Pdb {
8 | internal class PdbReader {
9 | internal PdbReader(Stream reader, int pageSize) {
10 | this.pageSize = pageSize;
11 | this.reader = reader;
12 | }
13 |
14 | internal void Seek(int page, int offset) {
15 | reader.Seek(page * pageSize + offset, SeekOrigin.Begin);
16 | }
17 |
18 | internal void Read(byte[] bytes, int offset, int count) {
19 | reader.Read(bytes, offset, count);
20 | }
21 |
22 | internal int PagesFromSize(int size) {
23 | return (size + pageSize - 1) / (pageSize);
24 | }
25 |
26 | //internal int PageSize {
27 | // get { return pageSize; }
28 | //}
29 |
30 | internal readonly int pageSize;
31 | internal readonly Stream reader;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbScope.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal class PdbScope {
8 | internal PdbConstant[] constants;
9 | internal PdbSlot[] slots;
10 | internal PdbScope[] scopes;
11 | internal string[] usedNamespaces;
12 |
13 | //internal uint segment;
14 | internal uint address;
15 | internal uint offset;
16 | internal uint length;
17 |
18 | internal PdbScope(uint address, uint offset, uint length, PdbSlot[] slots, PdbConstant[] constants, string[] usedNamespaces) {
19 | this.constants = constants;
20 | this.slots = slots;
21 | this.scopes = ArrayT.Empty;
22 | this.usedNamespaces = usedNamespaces;
23 | this.address = address;
24 | this.offset = offset;
25 | this.length = length;
26 | }
27 |
28 | internal PdbScope(uint address, uint length, PdbSlot[] slots, PdbConstant[] constants, string[] usedNamespaces)
29 | : this(address, 0, length, slots, constants, usedNamespaces)
30 | {
31 | }
32 |
33 | internal PdbScope(uint funcOffset, BlockSym32 block, BitAccess bits, out uint typind) {
34 | //this.segment = block.seg;
35 | this.address = block.off;
36 | this.offset = block.off - funcOffset;
37 | this.length = block.len;
38 | typind = 0;
39 |
40 | int constantCount;
41 | int scopeCount;
42 | int slotCount;
43 | int namespaceCount;
44 | PdbFunction.CountScopesAndSlots(bits, block.end, out constantCount, out scopeCount, out slotCount, out namespaceCount);
45 | constants = ArrayT.Create(constantCount);
46 | scopes = ArrayT.Create(scopeCount);
47 | slots = ArrayT.Create(slotCount);
48 | usedNamespaces = ArrayT.Create(namespaceCount);
49 | int constant = 0;
50 | int scope = 0;
51 | int slot = 0;
52 | int usedNs = 0;
53 |
54 | while (bits.Position < block.end) {
55 | ushort siz;
56 | ushort rec;
57 |
58 | bits.ReadUInt16(out siz);
59 | int star = bits.Position;
60 | int stop = bits.Position + siz;
61 | bits.Position = star;
62 | bits.ReadUInt16(out rec);
63 |
64 | switch ((SYM)rec) {
65 | case SYM.S_BLOCK32: {
66 | BlockSym32 sub = new BlockSym32();
67 |
68 | bits.ReadUInt32(out sub.parent);
69 | bits.ReadUInt32(out sub.end);
70 | bits.ReadUInt32(out sub.len);
71 | bits.ReadUInt32(out sub.off);
72 | bits.ReadUInt16(out sub.seg);
73 | bits.SkipCString(out sub.name);
74 |
75 | bits.Position = stop;
76 | scopes[scope++] = new PdbScope(funcOffset, sub, bits, out typind);
77 | break;
78 | }
79 |
80 | case SYM.S_MANSLOT:
81 | slots[slot++] = new PdbSlot(bits);
82 | bits.Position = stop;
83 | break;
84 |
85 | case SYM.S_UNAMESPACE:
86 | bits.ReadCString(out usedNamespaces[usedNs++]);
87 | bits.Position = stop;
88 | break;
89 |
90 | case SYM.S_END:
91 | bits.Position = stop;
92 | break;
93 |
94 | case SYM.S_MANCONSTANT:
95 | constants[constant++] = new PdbConstant(bits);
96 | bits.Position = stop;
97 | break;
98 |
99 | default:
100 | //throw new PdbException("Unknown SYM in scope {0}", (SYM)rec);
101 | bits.Position = stop;
102 | break;
103 | }
104 | }
105 |
106 | if (bits.Position != block.end) {
107 | throw new Exception("Not at S_END");
108 | }
109 |
110 | ushort esiz;
111 | ushort erec;
112 | bits.ReadUInt16(out esiz);
113 | bits.ReadUInt16(out erec);
114 |
115 | if (erec != (ushort)SYM.S_END) {
116 | throw new Exception("Missing S_END");
117 | }
118 | }
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbSlot.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal class PdbSlot {
8 | internal uint slot;
9 | internal uint typeToken;
10 | internal string name;
11 | internal ushort flags;
12 | //internal uint segment;
13 | //internal uint address;
14 |
15 | internal PdbSlot(uint slot, uint typeToken, string name, ushort flags)
16 | {
17 | this.slot = slot;
18 | this.typeToken = typeToken;
19 | this.name = name;
20 | this.flags = flags;
21 | }
22 |
23 | internal PdbSlot(BitAccess bits) {
24 | AttrSlotSym slot;
25 |
26 | bits.ReadUInt32(out slot.index);
27 | bits.ReadUInt32(out slot.typind);
28 | bits.ReadUInt32(out slot.offCod);
29 | bits.ReadUInt16(out slot.segCod);
30 | bits.ReadUInt16(out slot.flags);
31 | bits.ReadCString(out slot.name);
32 |
33 | this.slot = slot.index;
34 | this.typeToken = slot.typind;
35 | this.name = slot.name;
36 | this.flags = slot.flags;
37 | //this.segment = slot.segCod;
38 | //this.address = slot.offCod;
39 |
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbSource.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal class PdbSource {
8 | //internal uint index;
9 | internal string name;
10 | internal Guid doctype;
11 | internal Guid language;
12 | internal Guid vendor;
13 | internal Guid checksumAlgorithm;
14 | internal byte[] checksum;
15 |
16 | internal PdbSource(/*uint index, */string name, Guid doctype, Guid language, Guid vendor, Guid checksumAlgorithm, byte[] checksum) {
17 | //this.index = index;
18 | this.name = name;
19 | this.doctype = doctype;
20 | this.language = language;
21 | this.vendor = vendor;
22 | this.checksumAlgorithm = checksumAlgorithm;
23 | this.checksum = checksum;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/PdbTokenLine.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Cci.Pdb {
7 | internal class PdbTokenLine {
8 | internal uint token;
9 | internal uint file_id;
10 | internal uint line;
11 | internal uint column;
12 | internal uint endLine;
13 | internal uint endColumn;
14 | internal PdbSource sourceFile;
15 | internal PdbTokenLine/*?*/ nextLine;
16 |
17 | internal PdbTokenLine(uint token, uint file_id, uint line, uint column, uint endLine, uint endColumn) {
18 | this.token = token;
19 | this.file_id = file_id;
20 | this.line = line;
21 | this.column = column;
22 | this.endLine = endLine;
23 | this.endColumn = endColumn;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbReader/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("PdbReaderAndWriter")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("b798fe0d-39bf-4bf3-b8b1-cb09cf4f07a0")]
25 |
26 |
--------------------------------------------------------------------------------
/PDBReaderAndWriter/PdbWriter/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("PdbWriter")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("15dcf2b3-89c3-4465-8d53-633b40f7ed62")]
25 |
26 |
--------------------------------------------------------------------------------
/PEReaderAndWriter/PEReader/AliasForTypeExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using Microsoft.Cci.MetadataReader.ObjectModelImplementation;
5 | using System;
6 |
7 | namespace Microsoft.Cci.MetadataReader.Extensions
8 | {
9 | public static class AliasForTypeExtensions
10 | {
11 | ///
12 | /// Helper to step through one indirection of IAliasForType.
13 | /// The method gets the type reference on the target of the alias
14 | /// and if that target is another alias it also returns its IAliasForType.
15 | /// This can be used to step over aliases one by one, as opposed to IAliasForType.AliasedType
16 | /// which sometimes resolves all the way through to the type def.
17 | /// It also provides a way to get to the target's IAliasForType which is otherwise
18 | /// really hard to get to (a simple type ref pointing to it is not enough, it will still report itself as non-alias).
19 | ///
20 | /// The alias to step through.
21 | /// If the target points to another alias this will contain IAliasForType for it.
22 | /// The type ref for the target of the source alias. The type ref can be resolved, but its IsAlias property can't be trusted
23 | /// as it will always return false.
24 | public static INamedTypeReference GetUnresolvedAliasedTypeReference(this IAliasForType aliasForType, out IAliasForType referencedAliasForType)
25 | {
26 | referencedAliasForType = null;
27 |
28 | var exportedAliasForType = aliasForType as ExportedTypeAliasBase;
29 | if (exportedAliasForType == null)
30 | throw new NotSupportedException("An IAliasForType created using PEReader is required.");
31 |
32 | IMetadataReaderNamedTypeReference typeReference = exportedAliasForType.UnresolvedAliasedTypeReference as IMetadataReaderNamedTypeReference;
33 | if (typeReference == null)
34 | throw new NotSupportedException("A type reference created using PEReader is required.");
35 |
36 | var internalAssembly = typeReference.ModuleReference.ResolvedUnit as Assembly;
37 | if (internalAssembly != null)
38 | {
39 | // Try if the other assembly has this as yet another type alias, since there's no good way of getting from a normal type reference
40 | // to the alias. This is basically the only way to do that.
41 | referencedAliasForType = internalAssembly.PEFileToObjectModel.TryToResolveAsNamespaceTypeAlias(typeReference.NamespaceFullName, typeReference.MangledTypeName);
42 | }
43 |
44 | return typeReference;
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/PEReaderAndWriter/PEReader/ModuleExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | #pragma warning disable 1591 // missing doc comments
5 |
6 | using Microsoft.Cci.MetadataReader.ObjectModelImplementation;
7 | using System;
8 | using System.Collections.Generic;
9 |
10 | namespace Microsoft.Cci.MetadataReader.Extensions
11 | {
12 | public static class ModuleExtensions
13 | {
14 | public static IEnumerable GetConstructedTypeInstanceMembers(
15 | this IModule module
16 | ) {
17 | if (!(module is Module))
18 | throw new NotSupportedException("An IModule created using PEReader is required.");
19 | var readerModule = module as Module;
20 | return readerModule.GetConstructedTypeInstanceMembers();
21 | }
22 |
23 | public static IEnumerable GetMethodSpecs(
24 | this IModule module
25 | ) {
26 | if (!(module is Module))
27 | throw new NotSupportedException("An IModule created using PEReader is required.");
28 | var readerModule = module as Module;
29 | return readerModule.GetMethodSpecs();
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/PEReaderAndWriter/PEReader/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("Microsoft.Cci.PEReader")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("dc891919-b1b9-441c-b5b7-ce68dfba0b55")]
25 |
--------------------------------------------------------------------------------
/PEReaderAndWriter/PEWriter/PdbWriterInterface.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 |
6 | //^ using Microsoft.Contracts;
7 |
8 | namespace Microsoft.Cci {
9 |
10 | public interface IPdbWriter {
11 | void CloseMethod(uint offset);
12 | void CloseScope(uint offset);
13 | void CloseTokenSourceLocationsScope();
14 | void DefineCustomMetadata(string name, byte[] metadata);
15 | void DefineLocalConstant(string name, object value, uint contantSignatureToken);
16 | void DefineLocalVariable(uint index, string name, bool isCompilerGenerated, uint localVariablesSignatureToken);
17 | void DefineSequencePoint(ILocation location, uint offset);
18 | void DefineTokenSourceLocation(uint token, ILocation location);
19 | PeDebugDirectory GetDebugDirectory();
20 | void OpenMethod(uint methodToken);
21 | void OpenScope(uint offset);
22 | void OpenTokenSourceLocationsScope();
23 | void SetEntryPoint(uint entryMethodToken);
24 | void UsingNamespace(string fullName);
25 | }
26 |
27 | public interface IUnmanagedPdbWriter : IPdbWriter, IDisposable {
28 | void SetMetadataEmitter(object metadataEmitter);
29 | }
30 |
31 | public class PeDebugDirectory {
32 | public uint Characteristics;
33 | public uint TimeDateStamp;
34 | public ushort MajorVersion;
35 | public ushort MinorVersion;
36 | public uint Type;
37 | public uint SizeOfData;
38 | public uint AddressOfRawData;
39 | public uint PointerToRawData;
40 | public byte[] Data;
41 | }
42 |
43 | }
--------------------------------------------------------------------------------
/PEReaderAndWriter/PEWriter/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("ModuleWriter")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("ca48caa0-6b9b-42d0-a4e0-17f9120575b5")]
25 |
26 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Common Compiler Infrastructure (CCI)
2 |
3 | ## IMPORTANT
4 | Moving forward, there will only be servicing investments in CCI to support existing uses. New projects that need related functionality should look to the following instead:
5 |
6 | * [Roslyn](https://github.com/dotnet/roslyn)
7 | * [Mono.Cecil](https://github.com/jbevain/cecil)
8 | * [System.Reflection.Metadata](https://github.com/dotnet/corefx)
9 |
10 | ## GitHub vs. CodePlex
11 | This GitHub repository is the new central location for CCI and will replace https://ccimetadata.codeplex.com and https://cciast.codeplex.com.
12 |
--------------------------------------------------------------------------------
/Samples/AsmMeta/CCRefGenTask.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Build.Utilities;
8 | using Microsoft.Build.Framework;
9 |
10 | namespace Microsoft.Research {
11 | public class CCRefGen : Task {
12 | #region Properties
13 |
14 | bool sourceText = true;
15 | public bool IncludeSourceTextInContracts { get { return sourceText; } set { sourceText = value; } }
16 |
17 | public bool Verifiable { get; set; }
18 |
19 | public string Output { get; set; }
20 |
21 | public string Input { get; set; }
22 |
23 | public bool WritePDB { get; set; }
24 |
25 | public ITaskItem[] LibPaths { get; set; }
26 |
27 | public ITaskItem[] ResolvedPaths { get; set; }
28 |
29 | public bool Break { get; set; }
30 |
31 | #endregion
32 |
33 |
34 | public override bool Execute() {
35 |
36 | #if DEBUG
37 | if (!System.Diagnostics.Debugger.IsAttached)
38 | {
39 | System.Diagnostics.Debugger.Launch();
40 | }
41 | #endif
42 |
43 | try {
44 | #region Setup parameters
45 |
46 | if (Input == null) { this.Log.LogError("Input parameter must be specified"); return false; }
47 |
48 | AsmMeta.AsmMeta asmmeta = new AsmMeta.AsmMeta(this.ErrorLogger);
49 | asmmeta.options.GeneralArguments.Add(Input);
50 | asmmeta.options.output = Output;
51 | asmmeta.options.includeSourceTextInContract = IncludeSourceTextInContracts;
52 | asmmeta.options.writePDB = WritePDB;
53 | if (ResolvedPaths!= null) {
54 | foreach (var lp in ResolvedPaths)
55 | {
56 | asmmeta.options.resolvedPaths.Add(lp.ItemSpec);
57 | }
58 | }
59 | if (LibPaths != null)
60 | {
61 | foreach (var lp in LibPaths)
62 | {
63 | asmmeta.options.libPaths.Add(lp.ItemSpec);
64 | }
65 | }
66 | asmmeta.options.doBreak = Break;
67 | #endregion
68 |
69 | var result = asmmeta.Run();
70 |
71 | return (result == 0);
72 | } catch (Exception e) {
73 | this.Log.LogError("Exception: {0} caught", e.Message);
74 | return false;
75 | }
76 | }
77 |
78 | void ErrorLogger(string format, params string[] args) {
79 | this.Log.LogError(format, args);
80 | }
81 |
82 | }
83 |
84 | }
--------------------------------------------------------------------------------
/Samples/AsmMeta/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("AsmMeta")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyCulture("")]
14 |
15 | // Setting ComVisible to false makes the types in this assembly not visible
16 | // to COM components. If you need to access a type in this assembly from
17 | // COM, set the ComVisible attribute to true on that type.
18 | [assembly: ComVisible(false)]
19 |
20 | // The following GUID is for the ID of the typelib if this project is exposed to COM
21 | [assembly: Guid("5ec36bc2-06a7-4ed3-8714-3c3cfed37c6c")]
22 |
23 |
--------------------------------------------------------------------------------
/Samples/AsmMeta/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Samples/ILMerge/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ILMerge")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("CCI")]
13 | [assembly: AssemblyCopyright("Copyright © 2009")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("243487c9-d080-403a-87e9-da1c60c0f403")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Samples/ILMerge/README.md:
--------------------------------------------------------------------------------
1 | # ILMerge
2 |
3 | ILMerge is a utility that merges multiple .NET assemblies into a single assembly.
4 |
5 | This is the beginning of a port of [ILMerge](https://github.com/Microsoft/ILMerge) to use this version of CCI.
6 | It has some of the rudimentary functionality, but is lacking many (*many*) of the options/features that the
7 | existing version has.
8 |
--------------------------------------------------------------------------------
/Samples/PeToPe/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("PeToPe")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("MSIT")]
12 | [assembly: AssemblyProduct("CCI")]
13 | [assembly: AssemblyCopyright("Copyright © MSIT 2008")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("fd69a30a-319d-48fe-b7c2-2b3d10a263cd")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Samples/PeToText/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using CSharpSourceEmitter;
4 | using Microsoft.Cci;
5 | using Microsoft.Cci.Contracts;
6 | using Microsoft.Cci.ILToCodeModel;
7 | using Microsoft.Cci.MetadataReader;
8 |
9 | namespace PeToText {
10 | class Program {
11 | static void Main(string[] args) {
12 | if (args == null || args.Length == 0) {
13 | Console.WriteLine("usage: peToText [path]fileName.ext [noIL] [noStack]");
14 | return;
15 | }
16 | bool noIL = args.Length >= 2;
17 | bool noStack = args.Length >= 3;
18 | using (var host = new HostEnvironment())
19 | {
20 | IModule/*?*/ module = host.LoadUnitFrom(args[0]) as IModule;
21 | if (module == null || module is Dummy) {
22 | Console.WriteLine(args[0]+" is not a PE file containing a CLR module or assembly.");
23 | return;
24 | }
25 |
26 | PdbReader/*?*/ pdbReader = null;
27 | string pdbFile = Path.ChangeExtension(module.Location, "pdb");
28 | if (File.Exists(pdbFile)) {
29 | using (var pdbStream = File.OpenRead(pdbFile)) {
30 | pdbReader = new PdbReader(pdbStream, host);
31 | }
32 | }
33 | using (pdbReader) {
34 | var options = DecompilerOptions.AnonymousDelegates | DecompilerOptions.Iterators | DecompilerOptions.Loops;
35 | if (noStack) options |= DecompilerOptions.Unstack;
36 | module = Decompiler.GetCodeModelFromMetadataModel(host, module, pdbReader, options);
37 | SourceEmitterOutputString sourceEmitterOutput = new SourceEmitterOutputString();
38 | SourceEmitter csSourceEmitter = new SourceEmitter(sourceEmitterOutput, host, pdbReader, noIL, printCompilerGeneratedMembers:true);
39 | csSourceEmitter.Traverse(module);
40 | string txtFile = Path.ChangeExtension(pdbFile, "txt");
41 | File.WriteAllText(txtFile, sourceEmitterOutput.Data, System.Text.Encoding.UTF8);
42 | }
43 | }
44 | }
45 | }
46 |
47 | internal class HostEnvironment : WindowsRuntimeMetadataReaderHost {
48 | PeReader peReader;
49 | internal HostEnvironment()
50 | : base(new NameTable(), new InternFactory(), 0, null, false, true) {
51 | this.peReader = new PeReader(this);
52 | }
53 |
54 | public override IUnit LoadUnitFrom(string location) {
55 | IUnit result = this.peReader.OpenModule(BinaryDocument.GetBinaryDocumentForFile(location, this));
56 | this.RegisterAsLatest(result);
57 | return result;
58 | }
59 |
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/Samples/PeToText/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("PeToText")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("MSIT")]
12 | [assembly: AssemblyProduct("CCI")]
13 | [assembly: AssemblyCopyright("Copyright © MSIT 2008")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("5831014d-e34d-49e6-9e09-61c455483807")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/AttributeSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter {
11 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
12 |
13 | public virtual void PrintAttributes(IReference target) {
14 | Contract.Requires(target != null);
15 |
16 | foreach (var attribute in SortAttributes(target.Attributes)) {
17 | this.PrintAttribute(target, attribute, true, null);
18 | }
19 | }
20 |
21 | public static IEnumerable SortAttributes(IEnumerable attributes) {
22 | List attrs = new List(attributes);
23 | //Attribute tokens are not stable under repeated compilation of the same source, so we'll sort by attribute type name.
24 | //This is not stable when multiple attributes of the same type are present, but it should be good enough for repeatable tests.
25 | attrs.Sort(new Comparison((a1, a2) => {
26 | return string.CompareOrdinal(TypeHelper.GetTypeName(a1.Type), TypeHelper.GetTypeName(a2.Type));
27 | }));
28 |
29 | return attrs;
30 | }
31 |
32 | public virtual void PrintAttribute(IReference target, ICustomAttribute attribute, bool newLine, string targetType) {
33 | Contract.Requires(attribute != null);
34 |
35 | this.sourceEmitterOutput.Write("[", newLine);
36 | if (targetType != null) {
37 | this.sourceEmitterOutput.Write(targetType);
38 | this.sourceEmitterOutput.Write(": ");
39 | }
40 | this.PrintTypeReferenceName(attribute.Constructor.ContainingType);
41 | if (attribute.NumberOfNamedArguments > 0 || IteratorHelper.EnumerableIsNotEmpty(attribute.Arguments)) {
42 | this.sourceEmitterOutput.Write("(");
43 | bool first = true;
44 | foreach (var argument in attribute.Arguments) {
45 | if (first)
46 | first = false;
47 | else
48 | this.sourceEmitterOutput.Write(", ");
49 | this.Traverse(argument);
50 | }
51 | foreach (var namedArgument in attribute.NamedArguments) {
52 | if (first)
53 | first = false;
54 | else
55 | this.sourceEmitterOutput.Write(", ");
56 | this.Traverse(namedArgument);
57 | }
58 | this.sourceEmitterOutput.Write(")");
59 | }
60 | this.sourceEmitterOutput.Write("]");
61 | if (newLine) this.sourceEmitterOutput.WriteLine("");
62 | }
63 |
64 | ///
65 | /// Prints out a C# attribute which doesn't actually exist as an attribute in the metadata.
66 | ///
67 | ///
68 | /// Perhaps callers should instead construct an ICustomAttribute instance (using some helpers), then they could just
69 | /// call PrintAttribute.
70 | ///
71 | public virtual void PrintPseudoCustomAttribute(IReference target, string typeName, string arguments, bool newLine, string targetType) {
72 | this.sourceEmitterOutput.Write("[", newLine);
73 | if (targetType != null) {
74 | this.sourceEmitterOutput.Write(targetType);
75 | this.sourceEmitterOutput.Write(": ");
76 | }
77 | this.sourceEmitterOutput.Write(typeName);
78 | if (arguments != null) {
79 | this.sourceEmitterOutput.Write("(");
80 | this.sourceEmitterOutput.Write(arguments);
81 | this.sourceEmitterOutput.Write(")");
82 | }
83 | this.sourceEmitterOutput.Write("]");
84 | if (newLine) this.sourceEmitterOutput.WriteLine("");
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/BaseTypeOrInterfaceSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter {
11 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
12 | public virtual void PrintBaseTypeOrInterfaceName(ITypeReference typeReference) {
13 | Contract.Requires(typeReference != null);
14 |
15 | PrintTypeReference(typeReference);
16 | }
17 |
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/BaseTypesAndInterfacesListSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter {
11 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
12 | public virtual void PrintBaseTypesAndInterfacesList(ITypeDefinition typeDefinition) {
13 | Contract.Requires(typeDefinition != null);
14 |
15 | IEnumerable basesList = typeDefinition.BaseClasses;
16 | IEnumerable interfacesList = typeDefinition.Interfaces;
17 |
18 | bool fFirstBase = true;
19 | if (typeDefinition.IsEnum && typeDefinition.UnderlyingType.TypeCode != PrimitiveTypeCode.Int32) {
20 | PrintBaseTypesAndInterfacesColon();
21 | PrintBaseTypeOrInterface(typeDefinition.UnderlyingType);
22 | fFirstBase = false;
23 | }
24 |
25 | foreach (ITypeReference baseTypeReference in basesList) {
26 | if (fFirstBase && TypeHelper.TypesAreEquivalent(baseTypeReference, typeDefinition.PlatformType.SystemObject))
27 | continue;
28 |
29 | if (fFirstBase && TypeHelper.TypesAreEquivalent(baseTypeReference, typeDefinition.PlatformType.SystemValueType))
30 | continue;
31 |
32 | if (TypeHelper.TypesAreEquivalent(baseTypeReference, typeDefinition.PlatformType.SystemEnum))
33 | continue;
34 |
35 | if (fFirstBase)
36 | PrintBaseTypesAndInterfacesColon();
37 | else
38 | PrintBaseTypesAndInterfacesListDelimiter();
39 |
40 | PrintBaseTypeOrInterface(baseTypeReference);
41 | fFirstBase = false;
42 | }
43 |
44 | foreach (ITypeReference interfaceTypeReference in interfacesList) {
45 | if (fFirstBase)
46 | PrintBaseTypesAndInterfacesColon();
47 | else
48 | PrintBaseTypesAndInterfacesListDelimiter();
49 |
50 | PrintBaseTypeOrInterface(interfaceTypeReference);
51 | fFirstBase = false;
52 | }
53 | }
54 |
55 | public virtual void PrintBaseTypesAndInterfacesColon() {
56 | PrintToken(CSharpToken.Space);
57 | PrintToken(CSharpToken.Colon);
58 | PrintToken(CSharpToken.Space);
59 | }
60 |
61 | public virtual void PrintBaseTypesAndInterfacesListDelimiter() {
62 | PrintToken(CSharpToken.Comma);
63 | PrintToken(CSharpToken.Space);
64 | }
65 |
66 | public virtual void PrintBaseTypeOrInterface(ITypeReference baseTypeReference) {
67 | Contract.Requires(baseTypeReference != null);
68 |
69 | PrintBaseTypeOrInterfaceName(baseTypeReference);
70 | }
71 |
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/EventSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter
11 | {
12 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter
13 | {
14 | public override void TraverseChildren(IEventDefinition eventDefinition) {
15 |
16 | PrintAttributes(eventDefinition);
17 | PrintToken(CSharpToken.Indent);
18 | IMethodDefinition eventMeth = eventDefinition.Adder == null ?
19 | eventDefinition.Remover.ResolvedMethod :
20 | eventDefinition.Adder.ResolvedMethod;
21 | if (!eventDefinition.ContainingTypeDefinition.IsInterface &&
22 | IteratorHelper.EnumerableIsEmpty(MemberHelper.GetExplicitlyOverriddenMethods(eventMeth)))
23 | PrintEventDefinitionVisibility(eventDefinition);
24 | PrintMethodDefinitionModifiers(eventMeth);
25 | PrintToken(CSharpToken.Event);
26 | PrintEventDefinitionDelegateType(eventDefinition);
27 | PrintToken(CSharpToken.Space);
28 | PrintEventDefinitionName(eventDefinition);
29 | PrintToken(CSharpToken.Semicolon);
30 | }
31 |
32 | public virtual void PrintEventDefinitionVisibility(IEventDefinition eventDefinition) {
33 | Contract.Requires(eventDefinition != null);
34 |
35 | PrintTypeMemberVisibility(eventDefinition.Visibility);
36 | }
37 |
38 | public virtual void PrintEventDefinitionDelegateType(IEventDefinition eventDefinition) {
39 | Contract.Requires(eventDefinition != null);
40 |
41 | PrintTypeReference(eventDefinition.Type);
42 | }
43 |
44 | public virtual void PrintEventDefinitionName(IEventDefinition eventDefinition) {
45 | Contract.Requires(eventDefinition != null);
46 |
47 | PrintIdentifier(eventDefinition.Name);
48 | }
49 |
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/GenericTypeParameterSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace CSharpSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
11 | public override void TraverseChildren(IGenericTypeParameter genericTypeParameter) {
12 | sourceEmitterOutput.Write(genericTypeParameter.Name.Value);
13 | }
14 |
15 | public override void TraverseChildren(IGenericMethodParameter genericMethodParameter) {
16 | sourceEmitterOutput.Write(genericMethodParameter.Name.Value);
17 | }
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/GenericTypeParametersListSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter {
11 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
12 | public new void Traverse(IEnumerable genericParameters) {
13 | Contract.Requires(genericParameters != null);
14 |
15 | PrintToken(CSharpToken.LeftAngleBracket);
16 |
17 | bool fFirstParameter = true;
18 | foreach (IGenericTypeParameter genericTypeParameter in genericParameters) {
19 | if (!fFirstParameter)
20 | PrintGenericTypeParametersListDelimiter();
21 |
22 | this.Traverse(genericTypeParameter);
23 |
24 | fFirstParameter = false;
25 | }
26 |
27 | PrintToken(CSharpToken.RightAngleBracket);
28 | }
29 |
30 | public new void Traverse(IEnumerable genericParameters) {
31 | Contract.Requires(genericParameters != null);
32 |
33 | PrintToken(CSharpToken.LeftAngleBracket);
34 |
35 | bool fFirstParameter = true;
36 | foreach (IGenericMethodParameter genericMethodParameter in genericParameters) {
37 | if (!fFirstParameter)
38 | PrintGenericTypeParametersListDelimiter();
39 |
40 | this.Traverse(genericMethodParameter);
41 |
42 | fFirstParameter = false;
43 | }
44 |
45 | PrintToken(CSharpToken.RightAngleBracket);
46 | }
47 |
48 | public virtual void PrintGenericTypeParametersListDelimiter() {
49 | PrintToken(CSharpToken.Comma);
50 | PrintToken(CSharpToken.Space);
51 | }
52 |
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/ICSharpSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using Microsoft.Cci;
6 |
7 | namespace CSharpSourceEmitter {
8 | ///
9 | /// This interface is a placeholder only (for now).
10 | /// We would like to derive this interface automatically from an annotated grammar file (X.language).
11 | /// This interface will reflect closely the grammar productions so that the code emitter stays
12 | /// in sync with the parser. For example, it will define methods signatures like these:
13 | ///
14 | /// ...
15 | /// void PrintMethodDefinitionModifiers(IMethodDefinition methodDefinition);
16 | /// void PrintMethodDefinitionVisibility(IMethodDefinition methodDefinition);
17 | /// void PrintMethodDefinitionName(IMethodDefinition methodDefinition);
18 | /// void PrintMethodDefinitionParameters(IMethodDefinition methodDefinition);
19 | /// ...
20 | ///
21 | ///
22 | interface ICSharpSourceEmitter {
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/ISourceEmitterOutput.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 |
8 | namespace CSharpSourceEmitter {
9 | public interface ISourceEmitterOutput {
10 | void WriteLine(string str, bool fIndent);
11 | void WriteLine(string str);
12 | void Write(string str, bool fIndent);
13 | void Write(string str);
14 | void IncreaseIndent();
15 | void DecreaseIndent();
16 |
17 | ///
18 | /// Indicates whether anything has been written to the current line yet
19 | ///
20 | bool CurrentLineEmpty { get; }
21 |
22 | ///
23 | /// Invoked at the start of a new non-empty line, just before writing the indent
24 | ///
25 | event Action LineStart;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/MemberBaseSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace CSharpSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
11 | public virtual void PrintTypeMemberVisibility(TypeMemberVisibility visibility) {
12 | switch (visibility) {
13 | case TypeMemberVisibility.Public:
14 | PrintKeywordPublic();
15 | break;
16 |
17 | case TypeMemberVisibility.Private:
18 | PrintKeywordPrivate();
19 | break;
20 |
21 | case TypeMemberVisibility.Assembly:
22 | PrintKeywordInternal();
23 | break;
24 |
25 | case TypeMemberVisibility.Family:
26 | PrintKeywordProtected();
27 | break;
28 |
29 | case TypeMemberVisibility.FamilyOrAssembly:
30 | PrintKeywordProtectedInternal();
31 | break;
32 |
33 | case TypeMemberVisibility.FamilyAndAssembly:
34 | default:
35 | sourceEmitterOutput.Write("Invalid-visibility ");
36 | break;
37 | }
38 | }
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/NamespaceSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter {
11 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
12 | public override void TraverseChildren(INestedUnitNamespace nestedUnitNamespace) {
13 | PrintNamespaceDefinition((INamespaceDefinition)nestedUnitNamespace);
14 | }
15 |
16 | public virtual void PrintNamespaceDefinition(INamespaceDefinition namespaceDefinition) {
17 | Contract.Requires(namespaceDefinition != null);
18 |
19 | PrintNamespaceDefinitionAttributes(namespaceDefinition);
20 | PrintToken(CSharpToken.Indent);
21 | PrintKeywordNamespace();
22 | PrintNamespaceDefinitionName(namespaceDefinition);
23 | PrintNamespaceDefinitionLeftCurly(namespaceDefinition);
24 | this.Traverse(namespaceDefinition.Members);
25 | PrintNamespaceDefinitionRightCurly(namespaceDefinition);
26 | }
27 |
28 | public virtual void PrintNamespaceDefinitionAttributes(INamespaceDefinition namespaceDefinition) {
29 | Contract.Requires(namespaceDefinition != null);
30 |
31 | foreach (var attribute in SortAttributes(namespaceDefinition.Attributes)) {
32 | PrintAttribute(namespaceDefinition, attribute, true, "assembly");
33 | }
34 | }
35 |
36 | public virtual void PrintNamespaceDefinitionName(INamespaceDefinition namespaceDefinition) {
37 | Contract.Requires(namespaceDefinition != null);
38 |
39 | PrintIdentifier(namespaceDefinition.Name);
40 | }
41 |
42 | public virtual void PrintNamespaceDefinitionLeftCurly(INamespaceDefinition namespaceDefinition) {
43 | PrintToken(CSharpToken.LeftCurly);
44 | }
45 |
46 | public virtual void PrintNamespaceDefinitionRightCurly(INamespaceDefinition namespaceDefinition) {
47 | PrintToken(CSharpToken.RightCurly);
48 | }
49 |
50 | public new virtual void Traverse(IEnumerable namespaceMembers) {
51 | // Try to sort in a way that preserves the original compiler order (captured in token value).
52 | // Put things with no tokens (eg. nested namespaces) before those with tokens, sorted by name
53 | var members = new List(namespaceMembers);
54 | members.Sort(new Comparison((m1, m2) => {
55 | var t1 = m1 as IMetadataObjectWithToken;
56 | var t2 = m2 as IMetadataObjectWithToken;
57 |
58 | if (t1 == null && t2 != null) return -1; //t1 is a namespace and t2 a type, make the namespace come before the type.
59 | if (t1 != null && t2 == null) return 1;
60 | if (t1 != null && t2 != null) {
61 | if (t1.TokenValue == uint.MaxValue) { //t1 does not really have a token
62 | if (t2.TokenValue != uint.MaxValue) return -1;
63 | return m1.Name.Value.CompareTo(m2.Name.Value);
64 | } else if (t2.TokenValue == uint.MaxValue)
65 | return 1;
66 | return ((int)t1.TokenValue) - (int)t2.TokenValue;
67 | }
68 | return m1.Name.Value.CompareTo(m2.Name.Value);
69 | }));
70 |
71 | // Print the members with a blank line between them
72 | VisitWithInterveningBlankLines(members, m => Traverse(m));
73 | }
74 |
75 | public virtual void VisitWithInterveningBlankLines(IEnumerable members, Action onVisit) {
76 | Contract.Requires(members != null);
77 |
78 | // Print the members with a blank line between any non-empty ones
79 | // We go to some effort here to avoid blank lines at the start or end of a block,
80 | // and double blank lines.
81 | bool blankLinePending = false;
82 | bool wroteSomething = false;
83 | var onLineStart = new Action((o) => {
84 | wroteSomething = true;
85 | if (blankLinePending) {
86 | this.sourceEmitterOutput.WriteLine("");
87 | blankLinePending = false;
88 | }
89 | });
90 | this.sourceEmitterOutput.LineStart += onLineStart;
91 | foreach (var member in members) {
92 | wroteSomething = false;
93 | onVisit(member);
94 | // Only output a blank line when we've previously written something, and we're
95 | // about to start writing a new line
96 | if (wroteSomething)
97 | blankLinePending = true;
98 | }
99 | this.sourceEmitterOutput.LineStart -= onLineStart;
100 | }
101 | }
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/ParameterListSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter {
11 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
12 | public new void Traverse(IEnumerable parameters) {
13 | Contract.Requires(parameters != null);
14 |
15 | PrintToken(CSharpToken.LeftParenthesis);
16 |
17 | bool fFirstParameter = true;
18 | foreach (IParameterDefinition parameterDefinition in parameters) {
19 | if (!fFirstParameter)
20 | PrintParameterListDelimiter();
21 |
22 | this.Traverse(parameterDefinition);
23 | fFirstParameter = false;
24 | }
25 |
26 | PrintToken(CSharpToken.RightParenthesis);
27 | }
28 |
29 | public virtual void PrintParameterListDelimiter() {
30 | PrintToken(CSharpToken.Comma);
31 | PrintToken(CSharpToken.Space);
32 | }
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/ParameterSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter {
11 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
12 | public override void TraverseChildren(IParameterDefinition parameterDefinition) {
13 | PrintParameterDefinitionModifiers(parameterDefinition);
14 | PrintParameterDefinitionType(parameterDefinition);
15 | PrintToken(CSharpToken.Space);
16 | PrintParameterDefinitionName(parameterDefinition);
17 | }
18 |
19 | public virtual void PrintParameterDefinitionModifiers(IParameterDefinition parameterDefinition) {
20 | Contract.Requires(parameterDefinition != null);
21 |
22 | if (parameterDefinition.Index == 0) {
23 | var meth = parameterDefinition.ContainingSignature as IMethodDefinition;
24 | if (meth != null ) {
25 | if (Utils.FindAttribute(meth.Attributes, SpecialAttribute.Extension) != null) {
26 | PrintToken(CSharpToken.This);
27 | PrintToken(CSharpToken.Space);
28 | }
29 | }
30 | }
31 |
32 | foreach (var attribute in SortAttributes(parameterDefinition.Attributes)) {
33 | if (Utils.GetAttributeType(attribute) == SpecialAttribute.ParamArray)
34 | sourceEmitterOutput.Write("params");
35 | else
36 | this.PrintAttribute(parameterDefinition, attribute, false, null);
37 |
38 | PrintToken(CSharpToken.Space);
39 | }
40 | if (parameterDefinition.IsOut && !parameterDefinition.IsIn && parameterDefinition.IsByReference) {
41 | // C# out keyword means [Out] ref (with no [In] allowed)
42 | PrintKeywordOut();
43 | } else {
44 | if (parameterDefinition.IsIn)
45 | PrintPseudoCustomAttribute(parameterDefinition, "System.Runtime.InteropServices.In", null, false, null);
46 | if (parameterDefinition.IsOut)
47 | PrintPseudoCustomAttribute(parameterDefinition, "System.Runtime.InteropServices.Out", null, false, null);
48 | if (parameterDefinition.IsByReference)
49 | PrintKeywordRef();
50 | }
51 | }
52 |
53 | public virtual void PrintParameterDefinitionType(IParameterDefinition parameterDefinition) {
54 | Contract.Requires(parameterDefinition != null);
55 |
56 | PrintTypeReference(parameterDefinition.Type);
57 | }
58 |
59 | public virtual void PrintParameterDefinitionName(IParameterDefinition parameterDefinition) {
60 | Contract.Requires(parameterDefinition != null);
61 |
62 | PrintIdentifier(parameterDefinition.Name);
63 | }
64 |
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("CSharpCodeEmitter")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("CCI")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("fff4706c-8bed-49b5-85da-15c4fc4c2150")]
25 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/PropertySourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter {
11 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
12 | public override void TraverseChildren(IPropertyDefinition propertyDefinition) {
13 |
14 | PrintAttributes(propertyDefinition);
15 |
16 | bool isIndexer = false;
17 | if (IteratorHelper.EnumerableIsNotEmpty(propertyDefinition.Parameters)) {
18 | // We have an indexer. Note that this could still be an explicit interface implementation.
19 | // If it's got a name other than 'Item', we need an attribute to rename it.
20 | // Note that there will usually be a DefaultMemberAttribute on the class with the name
21 | // but the attribute doesn't always exist (eg. if it's an explicit interaface impl)
22 | isIndexer = true;
23 | string id = propertyDefinition.Name.Value;
24 | string simpleId = id.Substring(id.LastIndexOf('.') + 1); // excludes any interface type
25 | if (simpleId != "Item") {
26 | PrintPseudoCustomAttribute(propertyDefinition, "System.Runtime.CompilerServices.IndexerName", QuoteString(simpleId), true, null);
27 | }
28 | }
29 |
30 | PrintToken(CSharpToken.Indent);
31 |
32 | IMethodDefinition propMeth = propertyDefinition.Getter == null ?
33 | propertyDefinition.Setter.ResolvedMethod :
34 | propertyDefinition.Getter.ResolvedMethod;
35 | if (!propertyDefinition.ContainingTypeDefinition.IsInterface &&
36 | IteratorHelper.EnumerableIsEmpty(MemberHelper.GetExplicitlyOverriddenMethods(propMeth)))
37 | PrintPropertyDefinitionVisibility(propertyDefinition);
38 | PrintPropertyDefinitionModifiers(propertyDefinition);
39 | PrintPropertyDefinitionReturnType(propertyDefinition);
40 | PrintToken(CSharpToken.Space);
41 |
42 | if (isIndexer) {
43 | // Indexers are always identified with a 'this' keyword, but might have an interface prefix
44 | string id = propertyDefinition.Name.Value;
45 | int lastDot = id.LastIndexOf('.');
46 | if (lastDot != -1)
47 | sourceEmitterOutput.Write(id.Substring(0, lastDot +1));
48 | PrintToken(CSharpToken.This);
49 | PrintToken(CSharpToken.LeftSquareBracket);
50 | bool fFirstParameter = true;
51 | var parms = propertyDefinition.Parameters;
52 | if (propertyDefinition.Getter != null)
53 | parms = propertyDefinition.Getter.ResolvedMethod.Parameters; // more likely to have names
54 | else if (propertyDefinition.Setter != null) {
55 | // Use the setter's names except for the final 'value' parameter
56 | var l = new List(propertyDefinition.Setter.ResolvedMethod.Parameters);
57 | l.RemoveAt(l.Count - 1);
58 | parms = l;
59 | }
60 | foreach (IParameterDefinition parameterDefinition in parms) {
61 | if (!fFirstParameter)
62 | PrintParameterListDelimiter();
63 | this.Traverse(parameterDefinition);
64 | fFirstParameter = false;
65 | }
66 | PrintToken(CSharpToken.RightSquareBracket);
67 | } else {
68 | PrintPropertyDefinitionName(propertyDefinition);
69 | }
70 | PrintToken(CSharpToken.LeftCurly);
71 | if (propertyDefinition.Getter != null) {
72 | PrintToken(CSharpToken.Indent);
73 | var getMeth = propertyDefinition.Getter.ResolvedMethod;
74 | if (getMeth.Visibility != propertyDefinition.Visibility)
75 | PrintTypeMemberVisibility(getMeth.Visibility);
76 | PrintToken(CSharpToken.Get);
77 | if (getMeth.IsAbstract || getMeth.IsExternal)
78 | PrintToken(CSharpToken.Semicolon);
79 | else
80 | Traverse(getMeth.Body);
81 | }
82 | if (propertyDefinition.Setter != null) {
83 | PrintToken(CSharpToken.Indent);
84 | var setMeth = propertyDefinition.Setter.ResolvedMethod;
85 | if (setMeth.Visibility != propertyDefinition.Visibility)
86 | PrintTypeMemberVisibility(setMeth.Visibility);
87 | PrintToken(CSharpToken.Set);
88 | if (setMeth.IsAbstract || setMeth.IsExternal)
89 | PrintToken(CSharpToken.Semicolon);
90 | else
91 | Traverse(setMeth.Body);
92 | }
93 | PrintToken(CSharpToken.RightCurly);
94 | }
95 |
96 | public virtual void PrintPropertyDefinitionVisibility(IPropertyDefinition propertyDefinition) {
97 | Contract.Requires(propertyDefinition != null);
98 |
99 | PrintTypeMemberVisibility(propertyDefinition.Visibility);
100 | }
101 |
102 | public virtual void PrintPropertyDefinitionReturnType(IPropertyDefinition propertyDefinition) {
103 | Contract.Requires(propertyDefinition != null);
104 |
105 | PrintTypeReference(propertyDefinition.Type);
106 | }
107 |
108 | public virtual void PrintPropertyDefinitionName(IPropertyDefinition propertyDefinition) {
109 | Contract.Requires(propertyDefinition != null);
110 |
111 | PrintIdentifier(propertyDefinition.Name);
112 | }
113 |
114 | public virtual void PrintPropertyDefinitionModifiers(IPropertyDefinition propertyDefinition) {
115 | Contract.Requires(propertyDefinition != null);
116 |
117 | PrintMethodDefinitionModifiers(propertyDefinition.Getter == null ?
118 | propertyDefinition.Setter.ResolvedMethod :
119 | propertyDefinition.Getter.ResolvedMethod);
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/SourceEmitterOutputString.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using System.IO;
8 |
9 | namespace CSharpSourceEmitter {
10 | public class SourceEmitterOutputString : SourceEmitterOutputTextWriter {
11 | public SourceEmitterOutputString()
12 | : base(new StringWriter()) {
13 | }
14 |
15 | public SourceEmitterOutputString(int indentLevel)
16 | : base(new StringWriter(), indentLevel) {
17 | }
18 |
19 | public string Data {
20 | get {
21 | return ((StringWriter)this.outputWriter).ToString();
22 | }
23 | }
24 |
25 | public void ClearData() {
26 | var sw = (StringWriter)this.outputWriter;
27 | sw.Flush();
28 | sw.GetStringBuilder().Length = 0;
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/SourceEmitterOutputTextWriter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using System.IO;
8 |
9 | namespace CSharpSourceEmitter {
10 | public class SourceEmitterOutputTextWriter : ISourceEmitterOutput {
11 |
12 | public SourceEmitterOutputTextWriter(TextWriter outputWriter, int indentSize) {
13 | this.outputWriter = outputWriter;
14 | this.indentLevel = indentSize;
15 | this.strIndent = "";
16 | this.CurrentLineEmpty = true;
17 | }
18 |
19 | public SourceEmitterOutputTextWriter(TextWriter outputWriter) : this(outputWriter, 4)
20 | {
21 | }
22 |
23 | public virtual void WriteLine(string str, bool fIndent) {
24 | OutputBegin(fIndent);
25 | outputWriter.WriteLine(str);
26 | this.CurrentLineEmpty = true;
27 | }
28 |
29 | public virtual void WriteLine(string str) {
30 | WriteLine(str, false);
31 | }
32 |
33 | public virtual void Write(string str, bool fIndent) {
34 | OutputBegin(fIndent);
35 | outputWriter.Write(str);
36 | this.CurrentLineEmpty = false;
37 | }
38 |
39 | public virtual void Write(string str) {
40 | Write(str, false);
41 | }
42 |
43 | public virtual void IncreaseIndent() {
44 | int newIndent = strIndent.Length + indentLevel;
45 | strIndent = new String(' ', newIndent);
46 | }
47 |
48 | public virtual void DecreaseIndent() {
49 | int newIndent = strIndent.Length - indentLevel;
50 | strIndent = new String(' ', newIndent);
51 | }
52 |
53 | public bool CurrentLineEmpty {
54 | get;
55 | private set;
56 | }
57 |
58 | public event Action LineStart;
59 |
60 | protected virtual void OutputBegin(bool fIndent)
61 | {
62 | if (fIndent) {
63 | if (LineStart != null)
64 | LineStart(this);
65 | outputWriter.Write(strIndent);
66 | }
67 | }
68 |
69 | protected TextWriter outputWriter;
70 | protected string strIndent;
71 | protected readonly int indentLevel;
72 | }
73 |
74 | public class SourceEmitterOutputConsole : SourceEmitterOutputTextWriter {
75 | public SourceEmitterOutputConsole(int indentSize) :
76 | base(System.Console.Out, indentSize)
77 | {
78 | }
79 |
80 | public SourceEmitterOutputConsole() :
81 | base(System.Console.Out)
82 | {
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/TypeReferenceSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 | using System.Diagnostics.Contracts;
9 |
10 | namespace CSharpSourceEmitter {
11 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
12 | public virtual void PrintTypeReference(ITypeReference typeReference) {
13 | Contract.Requires(typeReference != null);
14 |
15 | PrintTypeReferenceName(typeReference);
16 | }
17 |
18 | public virtual void PrintTypeReferenceName(ITypeReference typeReference) {
19 | Contract.Requires(typeReference != null);
20 |
21 | var typeName = TypeHelper.GetTypeName(typeReference,
22 | NameFormattingOptions.ContractNullable|NameFormattingOptions.UseTypeKeywords|
23 | NameFormattingOptions.TypeParameters|NameFormattingOptions.EmptyTypeParameterList|
24 | NameFormattingOptions.OmitCustomModifiers);
25 | sourceEmitterOutput.Write(typeName);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/SourceEmitters/CSharpSourceEmitter/TypeSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace CSharpSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, ICSharpSourceEmitter {
11 | public override void TraverseChildren(INamespaceTypeDefinition namespaceTypeDefinition) {
12 | PrintTypeDefinition(namespaceTypeDefinition as ITypeDefinition);
13 | }
14 |
15 | public override void TraverseChildren(INestedTypeDefinition nestedTypeDefinition) {
16 | if (!this.printCompilerGeneratedMembers && AttributeHelper.Contains(nestedTypeDefinition.Attributes, nestedTypeDefinition.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute))
17 | return;
18 | PrintTypeDefinition(nestedTypeDefinition as ITypeDefinition);
19 | }
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/SourceEmitters/SourceEmitter/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("SourceEmitter")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyProduct("SourceEmitter")]
15 | [assembly: AssemblyTrademark("")]
16 | [assembly: AssemblyCulture("")]
17 |
18 | // Setting ComVisible to false makes the types in this assembly not visible
19 | // to COM components. If you need to access a type in this assembly from
20 | // COM, set the ComVisible attribute to true on that type.
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 | [assembly: Guid("f3b6d4dc-ce62-4215-830f-e1895964c7c0")]
25 |
26 |
--------------------------------------------------------------------------------
/SourceEmitters/SourceEmitter/SourceEmitter.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 8.0.30703
7 | 2.0
8 | {584898C1-C197-4D9A-8231-90B41C2793C9}
9 | Library
10 | Properties
11 | Microsoft.Cci
12 | Microsoft.Cci.SourceEmitter
13 | v4.5
14 | 512
15 | SAK
16 | SAK
17 | SAK
18 | SAK
19 | 0
20 |
21 |
22 | true
23 | full
24 | false
25 | bin\Debug\
26 | DEBUG;TRACE
27 | prompt
28 | 4
29 | True
30 | False
31 | True
32 | False
33 | False
34 | True
35 | True
36 | True
37 | True
38 | True
39 | False
40 | True
41 | True
42 | True
43 | True
44 | False
45 | True
46 | False
47 | False
48 | True
49 | True
50 | False
51 | True
52 |
53 |
54 |
55 |
56 |
57 |
58 | True
59 | Full
60 | Build
61 | 2
62 | bin\Debug\Microsoft.Cci.SourceEmitter.XML
63 | True
64 | cloudotserver
65 | False
66 |
67 |
68 | pdbonly
69 | true
70 | bin\Release\
71 | TRACE
72 | prompt
73 | 4
74 |
75 |
76 | false
77 |
78 |
79 |
80 | Build\Version.cs
81 |
82 |
83 |
84 |
85 |
86 |
93 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/AttributeSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 |
12 | public virtual void PrintAttributes(IReference target) {
13 | foreach (var attribute in target.Attributes) {
14 | this.PrintAttribute(target, attribute, true, null);
15 | }
16 | }
17 |
18 | public virtual void PrintAttribute(IReference target, ICustomAttribute attribute, bool newLine, string targetType) {
19 | this.sourceEmitterOutput.Write("[", newLine);
20 | if (targetType != null) {
21 | this.sourceEmitterOutput.Write(targetType);
22 | this.sourceEmitterOutput.Write(": ");
23 | }
24 | this.PrintTypeReferenceName(attribute.Constructor.ContainingType);
25 | if (attribute.NumberOfNamedArguments > 0 || IteratorHelper.EnumerableIsNotEmpty(attribute.Arguments)) {
26 | this.sourceEmitterOutput.Write("(");
27 | bool first = true;
28 | foreach (var argument in attribute.Arguments) {
29 | if (first)
30 | first = false;
31 | else
32 | this.sourceEmitterOutput.Write(", ");
33 | this.Traverse(argument);
34 | }
35 | foreach (var namedArgument in attribute.NamedArguments) {
36 | if (first)
37 | first = false;
38 | else
39 | this.sourceEmitterOutput.Write(", ");
40 | this.Traverse(namedArgument);
41 | }
42 | this.sourceEmitterOutput.Write(")");
43 | }
44 | this.sourceEmitterOutput.Write("]");
45 | if (newLine) this.sourceEmitterOutput.WriteLine("");
46 | }
47 |
48 | ///
49 | /// Prints out a C# attribute which doesn't actually exist as an attribute in the metadata.
50 | ///
51 | ///
52 | /// Perhaps callers should instead construct an ICustomAttribute instance (using some helpers), then they could just
53 | /// call PrintAttribute.
54 | ///
55 | public virtual void PrintPseudoCustomAttribute(IReference target, string typeName, string arguments, bool newLine, string targetType) {
56 | this.sourceEmitterOutput.Write("[", newLine);
57 | if (targetType != null) {
58 | this.sourceEmitterOutput.Write(targetType);
59 | this.sourceEmitterOutput.Write(": ");
60 | }
61 | this.sourceEmitterOutput.Write(typeName);
62 | if (arguments != null) {
63 | this.sourceEmitterOutput.Write("(");
64 | this.sourceEmitterOutput.Write(arguments);
65 | this.sourceEmitterOutput.Write(")");
66 | }
67 | this.sourceEmitterOutput.Write("]");
68 | if (newLine) this.sourceEmitterOutput.WriteLine("");
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/BaseTypeOrInterfaceSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public virtual void PrintBaseTypeOrInterfaceName(ITypeReference typeReference) {
12 | PrintTypeReference(typeReference);
13 | }
14 |
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/BaseTypesAndInterfacesListSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public virtual void PrintBaseTypesAndInterfacesList(ITypeDefinition typeDefinition) {
12 | IEnumerable basesList = typeDefinition.BaseClasses;
13 | IEnumerable interfacesList = typeDefinition.Interfaces;
14 |
15 | bool fFirstBase = true;
16 | if (typeDefinition.IsEnum && typeDefinition.UnderlyingType.TypeCode != PrimitiveTypeCode.Int32) {
17 | PrintBaseTypesAndInterfacesColon();
18 | PrintBaseTypeOrInterface(typeDefinition.UnderlyingType);
19 | fFirstBase = false;
20 | }
21 |
22 | foreach (ITypeReference baseTypeReference in basesList) {
23 | if (fFirstBase && TypeHelper.TypesAreEquivalent(baseTypeReference, typeDefinition.PlatformType.SystemObject))
24 | continue;
25 |
26 | if (fFirstBase && TypeHelper.TypesAreEquivalent(baseTypeReference, typeDefinition.PlatformType.SystemValueType))
27 | continue;
28 |
29 | if (TypeHelper.TypesAreEquivalent(baseTypeReference, typeDefinition.PlatformType.SystemEnum))
30 | continue;
31 |
32 | if (fFirstBase)
33 | PrintBaseTypesAndInterfacesColon();
34 | else
35 | PrintBaseTypesAndInterfacesListDelimiter();
36 |
37 | PrintBaseTypeOrInterface(baseTypeReference);
38 | fFirstBase = false;
39 | }
40 |
41 | foreach (ITypeReference interfaceTypeReference in interfacesList) {
42 | if (fFirstBase)
43 | PrintBaseTypesAndInterfacesColon();
44 | else
45 | PrintBaseTypesAndInterfacesListDelimiter();
46 |
47 | PrintBaseTypeOrInterface(interfaceTypeReference);
48 | fFirstBase = false;
49 | }
50 | }
51 |
52 | public virtual void PrintBaseTypesAndInterfacesColon() {
53 | PrintToken(VBToken.Space);
54 | PrintToken(VBToken.Colon);
55 | PrintToken(VBToken.Space);
56 | }
57 |
58 | public virtual void PrintBaseTypesAndInterfacesListDelimiter() {
59 | PrintToken(VBToken.Comma);
60 | PrintToken(VBToken.Space);
61 | }
62 |
63 | public virtual void PrintBaseTypeOrInterface(ITypeReference baseTypeReference) {
64 | PrintBaseTypeOrInterfaceName(baseTypeReference);
65 | }
66 |
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/EventSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter
10 | {
11 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter
12 | {
13 | public override void TraverseChildren(IEventDefinition eventDefinition) {
14 |
15 | PrintAttributes(eventDefinition);
16 | PrintToken(VBToken.Indent);
17 | IMethodDefinition eventMeth = eventDefinition.Adder == null ?
18 | eventDefinition.Remover.ResolvedMethod :
19 | eventDefinition.Adder.ResolvedMethod;
20 | if (!eventDefinition.ContainingTypeDefinition.IsInterface &&
21 | IteratorHelper.EnumerableIsEmpty(MemberHelper.GetExplicitlyOverriddenMethods(eventMeth)))
22 | PrintEventDefinitionVisibility(eventDefinition);
23 | PrintMethodDefinitionModifiers(eventMeth);
24 | PrintToken(VBToken.Event);
25 | PrintEventDefinitionDelegateType(eventDefinition);
26 | PrintToken(VBToken.Space);
27 | PrintEventDefinitionName(eventDefinition);
28 | PrintToken(VBToken.Semicolon);
29 | }
30 |
31 | public virtual void PrintEventDefinitionVisibility(IEventDefinition eventDefinition) {
32 | PrintTypeMemberVisibility(eventDefinition.Visibility);
33 | }
34 |
35 | public virtual void PrintEventDefinitionDelegateType(IEventDefinition eventDefinition) {
36 | PrintTypeReference(eventDefinition.Type);
37 | }
38 |
39 | public virtual void PrintEventDefinitionName(IEventDefinition eventDefinition) {
40 | PrintIdentifier(eventDefinition.Name);
41 | }
42 |
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/GenericTypeParameterSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public override void TraverseChildren(IGenericTypeParameter genericTypeParameter) {
12 | sourceEmitterOutput.Write(genericTypeParameter.Name.Value);
13 | }
14 |
15 | public override void TraverseChildren(IGenericMethodParameter genericMethodParameter) {
16 | sourceEmitterOutput.Write(genericMethodParameter.Name.Value);
17 | }
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/GenericTypeParametersListSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public new void Traverse(IEnumerable genericParameters) {
12 | PrintToken(VBToken.LeftAngleBracket);
13 |
14 | bool fFirstParameter = true;
15 | foreach (IGenericTypeParameter genericTypeParameter in genericParameters) {
16 | if (!fFirstParameter)
17 | PrintGenericTypeParametersListDelimiter();
18 |
19 | this.Traverse(genericTypeParameter);
20 |
21 | fFirstParameter = false;
22 | }
23 |
24 | PrintToken(VBToken.RightAngleBracket);
25 | }
26 |
27 | public new void Traverse(IEnumerable genericParameters) {
28 | PrintToken(VBToken.LeftAngleBracket);
29 |
30 | bool fFirstParameter = true;
31 | foreach (IGenericMethodParameter genericMethodParameter in genericParameters) {
32 | if (!fFirstParameter)
33 | PrintGenericTypeParametersListDelimiter();
34 |
35 | this.Traverse(genericMethodParameter);
36 |
37 | fFirstParameter = false;
38 | }
39 |
40 | PrintToken(VBToken.RightAngleBracket);
41 | }
42 |
43 | public virtual void PrintGenericTypeParametersListDelimiter() {
44 | PrintToken(VBToken.Comma);
45 | PrintToken(VBToken.Space);
46 | }
47 |
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/ISourceEmitterOutput.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 |
8 | namespace VBSourceEmitter {
9 | public interface ISourceEmitterOutput {
10 | void WriteLine(string str, bool fIndent);
11 | void WriteLine(string str);
12 | void Write(string str, bool fIndent);
13 | void Write(string str);
14 | void IncreaseIndent();
15 | void DecreaseIndent();
16 |
17 | ///
18 | /// Indicates whether anything has been written to the current line yet
19 | ///
20 | bool CurrentLineEmpty { get; }
21 |
22 | ///
23 | /// Invoked at the start of a new non-empty line, just before writing the indent
24 | ///
25 | event Action LineStart;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/IVBSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using Microsoft.Cci;
6 |
7 | namespace VBSourceEmitter {
8 | ///
9 | /// This interface is a placeholder only (for now).
10 | /// We would like to derive this interface automatically from an annotated grammar file (X.language).
11 | /// This interface will reflect closely the grammar productions so that the code emitter stays
12 | /// in sync with the parser. For example, it will define methods signatures like these:
13 | ///
14 | /// ...
15 | /// void PrintMethodDefinitionModifiers(IMethodDefinition methodDefinition);
16 | /// void PrintMethodDefinitionVisibility(IMethodDefinition methodDefinition);
17 | /// void PrintMethodDefinitionName(IMethodDefinition methodDefinition);
18 | /// void PrintMethodDefinitionParameters(IMethodDefinition methodDefinition);
19 | /// ...
20 | ///
21 | ///
22 | interface IVBSourceEmitter {
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/MemberBaseSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public virtual void PrintTypeMemberVisibility(TypeMemberVisibility visibility) {
12 | switch (visibility) {
13 | case TypeMemberVisibility.Public:
14 | PrintKeywordPublic();
15 | break;
16 |
17 | case TypeMemberVisibility.Private:
18 | PrintKeywordPrivate();
19 | break;
20 |
21 | case TypeMemberVisibility.Assembly:
22 | PrintKeywordInternal();
23 | break;
24 |
25 | case TypeMemberVisibility.Family:
26 | PrintKeywordProtected();
27 | break;
28 |
29 | case TypeMemberVisibility.FamilyOrAssembly:
30 | PrintKeywordProtectedInternal();
31 | break;
32 |
33 | case TypeMemberVisibility.FamilyAndAssembly:
34 | default:
35 | sourceEmitterOutput.Write("Invalid-visibility ");
36 | break;
37 | }
38 | }
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/NamespaceSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public override void TraverseChildren(INestedUnitNamespace nestedUnitNamespace) {
12 | PrintNamespaceDefinition((INamespaceDefinition)nestedUnitNamespace);
13 | }
14 |
15 | public virtual void PrintNamespaceDefinition(INamespaceDefinition namespaceDefinition) {
16 | PrintNamespaceDefinitionAttributes(namespaceDefinition);
17 | PrintToken(VBToken.Indent);
18 | PrintKeywordNamespace();
19 | PrintNamespaceDefinitionName(namespaceDefinition);
20 | //PrintNamespaceDefinitionLeftCurly(namespaceDefinition);
21 | this.Traverse(namespaceDefinition.Members);
22 | //PrintNamespaceDefinitionRightCurly(namespaceDefinition);
23 | }
24 |
25 | public virtual void PrintNamespaceDefinitionAttributes(INamespaceDefinition namespaceDefinition) {
26 | foreach (var attribute in namespaceDefinition.Attributes) {
27 | PrintAttribute(namespaceDefinition, attribute, true, "assembly");
28 | }
29 | }
30 |
31 | public virtual void PrintNamespaceDefinitionName(INamespaceDefinition namespaceDefinition) {
32 | PrintIdentifier(namespaceDefinition.Name);
33 | }
34 |
35 | //public virtual void PrintNamespaceDefinitionLeftCurly(INamespaceDefinition namespaceDefinition) {
36 | // PrintToken(CSharpToken.LeftCurly);
37 | //}
38 |
39 | //public virtual void PrintNamespaceDefinitionRightCurly(INamespaceDefinition namespaceDefinition) {
40 | // PrintToken(CSharpToken.RightCurly);
41 | //}
42 |
43 | public new void Traverse(IEnumerable namespaceMembers) {
44 | // Try to sort in a way that preserves the original compiler order (captured in token value).
45 | // Put things with no tokens (eg. nested namespaces) after those with tokens, sorted by name
46 | var members = new List(namespaceMembers);
47 | members.Sort(new Comparison((m1, m2) =>
48 | {
49 | var t1 = m1 as IMetadataObjectWithToken;
50 | var t2 = m2 as IMetadataObjectWithToken;
51 |
52 | var tc = (t1 == null).CompareTo(t2 == null);
53 | if (tc != 0)
54 | return tc;
55 |
56 | if (t1 != null)
57 | return t1.TokenValue.CompareTo(t2.TokenValue);
58 |
59 | return m1.Name.Value.CompareTo(m2.Name.Value);
60 | }));
61 |
62 | // Print the members with a blank line between them
63 | VisitWithInterveningBlankLines(members, m => Traverse(m));
64 | }
65 |
66 | public virtual void VisitWithInterveningBlankLines(IEnumerable members, Action onVisit) {
67 | // Print the members with a blank line between any non-empty ones
68 | // We go to some effort here to avoid blank lines at the start or end of a block,
69 | // and double blank lines.
70 | bool blankLinePending = false;
71 | bool wroteSomething = false;
72 | var onLineStart = new Action((o) => {
73 | wroteSomething = true;
74 | if (blankLinePending) {
75 | this.sourceEmitterOutput.WriteLine("");
76 | blankLinePending = false;
77 | }
78 | });
79 | this.sourceEmitterOutput.LineStart += onLineStart;
80 | foreach (var member in members) {
81 | wroteSomething = false;
82 | onVisit(member);
83 | // Only output a blank line when we've previously written something, and we're
84 | // about to start writing a new line
85 | if (wroteSomething)
86 | blankLinePending = true;
87 | }
88 | this.sourceEmitterOutput.LineStart -= onLineStart;
89 | }
90 | }
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/ParameterListSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public new void Traverse(IEnumerable parameters) {
12 | PrintToken(VBToken.LeftParenthesis);
13 |
14 | bool fFirstParameter = true;
15 | foreach (IParameterDefinition parameterDefinition in parameters) {
16 | if (!fFirstParameter)
17 | PrintParameterListDelimiter();
18 |
19 | this.Traverse(parameterDefinition);
20 | fFirstParameter = false;
21 | }
22 |
23 | PrintToken(VBToken.RightParenthesis);
24 | }
25 |
26 | public virtual void PrintParameterListDelimiter() {
27 | PrintToken(VBToken.Comma);
28 | PrintToken(VBToken.Space);
29 | }
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/ParameterSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public override void TraverseChildren(IParameterDefinition parameterDefinition) {
12 | PrintParameterDefinitionModifiers(parameterDefinition);
13 | PrintParameterDefinitionName(parameterDefinition);
14 | PrintToken(VBToken.Space);
15 | PrintToken(VBToken.As);
16 | PrintToken(VBToken.Space);
17 | PrintParameterDefinitionType(parameterDefinition);
18 | }
19 |
20 | public virtual void PrintParameterDefinitionModifiers(IParameterDefinition parameterDefinition) {
21 |
22 | if (parameterDefinition.Index == 0) {
23 | var meth = parameterDefinition.ContainingSignature as IMethodDefinition;
24 | if (meth != null ) {
25 | if (Utils.FindAttribute(meth.Attributes, SpecialAttribute.Extension) != null) {
26 | PrintToken(VBToken.This);
27 | PrintToken(VBToken.Space);
28 | }
29 | }
30 | }
31 |
32 | foreach (var attribute in parameterDefinition.Attributes) {
33 | if (Utils.GetAttributeType(attribute) == SpecialAttribute.ParamArray)
34 | sourceEmitterOutput.Write("params");
35 | else
36 | this.PrintAttribute(parameterDefinition, attribute, false, null);
37 |
38 | PrintToken(VBToken.Space);
39 | }
40 | if (parameterDefinition.IsOut && !parameterDefinition.IsIn && parameterDefinition.IsByReference) {
41 | // C# out keyword means [Out] ref (with no [In] allowed)
42 | PrintKeywordOut();
43 | } else {
44 | if (parameterDefinition.IsIn)
45 | PrintPseudoCustomAttribute(parameterDefinition, "System.Runtime.InteropServices.In", null, false, null);
46 | if (parameterDefinition.IsOut)
47 | PrintPseudoCustomAttribute(parameterDefinition, "System.Runtime.InteropServices.Out", null, false, null);
48 | if (parameterDefinition.IsByReference)
49 | PrintKeywordRef();
50 | }
51 | }
52 |
53 | public virtual void PrintParameterDefinitionType(IParameterDefinition parameterDefinition) {
54 | PrintTypeReference(parameterDefinition.Type);
55 | }
56 |
57 | public virtual void PrintParameterDefinitionName(IParameterDefinition parameterDefinition) {
58 | PrintIdentifier(parameterDefinition.Name);
59 | }
60 |
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 |
8 | // General Information about an assembly is controlled through the following
9 | // set of attributes. Change these attribute values to modify the information
10 | // associated with an assembly.
11 | [assembly: AssemblyTitle("VBSourceEmitter")]
12 | [assembly: AssemblyDescription("")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyCompany("MSIT")]
15 | [assembly: AssemblyProduct("VBSourceEmitter")]
16 | [assembly: AssemblyCopyright("Copyright © MSIT 2012")]
17 | [assembly: AssemblyTrademark("")]
18 | [assembly: AssemblyCulture("")]
19 |
20 | // Setting ComVisible to false makes the types in this assembly not visible
21 | // to COM components. If you need to access a type in this assembly from
22 | // COM, set the ComVisible attribute to true on that type.
23 | [assembly: ComVisible(false)]
24 |
25 | // The following GUID is for the ID of the typelib if this project is exposed to COM
26 | [assembly: Guid("3ac125c4-7182-4a33-88f6-db62596880f0")]
27 |
28 | // Version information for an assembly consists of the following four values:
29 | //
30 | // Major Version
31 | // Minor Version
32 | // Build Number
33 | // Revision
34 | //
35 | // You can specify all the values or you can default the Build and Revision Numbers
36 | // by using the '*' as shown below:
37 | // [assembly: AssemblyVersion("1.0.*")]
38 | [assembly: AssemblyVersion("1.0.0.0")]
39 | [assembly: AssemblyFileVersion("1.0.0.0")]
40 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/PropertySourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public override void TraverseChildren(IPropertyDefinition propertyDefinition) {
12 |
13 | PrintAttributes(propertyDefinition);
14 |
15 | bool isIndexer = false;
16 | if (IteratorHelper.EnumerableIsNotEmpty(propertyDefinition.Parameters)) {
17 | // We have an indexer. Note that this could still be an explicit interface implementation.
18 | // If it's got a name other than 'Item', we need an attribute to rename it.
19 | // Note that there will usually be a DefaultMemberAttribute on the class with the name
20 | // but the attribute doesn't always exist (eg. if it's an explicit interaface impl)
21 | isIndexer = true;
22 | string id = propertyDefinition.Name.Value;
23 | string simpleId = id.Substring(id.LastIndexOf('.') + 1); // excludes any interface type
24 | if (simpleId != "Item") {
25 | PrintPseudoCustomAttribute(propertyDefinition, "System.Runtime.CompilerServices.IndexerName", QuoteString(simpleId), true, null);
26 | }
27 | }
28 |
29 | PrintToken(VBToken.Indent);
30 |
31 | IMethodDefinition propMeth = propertyDefinition.Getter == null ?
32 | propertyDefinition.Setter.ResolvedMethod :
33 | propertyDefinition.Getter.ResolvedMethod;
34 | if (!propertyDefinition.ContainingTypeDefinition.IsInterface &&
35 | IteratorHelper.EnumerableIsEmpty(MemberHelper.GetExplicitlyOverriddenMethods(propMeth)))
36 | PrintPropertyDefinitionVisibility(propertyDefinition);
37 | PrintPropertyDefinitionModifiers(propertyDefinition);
38 | PrintPropertyDefinitionReturnType(propertyDefinition);
39 | PrintToken(VBToken.Space);
40 |
41 | if (isIndexer) {
42 | // Indexers are always identified with a 'this' keyword, but might have an interface prefix
43 | string id = propertyDefinition.Name.Value;
44 | int lastDot = id.LastIndexOf('.');
45 | if (lastDot != -1)
46 | sourceEmitterOutput.Write(id.Substring(0, lastDot +1));
47 | PrintToken(VBToken.This);
48 | PrintToken(VBToken.LeftSquareBracket);
49 | bool fFirstParameter = true;
50 | var parms = propertyDefinition.Parameters;
51 | if (propertyDefinition.Getter != null)
52 | parms = propertyDefinition.Getter.ResolvedMethod.Parameters; // more likely to have names
53 | else if (propertyDefinition.Setter != null) {
54 | // Use the setter's names except for the final 'value' parameter
55 | var l = new List(propertyDefinition.Setter.ResolvedMethod.Parameters);
56 | l.RemoveAt(l.Count - 1);
57 | parms = l;
58 | }
59 | foreach (IParameterDefinition parameterDefinition in parms) {
60 | if (!fFirstParameter)
61 | PrintParameterListDelimiter();
62 | this.Traverse(parameterDefinition);
63 | fFirstParameter = false;
64 | }
65 | PrintToken(VBToken.RightSquareBracket);
66 | } else {
67 | PrintPropertyDefinitionName(propertyDefinition);
68 | }
69 | //PrintToken(CSharpToken.LeftCurly);
70 | if (propertyDefinition.Getter != null) {
71 | PrintToken(VBToken.Indent);
72 | var getMeth = propertyDefinition.Getter.ResolvedMethod;
73 | if (getMeth.Visibility != propertyDefinition.Visibility)
74 | PrintTypeMemberVisibility(getMeth.Visibility);
75 | PrintToken(VBToken.Get);
76 | if (getMeth.IsAbstract || getMeth.IsExternal)
77 | PrintToken(VBToken.Semicolon);
78 | else
79 | Traverse(getMeth.Body);
80 | }
81 | if (propertyDefinition.Setter != null) {
82 | PrintToken(VBToken.Indent);
83 | var setMeth = propertyDefinition.Setter.ResolvedMethod;
84 | if (setMeth.Visibility != propertyDefinition.Visibility)
85 | PrintTypeMemberVisibility(setMeth.Visibility);
86 | PrintToken(VBToken.Set);
87 | if (setMeth.IsAbstract || setMeth.IsExternal)
88 | PrintToken(VBToken.Semicolon);
89 | else
90 | Traverse(setMeth.Body);
91 | }
92 | //PrintToken(CSharpToken.RightCurly);
93 | }
94 |
95 | public virtual void PrintPropertyDefinitionVisibility(IPropertyDefinition propertyDefinition) {
96 | PrintTypeMemberVisibility(propertyDefinition.Visibility);
97 | }
98 |
99 | public virtual void PrintPropertyDefinitionReturnType(IPropertyDefinition propertyDefinition) {
100 | PrintTypeReference(propertyDefinition.Type);
101 | }
102 |
103 | public virtual void PrintPropertyDefinitionName(IPropertyDefinition propertyDefinition) {
104 | PrintIdentifier(propertyDefinition.Name);
105 | }
106 |
107 | public virtual void PrintPropertyDefinitionModifiers(IPropertyDefinition propertyDefinition) {
108 | PrintMethodDefinitionModifiers(propertyDefinition.Getter == null ?
109 | propertyDefinition.Setter.ResolvedMethod :
110 | propertyDefinition.Getter.ResolvedMethod);
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/SourceEmitterOutputString.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using System.IO;
8 |
9 | namespace VBSourceEmitter {
10 | public class SourceEmitterOutputString : SourceEmitterOutputTextWriter {
11 | public SourceEmitterOutputString()
12 | : base(new StringWriter()) {
13 | }
14 |
15 | public SourceEmitterOutputString(int indentLevel)
16 | : base(new StringWriter(), indentLevel) {
17 | }
18 |
19 | public string Data {
20 | get {
21 | return ((StringWriter)this.outputWriter).ToString();
22 | }
23 | }
24 |
25 | public void ClearData() {
26 | var sw = (StringWriter)this.outputWriter;
27 | sw.Flush();
28 | sw.GetStringBuilder().Length = 0;
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/SourceEmitterOutputTextWriter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using System.IO;
8 |
9 | namespace VBSourceEmitter {
10 | public class SourceEmitterOutputTextWriter : ISourceEmitterOutput {
11 |
12 | public SourceEmitterOutputTextWriter(TextWriter outputWriter, int indentSize) {
13 | this.outputWriter = outputWriter;
14 | this.indentLevel = indentSize;
15 | this.strIndent = "";
16 | this.CurrentLineEmpty = true;
17 | }
18 |
19 | public SourceEmitterOutputTextWriter(TextWriter outputWriter) : this(outputWriter, 4)
20 | {
21 | }
22 |
23 | public virtual void WriteLine(string str, bool fIndent) {
24 | OutputBegin(fIndent);
25 | outputWriter.WriteLine(str);
26 | this.CurrentLineEmpty = true;
27 | }
28 |
29 | public virtual void WriteLine(string str) {
30 | WriteLine(str, false);
31 | }
32 |
33 | public virtual void Write(string str, bool fIndent) {
34 | OutputBegin(fIndent);
35 | outputWriter.Write(str);
36 | this.CurrentLineEmpty = false;
37 | }
38 |
39 | public virtual void Write(string str) {
40 | Write(str, false);
41 | }
42 |
43 | public virtual void IncreaseIndent() {
44 | int newIndent = strIndent.Length + indentLevel;
45 | strIndent = new String(' ', newIndent);
46 | }
47 |
48 | public virtual void DecreaseIndent() {
49 | int newIndent = strIndent.Length - indentLevel;
50 | strIndent = new String(' ', newIndent);
51 | }
52 |
53 | public bool CurrentLineEmpty {
54 | get;
55 | private set;
56 | }
57 |
58 | public event Action LineStart;
59 |
60 | protected virtual void OutputBegin(bool fIndent)
61 | {
62 | if (fIndent) {
63 | if (LineStart != null)
64 | LineStart(this);
65 | outputWriter.Write(strIndent);
66 | }
67 | }
68 |
69 | protected TextWriter outputWriter;
70 | protected string strIndent;
71 | protected readonly int indentLevel;
72 | }
73 |
74 | public class SourceEmitterOutputConsole : SourceEmitterOutputTextWriter {
75 | public SourceEmitterOutputConsole(int indentSize) :
76 | base(System.Console.Out, indentSize)
77 | {
78 | }
79 |
80 | public SourceEmitterOutputConsole() :
81 | base(System.Console.Out)
82 | {
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/TypeReferenceSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public virtual void PrintTypeReference(ITypeReference typeReference) {
12 | PrintTypeReferenceName(typeReference);
13 | }
14 |
15 | public virtual void PrintTypeReferenceName(ITypeReference typeReference) {
16 | if (typeReference.TypeCode != PrimitiveTypeCode.NotPrimitive) {
17 | PrintPrimitive(typeReference.TypeCode);
18 | } else {
19 | this.sourceEmitterOutput.Write(this.helper.GetTypeName(typeReference.ResolvedType));
20 | }
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/SourceEmitters/VB/VBSourceEmitter/TypeSourceEmitter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Cci;
8 |
9 | namespace VBSourceEmitter {
10 | public partial class SourceEmitter : CodeTraverser, IVBSourceEmitter {
11 | public override void TraverseChildren(INamespaceTypeDefinition namespaceTypeDefinition) {
12 | PrintTypeDefinition(namespaceTypeDefinition as ITypeDefinition);
13 | }
14 |
15 | public override void TraverseChildren(INestedTypeDefinition nestedTypeDefinition) {
16 | if (!this.printCompilerGeneratedMembers && AttributeHelper.Contains(nestedTypeDefinition.Attributes, nestedTypeDefinition.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute))
17 | return;
18 | PrintTypeDefinition(nestedTypeDefinition as ITypeDefinition);
19 | }
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/project.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "NETStandard.Library": "1.6.0",
4 | "System.Collections.NonGeneric": "4.0.1",
5 | "System.Diagnostics.Contracts": "4.0.1"
6 | },
7 | "frameworks": {
8 | "netstandard1.3": {}
9 | }
10 | }
--------------------------------------------------------------------------------