Documentation update
[mono.git] / mcs / docs / compiler.txt
1                        The Internals of the Mono C# Compiler
2         
3                                 Miguel de Icaza
4                               (miguel@ximian.com)
5                                2002, 2007, 2009
6
7 * Abstract
8
9         The Mono C# compiler is a C# compiler written in C# itself.
10         Its goals are to provide a free and alternate implementation
11         of the C# language.  The Mono C# compiler generates ECMA CIL
12         images through the use of the System.Reflection.Emit API which
13         enable the compiler to be platform independent.
14         
15 * Overview: How the compiler fits together
16
17         The compilation process is managed by the compiler driver (it
18         lives in driver.cs).
19
20         The compiler reads a set of C# source code files, and parses
21         them.  Any assemblies or modules that the user might want to
22         use with his project are loaded after parsing is done.
23
24         Once all the files have been parsed, the type hierarchy is
25         resolved.  First interfaces are resolved, then types and
26         enumerations.
27
28         Once the type hierarchy is resolved, every type is populated:
29         fields, methods, indexers, properties, events and delegates
30         are entered into the type system.  
31
32         At this point the program skeleton has been completed.  The
33         next process is to actually emit the code for each of the
34         executable methods.  The compiler drives this from
35         RootContext.EmitCode.
36
37         Each type then has to populate its methods: populating a
38         method requires creating a structure that is used as the state
39         of the block being emitted (this is the EmitContext class) and
40         then generating code for the topmost statement (the Block).
41
42         Code generation has two steps: the first step is the semantic
43         analysis (Resolve method) that resolves any pending tasks, and
44         guarantees that the code is correct.  The second phase is the
45         actual code emission.  All errors are flagged during in the
46         "Resolution" process. 
47
48         After all code has been emitted, then the compiler closes all
49         the types (this basically tells the Reflection.Emit library to
50         finish up the types), resources, and definition of the entry
51         point are done at this point, and the output is saved to
52         disk. 
53
54         The following list will give you an idea of where the
55         different pieces of the compiler live:
56
57         Infrastructure:
58
59             driver.cs:
60                 This drives the compilation process: loading of
61                 command line options; parsing the inputs files;
62                 loading the referenced assemblies; resolving the type
63                 hierarchy and emitting the code. 
64
65             codegen.cs:
66                 
67                 The state tracking for code generation. 
68
69             attribute.cs:
70
71                 Code to do semantic analysis and emit the attributes
72                 is here.
73
74             rootcontext.cs:
75
76                 Keeps track of the types defined in the source code,
77                 as well as the assemblies loaded.  
78
79             typemanager.cs:
80
81                 This contains the MCS type system.
82
83             report.cs:
84
85                 Error and warning reporting methods.
86
87             support.cs:
88
89                 Assorted utility functions used by the compiler.
90                 
91         Parsing
92
93             cs-tokenizer.cs:
94
95                 The tokenizer for the C# language, it includes also
96                 the C# pre-processor.
97
98             cs-parser.jay, cs-parser.cs:
99
100                 The parser is implemented using a C# port of the Yacc
101                 parser.  The parser lives in the cs-parser.jay file,
102                 and cs-parser.cs is the generated parser.
103
104             location.cs:
105
106                 The `location' structure is a compact representation
107                 of a file, line, column where a token, or a high-level
108                 construct appears.  This is used to report errors.
109
110         Expressions:
111           
112             ecore.cs
113         
114                 Basic expression classes, and interfaces most shared
115                 code and static methods are here.
116
117             expression.cs:
118
119                 Most of the different kinds of expressions classes
120                 live in this file.
121
122             assign.cs:
123
124                 The assignment expression got its own file.
125
126             constant.cs:
127
128                 The classes that represent the constant expressions.
129
130             literal.cs
131                 
132                 Literals are constants that have been entered manually
133                 in the source code, like `1' or `true'.  The compiler
134                 needs to tell constants from literals apart during the
135                 compilation process, as literals sometimes have some
136                 implicit extra conversions defined for them. 
137
138             cfold.cs:
139
140                 The constant folder for binary expressions.
141
142         Statements
143
144             statement.cs:
145
146                 All of the abstract syntax tree elements for
147                 statements live in this file.  This also drives the
148                 semantic analysis process.
149
150             iterators.cs:
151
152                 Contains the support for implementing iterators from
153                 the C# 2.0 specification.
154
155         Declarations, Classes, Structs, Enumerations
156
157             decl.cs
158
159                 This contains the base class for Members and
160                 Declaration Spaces.   A declaration space introduces
161                 new names in types, so classes, structs, delegates and
162                 enumerations derive from it.
163
164             class.cs:
165                 
166                 Methods for holding and defining class and struct
167                 information, and every member that can be in these
168                 (methods, fields, delegates, events, etc).
169
170                 The most interesting type here is the `TypeContainer'
171                 which is a derivative of the `DeclSpace' 
172
173             delegate.cs:
174
175                 Handles delegate definition and use. 
176
177             enum.cs:
178
179                 Handles enumerations.
180
181             interface.cs:
182
183                 Holds and defines interfaces.  All the code related to
184                 interface declaration lives here.
185
186             parameter.cs:
187
188                 During the parsing process, the compiler encapsulates
189                 parameters in the Parameter and Parameters classes.
190                 These classes provide definition and resolution tools
191                 for them.
192
193             pending.cs:
194
195                 Routines to track pending implementations of abstract
196                 methods and interfaces.  These are used by the
197                 TypeContainer-derived classes to track whether every
198                 method required is implemented.
199
200         
201 * The parsing process
202
203         All the input files that make up a program need to be read in
204         advance, because C# allows declarations to happen after an
205         entity is used, for example, the following is a valid program:
206
207         class X : Y {
208                 static void Main ()
209                 {
210                         a = "hello"; b = "world";
211                 }
212                 string a;
213         }
214         
215         class Y {
216                 public string b;
217         }
218
219         At the time the assignment expression `a = "hello"' is parsed,
220         it is not know whether a is a class field from this class, or
221         its parents, or whether it is a property access or a variable
222         reference.  The actual meaning of `a' will not be discovered
223         until the semantic analysis phase.
224
225 ** The Tokenizer and the pre-processor
226
227         The tokenizer is contained in the file `cs-tokenizer.cs', and
228         the main entry point is the `token ()' method.  The tokenizer
229         implements the `yyParser.yyInput' interface, which is what the
230         Yacc/Jay parser will use when fetching tokens.  
231
232         Token definitions are generated by jay during the compilation
233         process, and those can be references from the tokenizer class
234         with the `Token.' prefix. 
235
236         Each time a token is returned, the location for the token is
237         recorded into the `Location' property, that can be accessed by
238         the parser.  The parser retrieves the Location properties as
239         it builds its internal representation to allow the semantic
240         analysis phase to produce error messages that can pin point
241         the location of the problem. 
242
243         Some tokens have values associated with it, for example when
244         the tokenizer encounters a string, it will return a
245         LITERAL_STRING token, and the actual string parsed will be
246         available in the `Value' property of the tokenizer.   The same
247         mechanism is used to return integers and floating point
248         numbers. 
249
250         C# has a limited pre-processor that allows conditional
251         compilation, but it is not as fully featured as the C
252         pre-processor, and most notably, macros are missing.  This
253         makes it simple to implement in very few lines and mesh it
254         with the tokenizer.
255
256         The `handle_preprocessing_directive' method in the tokenizer
257         handles all the pre-processing, and it is invoked when the '#'
258         symbol is found as the first token in a line.  
259
260         The state of the pre-processor is contained in a Stack called
261         `ifstack', this state is used to track the if/elif/else/endif
262         nesting and the current state.  The state is encoded in the
263         top of the stack as a number of values `TAKING',
264         `TAKEN_BEFORE', `ELSE_SEEN', `PARENT_TAKING'.
265
266 ** Locations
267
268         Locations are encoded as a 32-bit number (the Location
269         struct) that map each input source line to a linear number.
270         As new files are parsed, the Location manager is informed of
271         the new file, to allow it to map back from an int constant to
272         a file + line number.
273
274         Prior to parsing/tokenizing any source files, the compiler
275         generates a list of all the source files and then reserves the
276         low N bits of the location to hold the source file, where N is
277         large enough to hold at least twice as many source files as were
278         specified on the command line (to allow for a #line in each file).
279         The upper 32-N bits are the line number in that file.
280
281         The token 0 is reserved for ``anonymous'' locations, ie. if we
282         don't know the location (Location.Null).
283
284         The tokenizer also tracks the column number for a token, but
285         this is currently not being used or encoded.  It could
286         probably be encoded in the low 9 bits, allowing for columns
287         from 1 to 512 to be encoded.
288
289 * The Parser
290
291         The parser is written using Jay, which is a port of Berkeley
292         Yacc to Java, that I later ported to C#. 
293
294         Many people ask why the grammar of the parser does not match
295         exactly the definition in the C# specification.  The reason is
296         simple: the grammar in the C# specification is designed to be
297         consumed by humans, and not by a computer program.  Before
298         you can feed this grammar to a tool, it needs to be simplified
299         to allow the tool to generate a correct parser for it. 
300
301         In the Mono C# compiler, we use a class for each of the
302         statements and expressions in the C# language.  For example,
303         there is a `While' class for the the `while' statement, a
304         `Cast' class to represent a cast expression and so on.
305
306         There is a Statement class, and an Expression class which are
307         the base classes for statements and expressions. 
308
309 ** Namespaces
310         
311         Using list.
312
313 * Internal Representation
314
315 ** Expressions
316
317         Expressions in the Mono C# compiler are represented by the
318         `Expression' class.  This is an abstract class that particular
319         kinds of expressions have to inherit from and override a few
320         methods.
321
322         The base Expression class contains two fields: `eclass' which
323         represents the "expression classification" (from the C#
324         specs) and the type of the expression.
325
326         During parsing, the compiler will create the various trees of
327         expressions.  These expressions have to be resolved before they
328         are can be used.    The semantic analysis is implemented by
329         resolving each of the expressions created during parsing and
330         creating fully resolved expressions.
331
332         A common pattern that you will notice in the compiler is this:
333
334                   Expression expr;
335                   ...
336         
337                   expr = expr.Resolve (ec);
338                   if (expr == null)
339                         // There was an error, stop processing by returning
340
341         The resolution process is implemented by overriding the
342         `DoResolve' method.  The DoResolve method has to set the `eclass'
343         field and the `type', perform all error checking and computations
344         that will be required for code generation at this stage.
345
346         The return value from DoResolve is an expression.  Most of the
347         time an Expression derived class will return itself (return
348         this) when it will handle the emission of the code itself, or
349         it can return a new Expression.
350
351         For example, the parser will create an "ElementAccess" class
352         for:
353
354                 a [0] = 1;
355
356         During the resolution process, the compiler will know whether
357         this is an array access, or an indexer access.  And will
358         return either an ArrayAccess expression or an IndexerAccess
359         expression from DoResolve.
360
361         All errors must be reported during the resolution phase
362         (DoResolve) and if an error is detected the DoResolve method
363         will return null which is used to flag that an error condition
364         has occurred, this will be used to stop compilation later on.
365         This means that anyone that calls Expression.Resolve must
366         check the return value for null which would indicate an error
367         condition.
368
369         The second stage that Expressions participate in is code
370         generation, this is done by overwriting the "Emit" method of
371         the Expression class.  No error checking must be performed
372         during this stage.
373
374         We take advantage of the distinction between the expressions that
375         are generated by the parser and the expressions that are the
376         result of the semantic analysis phase for lambda expressions (more
377         information in the "Lambda Expressions" section).
378
379         But what is important is that expressions and statements that are
380         generated by the parser should implement the cloning
381         functionality.  This is used lambda expressions require the
382         compiler to attempt to resolve a given block of code with
383         different possible types for parameters that have their types
384         implicitly inferred. 
385
386 ** Simple Names, MemberAccess
387
388         One of the most important classes in the compiler is
389         "SimpleName" which represents a simple name (from the C#
390         specification).  The names during the resolution time are
391         bound to field names, parameter names or local variable names.
392
393         More complicated expressions like:
394
395                 Math.Sin
396
397         Are composed using the MemberAccess class which contains a
398         name (Math) and a SimpleName (Sin), this helps driving the
399         resolution process.
400
401 ** Types
402
403         The parser creates expressions to represent types during
404         compilation.  For example:
405
406            class Sample {
407
408                 Version vers;
409
410            }
411
412
413         That will produce a "SimpleName" expression for the "Version"
414         word.  And in this particular case, the parser will introduce
415         "Version vers" as a field declaration.
416
417         During the resolution process for the fields, the compiler
418         will have to resolve the word "Version" to a type.  This is
419         done by using the "ResolveAsType" method in Expression instead
420         of using "Resolve".
421
422         ResolveAsType just turns on a different set of code paths for
423         things like SimpleNames and does a different kind of error
424         checking than the one used by regular expressions. 
425
426 ** Constants
427
428         Constants in the Mono C# compiler are represented by the
429         abstract class `Constant'.  Constant is in turn derived from
430         Expression.  The base constructor for `Constant' just sets the
431         expression class to be an `ExprClass.Value', Constants are
432         born in a fully resolved state, so the `DoResolve' method
433         only returns a reference to itself.
434
435         Each Constant should implement the `GetValue' method which
436         returns an object with the actual contents of this constant, a
437         utility virtual method called `AsString' is used to render a
438         diagnostic message.  The output of AsString is shown to the
439         developer when an error or a warning is triggered.
440
441         Constant classes also participate in the constant folding
442         process.  Constant folding is invoked by those expressions
443         that can be constant folded invoking the functionality
444         provided by the ConstantFold class (cfold.cs).   
445
446         Each Constant has to implement a number of methods to convert
447         itself into a Constant of a different type.  These methods are
448         called `ConvertToXXXX' and they are invoked by the wrapper
449         functions `ToXXXX'.  These methods only perform implicit
450         numeric conversions.  Explicit conversions are handled by the
451         `Cast' expression class.
452
453         The `ToXXXX' methods are the entry point, and provide error
454         reporting in case a conversion can not be performed.
455
456 ** Constant Folding
457
458         The C# language requires constant folding to be implemented.
459         Constant folding is hooked up in the Binary.Resolve method.
460         If both sides of a binary expression are constants, then the
461         ConstantFold.BinaryFold routine is invoked.  
462
463         This routine implements all the binary operator rules, it
464         is a mirror of the code that generates code for binary
465         operators, but that has to be evaluated at runtime.
466
467         If the constants can be folded, then a new constant expression
468         is returned, if not, then the null value is returned (for
469         example, the concatenation of a string constant and a numeric
470         constant is deferred to the runtime). 
471
472 ** Side effects
473
474         a [i++]++ 
475         a [i++] += 5;
476
477 ** Statements
478
479 *** Invariant meaning in a block
480
481         The seemingly small section in the standard entitled
482         "invariant meaning in a block" has several subtleties
483         involved, especially when we try to implement the semantics
484         efficiently.
485
486         Most of the semantics are trivial, and basically prevent local
487         variables from shadowing parameters and other local variables.
488         However, this notion is not limited to that, but affects all
489         simple name accesses within a block.  And therein lies the rub
490         -- instead of just worrying about the issue when we arrive at
491         variable declarations, we need to verify this property at
492         every use of a simple name within a block.
493
494         The key notion that helps us is to note the bi-directional
495         action of a variable declaration.  The declaration together
496         with anti-shadowing rules can maintain the IMiaB property for
497         the block containing the declaration and all nested sub
498         blocks.  But, the IMiaB property also forces all surrounding
499         blocks to avoid using the name.  We thus need to maintain a
500         blacklist of taboo names in all surrounding blocks -- and we
501         take the expedient of doing so simply: actually maintaining a
502         (superset of the) blacklist in each block data structure, which
503         we call the 'known_variable' list.
504
505         Because we create the 'known_variable' list during the parse
506         process, by the time we do simple name resolution, all the
507         blacklists are fully populated.  So, we can just enforce the
508         rest of the IMiaB property by looking up a couple of lists.
509
510         This turns out to be quite efficient: when we used a block
511         tree walk, a test case took 5-10mins, while with this simple
512         mildly-redundant data structure, the time taken for the same
513         test case came down to a couple of seconds.
514
515         The IKnownVariable interface is a small wrinkle.  Firstly, the
516         IMiaB also applies to parameter names, especially those of
517         anonymous methods.  Secondly, we need more information than
518         just the name in the blacklist -- we need the location of the
519         name and where it's declared.  We use the IKnownVariable
520         interface to abstract out the parser information stored for
521         local variables and parameters.
522
523 * The semantic analysis 
524
525         Hence, the compiler driver has to parse all the input files.
526         Once all the input files have been parsed, and an internal
527         representation of the input program exists, the following
528         steps are taken:
529
530                 * The interface hierarchy is resolved first.
531                   As the interface hierarchy is constructed,
532                   TypeBuilder objects are created for each one of
533                   them. 
534
535                 * Classes and structure hierarchy is resolved next,
536                   TypeBuilder objects are created for them.
537
538                 * Constants and enumerations are resolved.
539
540                 * Method, indexer, properties, delegates and event
541                   definitions are now entered into the TypeBuilders. 
542
543                 * Elements that contain code are now invoked to
544                   perform semantic analysis and code generation.
545
546 * Output Generation
547
548 ** Code Generation
549
550         The EmitContext class is created any time that IL code is to
551         be generated (methods, properties, indexers and attributes all
552         create EmitContexts).  
553
554         The EmitContext keeps track of the current namespace and type
555         container.  This is used during name resolution.
556
557         An EmitContext is used by the underlying code generation
558         facilities to track the state of code generation:
559
560                 * The ILGenerator used to generate code for this
561                   method.
562
563                 * The TypeContainer where the code lives, this is used
564                   to access the TypeBuilder.
565
566                 * The DeclSpace, this is used to resolve names through
567                   RootContext.LookupType in the various statements and
568                   expressions. 
569         
570         Code generation state is also tracked here:
571
572                 * CheckState:
573
574                   This variable tracks the `checked' state of the
575                   compilation, it controls whether we should generate
576                   code that does overflow checking, or if we generate
577                   code that ignores overflows.
578                   
579                   The default setting comes from the command line
580                   option to generate checked or unchecked code plus
581                   any source code changes using the checked/unchecked
582                   statements or expressions.  Contrast this with the
583                   ConstantCheckState flag.
584
585                 * ConstantCheckState
586                   
587                   The constant check state is always set to `true' and
588                   cant be changed from the command line.  The source
589                   code can change this setting with the `checked' and
590                   `unchecked' statements and expressions.
591                   
592                 * IsStatic
593                   
594                   Whether we are emitting code inside a static or
595                   instance method
596                   
597                 * ReturnType
598                   
599                   The value that is allowed to be returned or NULL if
600                   there is no return type.
601                   
602                 * ReturnLabel 
603
604                   A `Label' used by the code if it must jump to it.
605                   This is used by a few routines that deals with exception
606                   handling.
607
608                 * HasReturnLabel
609
610                   Whether we have a return label defined by the toplevel
611                   driver.
612                   
613                 * ContainerType
614                   
615                   Points to the Type (extracted from the
616                   TypeContainer) that declares this body of code
617                   summary>
618                   
619                   
620                 * IsConstructor
621                   
622                   Whether this is generating code for a constructor
623
624                 * CurrentBlock
625
626                   Tracks the current block being generated.
627
628                 * ReturnLabel;
629                 
630                   The location where return has to jump to return the
631                   value
632
633         A few variables are used to track the state for checking in
634         for loops, or in try/catch statements:
635
636                 * InFinally
637                 
638                   Whether we are in a Finally block
639
640                 * InTry
641
642                   Whether we are in a Try block
643
644                 * InCatch
645                   
646                   Whether we are in a Catch block
647
648                 * InUnsafe
649                   Whether we are inside an unsafe block
650
651         Methods exposed by the EmitContext:
652
653                 * EmitTopBlock()
654
655                   This emits a toplevel block. 
656
657                   This routine is very simple, to allow the anonymous
658                   method support to roll its two-stage version of this
659                   routine on its own.
660
661                 * NeedReturnLabel ():
662
663                   This is used to flag during the resolution phase that 
664                   the driver needs to initialize the `ReturnLabel'
665
666 * Anonymous Methods
667
668         The introduction of anonymous methods in the compiler changed
669         various ways of doing things in the compiler.  The most
670         significant one is the hard split between the resolution phase
671         and the emission phases of the compiler.
672
673         For instance, routines that referenced local variables no
674         longer can safely create temporary variables during the
675         resolution phase: they must do so from the emission phase,
676         since the variable might have been "captured", hence access to
677         it can not be done with the local-variable operations from the
678         runtime.
679
680         The code emission is in:
681
682                 EmitTopBlock ()
683
684         Which drives the process, it first resolves the topblock, then
685         emits the required metadata (local variable definitions) and
686         finally emits the code.
687
688         A detailed description of anonymous methods and iterators is
689         on the new-anonymous-design.txt file in this directory.
690
691 * Lambda Expressions
692
693         Lambda expressions can come in two forms: those that have implicit
694         parameter types and those that have explicit parameter types, for
695         example:
696
697                 Explicit:       
698
699                         Foo ((int x) => x + 1);
700
701                 Implicit:
702
703                         Foo (x => x + 1)
704
705
706         One of the problems that we faced with lambda expressions is
707         that lambda expressions need to be "probed" with different
708         types until a working combination is found.
709
710         For example:
711
712             x => x.i
713
714         The above expression could mean vastly different things depending
715         on the type of "x".  The compiler determines the type of "x" (left
716         hand side "x") at the moment the above expression is "bound",
717         which means that during the compilation process it will try to
718         match the above lambda with all the possible types available, for
719         example:
720
721         delegate int di (int x);
722         delegate string ds (string s);
723         ..
724         Foo (di x) {}
725         Foo (ds x) {}
726         ...
727         Foo (x => "string")
728
729         In the above example, overload resolution will try "x" as an "int"
730         and will try "x" as a string.  And if one of them "compiles" thats
731         the one it picks (and it also copes with ambiguities if there was
732         more than one matching method).
733
734         To compile this, we need to hook into the resolution process,
735         but since the resolution process has side effects (calling
736         Resolve can either return instances of the resolved expression
737         type, or can alter field internals) it was necessary to
738         incorporate a framework to "clone" expressions before we
739         probe.
740
741         The support for cloning was added into Statements and
742         Expressions and is only necessary for objects of those types
743         that are created during parsing.   It is not necessary to
744         support these in the classes that are the result of calling
745         Resolve.   This means that SimpleName needs support for
746         Cloning, but FieldExpr does not need it (SimpleName is created
747         by the parser, FieldExpr is created during semantic analysis
748         resolution).   
749
750         The work happens through the public method called "Clone" that
751         clones the given Statement or Expression.  The base method in
752         Statement and Expression merely does a MemberwiseCopy of the
753         elements and then calls the virtual CloneTo method to complete
754         the copy.    By default this method throws an exception, this
755         is useful to catch cases where we forgot to override CloneTo
756         for a given Statement/Expression. 
757
758         With the cloning capability it became possible to call resolve
759         multiple times (once for each Cloned copy) and based on this
760         picking the one implementation that would compile and that
761         would not be ambiguous.
762
763         The cloning process is basically a deep copy that happens in the
764         LambdaExpression class and it clones the top-level block for the
765         lambda expression.    The cloning has the side effect of cloning
766         the entire containing block as well. 
767
768         This happens inside this method:
769
770         public override bool ImplicitStandardConversionExists (Type delegate_type)
771
772         This is used to determine if the current Lambda expression can be
773         implicitly converted to the given delegate type.
774
775         And also happens as a result of the generic method parameter
776         type inferencing. 
777
778 ** Lambda Expressions and Cloning
779
780         All statements that are created during the parsing method should
781         implement the CloneTo method:
782
783                 protected virtual void CloneTo (CloneContext clonectx, Statement target)
784
785         This method is called by the Statement.Clone method after it has
786         done a shallow-copy of all the fields in the statement, and they
787         should typically Clone any child statements.
788
789         Expressions should implement the CloneTo method as well:
790
791                 protected virtual void CloneTo (CloneContext clonectx, Expression target)
792
793 ** Lambda Expressions and Contextual Return
794
795         When an expression is parsed as a lambda expression, the parser
796         inserts a call to a special statement, the contextual return.
797
798         The expression:
799
800             a => a+1
801
802         Is actually compiled as:
803
804             a => contextual_return (a+1)
805
806         The contextual_return statement will behave differently depending
807         on the return type of the delegate that the expression will be
808         converted to.
809
810         If the delegate return type is void, the above will basically turn
811         into an empty operation.   Otherwise the above will become
812         a return statement that can infer return types.
813
814 * Evaluation API
815
816         The compiler can now be used as a library, the API exposed
817         lives in the Mono.CSharp.Evaluator class and it can currently
818         compile statements and expressions passed as strings and
819         compile or compile and execute immediately.
820
821         As of April 2009 this creates a new in-memory assembly for
822         each statement evaluated.   
823
824         To support this evaluator mode, the evaluator API primes the
825         tokenizer with an initial character that would not appear in
826         valid C# code and is one of:
827
828             int EvalStatementParserCharacter = 0x2190;   // Unicode Left Arrow
829             int EvalCompilationUnitParserCharacter = 0x2191;  // Unicode Arrow
830             int EvalUsingDeclarationsParserCharacter = 0x2192;  // Unicode Arrow
831
832         These character are turned into the following tokens:
833
834           %token EVAL_STATEMENT_PARSER
835           %token EVAL_COMPILATION_UNIT_PARSER
836           %token EVAL_USING_DECLARATIONS_UNIT_PARSER
837
838         This means that the first token returned by the tokenizer when
839         used by the Evalutor API is a special token that helps the
840         yacc parser go from the traditional parsing of a full
841         compilation-unit to the interactive parsing:
842
843         The entry production for the compiler basically becomes:
844
845           compilation_unit
846                 //
847                 // The standard rules
848                 //
849                 : outer_declarations opt_EOF  
850                 | outer_declarations global_attributes opt_EOF
851                 | global_attributes opt_EOF
852                 | opt_EOF /* allow empty files */
853
854                 //
855                 // The rule that allows interactive parsing
856                 //
857                 | interactive_parsing  { Lexer.CompleteOnEOF = false; } opt_EOF
858                 ;
859           
860           //
861           // This is where Evaluator API drives the compilation
862           //
863           interactive_parsing
864                 : EVAL_STATEMENT_PARSER EOF 
865                 | EVAL_USING_DECLARATIONS_UNIT_PARSER using_directives
866                 | EVAL_STATEMENT_PARSER 
867                   interactive_statement_list opt_COMPLETE_COMPLETION 
868                 | EVAL_COMPILATION_UNIT_PARSER 
869                   interactive_compilation_unit
870                 ;
871         
872         Since there is a little bit of ambiguity for example in the
873         presence of the using directive and the using statement a
874         micro-predicting parser with multiple token look aheads is
875         used in eval.cs to resolve the ambiguity and produce the
876         actual token that will drive the compilation.
877
878         This helps this scenario:
879              using System;
880            vs
881              using (var x = File.OpenRead) {}
882
883         This is the meaning of these new initial tokens:
884
885              EVAL_STATEMENT_PARSER
886                 Used to parse statements or expressions as statements.
887
888              EVAL_USING_DECLARATIONS_UNIT_PARSER
889                 This instructs the parser to merely do using-directive
890                 parsing instead of statement parsing. 
891
892              EVAL_COMPILATION_UNIT_PARSER
893                 Used to evaluate toplevel declarations like namespaces
894                 and classes.   
895
896                 The feature is currently disabled because later stages
897                 of the compiler are not yet able to lookup previous
898                 definitions of classes.   
899
900                 What happens is that between each call to Evaluate()
901                 we reset the compiler state and at this stage we drop
902                 also any existing definitions, so evaluating "class X
903                 {}" followed by "class Y : X {}" does not currently
904                 work. 
905
906                 We need to make sure that new type definitions used
907                 interactively are preseved from one evaluation to the
908                 next. 
909
910         The evaluator the expression or statement `BODY' is hosted
911         inside a wrapper class.   If the statement is a variable
912         declaration then the declaration is split from the assignment
913         into a DECLARATION and BODY.   
914
915         This is what the code generated looks like:
916
917              public class Foo : $InteractiveBaseClass {
918                     DECLARATION
919
920                     static void Host (ref object $retval)
921                     {
922                         BODY
923                     }
924              }
925
926         Since both statements and expressions are mixed together and
927         it is useful to use the Evaluator to compute expressions we
928         return expressions for example for "1+2" in the `retval'
929         reference object. 
930
931         To support this, the reference retval parameter is set to a
932         special internal value that means "Value was not set" before
933         the method Host is invoked.    During parsing the parser turns
934         expressions like "1+2" into:
935
936                     retval = 1 + 2;
937
938         This is done using a special OptionalAssign
939         ExpressionStatement class. 
940
941         When the Host method return, if the value of retval is still
942         the special flag no value was set.  Otherwise the result of
943         the expression is in retval.
944
945         The `InteractiveBaseClass' is the base class for the method,
946         this allows for embedders to provide different base classes
947         that could expose new static methods that could be useful
948         during expression evaluation.
949         
950         Our default implementation is InteractiveBaseClass and new
951         implementations should derive from this and set the property
952         in the Evaluator to it. 
953
954         In the future we will move to creating dynamic methods as the
955         wrapper for this code.
956
957 * Code Completion
958
959         Support for code completion is available to allow the compiler
960         to provide a list of possible completions at any given point
961         int he parsing process.   This is used for Tab-completion in
962         an interactive shell or visual aids in GUI shells for possible
963         method completions. 
964
965         This method is available as part of the Evaluator API where a
966         special method GetCompletions returns a list of possible
967         completions given a partial input.
968
969         The parser and tokenizer work together so that the tokenizer
970         upon reaching the end of the input generates the following
971         tokens: GENERATE_COMPLETION followed by as many
972         COMPLETE_COMPLETION token and finally the EOF token.
973
974         GENERATE_COMPLETION needs to be handled in every production
975         where the user is likely to press the TAB key in the shell (or
976         in the future the GUI, or an explicit request in an IDE).
977         COMPLETE_COMPLETION must be handled throughout the grammar to
978         provide a way of completing the parsed expression.  See below
979         for details.
980
981         For the member access case, I have added productions that
982         mirror the non-completing productions, for example:
983
984           primary_expression DOT IDENTIFIER GENERATE_COMPLETION 
985           {
986                 LocatedToken lt = (LocatedToken) $3;
987                 $$ = new CompletionMemberAccess ((Expression) $1, lt.Value, lt.Location);
988           }
989         
990         This mirrors:
991
992           primary_expression DOT IDENTIFIER opt_type_argument_list
993           {
994                 LocatedToken lt = (LocatedToken) $3;
995                 $$ = new MemberAccess ((Expression) $1, lt.Value, (TypeArguments) $4, lt.Location);
996           }
997         
998         The CompletionMemberAccess is a new kind of
999         Mono.CSharp.Expression that does the actual lookup.  It
1000         internally mimics some of the MemberAccess code but has been
1001         tuned for this particular use.
1002
1003         After this initial token is processed GENERATE_COMPLETION the
1004         tokenizer will emit COMPLETE_COMPLETION tokens.  This is done
1005         to help the parser basically produce a valid result from the
1006         partial input it received.  For example it is able to produce
1007         a valid AST from "(x" even if no parenthesis has been closed.
1008         This is achieved by sprinkling the grammar with productions
1009         that can cope with this "winding down" token, for example this
1010         is what parenthesized_expression looks like now:
1011
1012           parenthesized_expression
1013                   : OPEN_PARENS expression CLOSE_PARENS
1014                     {
1015                           $$ = new ParenthesizedExpression ((Expression) $2);
1016                     }
1017                   //
1018                   // New production
1019                   //
1020                   | OPEN_PARENS expression COMPLETE_COMPLETION
1021                     {
1022                           $$ = new ParenthesizedExpression ((Expression) $2);
1023                     }
1024                   ;
1025           
1026           Once we have wrapped up everything we generate the last EOF token.
1027
1028         When the AST is complete we actually trigger the regular
1029         semantic analysis process.  The DoResolve method of each node
1030         in our abstract syntax tree will compute the result and
1031         communicate the possible completions by throwing an exception
1032         of type CompletionResult.
1033
1034         So for example if the user type "T" and the completion is
1035         "ToString" we return "oString".
1036
1037 ** Enhancing Completion
1038
1039         Code completion is a process that will be curated over time.  
1040         Just like producing good error reports and warnings is an
1041         iterative process, to find a good balance, the code completion
1042         engine in the compiler will require tuning to find the right
1043         balance for the end user. 
1044
1045         This section explains the basic process by which you can
1046         improve the code completion by using a real life sample.
1047
1048         Once you add the GENERATE_COMPLETION token to your grammar
1049         rule, chances are, you will need to alter the grammar to
1050         support COMPLETE_COMPLETION all the way up to the toplevel
1051         production.
1052
1053         To debug this, you will want to try the completion with either
1054         a sample program or with the `csharp' tool.
1055
1056         I use this setup:
1057
1058         $ csharp -v -v
1059
1060         This will turn on the parser debugging output and will
1061         generate a lot of data when parsing its input.
1062
1063         To start with a new completion scheme, type your C# code and
1064         then hit the tab key to trigger the completion engine.  In the
1065         generated output you will want to look for the first time that
1066         the parser got the GENERATE_COMPLETION token, it will look
1067         like this:
1068
1069         lex     state 414       reading GENERATE_COMPLETION value {interactive}(1,35):
1070
1071         The first word `lex' indicates that the parser called the
1072         lexer at state 414 (more on this in a second) and it got back
1073         from the lexer the token GENERATE_COMPLETION.   If this is a
1074         kind of completion chances are, you will get an error
1075         immediately as the rules at that point do not know how to cope
1076         with the stream of COMPLETE_COMPLETION tokens that will
1077         follow, they will look like this:
1078
1079         error   syntax error
1080         pop     state 414       on error
1081         pop     state 805       on error
1082         pop     state 628       on error
1083         pop     state 417       on error
1084         
1085         The first line means that the parser has entered the error
1086         state and will pop states until it can find a production that
1087         can deal with the error.   At that point an error message will
1088         be displayed.
1089
1090         Open the file `y.output' which describes the parser states
1091         generated by jay and search for the state that was reported
1092         previously in `lex' that got the GENERATE_COMPLETION:
1093
1094         state 414
1095                 object_or_collection_initializer : OPEN_BRACE . opt_member_initializer_list CLOSE_BRACE  (444)
1096                 object_or_collection_initializer : OPEN_BRACE . member_initializer_list COMMA CLOSE_BRACE  (445)
1097                 opt_member_initializer_list : .  (446)
1098         
1099         We now know that the parser was in the middle of parsing an
1100         `object_or_collection_initializer' and had alread seen the
1101         OPEN_BRACE token.
1102
1103         The `.' after OPEN_BRACE indicates the current state of the
1104         parser, and this is where our parser got the
1105         GENERATE_COMPLETION token.   As you can see from the three
1106         rules in this sample, support for GENERATE_COMPLETION did not
1107         exist.
1108
1109         So we must edit the grammar to add a production for this case,
1110         I made the code look like this:
1111
1112         member_initializer
1113                 [...]
1114                 | GENERATE_COMPLETION 
1115                   {
1116                         LocatedToken lt = $1 as LocatedToken;
1117                         $$ = new CompletionElementInitializer (GetLocation ($1));
1118                   }
1119                 [...]
1120
1121         This new production creates the class
1122         CompletionElementInitializer and returns this as the value for
1123         this.   The following is a trivial implementation that always
1124         returns "foo" and "bar" as the two completions and it
1125         illustrates how things work:
1126
1127         public class CompletionElementInitializer : CompletingExpression {
1128                 public CompletionElementInitializer (Location l)
1129                 {
1130                         this.loc = l;
1131                 }
1132
1133                 public override Expression DoResolve (EmitContext ec)
1134                 {
1135                         string [] = new string [] { "foo", "bar" };
1136                         throw new CompletionResult ("", result);
1137                 }
1138
1139                 // 
1140                 // You should implement CloneTo if your CompletingExpression
1141                 // keeps copies to Statements or Expressions.   CloneTo
1142                 // is used by the lambda engine, so you should always
1143                 // implement this
1144                 //
1145                 protected override void CloneTo (CloneContext clonectx, Expression t)
1146                 {
1147                         // We do not keep references to anything interesting
1148                         // so cloning is an empty operation.
1149                 }
1150         }
1151         
1152
1153         We then rebuild our compiler:
1154
1155         (cd mcs/; make cs-parser.jay)
1156         (cd tools/csharplib; make install)
1157
1158         And re-run csharp:
1159
1160         (cd tools/csharp; csharp -v -v)
1161
1162         Chances are, you will get another error, but this time it will
1163         not be for the GENERATE_COMPLETION, we already handled that
1164         one.   This time it will be for COMPLETE_COMPLETION.  
1165
1166         The remaining of the process is iterative: you need to locate
1167         the state where this error happens.   It will look like this:
1168
1169         lex     state 623       reading COMPLETE_COMPLETION     value {interactive}(1,35):
1170         error   syntax error
1171         
1172         And make sure that the state can handle at this point a
1173         COMPLETE_COMPLETION.   When receiving COMPLETE_COMPLETION the
1174         parser needs to complete constructing the parse tree, so
1175         productions that handle COMPLETE_COMPLETION need to wrap
1176         things up with whatever data they have available and just make
1177         it so that the parser can complete.
1178
1179         To avoid rule duplication you can use the
1180         opt_COMPLETE_COMPLETION production and append it to an
1181         existing production:
1182
1183         foo : bar opt_COMPLETE_COMPLETION {
1184             ..
1185         }
1186
1187 * Miscellaneous
1188
1189 ** Error Processing.
1190
1191         Errors are reported during the various stages of the
1192         compilation process.  The compiler stops its processing if
1193         there are errors between the various phases.  This simplifies
1194         the code, because it is safe to assume always that the data
1195         structures that the compiler is operating on are always
1196         consistent.
1197
1198         The error codes in the Mono C# compiler are the same as those
1199         found in the Microsoft C# compiler, with a few exceptions
1200         (where we report a few more errors, those are documented in
1201         mcs/errors/errors.txt).  The goal is to reduce confusion to
1202         the users, and also to help us track the progress of the
1203         compiler in terms of the errors we report. 
1204
1205         The Report class provides error and warning display functions,
1206         and also keeps an error count which is used to stop the
1207         compiler between the phases.  
1208
1209         A couple of debugging tools are available here, and are useful
1210         when extending or fixing bugs in the compiler.  If the
1211         `--fatal' flag is passed to the compiler, the Report.Error
1212         routine will throw an exception.  This can be used to pinpoint
1213         the location of the bug and examine the variables around the
1214         error location.  If you pass a number to --fatal the exception
1215         will only be thrown when the error count reaches the specified
1216         count. 
1217
1218         Warnings can be turned into errors by using the `--werror'
1219         flag to the compiler. 
1220
1221         The report class also ignores warnings that have been
1222         specified on the command line with the `--nowarn' flag.
1223
1224         Finally, code in the compiler uses the global variable
1225         RootContext.WarningLevel in a few places to decide whether a
1226         warning is worth reporting to the user or not.  
1227
1228 ** Debugging the compiler
1229
1230         Sometimes it is convenient to find *how* a particular error
1231         message is being reported from, to do that, you might want to use
1232         the --fatal flag to mcs.  The flag will instruct the compiler to 
1233         abort with a stack trace execution when the error is reported.
1234
1235         You can use this with -warnaserror to obtain the same effect
1236         with warnings. 
1237
1238 ** Debugging the Parser.
1239
1240         A useful trick while debugging the parser is to pass the -v
1241         command line option to the compiler.
1242
1243         The -v command line option will dump the various Yacc states
1244         as well as the tokens that are being returned from the
1245         tokenizer to the compiler.
1246
1247         This is useful when tracking down problems when the compiler
1248         is not able to parse an expression correctly.
1249
1250         You can match the states reported with the contents of the
1251         y.output file, a file that contains the parsing tables and
1252         human-readable information about the generated parser.
1253
1254 * Editing the compiler sources
1255
1256         The compiler sources are intended to be edited with 134
1257         columns of width.
1258
1259 * Quick Hacks
1260
1261         Once you have a full build of mcs, you can improve your
1262         development time by just issuing make in the `mcs' directory or
1263         using `make qh' in the gmcs directory.