CodeGenerator.cs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. //
  2. // System.CodeDom.Compiler.CodeGenerator.cs
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. // Daniel Stodden ([email protected])
  7. // Gonzalo Paniagua Javier ([email protected])
  8. // Andreas Nahr ([email protected])
  9. // Marek Safar ([email protected])
  10. //
  11. // (C) 2001-2003 Ximian, Inc.
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System.Globalization;
  34. using System.CodeDom;
  35. using System.Reflection;
  36. using System.IO;
  37. using System.Collections;
  38. namespace System.CodeDom.Compiler {
  39. public abstract class CodeGenerator : ICodeGenerator
  40. {
  41. private IndentedTextWriter output;
  42. private CodeGeneratorOptions options;
  43. private CodeTypeMember currentMember;
  44. private CodeTypeDeclaration currentType;
  45. //
  46. // Constructors
  47. //
  48. protected CodeGenerator()
  49. {
  50. }
  51. //
  52. // Properties
  53. //
  54. #if NET_2_0
  55. protected CodeTypeDeclaration CurrentClass {
  56. get {
  57. return currentType;
  58. }
  59. }
  60. #endif
  61. protected CodeTypeMember CurrentMember {
  62. get {
  63. return currentMember;
  64. }
  65. }
  66. protected string CurrentMemberName {
  67. get {
  68. if (currentMember == null)
  69. return "<% unknown %>";
  70. return currentMember.Name;
  71. }
  72. }
  73. protected string CurrentTypeName {
  74. get {
  75. if (currentType == null)
  76. return "<% unknown %>";
  77. return currentType.Name;
  78. }
  79. }
  80. protected int Indent {
  81. get {
  82. return output.Indent;
  83. }
  84. set {
  85. output.Indent = value;
  86. }
  87. }
  88. protected bool IsCurrentClass {
  89. get {
  90. if (currentType == null)
  91. return false;
  92. return currentType.IsClass && !(currentType is CodeTypeDelegate);
  93. }
  94. }
  95. protected bool IsCurrentDelegate {
  96. get {
  97. return currentType is CodeTypeDelegate;
  98. }
  99. }
  100. protected bool IsCurrentEnum {
  101. get {
  102. if (currentType == null)
  103. return false;
  104. return currentType.IsEnum;
  105. }
  106. }
  107. protected bool IsCurrentInterface {
  108. get {
  109. if (currentType == null)
  110. return false;
  111. return currentType.IsInterface;
  112. }
  113. }
  114. protected bool IsCurrentStruct {
  115. get {
  116. if (currentType == null)
  117. return false;
  118. return currentType.IsStruct;
  119. }
  120. }
  121. protected abstract string NullToken {
  122. get;
  123. }
  124. protected CodeGeneratorOptions Options {
  125. get {
  126. return options;
  127. }
  128. }
  129. protected TextWriter Output {
  130. get {
  131. return output;
  132. }
  133. }
  134. //
  135. // Methods
  136. //
  137. protected virtual void ContinueOnNewLine (string st)
  138. {
  139. output.WriteLine (st);
  140. }
  141. /*
  142. * Code Generation methods
  143. */
  144. protected abstract void GenerateArgumentReferenceExpression (CodeArgumentReferenceExpression e);
  145. protected abstract void GenerateArrayCreateExpression (CodeArrayCreateExpression e);
  146. protected abstract void GenerateArrayIndexerExpression (CodeArrayIndexerExpression e);
  147. protected abstract void GenerateAssignStatement (CodeAssignStatement s);
  148. protected abstract void GenerateAttachEventStatement (CodeAttachEventStatement s);
  149. protected abstract void GenerateAttributeDeclarationsStart (CodeAttributeDeclarationCollection attributes);
  150. protected abstract void GenerateAttributeDeclarationsEnd (CodeAttributeDeclarationCollection attributes);
  151. protected abstract void GenerateBaseReferenceExpression (CodeBaseReferenceExpression e);
  152. protected virtual void GenerateBinaryOperatorExpression (CodeBinaryOperatorExpression e)
  153. {
  154. output.Write ('(');
  155. GenerateExpression (e.Left);
  156. output.Write (' ');
  157. OutputOperator (e.Operator);
  158. output.Write (' ');
  159. GenerateExpression (e.Right);
  160. output.Write (')');
  161. }
  162. protected abstract void GenerateCastExpression (CodeCastExpression e);
  163. #if NET_2_0
  164. [MonoTODO]
  165. public virtual void GenerateCodeFromMember (CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options)
  166. {
  167. throw new NotImplementedException ();
  168. }
  169. #endif
  170. protected abstract void GenerateComment (CodeComment comment);
  171. protected virtual void GenerateCommentStatement (CodeCommentStatement statement)
  172. {
  173. GenerateComment (statement.Comment);
  174. }
  175. protected virtual void GenerateCommentStatements (CodeCommentStatementCollection statements)
  176. {
  177. foreach (CodeCommentStatement comment in statements)
  178. GenerateCommentStatement (comment);
  179. }
  180. protected virtual void GenerateCompileUnit (CodeCompileUnit compileUnit)
  181. {
  182. GenerateCompileUnitStart (compileUnit);
  183. CodeAttributeDeclarationCollection attributes = compileUnit.AssemblyCustomAttributes;
  184. if (attributes.Count != 0) {
  185. foreach (CodeAttributeDeclaration att in attributes) {
  186. GenerateAttributeDeclarationsStart (attributes);
  187. output.Write ("assembly: ");
  188. OutputAttributeDeclaration (att);
  189. GenerateAttributeDeclarationsEnd (attributes);
  190. }
  191. output.WriteLine ();
  192. }
  193. foreach (CodeNamespace ns in compileUnit.Namespaces)
  194. GenerateNamespace (ns);
  195. GenerateCompileUnitEnd (compileUnit);
  196. }
  197. protected virtual void GenerateCompileUnitEnd (CodeCompileUnit compileUnit)
  198. {
  199. #if NET_2_0
  200. if (compileUnit.EndDirectives.Count > 0)
  201. GenerateDirectives (compileUnit.EndDirectives);
  202. #endif
  203. }
  204. protected virtual void GenerateCompileUnitStart (CodeCompileUnit compileUnit)
  205. {
  206. #if NET_2_0
  207. if (compileUnit.StartDirectives.Count > 0) {
  208. GenerateDirectives (compileUnit.StartDirectives);
  209. Output.WriteLine ();
  210. }
  211. #endif
  212. }
  213. protected abstract void GenerateConditionStatement (CodeConditionStatement s);
  214. protected abstract void GenerateConstructor (CodeConstructor x, CodeTypeDeclaration d);
  215. protected virtual void GenerateDecimalValue (Decimal d)
  216. {
  217. Output.Write (d.ToString (CultureInfo.InvariantCulture));
  218. }
  219. #if NET_2_0
  220. [MonoTODO]
  221. protected virtual void GenerateDefaultValueExpression (CodeDefaultValueExpression e)
  222. {
  223. throw new NotImplementedException ();
  224. }
  225. #endif
  226. protected abstract void GenerateDelegateCreateExpression (CodeDelegateCreateExpression e);
  227. protected abstract void GenerateDelegateInvokeExpression (CodeDelegateInvokeExpression e);
  228. protected virtual void GenerateDirectionExpression (CodeDirectionExpression e)
  229. {
  230. OutputDirection (e.Direction);
  231. output.Write (' ');
  232. GenerateExpression (e.Expression);
  233. }
  234. protected virtual void GenerateDoubleValue (Double d)
  235. {
  236. Output.Write (d.ToString (CultureInfo.InvariantCulture));
  237. }
  238. protected abstract void GenerateEntryPointMethod (CodeEntryPointMethod m, CodeTypeDeclaration d);
  239. protected abstract void GenerateEvent (CodeMemberEvent ev, CodeTypeDeclaration d);
  240. protected abstract void GenerateEventReferenceExpression (CodeEventReferenceExpression e);
  241. protected void GenerateExpression (CodeExpression e)
  242. {
  243. if (e == null)
  244. throw new ArgumentNullException ("Value cannot be null.");
  245. CodeArgumentReferenceExpression argref = e as CodeArgumentReferenceExpression;
  246. if (argref != null) {
  247. GenerateArgumentReferenceExpression (argref);
  248. return;
  249. }
  250. CodeArrayCreateExpression mkarray = e as CodeArrayCreateExpression;
  251. if (mkarray != null) {
  252. GenerateArrayCreateExpression (mkarray);
  253. return;
  254. }
  255. CodeArrayIndexerExpression arrayidx = e as CodeArrayIndexerExpression;
  256. if (arrayidx != null) {
  257. GenerateArrayIndexerExpression (arrayidx);
  258. return;
  259. }
  260. CodeBaseReferenceExpression baseref = e as CodeBaseReferenceExpression;
  261. if (baseref != null) {
  262. GenerateBaseReferenceExpression (baseref);
  263. return;
  264. }
  265. CodeBinaryOperatorExpression binary = e as CodeBinaryOperatorExpression;
  266. if (binary != null) {
  267. GenerateBinaryOperatorExpression (binary);
  268. return;
  269. }
  270. CodeCastExpression cast = e as CodeCastExpression;
  271. if (cast != null) {
  272. GenerateCastExpression (cast);
  273. return;
  274. }
  275. CodeDelegateCreateExpression mkdel = e as CodeDelegateCreateExpression;
  276. if (mkdel != null) {
  277. GenerateDelegateCreateExpression (mkdel);
  278. return;
  279. }
  280. CodeDelegateInvokeExpression delinvoke = e as CodeDelegateInvokeExpression;
  281. if (delinvoke != null) {
  282. GenerateDelegateInvokeExpression (delinvoke);
  283. return;
  284. }
  285. CodeDirectionExpression direction = e as CodeDirectionExpression;
  286. if (direction != null) {
  287. GenerateDirectionExpression (direction);
  288. return;
  289. }
  290. CodeEventReferenceExpression eventref = e as CodeEventReferenceExpression;
  291. if ( eventref != null ) {
  292. GenerateEventReferenceExpression( eventref );
  293. return;
  294. }
  295. CodeFieldReferenceExpression fieldref = e as CodeFieldReferenceExpression;
  296. if (fieldref != null) {
  297. GenerateFieldReferenceExpression (fieldref);
  298. return;
  299. }
  300. CodeIndexerExpression idx = e as CodeIndexerExpression;
  301. if (idx != null) {
  302. GenerateIndexerExpression (idx);
  303. return;
  304. }
  305. CodeMethodInvokeExpression methodinv = e as CodeMethodInvokeExpression;
  306. if (methodinv != null) {
  307. GenerateMethodInvokeExpression (methodinv);
  308. return;
  309. }
  310. CodeMethodReferenceExpression methodref = e as CodeMethodReferenceExpression;
  311. if (methodref != null) {
  312. GenerateMethodReferenceExpression (methodref);
  313. return;
  314. }
  315. CodeObjectCreateExpression objref = e as CodeObjectCreateExpression;
  316. if (objref != null) {
  317. GenerateObjectCreateExpression (objref);
  318. return;
  319. }
  320. CodeParameterDeclarationExpression param = e as CodeParameterDeclarationExpression;
  321. if (param != null) {
  322. GenerateParameterDeclarationExpression (param);
  323. return;
  324. }
  325. CodePrimitiveExpression primitive = e as CodePrimitiveExpression;
  326. if (primitive != null) {
  327. GeneratePrimitiveExpression (primitive);
  328. return;
  329. }
  330. CodePropertyReferenceExpression propref = e as CodePropertyReferenceExpression;
  331. if (propref != null) {
  332. GeneratePropertyReferenceExpression (propref);
  333. return;
  334. }
  335. CodePropertySetValueReferenceExpression propset = e as CodePropertySetValueReferenceExpression;
  336. if (propset != null) {
  337. GeneratePropertySetValueReferenceExpression (propset);
  338. return;
  339. }
  340. CodeSnippetExpression snippet = e as CodeSnippetExpression;
  341. if (snippet != null) {
  342. GenerateSnippetExpression (snippet);
  343. return;
  344. }
  345. CodeThisReferenceExpression thisref = e as CodeThisReferenceExpression;
  346. if (thisref != null) {
  347. GenerateThisReferenceExpression (thisref);
  348. return;
  349. }
  350. CodeTypeOfExpression typeOf = e as CodeTypeOfExpression;
  351. if (typeOf != null) {
  352. GenerateTypeOfExpression (typeOf);
  353. return;
  354. }
  355. CodeTypeReferenceExpression typeref = e as CodeTypeReferenceExpression;
  356. if (typeref != null) {
  357. GenerateTypeReferenceExpression (typeref);
  358. return;
  359. }
  360. CodeVariableReferenceExpression varref = e as CodeVariableReferenceExpression;
  361. if (varref != null) {
  362. GenerateVariableReferenceExpression (varref);
  363. return;
  364. }
  365. throw new ArgumentException ("Element type " + e + " is not supported.");
  366. }
  367. protected abstract void GenerateExpressionStatement (CodeExpressionStatement statement);
  368. protected abstract void GenerateField (CodeMemberField f);
  369. protected abstract void GenerateFieldReferenceExpression (CodeFieldReferenceExpression e);
  370. protected abstract void GenerateGotoStatement (CodeGotoStatement statement);
  371. protected abstract void GenerateIndexerExpression (CodeIndexerExpression e);
  372. protected abstract void GenerateIterationStatement (CodeIterationStatement s);
  373. protected abstract void GenerateLabeledStatement (CodeLabeledStatement statement);
  374. protected abstract void GenerateLinePragmaStart (CodeLinePragma p);
  375. protected abstract void GenerateLinePragmaEnd (CodeLinePragma p);
  376. protected abstract void GenerateMethod (CodeMemberMethod m, CodeTypeDeclaration d);
  377. protected abstract void GenerateMethodInvokeExpression (CodeMethodInvokeExpression e);
  378. protected abstract void GenerateMethodReferenceExpression (CodeMethodReferenceExpression e);
  379. protected abstract void GenerateMethodReturnStatement (CodeMethodReturnStatement e);
  380. protected virtual void GenerateNamespace (CodeNamespace ns)
  381. {
  382. foreach (CodeCommentStatement statement in ns.Comments)
  383. GenerateCommentStatement (statement);
  384. GenerateNamespaceStart (ns);
  385. foreach (CodeNamespaceImport import in ns.Imports) {
  386. if (import.LinePragma != null)
  387. GenerateLinePragmaStart (import.LinePragma);
  388. GenerateNamespaceImport (import);
  389. if (import.LinePragma != null)
  390. GenerateLinePragmaEnd (import.LinePragma);
  391. }
  392. output.WriteLine();
  393. foreach (CodeTypeDeclaration type in ns.Types) {
  394. GenerateType (type);
  395. output.WriteLine();
  396. }
  397. GenerateNamespaceEnd (ns);
  398. }
  399. protected abstract void GenerateNamespaceStart (CodeNamespace ns);
  400. protected abstract void GenerateNamespaceEnd (CodeNamespace ns);
  401. protected abstract void GenerateNamespaceImport (CodeNamespaceImport i);
  402. protected void GenerateNamespaceImports (CodeNamespace e)
  403. {
  404. foreach (CodeNamespaceImport import in e.Imports) {
  405. if (import.LinePragma != null)
  406. GenerateLinePragmaStart (import.LinePragma);
  407. GenerateNamespaceImport (import);
  408. if (import.LinePragma != null)
  409. GenerateLinePragmaEnd (import.LinePragma);
  410. }
  411. }
  412. protected void GenerateNamespaces (CodeCompileUnit e)
  413. {
  414. foreach (CodeNamespace ns in e.Namespaces)
  415. GenerateNamespace (ns);
  416. }
  417. protected abstract void GenerateObjectCreateExpression (CodeObjectCreateExpression e);
  418. protected virtual void GenerateParameterDeclarationExpression (CodeParameterDeclarationExpression e)
  419. {
  420. if (e.CustomAttributes != null && e.CustomAttributes.Count > 0)
  421. OutputAttributeDeclarations (e.CustomAttributes);
  422. OutputDirection (e.Direction);
  423. OutputType (e.Type);
  424. output.Write (' ');
  425. output.Write (e.Name);
  426. }
  427. protected virtual void GeneratePrimitiveExpression (CodePrimitiveExpression e)
  428. {
  429. if (e.Value == null) {
  430. output.Write (NullToken);
  431. return;
  432. }
  433. Type type = e.Value.GetType ();
  434. if (type == typeof (bool)) {
  435. output.Write (e.Value.ToString ().ToLower (CultureInfo.InvariantCulture));
  436. } else if (type == typeof (char)) {
  437. output.Write ("'" + e.Value.ToString () + "'");
  438. } else if (type == typeof (string)) {
  439. output.Write (QuoteSnippetString ((string) e.Value));
  440. } else if (type == typeof (byte) || type == typeof (sbyte) || type == typeof (short) ||
  441. type == typeof (int) || type == typeof (long) || type == typeof (float) ||
  442. type == typeof (double) || type == typeof (decimal)) {
  443. // All of these should be IFormatable, I am just being safe/slow
  444. IFormattable formattable = e.Value as IFormattable;
  445. if (formattable != null)
  446. output.Write (formattable.ToString (null, CultureInfo.InvariantCulture));
  447. else
  448. output.Write (e.Value.ToString ());
  449. if (type == typeof (float))
  450. output.Write ("f");
  451. } else {
  452. throw new ArgumentException ("Value type (" + type + ") is not a primitive type");
  453. }
  454. }
  455. protected abstract void GenerateProperty (CodeMemberProperty p, CodeTypeDeclaration d);
  456. protected abstract void GeneratePropertyReferenceExpression (CodePropertyReferenceExpression e);
  457. protected abstract void GeneratePropertySetValueReferenceExpression (CodePropertySetValueReferenceExpression e);
  458. protected abstract void GenerateRemoveEventStatement (CodeRemoveEventStatement statement);
  459. protected virtual void GenerateSingleFloatValue (Single s)
  460. {
  461. output.Write (s.ToString(CultureInfo.InvariantCulture));
  462. }
  463. protected virtual void GenerateSnippetCompileUnit (CodeSnippetCompileUnit e)
  464. {
  465. if (e.LinePragma != null)
  466. GenerateLinePragmaStart (e.LinePragma);
  467. output.WriteLine (e.Value);
  468. if (e.LinePragma != null)
  469. GenerateLinePragmaEnd (e.LinePragma);
  470. }
  471. protected abstract void GenerateSnippetExpression (CodeSnippetExpression e);
  472. protected abstract void GenerateSnippetMember (CodeSnippetTypeMember m);
  473. protected virtual void GenerateSnippetStatement (CodeSnippetStatement s)
  474. {
  475. output.WriteLine (s.Value);
  476. }
  477. protected void GenerateStatement (CodeStatement s)
  478. {
  479. bool handled = false;
  480. #if NET_2_0
  481. if (s.StartDirectives.Count > 0)
  482. GenerateDirectives (s.StartDirectives);
  483. #endif
  484. if (s.LinePragma != null)
  485. GenerateLinePragmaStart (s.LinePragma);
  486. CodeAssignStatement assign = s as CodeAssignStatement;
  487. if (assign != null) {
  488. GenerateAssignStatement (assign);
  489. handled = true;
  490. }
  491. CodeAttachEventStatement attach = s as CodeAttachEventStatement;
  492. if (attach != null) {
  493. GenerateAttachEventStatement (attach);
  494. handled = true;
  495. }
  496. CodeCommentStatement comment = s as CodeCommentStatement;
  497. if (comment != null) {
  498. GenerateCommentStatement (comment);
  499. handled = true;
  500. }
  501. CodeConditionStatement condition = s as CodeConditionStatement;
  502. if (condition != null) {
  503. GenerateConditionStatement (condition);
  504. handled = true;
  505. }
  506. CodeExpressionStatement expression = s as CodeExpressionStatement;
  507. if (expression != null) {
  508. GenerateExpressionStatement (expression);
  509. handled = true;
  510. }
  511. CodeGotoStatement gotostmt = s as CodeGotoStatement;
  512. if (gotostmt != null) {
  513. GenerateGotoStatement (gotostmt);
  514. handled = true;
  515. }
  516. CodeIterationStatement iteration = s as CodeIterationStatement;
  517. if (iteration != null) {
  518. GenerateIterationStatement (iteration);
  519. handled = true;
  520. }
  521. CodeLabeledStatement label = s as CodeLabeledStatement;
  522. if (label != null) {
  523. GenerateLabeledStatement (label);
  524. handled = true;
  525. }
  526. CodeMethodReturnStatement returnstmt = s as CodeMethodReturnStatement;
  527. if (returnstmt != null) {
  528. GenerateMethodReturnStatement (returnstmt);
  529. handled = true;
  530. }
  531. CodeRemoveEventStatement remove = s as CodeRemoveEventStatement;
  532. if (remove != null) {
  533. GenerateRemoveEventStatement (remove);
  534. handled = true;
  535. }
  536. CodeSnippetStatement snippet = s as CodeSnippetStatement;
  537. if (snippet != null) {
  538. #if NET_2_0
  539. int indent = Indent;
  540. try {
  541. Indent = 0;
  542. GenerateSnippetStatement (snippet);
  543. } finally {
  544. Indent = indent;
  545. }
  546. #else
  547. GenerateSnippetStatement (snippet);
  548. #endif
  549. handled = true;
  550. }
  551. CodeThrowExceptionStatement exception = s as CodeThrowExceptionStatement;
  552. if (exception != null) {
  553. GenerateThrowExceptionStatement (exception);
  554. handled = true;
  555. }
  556. CodeTryCatchFinallyStatement trycatch = s as CodeTryCatchFinallyStatement;
  557. if (trycatch != null) {
  558. GenerateTryCatchFinallyStatement (trycatch);
  559. handled = true;
  560. }
  561. CodeVariableDeclarationStatement declaration = s as CodeVariableDeclarationStatement;
  562. if (declaration != null) {
  563. GenerateVariableDeclarationStatement (declaration);
  564. handled = true;
  565. }
  566. if (!handled)
  567. throw new ArgumentException ("Element type " + s + " is not supported.");
  568. if (s.LinePragma != null)
  569. GenerateLinePragmaEnd (s.LinePragma);
  570. #if NET_2_0
  571. if (s.EndDirectives.Count > 0)
  572. GenerateDirectives (s.EndDirectives);
  573. #endif
  574. }
  575. protected void GenerateStatements (CodeStatementCollection c)
  576. {
  577. foreach (CodeStatement statement in c)
  578. GenerateStatement (statement);
  579. }
  580. protected abstract void GenerateThisReferenceExpression (CodeThisReferenceExpression e);
  581. protected abstract void GenerateThrowExceptionStatement (CodeThrowExceptionStatement s);
  582. protected abstract void GenerateTryCatchFinallyStatement (CodeTryCatchFinallyStatement s);
  583. protected abstract void GenerateTypeEnd (CodeTypeDeclaration declaration);
  584. protected abstract void GenerateTypeConstructor (CodeTypeConstructor constructor);
  585. protected virtual void GenerateTypeOfExpression (CodeTypeOfExpression e)
  586. {
  587. output.Write ("typeof(");
  588. OutputType (e.Type);
  589. output.Write (")");
  590. }
  591. protected virtual void GenerateTypeReferenceExpression (CodeTypeReferenceExpression e)
  592. {
  593. OutputType (e.Type);
  594. }
  595. protected void GenerateTypes (CodeNamespace e)
  596. {
  597. foreach (CodeTypeDeclaration type in e.Types)
  598. GenerateType (type);
  599. }
  600. protected abstract void GenerateTypeStart (CodeTypeDeclaration declaration);
  601. protected abstract void GenerateVariableDeclarationStatement (CodeVariableDeclarationStatement e);
  602. protected abstract void GenerateVariableReferenceExpression (CodeVariableReferenceExpression e);
  603. //
  604. // Other members
  605. //
  606. /*
  607. * Output Methods
  608. */
  609. protected virtual void OutputAttributeArgument (CodeAttributeArgument argument)
  610. {
  611. string name = argument.Name;
  612. if ((name != null) && (name.Length > 0)) {
  613. output.Write (name);
  614. output.Write ('=');
  615. }
  616. GenerateExpression (argument.Value);
  617. }
  618. private void OutputAttributeDeclaration (CodeAttributeDeclaration attribute)
  619. {
  620. output.Write (attribute.Name.Replace ('+', '.'));
  621. output.Write ('(');
  622. IEnumerator enumerator = attribute.Arguments.GetEnumerator();
  623. if (enumerator.MoveNext()) {
  624. CodeAttributeArgument argument = (CodeAttributeArgument)enumerator.Current;
  625. OutputAttributeArgument (argument);
  626. while (enumerator.MoveNext()) {
  627. output.Write (',');
  628. argument = (CodeAttributeArgument)enumerator.Current;
  629. OutputAttributeArgument (argument);
  630. }
  631. }
  632. output.Write (')');
  633. }
  634. protected virtual void OutputAttributeDeclarations (CodeAttributeDeclarationCollection attributes)
  635. {
  636. GenerateAttributeDeclarationsStart (attributes);
  637. IEnumerator enumerator = attributes.GetEnumerator();
  638. if (enumerator.MoveNext()) {
  639. CodeAttributeDeclaration attribute = (CodeAttributeDeclaration)enumerator.Current;
  640. OutputAttributeDeclaration (attribute);
  641. while (enumerator.MoveNext()) {
  642. attribute = (CodeAttributeDeclaration)enumerator.Current;
  643. output.WriteLine (',');
  644. OutputAttributeDeclaration (attribute);
  645. }
  646. }
  647. GenerateAttributeDeclarationsEnd (attributes);
  648. }
  649. protected virtual void OutputDirection (FieldDirection direction)
  650. {
  651. switch (direction) {
  652. case FieldDirection.In:
  653. //output.Write ("in ");
  654. break;
  655. case FieldDirection.Out:
  656. output.Write ("out ");
  657. break;
  658. case FieldDirection.Ref:
  659. output.Write ("ref ");
  660. break;
  661. }
  662. }
  663. protected virtual void OutputExpressionList (CodeExpressionCollection expressions)
  664. {
  665. OutputExpressionList (expressions, false);
  666. }
  667. protected virtual void OutputExpressionList (CodeExpressionCollection expressions,
  668. bool newLineBetweenItems)
  669. {
  670. IEnumerator enumerator = expressions.GetEnumerator();
  671. if (enumerator.MoveNext()) {
  672. CodeExpression expression = (CodeExpression)enumerator.Current;
  673. GenerateExpression (expression);
  674. while (enumerator.MoveNext()) {
  675. expression = (CodeExpression)enumerator.Current;
  676. output.Write (',');
  677. if (newLineBetweenItems)
  678. output.WriteLine ();
  679. else
  680. output.Write (' ');
  681. GenerateExpression (expression);
  682. }
  683. }
  684. }
  685. protected virtual void OutputFieldScopeModifier (MemberAttributes attributes)
  686. {
  687. if ((attributes & MemberAttributes.VTableMask) == MemberAttributes.New)
  688. output.Write ("new ");
  689. switch (attributes & MemberAttributes.ScopeMask) {
  690. case MemberAttributes.Static:
  691. output.Write ("static ");
  692. break;
  693. case MemberAttributes.Const:
  694. output.Write ("const ");
  695. break;
  696. }
  697. }
  698. protected virtual void OutputIdentifier (string ident)
  699. {
  700. output.Write (ident);
  701. }
  702. protected virtual void OutputMemberAccessModifier (MemberAttributes attributes)
  703. {
  704. switch (attributes & MemberAttributes.AccessMask) {
  705. case MemberAttributes.Assembly:
  706. output.Write ("internal ");
  707. break;
  708. case MemberAttributes.FamilyAndAssembly:
  709. #if NET_2_0
  710. output.Write ("internal ");
  711. #else
  712. output.Write ("/*FamANDAssem*/ internal ");
  713. #endif
  714. break;
  715. case MemberAttributes.Family:
  716. output.Write ("protected ");
  717. break;
  718. case MemberAttributes.FamilyOrAssembly:
  719. output.Write ("protected internal ");
  720. break;
  721. case MemberAttributes.Private:
  722. output.Write ("private ");
  723. break;
  724. case MemberAttributes.Public:
  725. output.Write ("public ");
  726. break;
  727. }
  728. }
  729. protected virtual void OutputMemberScopeModifier (MemberAttributes attributes)
  730. {
  731. #if NET_2_0
  732. if ((attributes & MemberAttributes.VTableMask) == MemberAttributes.New)
  733. output.Write( "new " );
  734. #endif
  735. switch (attributes & MemberAttributes.ScopeMask) {
  736. case MemberAttributes.Abstract:
  737. output.Write ("abstract ");
  738. break;
  739. case MemberAttributes.Final:
  740. // Do nothing
  741. break;
  742. case MemberAttributes.Static:
  743. output.Write ("static ");
  744. break;
  745. case MemberAttributes.Override:
  746. output.Write ("override ");
  747. break;
  748. default:
  749. //
  750. // FUNNY! if the scope value is
  751. // rubbish (0 or >Const), and access
  752. // is public or protected, make it
  753. // "virtual".
  754. //
  755. // i'm not sure whether this is 100%
  756. // correct, but it seems to be MS
  757. // behavior.
  758. //
  759. // On .NET 2.0, internal members
  760. // are also marked "virtual".
  761. //
  762. MemberAttributes access = attributes & MemberAttributes.AccessMask;
  763. if (access == MemberAttributes.Public || access == MemberAttributes.Family)
  764. output.Write ("virtual ");
  765. break;
  766. }
  767. }
  768. protected virtual void OutputOperator (CodeBinaryOperatorType op)
  769. {
  770. switch (op) {
  771. case CodeBinaryOperatorType.Add:
  772. output.Write ("+");
  773. break;
  774. case CodeBinaryOperatorType.Subtract:
  775. output.Write ("-");
  776. break;
  777. case CodeBinaryOperatorType.Multiply:
  778. output.Write ("*");
  779. break;
  780. case CodeBinaryOperatorType.Divide:
  781. output.Write ("/");
  782. break;
  783. case CodeBinaryOperatorType.Modulus:
  784. output.Write ("%");
  785. break;
  786. case CodeBinaryOperatorType.Assign:
  787. output.Write ("=");
  788. break;
  789. case CodeBinaryOperatorType.IdentityInequality:
  790. output.Write ("!=");
  791. break;
  792. case CodeBinaryOperatorType.IdentityEquality:
  793. output.Write ("==");
  794. break;
  795. case CodeBinaryOperatorType.ValueEquality:
  796. output.Write ("==");
  797. break;
  798. case CodeBinaryOperatorType.BitwiseOr:
  799. output.Write ("|");
  800. break;
  801. case CodeBinaryOperatorType.BitwiseAnd:
  802. output.Write ("&");
  803. break;
  804. case CodeBinaryOperatorType.BooleanOr:
  805. output.Write ("||");
  806. break;
  807. case CodeBinaryOperatorType.BooleanAnd:
  808. output.Write ("&&");
  809. break;
  810. case CodeBinaryOperatorType.LessThan:
  811. output.Write ("<");
  812. break;
  813. case CodeBinaryOperatorType.LessThanOrEqual:
  814. output.Write ("<=");
  815. break;
  816. case CodeBinaryOperatorType.GreaterThan:
  817. output.Write (">");
  818. break;
  819. case CodeBinaryOperatorType.GreaterThanOrEqual:
  820. output.Write (">=");
  821. break;
  822. }
  823. }
  824. protected virtual void OutputParameters (CodeParameterDeclarationExpressionCollection parameters)
  825. {
  826. bool first = true;
  827. foreach (CodeParameterDeclarationExpression expr in parameters) {
  828. if (first)
  829. first = false;
  830. else
  831. output.Write (", ");
  832. GenerateExpression (expr);
  833. }
  834. }
  835. protected abstract void OutputType (CodeTypeReference t);
  836. protected virtual void OutputTypeAttributes (TypeAttributes attributes,
  837. bool isStruct,
  838. bool isEnum)
  839. {
  840. switch (attributes & TypeAttributes.VisibilityMask) {
  841. case TypeAttributes.NotPublic:
  842. // private by default
  843. break;
  844. case TypeAttributes.Public:
  845. case TypeAttributes.NestedPublic:
  846. output.Write ("public ");
  847. break;
  848. case TypeAttributes.NestedPrivate:
  849. output.Write ("private ");
  850. break;
  851. }
  852. if (isStruct)
  853. output.Write ("struct ");
  854. else if (isEnum)
  855. output.Write ("enum ");
  856. else {
  857. if ((attributes & TypeAttributes.Interface) != 0)
  858. output.Write ("interface ");
  859. else if (currentType is CodeTypeDelegate)
  860. output.Write ("delegate ");
  861. else {
  862. if ((attributes & TypeAttributes.Sealed) != 0)
  863. output.Write ("sealed ");
  864. if ((attributes & TypeAttributes.Abstract) != 0)
  865. output.Write ("abstract ");
  866. output.Write ("class ");
  867. }
  868. }
  869. }
  870. protected virtual void OutputTypeNamePair (CodeTypeReference type,
  871. string name)
  872. {
  873. OutputType (type);
  874. output.Write (' ');
  875. output.Write (name);
  876. }
  877. protected abstract string QuoteSnippetString (string value);
  878. /*
  879. * ICodeGenerator
  880. */
  881. protected abstract string CreateEscapedIdentifier (string value);
  882. string ICodeGenerator.CreateEscapedIdentifier (string value)
  883. {
  884. return CreateEscapedIdentifier (value);
  885. }
  886. protected abstract string CreateValidIdentifier (string value);
  887. string ICodeGenerator.CreateValidIdentifier (string value)
  888. {
  889. return CreateValidIdentifier (value);
  890. }
  891. private void InitOutput (TextWriter output, CodeGeneratorOptions options)
  892. {
  893. if (options == null)
  894. options = new CodeGeneratorOptions ();
  895. this.output = new IndentedTextWriter (output, options.IndentString);
  896. this.options = options;
  897. }
  898. void ICodeGenerator.GenerateCodeFromCompileUnit (CodeCompileUnit compileUnit,
  899. TextWriter output,
  900. CodeGeneratorOptions options)
  901. {
  902. InitOutput (output, options);
  903. if (compileUnit is CodeSnippetCompileUnit) {
  904. GenerateSnippetCompileUnit ((CodeSnippetCompileUnit) compileUnit);
  905. } else {
  906. GenerateCompileUnit (compileUnit);
  907. }
  908. }
  909. void ICodeGenerator.GenerateCodeFromExpression (CodeExpression expression,
  910. TextWriter output,
  911. CodeGeneratorOptions options)
  912. {
  913. InitOutput (output, options);
  914. GenerateExpression (expression);
  915. }
  916. void ICodeGenerator.GenerateCodeFromNamespace (CodeNamespace ns,
  917. TextWriter output,
  918. CodeGeneratorOptions options)
  919. {
  920. InitOutput (output, options);
  921. GenerateNamespace (ns);
  922. }
  923. void ICodeGenerator.GenerateCodeFromStatement (CodeStatement statement,
  924. TextWriter output,
  925. CodeGeneratorOptions options)
  926. {
  927. InitOutput (output, options);
  928. GenerateStatement (statement);
  929. }
  930. void ICodeGenerator.GenerateCodeFromType (CodeTypeDeclaration type,
  931. TextWriter output,
  932. CodeGeneratorOptions options)
  933. {
  934. InitOutput (output, options);
  935. GenerateType (type);
  936. }
  937. private void GenerateType (CodeTypeDeclaration type)
  938. {
  939. this.currentType = type;
  940. #if NET_2_0
  941. if (type.StartDirectives.Count > 0)
  942. GenerateDirectives (type.StartDirectives);
  943. #endif
  944. foreach (CodeCommentStatement statement in type.Comments)
  945. GenerateCommentStatement (statement);
  946. if (type.LinePragma != null)
  947. GenerateLinePragmaStart (type.LinePragma);
  948. GenerateTypeStart (type);
  949. CodeTypeMember[] members = new CodeTypeMember[type.Members.Count];
  950. type.Members.CopyTo (members, 0);
  951. #if NET_2_0
  952. if (!Options.VerbatimOrder)
  953. #endif
  954. {
  955. int[] order = new int[members.Length];
  956. for (int n = 0; n < members.Length; n++)
  957. order[n] = Array.IndexOf (memberTypes, members[n].GetType ()) * members.Length + n;
  958. Array.Sort (order, members);
  959. }
  960. // WARNING: if anything is missing in the foreach loop and you add it, add the type in
  961. // its corresponding place in CodeTypeMemberComparer class (below)
  962. CodeTypeDeclaration subtype = null;
  963. foreach (CodeTypeMember member in members) {
  964. CodeTypeMember prevMember = this.currentMember;
  965. this.currentMember = member;
  966. if (prevMember != null && subtype == null) {
  967. if (prevMember.LinePragma != null)
  968. GenerateLinePragmaEnd (prevMember.LinePragma);
  969. #if NET_2_0
  970. if (prevMember.EndDirectives.Count > 0)
  971. GenerateDirectives (prevMember.EndDirectives);
  972. #endif
  973. }
  974. if (options.BlankLinesBetweenMembers)
  975. output.WriteLine ();
  976. subtype = member as CodeTypeDeclaration;
  977. if (subtype != null) {
  978. GenerateType (subtype);
  979. this.currentType = type;
  980. continue;
  981. }
  982. #if NET_2_0
  983. if (currentMember.StartDirectives.Count > 0)
  984. GenerateDirectives (currentMember.StartDirectives);
  985. #endif
  986. foreach (CodeCommentStatement statement in member.Comments)
  987. GenerateCommentStatement (statement);
  988. if (member.LinePragma != null)
  989. GenerateLinePragmaStart (member.LinePragma);
  990. CodeMemberEvent eventm = member as CodeMemberEvent;
  991. if (eventm != null) {
  992. GenerateEvent (eventm, type);
  993. continue;
  994. }
  995. CodeMemberField field = member as CodeMemberField;
  996. if (field != null) {
  997. GenerateField (field);
  998. continue;
  999. }
  1000. CodeEntryPointMethod epmethod = member as CodeEntryPointMethod;
  1001. if (epmethod != null) {
  1002. GenerateEntryPointMethod (epmethod, type);
  1003. continue;
  1004. }
  1005. CodeTypeConstructor typeCtor = member as CodeTypeConstructor;
  1006. if (typeCtor != null) {
  1007. GenerateTypeConstructor (typeCtor);
  1008. continue;
  1009. }
  1010. CodeConstructor ctor = member as CodeConstructor;
  1011. if (ctor != null) {
  1012. GenerateConstructor (ctor, type);
  1013. continue;
  1014. }
  1015. CodeMemberMethod method = member as CodeMemberMethod;
  1016. if (method != null) {
  1017. GenerateMethod (method, type);
  1018. continue;
  1019. }
  1020. CodeMemberProperty property = member as CodeMemberProperty;
  1021. if (property != null) {
  1022. GenerateProperty (property, type);
  1023. continue;
  1024. }
  1025. CodeSnippetTypeMember snippet = member as CodeSnippetTypeMember;
  1026. if (snippet != null) {
  1027. GenerateSnippetMember (snippet);
  1028. continue;
  1029. }
  1030. this.currentMember = prevMember;
  1031. }
  1032. // Hack because of previous continue usage
  1033. if (currentMember != null && !(currentMember is CodeTypeDeclaration)) {
  1034. if (currentMember.LinePragma != null)
  1035. GenerateLinePragmaEnd (currentMember.LinePragma);
  1036. #if NET_2_0
  1037. if (currentMember.EndDirectives.Count > 0)
  1038. GenerateDirectives (currentMember.EndDirectives);
  1039. #endif
  1040. }
  1041. this.currentType = type;
  1042. GenerateTypeEnd (type);
  1043. if (type.LinePragma != null)
  1044. GenerateLinePragmaEnd (type.LinePragma);
  1045. #if NET_2_0
  1046. if (type.EndDirectives.Count > 0)
  1047. GenerateDirectives (type.EndDirectives);
  1048. #endif
  1049. }
  1050. protected abstract string GetTypeOutput (CodeTypeReference type);
  1051. string ICodeGenerator.GetTypeOutput (CodeTypeReference type)
  1052. {
  1053. return GetTypeOutput (type);
  1054. }
  1055. protected abstract bool IsValidIdentifier (string value);
  1056. bool ICodeGenerator.IsValidIdentifier (string value)
  1057. {
  1058. return IsValidIdentifier (value);
  1059. }
  1060. public static bool IsValidLanguageIndependentIdentifier (string value)
  1061. {
  1062. if (value == null)
  1063. return false;
  1064. if (value.Equals (string.Empty))
  1065. return false;
  1066. switch (char.GetUnicodeCategory (value[0]))
  1067. {
  1068. case UnicodeCategory.LetterNumber:
  1069. case UnicodeCategory.LowercaseLetter:
  1070. case UnicodeCategory.TitlecaseLetter:
  1071. case UnicodeCategory.UppercaseLetter:
  1072. case UnicodeCategory.OtherLetter:
  1073. case UnicodeCategory.ModifierLetter:
  1074. case UnicodeCategory.ConnectorPunctuation:
  1075. if (value.Length > 1)
  1076. {
  1077. for (int x = 0; x < value.Length; x++)
  1078. {
  1079. switch (char.GetUnicodeCategory (value[x]))
  1080. {
  1081. case UnicodeCategory.LetterNumber:
  1082. case UnicodeCategory.LowercaseLetter:
  1083. case UnicodeCategory.TitlecaseLetter:
  1084. case UnicodeCategory.UppercaseLetter:
  1085. case UnicodeCategory.OtherLetter:
  1086. case UnicodeCategory.ModifierLetter:
  1087. case UnicodeCategory.ConnectorPunctuation:
  1088. case UnicodeCategory.DecimalDigitNumber:
  1089. case UnicodeCategory.NonSpacingMark:
  1090. case UnicodeCategory.SpacingCombiningMark:
  1091. case UnicodeCategory.Format:
  1092. return true;
  1093. }
  1094. return false;
  1095. }
  1096. }
  1097. else
  1098. return true;
  1099. break;
  1100. }
  1101. return false;
  1102. }
  1103. protected abstract bool Supports (GeneratorSupport supports);
  1104. bool ICodeGenerator.Supports (GeneratorSupport value)
  1105. {
  1106. return Supports (value);
  1107. }
  1108. protected virtual void ValidateIdentifier (string value)
  1109. {
  1110. if (!(IsValidIdentifier (value)))
  1111. throw new ArgumentException ("Identifier is invalid", "value");
  1112. }
  1113. [MonoTODO]
  1114. public static void ValidateIdentifiers (CodeObject e)
  1115. {
  1116. throw new NotImplementedException();
  1117. }
  1118. void ICodeGenerator.ValidateIdentifier (string value)
  1119. {
  1120. ValidateIdentifier (value);
  1121. }
  1122. // The position in the array determines the order in which those
  1123. // kind of CodeTypeMembers are generated. Less is more ;-)
  1124. static Type [] memberTypes = { typeof (CodeMemberField),
  1125. typeof (CodeSnippetTypeMember),
  1126. typeof (CodeTypeConstructor),
  1127. typeof (CodeConstructor),
  1128. typeof (CodeMemberProperty),
  1129. typeof (CodeMemberEvent),
  1130. typeof (CodeMemberMethod),
  1131. typeof (CodeTypeDeclaration),
  1132. typeof (CodeEntryPointMethod)
  1133. };
  1134. #if NET_2_0
  1135. protected virtual void GenerateDirectives (CodeDirectiveCollection directives)
  1136. {
  1137. }
  1138. #endif
  1139. }
  1140. }