compiler 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. The Internals of the Mono C# Compiler
  2. Miguel de Icaza
  3. ([email protected])
  4. 2002
  5. * Abstract
  6. The Mono C# compiler is a C# compiler written in C# itself.
  7. Its goals are to provide a free and alternate implementation
  8. of the C# language. The Mono C# compiler generates ECMA CIL
  9. images through the use of the System.Reflection.Emit API which
  10. enable the compiler to be platform independent.
  11. * Overview: How the compiler fits together
  12. The compilation process is managed by the compiler driver (it
  13. lives in driver.cs).
  14. The compiler reads a set of C# source code files, and parses
  15. them. Any assemblies or modules that the user might want to
  16. use with his project are loaded after parsing is done.
  17. Once all the files have been parsed, the type hierarchy is
  18. resolved. First interfaces are resolved, then types and
  19. enumerations.
  20. Once the type hierarchy is resolved, every type is populated:
  21. fields, methods, indexers, properties, events and delegates
  22. are entered into the type system.
  23. At this point the program skeleton has been completed. The
  24. next process is to actually emit the code for each of the
  25. executable methods. The compiler drives this from
  26. RootContext.EmitCode.
  27. Each type then has to populate its methods: populating a
  28. method requires creating a structure that is used as the state
  29. of the block being emitted (this is the EmitContext class) and
  30. then generating code for the topmost statement (the Block).
  31. Code generation has two steps: the first step is the semantic
  32. analysis (Resolve method) that resolves any pending tasks, and
  33. guarantees that the code is correct. The second phase is the
  34. actual code emission. All errors are flagged during in the
  35. "Resolution" process.
  36. After all code has been emitted, then the compiler closes all
  37. the types (this basically tells the Reflection.Emit library to
  38. finish up the types), resources, and definition of the entry
  39. point are done at this point, and the output is saved to
  40. disk.
  41. The following list will give you an idea of where the
  42. different pieces of the compiler live:
  43. Infrastructure:
  44. driver.cs:
  45. This drives the compilation process: loading of
  46. command line options; parsing the inputs files;
  47. loading the referenced assemblies; resolving the type
  48. hierarchy and emitting the code.
  49. codegen.cs:
  50. The state tracking for code generation.
  51. attribute.cs:
  52. Code to do semantic analysis and emit the attributes
  53. is here.
  54. rootcontext.cs:
  55. Keeps track of the types defined in the source code,
  56. as well as the assemblies loaded.
  57. typemanager.cs:
  58. This contains the MCS type system.
  59. report.cs:
  60. Error and warning reporting methods.
  61. support.cs:
  62. Assorted utility functions used by the compiler.
  63. Parsing
  64. cs-tokenizer.cs:
  65. The tokenizer for the C# language, it includes also
  66. the C# pre-processor.
  67. cs-parser.jay, cs-parser.cs:
  68. The parser is implemented using a C# port of the Yacc
  69. parser. The parser lives in the cs-parser.jay file,
  70. and cs-parser.cs is the generated parser.
  71. location.cs:
  72. The `location' structure is a compact representation
  73. of a file, line, column where a token, or a high-level
  74. construct appears. This is used to report errors.
  75. Expressions:
  76. ecore.cs
  77. Basic expression classes, and interfaces most shared
  78. code and static methods are here.
  79. expression.cs:
  80. Most of the different kinds of expressions classes
  81. live in this file.
  82. assign.cs:
  83. The assignment expression got its own file.
  84. constant.cs:
  85. The classes that represent the constant expressions.
  86. literal.cs
  87. Literals are constants that have been entered manually
  88. in the source code, like `1' or `true'. The compiler
  89. needs to tell constants from literals apart during the
  90. compilation process, as literals sometimes have some
  91. implicit extra conversions defined for them.
  92. cfold.cs:
  93. The constant folder for binary expressions.
  94. Statements
  95. statement.cs:
  96. All of the abstract syntax tree elements for
  97. statements live in this file. This also drives the
  98. semantic analysis process.
  99. Declarations, Classes, Structs, Enumerations
  100. decl.cs
  101. This contains the base class for Members and
  102. Declaration Spaces. A declaration space introduces
  103. new names in types, so classes, structs, delegates and
  104. enumerations derive from it.
  105. class.cs:
  106. Methods for holding and defining class and struct
  107. information, and every member that can be in these
  108. (methods, fields, delegates, events, etc).
  109. The most interesting type here is the `TypeContainer'
  110. which is a derivative of the `DeclSpace'
  111. delegate.cs:
  112. Handles delegate definition and use.
  113. enum.cs:
  114. Handles enumerations.
  115. interface.cs:
  116. Holds and defines interfaces. All the code related to
  117. interface declaration lives here.
  118. parameter.cs:
  119. During the parsing process, the compiler encapsulates
  120. parameters in the Parameter and Parameters classes.
  121. These classes provide definition and resolution tools
  122. for them.
  123. pending.cs:
  124. Routines to track pending implementations of abstract
  125. methods and interfaces. These are used by the
  126. TypeContainer-derived classes to track whether every
  127. method required is implemented.
  128. * The parsing process
  129. All the input files that make up a program need to be read in
  130. advance, because C# allows declarations to happen after an
  131. entity is used, for example, the following is a valid program:
  132. class X : Y {
  133. static void Main ()
  134. {
  135. a = "hello"; b = "world";
  136. }
  137. string a;
  138. }
  139. class Y {
  140. public string b;
  141. }
  142. At the time the assignment expression `a = "hello"' is parsed,
  143. it is not know whether a is a class field from this class, or
  144. its parents, or whether it is a property access or a variable
  145. reference. The actual meaning of `a' will not be discvored
  146. until the semantic analysis phase.
  147. ** The Tokenizer and the pre-processor
  148. The tokenizer is contained in the file `cs-tokenizer.cs', and
  149. the main entry point is the `token ()' method. The tokenizer
  150. implements the `yyParser.yyInput' interface, which is what the
  151. Yacc/Jay parser will use when fetching tokens.
  152. Token definitions are generated by jay during the compilation
  153. process, and those can be references from the tokenizer class
  154. with the `Token.' prefix.
  155. Each time a token is returned, the location for the token is
  156. recorded into the `Location' property, that can be accessed by
  157. the parser. The parser retrieves the Location properties as
  158. it builds its internal representation to allow the semantic
  159. analysis phase to produce error messages that can pin point
  160. the location of the problem.
  161. Some tokens have values associated with it, for example when
  162. the tokenizer encounters a string, it will return a
  163. LITERAL_STRING token, and the actual string parsed will be
  164. available in the `Value' property of the tokenizer. The same
  165. mechanism is used to return integers and floating point
  166. numbers.
  167. C# has a limited pre-processor that allows conditional
  168. compilation, but it is not as fully featured as the C
  169. pre-processor, and most notably, macros are missing. This
  170. makes it simple to implement in very few lines and mesh it
  171. with the tokenizer.
  172. The `handle_preprocessing_directive' method in the tokenizer
  173. handles all the pre-processing, and it is invoked when the '#'
  174. symbol is found as the first token in a line.
  175. The state of the pre-processor is contained in a Stack called
  176. `ifstack', this state is used to track the if/elif/else/endif
  177. nesting and the current state. The state is encoded in the
  178. top of the stack as a number of values `TAKING',
  179. `TAKEN_BEFORE', `ELSE_SEEN', `PARENT_TAKING'.
  180. ** Locations
  181. Locations are encoded as a 32-bit number (the Location
  182. struct) that map each input source line to a linear number.
  183. As new files are parsed, the Location manager is informed of
  184. the new file, to allow it to map back from an int constant to
  185. a file + line number.
  186. The tokenizer also tracks the column number for a token, but
  187. this is currently not being used or encoded. It could
  188. probably be encoded in the low 9 bits, allowing for columns
  189. from 1 to 512 to be encoded.
  190. * The Parser
  191. The parser is written using Jay, which is a port of Berkeley
  192. Yacc to Java, that I later ported to C#.
  193. Many people ask why the grammar of the parser does not match
  194. exactly the definition in the C# specification. The reason is
  195. simple: the grammar in the C# specification is designed to be
  196. consumed by humans, and not by a computer program. Before
  197. you can feed this grammar to a tool, it needs to be simplified
  198. to allow the tool to generate a correct parser for it.
  199. In the Mono C# compiler, we use a class for each of the
  200. statements and expressions in the C# language. For example,
  201. there is a `While' class for the the `while' statement, a
  202. `Cast' class to represent a cast expression and so on.
  203. There is a Statement class, and an Expression class which are
  204. the base classes for statements and expressions.
  205. ** Namespaces
  206. Using list.
  207. * Internal Representation
  208. ** Expressions
  209. Expressions in the Mono C# compiler are represented by the
  210. `Expression' class. This is an abstract class that particular
  211. kinds of expressions have to inherit from and override a few
  212. methods.
  213. The base Expression class contains two fields: `eclass' which
  214. represents the "expression classification" (from the C#
  215. specs) and the type of the expression.
  216. Expressions have to be resolved before they are can be used.
  217. The resolution process is implemented by overriding the
  218. `DoResolve' method. The DoResolve method has to set the
  219. `eclass' field and the `type', perform all error checking and
  220. computations that will be required for code generation at this
  221. stage.
  222. The return value from DoResolve is an expression. Most of the
  223. time an Expression derived class will return itself (return
  224. this) when it will handle the emission of the code itself, or
  225. it can return a new Expression.
  226. For example, the parser will create an "ElementAccess" class
  227. for:
  228. a [0] = 1;
  229. During the resolution process, the compiler will know whether
  230. this is an array access, or an indexer access. And will
  231. return either an ArrayAccess expression or an IndexerAccess
  232. expression from DoResolve.
  233. *** The Expression Class
  234. The utility functions that can be called by all children of
  235. Expression.
  236. ** Constants
  237. Constants in the Mono C# compiler are reprensented by the
  238. abstract class `Constant'. Constant is in turn derived from
  239. Expression. The base constructor for `Constant' just sets the
  240. expression class to be an `ExprClass.Value', Constants are
  241. born in a fully resolved state, so the `DoResolve' method
  242. only returns a reference to itself.
  243. Each Constant should implement the `GetValue' method which
  244. returns an object with the actual contents of this constant, a
  245. utility virtual method called `AsString' is used to render a
  246. diagnostic message. The output of AsString is shown to the
  247. developer when an error or a warning is triggered.
  248. Constant classes also participate in the constant folding
  249. process. Constant folding is invoked by those expressions
  250. that can be constant folded invoking the functionality
  251. provided by the ConstantFold class (cfold.cs).
  252. Each Constant has to implement a number of methods to convert
  253. itself into a Constant of a different type. These methods are
  254. called `ConvertToXXXX' and they are invoked by the wrapper
  255. functions `ToXXXX'. These methods only perform implicit
  256. numeric conversions. Explicit conversions are handled by the
  257. `Cast' expression class.
  258. The `ToXXXX' methods are the entry point, and provide error
  259. reporting in case a conversion can not be performed.
  260. ** Constant Folding
  261. The C# language requires constant folding to be implemented.
  262. Constant folding is hooked up in the Binary.Resolve method.
  263. If both sides of a binary expression are constants, then the
  264. ConstantFold.BinaryFold routine is invoked.
  265. This routine implements all the binary operator rules, it
  266. is a mirror of the code that generates code for binary
  267. operators, but that has to be evaluated at runtime.
  268. If the constants can be folded, then a new constant expression
  269. is returned, if not, then the null value is returned (for
  270. example, the concatenation of a string constant and a numeric
  271. constant is deferred to the runtime).
  272. ** Side effects
  273. a [i++]++
  274. a [i++] += 5;
  275. ** Statements
  276. * The semantic analysis
  277. Hence, the compiler driver has to parse all the input files.
  278. Once all the input files have been parsed, and an internal
  279. representation of the input program exists, the following
  280. steps are taken:
  281. * The interface hierarchy is resolved first.
  282. As the interface hierarchy is constructed,
  283. TypeBuilder objects are created for each one of
  284. them.
  285. * Classes and structure hierarchy is resolved next,
  286. TypeBuilder objects are created for them.
  287. * Constants and enumerations are resolved.
  288. * Method, indexer, properties, delegates and event
  289. definitions are now entered into the TypeBuilders.
  290. * Elements that contain code are now invoked to
  291. perform semantic analysis and code generation.
  292. * Output Generation
  293. ** Code Generation
  294. The EmitContext class is created any time that IL code is to
  295. be generated (methods, properties, indexers and attributes all
  296. create EmitContexts).
  297. The EmitContext keeps track of the current namespace and type
  298. container. This is used during name resolution.
  299. An EmitContext is used by the underlying code generation
  300. facilities to track the state of code generation:
  301. * The ILGenerator used to generate code for this
  302. method.
  303. * The TypeContainer where the code lives, this is used
  304. to access the TypeBuilder.
  305. * The DeclSpace, this is used to resolve names through
  306. RootContext.LookupType in the various statements and
  307. expressions.
  308. Code generation state is also tracked here:
  309. * CheckState:
  310. This variable tracks the `checked' state of the
  311. compilation, it controls whether we should generate
  312. code that does overflow checking, or if we generate
  313. code that ignores overflows.
  314. The default setting comes from the command line
  315. option to generate checked or unchecked code plus
  316. any source code changes using the checked/unchecked
  317. statements or expressions. Contrast this with the
  318. ConstantCheckState flag.
  319. * ConstantCheckState
  320. The constant check state is always set to `true' and
  321. cant be changed from the command line. The source
  322. code can change this setting with the `checked' and
  323. `unchecked' statements and expressions.
  324. * IsStatic
  325. Whether we are emitting code inside a static or
  326. instance method
  327. * ReturnType
  328. The value that is allowed to be returned or NULL if
  329. there is no return type.
  330. * ContainerType
  331. Points to the Type (extracted from the
  332. TypeContainer) that declares this body of code
  333. summary>
  334. * IsConstructor
  335. Whether this is generating code for a constructor
  336. * CurrentBlock
  337. Tracks the current block being generated.
  338. * ReturnLabel;
  339. The location where return has to jump to return the
  340. value
  341. A few variables are used to track the state for checking in
  342. for loops, or in try/catch statements:
  343. * InFinally
  344. Whether we are in a Finally block
  345. * InTry
  346. Whether we are in a Try block
  347. * InCatch
  348. Whether we are in a Catch block
  349. * InUnsafe
  350. Whether we are inside an unsafe block
  351. * Miscelaneous
  352. ** Error Processing.
  353. Errors are reported during the various stages of the
  354. compilation process. The compiler stops its processing if
  355. there are errors between the various phases. This simplifies
  356. the code, because it is safe to assume always that the data
  357. structures that the compiler is operating on are always
  358. consistent.
  359. The error codes in the Mono C# compiler are the same as those
  360. found in the Microsoft C# compiler, with a few exceptions
  361. (where we report a few more errors, those are documented in
  362. mcs/errors/errors.txt). The goal is to reduce confussion to
  363. the users, and also to help us track the progress of the
  364. compiler in terms of the errors we report.
  365. The Report class provides error and warning display functions,
  366. and also keeps an error count which is used to stop the
  367. compiler between the phases.
  368. A couple of debugging tools are available here, and are useful
  369. when extending or fixing bugs in the compiler. If the
  370. `--fatal' flag is passed to the compiler, the Report.Error
  371. routine will throw an exception. This can be used to pinpoint
  372. the location of the bug and examine the variables around the
  373. error location.
  374. Warnings can be turned into errors by using the `--werror'
  375. flag to the compiler.
  376. The report class also ignores warnings that have been
  377. specified on the command line with the `--nowarn' flag.
  378. Finally, code in the compiler uses the global variable
  379. RootContext.WarningLevel in a few places to decide whether a
  380. warning is worth reporting to the user or not.