1 The Internals of the Mono C# Compiler
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.
15 * Overview: How the compiler fits together
17 The compilation process is managed by the compiler driver (it
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.
24 Once all the files have been parsed, the type hierarchy is
25 resolved. First interfaces are resolved, then types and
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.
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
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).
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
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
54 The following list will give you an idea of where the
55 different pieces of the compiler live:
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.
67 The state tracking for code generation.
71 Code to do semantic analysis and emit the attributes
76 Keeps track of the types defined in the source code,
77 as well as the assemblies loaded.
81 This contains the MCS type system.
85 Error and warning reporting methods.
89 Assorted utility functions used by the compiler.
95 The tokenizer for the C# language, it includes also
98 cs-parser.jay, cs-parser.cs:
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.
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.
114 Basic expression classes, and interfaces most shared
115 code and static methods are here.
119 Most of the different kinds of expressions classes
124 The assignment expression got its own file.
128 The classes that represent the constant expressions.
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.
140 The constant folder for binary expressions.
146 All of the abstract syntax tree elements for
147 statements live in this file. This also drives the
148 semantic analysis process.
152 Contains the support for implementing iterators from
153 the C# 2.0 specification.
155 Declarations, Classes, Structs, Enumerations
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.
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).
170 The most interesting type here is the `TypeContainer'
171 which is a derivative of the `DeclSpace'
175 Handles delegate definition and use.
179 Handles enumerations.
183 Holds and defines interfaces. All the code related to
184 interface declaration lives here.
188 During the parsing process, the compiler encapsulates
189 parameters in the Parameter and Parameters classes.
190 These classes provide definition and resolution tools
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.
201 * The parsing process
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:
210 a = "hello"; b = "world";
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.
225 ** The Tokenizer and the pre-processor
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.
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.
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.
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
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
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.
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'.
266 To debug problems in your grammar, you need to edit the
267 Makefile and make sure that the -ct options are passed to
268 jay. The current incarnation says:
270 ./../jay/jay -c < ./../jay/skeleton.cs cs-parser.jay
272 During debugging, you want to change this to:
274 ./../jay/jay -cvt < ./../jay/skeleton.cs cs-parser.jay
276 This generates a parser with debugging information and allows
277 you to activate verbose parser output in both the csharp
278 command and the mcs command by passing the "-v -v" flag (-v
281 When you do this, standard output will have a dump of the
282 tokens parsed and how the parser reacted to those. You can
283 look up the states with the y.output file that contains the
284 entire parser state diagram in human readable form.
288 Locations are encoded as a 32-bit number (the Location
289 struct) that map each input source line to a linear number.
290 As new files are parsed, the Location manager is informed of
291 the new file, to allow it to map back from an int constant to
292 a file + line number.
294 Prior to parsing/tokenizing any source files, the compiler
295 generates a list of all the source files and then reserves the
296 low N bits of the location to hold the source file, where N is
297 large enough to hold at least twice as many source files as were
298 specified on the command line (to allow for a #line in each file).
299 The upper 32-N bits are the line number in that file.
301 The token 0 is reserved for ``anonymous'' locations, ie. if we
302 don't know the location (Location.Null).
306 The parser is written using Jay, which is a port of Berkeley
307 Yacc to Java, that I later ported to C#.
309 Many people ask why the grammar of the parser does not match
310 exactly the definition in the C# specification. The reason is
311 simple: the grammar in the C# specification is designed to be
312 consumed by humans, and not by a computer program. Before
313 you can feed this grammar to a tool, it needs to be simplified
314 to allow the tool to generate a correct parser for it.
316 In the Mono C# compiler, we use a class for each of the
317 statements and expressions in the C# language. For example,
318 there is a `While' class for the `while' statement, a
319 `Cast' class to represent a cast expression and so on.
321 There is a Statement class, and an Expression class which are
322 the base classes for statements and expressions.
328 * Internal Representation
332 Expressions in the Mono C# compiler are represented by the
333 `Expression' class. This is an abstract class that particular
334 kinds of expressions have to inherit from and override a few
337 The base Expression class contains two fields: `eclass' which
338 represents the "expression classification" (from the C#
339 specs) and the type of the expression.
341 During parsing, the compiler will create the various trees of
342 expressions. These expressions have to be resolved before they
343 can be used. The semantic analysis is implemented by
344 resolving each of the expressions created during parsing and
345 creating fully resolved expressions.
347 A common pattern that you will notice in the compiler is this:
352 expr = expr.Resolve (ec);
354 // There was an error, stop processing by returning
356 The resolution process is implemented by overriding the
357 `DoResolve' method. The DoResolve method has to set the `eclass'
358 field and the `type', perform all error checking and computations
359 that will be required for code generation at this stage.
361 The return value from DoResolve is an expression. Most of the
362 time an Expression derived class will return itself (return
363 this) when it will handle the emission of the code itself, or
364 it can return a new Expression.
366 For example, the parser will create an "ElementAccess" class
371 During the resolution process, the compiler will know whether
372 this is an array access, or an indexer access. And will
373 return either an ArrayAccess expression or an IndexerAccess
374 expression from DoResolve.
376 All errors must be reported during the resolution phase
377 (DoResolve) and if an error is detected the DoResolve method
378 will return null which is used to flag that an error condition
379 has occurred, this will be used to stop compilation later on.
380 This means that anyone that calls Expression.Resolve must
381 check the return value for null which would indicate an error
384 The second stage that Expressions participate in is code
385 generation, this is done by overwriting the "Emit" method of
386 the Expression class. No error checking must be performed
389 We take advantage of the distinction between the expressions that
390 are generated by the parser and the expressions that are the
391 result of the semantic analysis phase for lambda expressions (more
392 information in the "Lambda Expressions" section).
394 But what is important is that expressions and statements that are
395 generated by the parser should implement the cloning
396 functionality. This is used lambda expressions require the
397 compiler to attempt to resolve a given block of code with
398 different possible types for parameters that have their types
401 ** Simple Names, MemberAccess
403 One of the most important classes in the compiler is
404 "SimpleName" which represents a simple name (from the C#
405 specification). The names during the resolution time are
406 bound to field names, parameter names or local variable names.
408 More complicated expressions like:
412 Are composed using the MemberAccess class which contains a
413 name (Math) and a SimpleName (Sin), this helps driving the
418 The parser creates expressions to represent types during
419 compilation. For example:
428 That will produce a "SimpleName" expression for the "Version"
429 word. And in this particular case, the parser will introduce
430 "Version vers" as a field declaration.
432 During the resolution process for the fields, the compiler
433 will have to resolve the word "Version" to a type. This is
434 done by using the "ResolveAsType" method in Expression instead
437 ResolveAsType just turns on a different set of code paths for
438 things like SimpleNames and does a different kind of error
439 checking than the one used by regular expressions.
443 Constants in the Mono C# compiler are represented by the
444 abstract class `Constant'. Constant is in turn derived from
445 Expression. The base constructor for `Constant' just sets the
446 expression class to be an `ExprClass.Value', Constants are
447 born in a fully resolved state, so the `DoResolve' method
448 only returns a reference to itself.
450 Each Constant should implement the `GetValue' method which
451 returns an object with the actual contents of this constant, a
452 utility virtual method called `AsString' is used to render a
453 diagnostic message. The output of AsString is shown to the
454 developer when an error or a warning is triggered.
456 Constant classes also participate in the constant folding
457 process. Constant folding is invoked by those expressions
458 that can be constant folded invoking the functionality
459 provided by the ConstantFold class (cfold.cs).
461 Each Constant has to implement a number of methods to convert
462 itself into a Constant of a different type. These methods are
463 called `ConvertToXXXX' and they are invoked by the wrapper
464 functions `ToXXXX'. These methods only perform implicit
465 numeric conversions. Explicit conversions are handled by the
466 `Cast' expression class.
468 The `ToXXXX' methods are the entry point, and provide error
469 reporting in case a conversion can not be performed.
473 The C# language requires constant folding to be implemented.
474 Constant folding is hooked up in the Binary.Resolve method.
475 If both sides of a binary expression are constants, then the
476 ConstantFold.BinaryFold routine is invoked.
478 This routine implements all the binary operator rules, it
479 is a mirror of the code that generates code for binary
480 operators, but that has to be evaluated at runtime.
482 If the constants can be folded, then a new constant expression
483 is returned, if not, then the null value is returned (for
484 example, the concatenation of a string constant and a numeric
485 constant is deferred to the runtime).
494 Compiler does some limited high-level optimalizations when
495 -optimize option is used
497 *** Instance field initializer to default value
508 int i = 0; // Field will not be redundantly assigned
509 int i2 = new int (); // This will be also completely optimized out
511 E e = E.Test; // Even this will go out.
516 *** Invariant meaning in a block
518 The seemingly small section in the standard entitled
519 "invariant meaning in a block" has several subtleties
520 involved, especially when we try to implement the semantics
523 Most of the semantics are trivial, and basically prevent local
524 variables from shadowing parameters and other local variables.
525 However, this notion is not limited to that, but affects all
526 simple name accesses within a block. And therein lies the rub
527 -- instead of just worrying about the issue when we arrive at
528 variable declarations, we need to verify this property at
529 every use of a simple name within a block.
531 The key notion that helps us is to note the bi-directional
532 action of a variable declaration. The declaration together
533 with anti-shadowing rules can maintain the IMiaB property for
534 the block containing the declaration and all nested sub
535 blocks. But, the IMiaB property also forces all surrounding
536 blocks to avoid using the name. We thus need to maintain a
537 blacklist of taboo names in all surrounding blocks -- and we
538 take the expedient of doing so simply: actually maintaining a
539 (superset of the) blacklist in each block data structure, which
540 we call the 'known_variable' list.
542 Because we create the 'known_variable' list during the parse
543 process, by the time we do simple name resolution, all the
544 blacklists are fully populated. So, we can just enforce the
545 rest of the IMiaB property by looking up a couple of lists.
547 This turns out to be quite efficient: when we used a block
548 tree walk, a test case took 5-10mins, while with this simple
549 mildly-redundant data structure, the time taken for the same
550 test case came down to a couple of seconds.
552 The IKnownVariable interface is a small wrinkle. Firstly, the
553 IMiaB also applies to parameter names, especially those of
554 anonymous methods. Secondly, we need more information than
555 just the name in the blacklist -- we need the location of the
556 name and where it's declared. We use the IKnownVariable
557 interface to abstract out the parser information stored for
558 local variables and parameters.
560 * The semantic analysis
562 Hence, the compiler driver has to parse all the input files.
563 Once all the input files have been parsed, and an internal
564 representation of the input program exists, the following
567 * The interface hierarchy is resolved first.
568 As the interface hierarchy is constructed,
569 TypeBuilder objects are created for each one of
572 * Classes and structure hierarchy is resolved next,
573 TypeBuilder objects are created for them.
575 * Constants and enumerations are resolved.
577 * Method, indexer, properties, delegates and event
578 definitions are now entered into the TypeBuilders.
580 * Elements that contain code are now invoked to
581 perform semantic analysis and code generation.
585 Most programs use external references (assemblies and modules).
586 Compiler loads all referenced top-level types from referenced
587 assemblies into import cached. It imports initialy only C#
588 valid top-level types all other members are imported on demand
591 * Namespaces definition
593 Before any type resolution can be done we define all compiled
594 namespaces. This is mainly done to prepare using clauses of each
595 namespace block before any type resolution takes a place.
599 The first step of type definition is to resolve base class or
600 base interfaces to correctly setup type hierarchy before any
603 At this point we do some error checking and verify that the
604 members inheritance is correct and some other members
607 By the time we are done, all classes, structs and interfaces
608 have been defined and all their members have been defined as
613 MemberCache is one of core compiler components. It maintains information
614 about types and their members. It tries to be as fast as possible
615 because almost all resolve operations end up querying members info in
618 MemberCache is not definition but specification oriented to maintain
619 differences between inflated versions of generic types. This makes usage
620 of MemberCache simple because consumer does not need to care how to inflate
621 current member and returned type information will always give correctly
622 inflated type. However setting MemberCache up is one of the most complicated
623 parts of the compiler due to possible dependencies when types are defined
624 and complexity of nested types.
630 The EmitContext class is created any time that IL code is to
631 be generated (methods, properties, indexers and attributes all
632 create EmitContexts).
634 The EmitContext keeps track of the current namespace and type
635 container. This is used during name resolution.
637 An EmitContext is used by the underlying code generation
638 facilities to track the state of code generation:
640 * The ILGenerator used to generate code for this
643 * The TypeContainer where the code lives, this is used
644 to access the TypeBuilder.
646 * The DeclSpace, this is used to resolve names through
647 RootContext.LookupType in the various statements and
650 Code generation state is also tracked here:
654 This variable tracks the `checked' state of the
655 compilation, it controls whether we should generate
656 code that does overflow checking, or if we generate
657 code that ignores overflows.
659 The default setting comes from the command line
660 option to generate checked or unchecked code plus
661 any source code changes using the checked/unchecked
662 statements or expressions. Contrast this with the
663 ConstantCheckState flag.
667 The constant check state is always set to `true' and
668 cant be changed from the command line. The source
669 code can change this setting with the `checked' and
670 `unchecked' statements and expressions.
674 Whether we are emitting code inside a static or
679 The value that is allowed to be returned or NULL if
680 there is no return type.
684 A `Label' used by the code if it must jump to it.
685 This is used by a few routines that deals with exception
690 Whether we have a return label defined by the toplevel
695 Points to the Type (extracted from the
696 TypeContainer) that declares this body of code
702 Whether this is generating code for a constructor
706 Tracks the current block being generated.
710 The location where return has to jump to return the
713 A few variables are used to track the state for checking in
714 for loops, or in try/catch statements:
718 Whether we are in a Finally block
722 Whether we are in a Try block
726 Whether we are in a Catch block
729 Whether we are inside an unsafe block
731 Methods exposed by the EmitContext:
735 This emits a toplevel block.
737 This routine is very simple, to allow the anonymous
738 method support to roll its two-stage version of this
741 * NeedReturnLabel ():
743 This is used to flag during the resolution phase that
744 the driver needs to initialize the `ReturnLabel'
748 The introduction of anonymous methods in the compiler changed
749 various ways of doing things in the compiler. The most
750 significant one is the hard split between the resolution phase
751 and the emission phases of the compiler.
753 For instance, routines that referenced local variables no
754 longer can safely create temporary variables during the
755 resolution phase: they must do so from the emission phase,
756 since the variable might have been "captured", hence access to
757 it can not be done with the local-variable operations from the
760 The code emission is in:
764 Which drives the process, it first resolves the topblock, then
765 emits the required metadata (local variable definitions) and
766 finally emits the code.
768 A detailed description of anonymous methods and iterators is
769 on the new-anonymous-design.txt file in this directory.
773 Lambda expressions can come in two forms: those that have implicit
774 parameter types and those that have explicit parameter types, for
779 Foo ((int x) => x + 1);
786 One of the problems that we faced with lambda expressions is
787 that lambda expressions need to be "probed" with different
788 types until a working combination is found.
794 The above expression could mean vastly different things depending
795 on the type of "x". The compiler determines the type of "x" (left
796 hand side "x") at the moment the above expression is "bound",
797 which means that during the compilation process it will try to
798 match the above lambda with all the possible types available, for
801 delegate int di (int x);
802 delegate string ds (string s);
809 In the above example, overload resolution will try "x" as an "int"
810 and will try "x" as a string. And if one of them "compiles" thats
811 the one it picks (and it also copes with ambiguities if there was
812 more than one matching method).
814 To compile this, we need to hook into the resolution process,
815 but since the resolution process has side effects (calling
816 Resolve can either return instances of the resolved expression
817 type, or can alter field internals) it was necessary to
818 incorporate a framework to "clone" expressions before we
821 The support for cloning was added into Statements and
822 Expressions and is only necessary for objects of those types
823 that are created during parsing. It is not necessary to
824 support these in the classes that are the result of calling
825 Resolve. This means that SimpleName needs support for
826 Cloning, but FieldExpr does not need it (SimpleName is created
827 by the parser, FieldExpr is created during semantic analysis
830 The work happens through the public method called "Clone" that
831 clones the given Statement or Expression. The base method in
832 Statement and Expression merely does a MemberwiseCopy of the
833 elements and then calls the virtual CloneTo method to complete
834 the copy. By default this method throws an exception, this
835 is useful to catch cases where we forgot to override CloneTo
836 for a given Statement/Expression.
838 With the cloning capability it became possible to call resolve
839 multiple times (once for each Cloned copy) and based on this
840 picking the one implementation that would compile and that
841 would not be ambiguous.
843 The cloning process is basically a deep copy that happens in the
844 LambdaExpression class and it clones the top-level block for the
845 lambda expression. The cloning has the side effect of cloning
846 the entire containing block as well.
848 This happens inside this method:
850 public override bool ImplicitStandardConversionExists (Type delegate_type)
852 This is used to determine if the current Lambda expression can be
853 implicitly converted to the given delegate type.
855 And also happens as a result of the generic method parameter
858 ** Lambda Expressions and Cloning
860 All statements that are created during the parsing method should
861 implement the CloneTo method:
863 protected virtual void CloneTo (CloneContext clonectx, Statement target)
865 This method is called by the Statement.Clone method after it has
866 done a shallow-copy of all the fields in the statement, and they
867 should typically Clone any child statements.
869 Expressions should implement the CloneTo method as well:
871 protected virtual void CloneTo (CloneContext clonectx, Expression target)
873 ** Lambda Expressions and Contextual Return
875 When an expression is parsed as a lambda expression, the parser
876 inserts a call to a special statement, the contextual return.
882 Is actually compiled as:
884 a => contextual_return (a+1)
886 The contextual_return statement will behave differently depending
887 on the return type of the delegate that the expression will be
890 If the delegate return type is void, the above will basically turn
891 into an empty operation. Otherwise the above will become
892 a return statement that can infer return types.
896 Compiler produces .mdb symbol file for better debugging experience. The
897 process is quite straightforward. For every statement or a block there
898 is an entry in symbol file. Each entry includes of start location of
899 the statement and it's starting IL offset in the method. For most statements
900 this is easy but few need special handling (e.g. do, while).
902 When sequence point is needed to represent original location and no IL
903 entry is written for the line we emit `nop' instruction. This is done only
904 for very few constructs (e.g. block opening brace).
906 Captured variables are not treated differently at the moment. Debugger has
907 internal knowledge of their mangled names and how to decode them.
909 * IKVM.Reflection vs System.Reflection
911 Mono compiler can be compiled using different reflection backends. At the
912 moment we support System.Reflection and IKVM.Reflection they both use same
913 API as official System.Reflection.Emit API which allows us to maintain only
914 single version of compiler with few using aliases to specialise.
916 The backends are not plug-able but require compiler to be compiled with
917 specific STATIC define when targeting IKVM.Reflection.
919 IKVM.Reflection is used for static compilation. This means the compiler runs
920 in batch mode like most compilers do. It can target any runtime version and
921 use any mscorlib. The mcs.exe is using IKVM.Reflection.
923 System.Reflection is used for dynamic compilation. This mode is used by
924 our REPL and Evaluator API. Produced IL code is not written to disc but
925 executed by runtime (JIT). Mono.CSharp.dll is using System.Reflection and
926 System.Reflection.Emit.
930 The compiler can now be used as a library, the API exposed
931 lives in the Mono.CSharp.Evaluator class and it can currently
932 compile statements and expressions passed as strings and
933 compile or compile and execute immediately.
935 As of April 2009 this creates a new in-memory assembly for
936 each statement evaluated.
938 To support this evaluator mode, the evaluator API primes the
939 tokenizer with an initial character that would not appear in
940 valid C# code and is one of:
942 int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
943 int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
944 int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
946 These character are turned into the following tokens:
948 %token EVAL_STATEMENT_PARSER
949 %token EVAL_COMPILATION_UNIT_PARSER
950 %token EVAL_USING_DECLARATIONS_UNIT_PARSER
952 This means that the first token returned by the tokenizer when
953 used by the Evalutor API is a special token that helps the
954 yacc parser go from the traditional parsing of a full
955 compilation-unit to the interactive parsing:
957 The entry production for the compiler basically becomes:
961 // The standard rules
963 : outer_declarations opt_EOF
964 | outer_declarations global_attributes opt_EOF
965 | global_attributes opt_EOF
966 | opt_EOF /* allow empty files */
969 // The rule that allows interactive parsing
971 | interactive_parsing { Lexer.CompleteOnEOF = false; } opt_EOF
975 // This is where Evaluator API drives the compilation
978 : EVAL_STATEMENT_PARSER EOF
979 | EVAL_USING_DECLARATIONS_UNIT_PARSER using_directives
980 | EVAL_STATEMENT_PARSER
981 interactive_statement_list opt_COMPLETE_COMPLETION
982 | EVAL_COMPILATION_UNIT_PARSER
983 interactive_compilation_unit
986 Since there is a little bit of ambiguity for example in the
987 presence of the using directive and the using statement a
988 micro-predicting parser with multiple token look aheads is
989 used in eval.cs to resolve the ambiguity and produce the
990 actual token that will drive the compilation.
992 This helps this scenario:
995 using (var x = File.OpenRead) {}
997 This is the meaning of these new initial tokens:
999 EVAL_STATEMENT_PARSER
1000 Used to parse statements or expressions as statements.
1002 EVAL_USING_DECLARATIONS_UNIT_PARSER
1003 This instructs the parser to merely do using-directive
1004 parsing instead of statement parsing.
1006 EVAL_COMPILATION_UNIT_PARSER
1007 Used to evaluate toplevel declarations like namespaces
1010 The feature is currently disabled because later stages
1011 of the compiler are not yet able to lookup previous
1012 definitions of classes.
1014 What happens is that between each call to Evaluate()
1015 we reset the compiler state and at this stage we drop
1016 also any existing definitions, so evaluating "class X
1017 {}" followed by "class Y : X {}" does not currently
1020 We need to make sure that new type definitions used
1021 interactively are preseved from one evaluation to the
1024 The evaluator the expression or statement `BODY' is hosted
1025 inside a wrapper class. If the statement is a variable
1026 declaration then the declaration is split from the assignment
1027 into a DECLARATION and BODY.
1029 This is what the code generated looks like:
1031 public class Foo : $InteractiveBaseClass {
1034 static void Host (ref object $retval)
1040 Since both statements and expressions are mixed together and
1041 it is useful to use the Evaluator to compute expressions we
1042 return expressions for example for "1+2" in the `retval'
1045 To support this, the reference retval parameter is set to a
1046 special internal value that means "Value was not set" before
1047 the method Host is invoked. During parsing the parser turns
1048 expressions like "1+2" into:
1052 This is done using a special OptionalAssign
1053 ExpressionStatement class.
1055 When the Host method return, if the value of retval is still
1056 the special flag no value was set. Otherwise the result of
1057 the expression is in retval.
1059 The `InteractiveBaseClass' is the base class for the method,
1060 this allows for embedders to provide different base classes
1061 that could expose new static methods that could be useful
1062 during expression evaluation.
1064 Our default implementation is InteractiveBaseClass and new
1065 implementations should derive from this and set the property
1066 in the Evaluator to it.
1068 In the future we will move to creating dynamic methods as the
1069 wrapper for this code.
1073 Support for code completion is available to allow the compiler
1074 to provide a list of possible completions at any given point
1075 int he parsing process. This is used for Tab-completion in
1076 an interactive shell or visual aids in GUI shells for possible
1079 This method is available as part of the Evaluator API where a
1080 special method GetCompletions returns a list of possible
1081 completions given a partial input.
1083 The parser and tokenizer work together so that the tokenizer
1084 upon reaching the end of the input generates the following
1085 tokens: GENERATE_COMPLETION followed by as many
1086 COMPLETE_COMPLETION token and finally the EOF token.
1088 GENERATE_COMPLETION needs to be handled in every production
1089 where the user is likely to press the TAB key in the shell (or
1090 in the future the GUI, or an explicit request in an IDE).
1091 COMPLETE_COMPLETION must be handled throughout the grammar to
1092 provide a way of completing the parsed expression. See below
1095 For the member access case, I have added productions that
1096 mirror the non-completing productions, for example:
1098 primary_expression DOT IDENTIFIER GENERATE_COMPLETION
1100 LocatedToken lt = (LocatedToken) $3;
1101 $$ = new CompletionMemberAccess ((Expression) $1, lt.Value, lt.Location);
1106 primary_expression DOT IDENTIFIER opt_type_argument_list
1108 LocatedToken lt = (LocatedToken) $3;
1109 $$ = new MemberAccess ((Expression) $1, lt.Value, (TypeArguments) $4, lt.Location);
1112 The CompletionMemberAccess is a new kind of
1113 Mono.CSharp.Expression that does the actual lookup. It
1114 internally mimics some of the MemberAccess code but has been
1115 tuned for this particular use.
1117 After this initial token is processed GENERATE_COMPLETION the
1118 tokenizer will emit COMPLETE_COMPLETION tokens. This is done
1119 to help the parser basically produce a valid result from the
1120 partial input it received. For example it is able to produce
1121 a valid AST from "(x" even if no parenthesis has been closed.
1122 This is achieved by sprinkling the grammar with productions
1123 that can cope with this "winding down" token, for example this
1124 is what parenthesized_expression looks like now:
1126 parenthesized_expression
1127 : OPEN_PARENS expression CLOSE_PARENS
1129 $$ = new ParenthesizedExpression ((Expression) $2);
1134 | OPEN_PARENS expression COMPLETE_COMPLETION
1136 $$ = new ParenthesizedExpression ((Expression) $2);
1140 Once we have wrapped up everything we generate the last EOF token.
1142 When the AST is complete we actually trigger the regular
1143 semantic analysis process. The DoResolve method of each node
1144 in our abstract syntax tree will compute the result and
1145 communicate the possible completions by throwing an exception
1146 of type CompletionResult.
1148 So for example if the user type "T" and the completion is
1149 "ToString" we return "oString".
1151 ** Enhancing Completion
1153 Code completion is a process that will be curated over time.
1154 Just like producing good error reports and warnings is an
1155 iterative process, to find a good balance, the code completion
1156 engine in the compiler will require tuning to find the right
1157 balance for the end user.
1159 This section explains the basic process by which you can
1160 improve the code completion by using a real life sample.
1162 Once you add the GENERATE_COMPLETION token to your grammar
1163 rule, chances are, you will need to alter the grammar to
1164 support COMPLETE_COMPLETION all the way up to the toplevel
1167 To debug this, you will want to try the completion with either
1168 a sample program or with the `csharp' tool.
1174 This will turn on the parser debugging output and will
1175 generate a lot of data when parsing its input (make sure that
1176 your parser has been compiled with the -v flag, see above for
1179 To start with a new completion scheme, type your C# code and
1180 then hit the tab key to trigger the completion engine. In the
1181 generated output you will want to look for the first time that
1182 the parser got the GENERATE_COMPLETION token, it will look
1185 lex state 414 reading GENERATE_COMPLETION value {interactive}(1,35):
1187 The first word `lex' indicates that the parser called the
1188 lexer at state 414 (more on this in a second) and it got back
1189 from the lexer the token GENERATE_COMPLETION. If this is a
1190 kind of completion chances are, you will get an error
1191 immediately as the rules at that point do not know how to cope
1192 with the stream of COMPLETE_COMPLETION tokens that will
1193 follow, they will look like this:
1196 pop state 414 on error
1197 pop state 805 on error
1198 pop state 628 on error
1199 pop state 417 on error
1201 The first line means that the parser has entered the error
1202 state and will pop states until it can find a production that
1203 can deal with the error. At that point an error message will
1206 Open the file `y.output' which describes the parser states
1207 generated by jay and search for the state that was reported
1208 previously in `lex' that got the GENERATE_COMPLETION:
1211 object_or_collection_initializer : OPEN_BRACE . opt_member_initializer_list CLOSE_BRACE (444)
1212 object_or_collection_initializer : OPEN_BRACE . member_initializer_list COMMA CLOSE_BRACE (445)
1213 opt_member_initializer_list : . (446)
1215 We now know that the parser was in the middle of parsing an
1216 `object_or_collection_initializer' and had alread seen the
1219 The `.' after OPEN_BRACE indicates the current state of the
1220 parser, and this is where our parser got the
1221 GENERATE_COMPLETION token. As you can see from the three
1222 rules in this sample, support for GENERATE_COMPLETION did not
1225 So we must edit the grammar to add a production for this case,
1226 I made the code look like this:
1230 | GENERATE_COMPLETION
1232 LocatedToken lt = $1 as LocatedToken;
1233 $$ = new CompletionElementInitializer (GetLocation ($1));
1237 This new production creates the class
1238 CompletionElementInitializer and returns this as the value for
1239 this. The following is a trivial implementation that always
1240 returns "foo" and "bar" as the two completions and it
1241 illustrates how things work:
1243 public class CompletionElementInitializer : CompletingExpression {
1244 public CompletionElementInitializer (Location l)
1249 public override Expression DoResolve (EmitContext ec)
1251 string [] = new string [] { "foo", "bar" };
1252 throw new CompletionResult ("", result);
1256 // You should implement CloneTo if your CompletingExpression
1257 // keeps copies to Statements or Expressions. CloneTo
1258 // is used by the lambda engine, so you should always
1261 protected override void CloneTo (CloneContext clonectx, Expression t)
1263 // We do not keep references to anything interesting
1264 // so cloning is an empty operation.
1269 We then rebuild our compiler:
1271 (cd mcs/; make cs-parser.jay)
1272 (cd class/Mono.CSharp; make install)
1276 (cd tools/csharp; csharp -v -v)
1278 Chances are, you will get another error, but this time it will
1279 not be for the GENERATE_COMPLETION, we already handled that
1280 one. This time it will be for COMPLETE_COMPLETION.
1282 The remaining of the process is iterative: you need to locate
1283 the state where this error happens. It will look like this:
1285 lex state 623 reading COMPLETE_COMPLETION value {interactive}(1,35):
1288 And make sure that the state can handle at this point a
1289 COMPLETE_COMPLETION. When receiving COMPLETE_COMPLETION the
1290 parser needs to complete constructing the parse tree, so
1291 productions that handle COMPLETE_COMPLETION need to wrap
1292 things up with whatever data they have available and just make
1293 it so that the parser can complete.
1295 To avoid rule duplication you can use the
1296 opt_COMPLETE_COMPLETION production and append it to an
1297 existing production:
1299 foo : bar opt_COMPLETE_COMPLETION {
1305 ** Error Processing.
1307 Errors are reported during the various stages of the
1308 compilation process. The compiler stops its processing if
1309 there are errors between the various phases. This simplifies
1310 the code, because it is safe to assume always that the data
1311 structures that the compiler is operating on are always
1314 The error codes in the Mono C# compiler are the same as those
1315 found in the Microsoft C# compiler, with a few exceptions
1316 (where we report a few more errors, those are documented in
1317 mcs/errors/errors.txt). The goal is to reduce confusion to
1318 the users, and also to help us track the progress of the
1319 compiler in terms of the errors we report.
1321 The Report class provides error and warning display functions,
1322 and also keeps an error count which is used to stop the
1323 compiler between the phases.
1325 A couple of debugging tools are available here, and are useful
1326 when extending or fixing bugs in the compiler. If the
1327 `--fatal' flag is passed to the compiler, the Report.Error
1328 routine will throw an exception. This can be used to pinpoint
1329 the location of the bug and examine the variables around the
1330 error location. If you pass a number to --fatal the exception
1331 will only be thrown when the error count reaches the specified
1334 Warnings can be turned into errors by using the `--werror'
1335 flag to the compiler.
1337 The report class also ignores warnings that have been
1338 specified on the command line with the `--nowarn' flag.
1340 Finally, code in the compiler uses the global variable
1341 RootContext.WarningLevel in a few places to decide whether a
1342 warning is worth reporting to the user or not.
1344 ** Debugging the compiler
1346 Sometimes it is convenient to find *how* a particular error
1347 message is being reported from, to do that, you might want to use
1348 the --fatal flag to mcs. The flag will instruct the compiler to
1349 abort with a stack trace execution when the error is reported.
1351 You can use this with -warnaserror to obtain the same effect
1354 ** Debugging the Parser.
1356 A useful trick while debugging the parser is to pass the -v
1357 command line option to the compiler.
1359 The -v command line option will dump the various Yacc states
1360 as well as the tokens that are being returned from the
1361 tokenizer to the compiler.
1363 This is useful when tracking down problems when the compiler
1364 is not able to parse an expression correctly.
1366 You can match the states reported with the contents of the
1367 y.output file, a file that contains the parsing tables and
1368 human-readable information about the generated parser.
1370 * Editing the compiler sources
1372 The compiler sources are intended to be edited with 134
1377 Once you have a full build of mcs, you can improve your
1378 development time by just issuing make in the `mcs' directory or
1379 using `make qh' in the gmcs directory.