[nemerle] r8434 committed - Working on Integration: Implementing CodeDom support.

8 views
Skip to first unread message

codesite...@google.com

unread,
Nov 11, 2009, 3:10:28 PM11/11/09
to nemer...@googlegroups.com
Revision: 8434
Author: v...@rsdn.ru
Date: Wed Nov 11 12:09:20 2009
Log: Working on Integration: Implementing CodeDom support.
http://code.google.com/p/nemerle/source/detail?r=8434

Added:

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Async/AsyncRequest/MergeCodeCompileUnitAsyncRequest.n
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/CodeDomHelper.n

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/FormCodeDomGenerator.n

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/FormCodeDomParser.n

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/NemerleCodeDomProvider.n

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/NemerleCodeParser.n

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/NemerleCodeParserBase.n

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Nemerle.Completion2/Engine/BackgroundWorks/Engine-MergeCodeCompileUnit.n
Deleted:
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDomHelper.n
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/FormCodeDomGenerator.n
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/FormCodeDomParser.n
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/FormCodeInfo.n

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/NemerleCodeDomProvider.n
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/NemerleCodeParser.n
Modified:

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Async/AsyncRequestType.n

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Nemerle.Compiler.Utils.csproj

/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Nemerle.Compiler.Utils.nproj

/nemerle/trunk/VsIntegration/Nemerle.VisualStudio/Project/NemerleFileNodeCodeDomProvider.cs

=======================================
--- /dev/null
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Async/AsyncRequest/MergeCodeCompileUnitAsyncRequest.n
Wed Nov 11 12:09:20 2009
@@ -0,0 +1,25 @@
+using System;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.Linq;
+using System.Threading;
+
+using Nemerle.Collections;
+using Nemerle.Completion2;
+using Nemerle.Utility;
+
+namespace Nemerle.Compiler.Utils.Async
+{
+ public class MergeCodeCompileUnitAsyncRequest : AsyncRequest
+ {
+ public this(engine : Engine, codeCompileUnit : CodeCompileUnit, work :
Action[AsyncRequest])
+ {
+ base(AsyncRequestType.MergeCodeCompileUnit, engine, null, work);
+ this.CodeCompileUnit = codeCompileUnit;
+ }
+
+ public CodeCompileUnit : CodeCompileUnit { get; private set; }
+
+ public MergeInfo : array[Location * string] { get; internal set; }
+ }
+}
=======================================
--- /dev/null
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/CodeDomHelper.n
Wed Nov 11 12:09:20 2009
@@ -0,0 +1,132 @@
+using System;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.Collections;
+using System.IO;
+using System.Reflection;
+
+using Nemerle.Compiler;
+using Nemerle.Compiler.Typedtree;
+using Nemerle.Collections;
+using SCG = System.Collections.Generic;
+
+namespace Nemerle.Compiler.Utils
+{
+ public module CodeDomHelper
+ {
+ public IsPartial(attrs: NemerleAttributes): bool
+ {
+ attrs %&& NemerleAttributes.Partial
+ }
+
+ public GetMemberAttributes(attrs: NemerleAttributes, field: bool =
false): MemberAttributes
+ {
+ mutable res: MemberAttributes;
+
+ when(attrs %&& NemerleAttributes.Static) res |=
MemberAttributes.Static;
+ when(attrs %&& NemerleAttributes.Public) res |=
MemberAttributes.Public;
+ when(attrs %&& NemerleAttributes.Private) res |=
MemberAttributes.Private;
+
+ if(attrs %&& NemerleAttributes.Internal && attrs %&&
NemerleAttributes.Protected)
+ res |= MemberAttributes.FamilyOrAssembly
+ else
+ {
+ when(attrs %&& NemerleAttributes.Internal) res |=
MemberAttributes.FamilyAndAssembly;
+ when(attrs %&& NemerleAttributes.Protected) res |=
MemberAttributes.Family;
+ }
+
+ when(field && !(attrs %&& NemerleAttributes.Mutable)) res |=
MemberAttributes.Const;
+
+ when(attrs %&& NemerleAttributes.New) res |= MemberAttributes.New;
+ when(attrs %&& NemerleAttributes.Override) res |=
MemberAttributes.Override;
+ when(attrs %&& NemerleAttributes.Sealed) res |=
MemberAttributes.Final;
+ when(attrs %&& NemerleAttributes.Virtual) res |=
MemberAttributes.VTableMask;
+
+ when(res == 0)
+ {
+ if(field)
+ res |= MemberAttributes.Private
+ else
+ res |= MemberAttributes.Assembly
+ }
+
+ res;
+ }
+
+ public GetTypeAttributes(attrs: NemerleAttributes): TypeAttributes
+ {
+ if(attrs == NemerleAttributes.None)
+ TypeAttributes.NotPublic;
+ else
+ {
+ mutable res: TypeAttributes =
+ if(attrs %&& NemerleAttributes.Public)
+ TypeAttributes.Public
+ else
+ TypeAttributes.NotPublic;
+
+ when(attrs %&& NemerleAttributes.Abstract) res |=
TypeAttributes.Abstract;
+ when(attrs %&& NemerleAttributes.Sealed) res |=
TypeAttributes.Sealed;
+ when(attrs %&& NemerleAttributes.SpecialName) res |=
TypeAttributes.SpecialName;
+ res;
+ }
+ }
+
+ public GetLinePragma(expr: TExpr) : CodeLinePragma
+ {
+ def loc = expr.Location;
+ CodeLinePragma(loc.File,loc.Line)
+ }
+
+ public MapFilterByType[T1,T2](this collection: SCG.IEnumerable[T1]) :
list[T2]
+ {
+ def res = SCG.List();
+ foreach(e is T2 in collection)
+ res.Add(e);
+
+ res.ToList()
+ }
+
+ public MapFilterByType[T2](this collection: IEnumerable) : list[T2]
+ {
+ def res = SCG.List();
+ foreach(e is T2 in collection)
+ res.Add(e);
+
+ res.ToList()
+ }
+
+ public StringToListOfLines(s: string) : SCG.List[string]
+ {
+ def res = SCG.List();
+
+ using(def sr = StringReader(s))
+ for(mutable s1 = sr.ReadLine(); s1 != null; s1 = sr.ReadLine())
+ res.Add(s1);
+
+ res
+ }
+
+ // Debug output method
+ public ToString(unit: CodeCompileUnit, generator: ICodeGenerator) :
string
+ {
+ mutable s : string = null;
+ using (def sw = StringWriter())
+ {
+ //def codeGen = NemerleCodeGenerator() : ICodeGenerator;
+ generator.GenerateCodeFromCompileUnit(unit,sw,null);
+ s = sw.ToString();
+ }
+ s
+ }
+
+ public PrintMacro(the_macro: IMacro) : string
+ {
+ $"[Macro:\n GetName = $(the_macro.GetName())\n"
+ " GetNamespace () = $(the_macro.GetNamespace ())\n"
+ " Keywords = $(the_macro.Keywords)\n"
+ " Usage = $(the_macro.Usage)\n";
+ //" SyntaxExtension = $(the_macro.SyntaxExtension())]";
+ }
+ }
+}
=======================================
--- /dev/null
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/FormCodeDomGenerator.n
Wed Nov 11 12:09:20 2009
@@ -0,0 +1,498 @@
+using System;
+using System.IO;
+using System.Collections;
+using System.Collections.Generic;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.ComponentModel.Design.Serialization;
+using System.Diagnostics;
+using System.Drawing;
+using SR = System.Reflection;
+
+using Nemerle.Assertions;
+using Nemerle.Collections;
+using Nemerle.Compiler;
+using Nemerle.Compiler.Parsetree;
+using Nemerle.Compiler.Typedtree;
+using Nemerle.Completion2;
+using Nemerle.Imperative;
+using Nemerle.Utility;
+
+namespace Nemerle.Compiler.Utils
+{
+ // now FormCodeDomGenerator only parses files from Project.CompileUnits
+ // it is not thread-safe at the moment!
+
+ // TODO : generation of new files
+ public class FormCodeDomGenerator : NemerleCodeGenerator
+ {
+ protected enum ChangeStatus { | Equal | NonEqual | Renamed };
+
+ mutable _project : Project;
+
+ mutable _mainFileIndex : int;
+ mutable _designerFileIndex : int;
+
+ mutable _mainFileMerger : IFileTextMerger;
+ mutable _designerFileMerger : IFileTextMerger;
+
+ mutable _codeDomMethods : list[CodeMemberMethod];
+ mutable _codeDomFields : list[CodeMemberField];
+
+ mutable _oldFields: list[FieldBuilder];
+ mutable _oldMethods: list[MethodBuilder];
+
+ public static ToString(statements : CodeStatementCollection) : string
+ {
+ def codeDomGenerator = FormCodeDomGenerator();
+ def writer = StringWriter();
+ codeDomGenerator.Output = writer;
+ codeDomGenerator.GenerateStatements(statements);
+ writer.ToString()
+ }
+
+ /*
+ mutable _output : TextWriter; // changed before immediate processing
+
+ protected new Output : TextWriter
+ {
+ get { _output }
+ set { _output = value; }
+ }
+
+ mutable _currentFileIndex : int;
+
+ protected SetMainOutput() : void
+ {
+ _currentFileIndex = _mainFileIndex;
+ Output = _mainFile;
+ }
+
+ protected SetDesignerOutput() : void
+ {
+ _currentFileIndex = _designerFileIndex;
+ Output = _designerFile;
+ }
+ */
+
+ public MergeFormCodeFromCompileUnit(
+ [NotNull] project : Project,
+ mainFilePath : string,
+ designerFilePath : string,
+ codeCompileUnit : CodeCompileUnit,
+ mainFileMerger : IFileTextMerger,
+ designerFileMerger : IFileTextMerger,
+ options : CodeGeneratorOptions
+ )
+ : void
+ {
+ _project = project;
+
+ _mainFileMerger = mainFileMerger;
+ _designerFileMerger = designerFileMerger;
+
+ _mainFileIndex = Location.GetFileIndex(mainFilePath);
+ _designerFileIndex = Location.GetFileIndex(designerFilePath);
+
+ Options = if (options != null) options else CodeGeneratorOptions();
+
+ Debug.Assert(codeCompileUnit.Namespaces.Count == 1,"CodeCompileUnit
for a form should contain only one namespace!");
+
+ // TODO : do we need to bother about namespace Imports?
+
+ Debug.Assert(codeCompileUnit.Namespaces[0].Types.Count == 1,
+ "CodeCompileUnit for a form should contain only one form class!");
+
+ def nsDecls =
project.CompileUnits.GetTopNamespace(_mainFileIndex).Decls.MapFilterByType.[Decl.Namespace]();
+
+ Debug.Assert(nsDecls.Length == 1,
+ "Root Decl for a form CompileUnit should contain only one form
class!" );
+ def nsDecl = nsDecls.Head;
+
+ // TODO : Check for form class
+ MergeClassDecl(codeCompileUnit.Namespaces[0].Types[0],
+ match(nsDecl.Decls.Find(_ is Decl.Type))
+ { | Some(Decl.Type(ast)) => ast
+ | _ => throw ApplicationException(
+ "Can't find typeBuilder for the Form class
in CodeDom")
+ }.TypeBuilder);
+
+ _mainFileMerger.Flush();
+ _designerFileMerger.Flush();
+ }
+
+ private allDeclaredFlags : SR.BindingFlags = BindingFlags.DeclaredOnly
|
+ BindingFlags.Instance |
+ BindingFlags.Static |
+ BindingFlags.Public |
+ BindingFlags.NonPublic;
+
+ protected MergeClassDecl(classDecl: CodeTypeDeclaration, typeBuilder:
TypeBuilder) : void
+ {
+ _oldMethods = typeBuilder.GetMembers(allDeclaredFlags).Filter(
+ m => match(m.MemberKind) { | MemberKinds.Method | Constructor =>
true | _ => false }
+ && !m.Name.OrdinalStartsWith("_N_field_initialiser"))
+ .MapFilterByType.[MethodBuilder]();
+
+ _codeDomMethods =
classDecl.Members.MapFilterByType.[CodeMemberMethod]();
+
+ _oldFields =
typeBuilder.GetFields(allDeclaredFlags).MapFilterByType.[FieldBuilder]();
+ _codeDomFields =
classDecl.Members.MapFilterByType.[CodeMemberField]();
+
+ MergeMethods(classDecl);
+ MergeFields();
+ }
+
+ protected MergeFields() : void
+ {
+ //classDecl.Members.Filter(_ is CodeMemberField).Map(_ :
CodeMemberField);
+
+ // DEBUG
+ Debug.Print("oldFields:\n");
+ _oldFields.Iter(f => Debug.Print($" field $(f.Name)") );
+
+ //Debug.Print("allFields:\n");
+ //typeBuilder.GetFields().Iter(f => Debug.Print($" field
$(f.Name)\n") );
+
+ Debug.Print("codedomFields:\n");
+ _codeDomFields.Iter(f => Debug.Print($" field $(f.Name)") );
+
+ def isAddLine = Options.BlankLinesBetweenMembers;
+
+ def AddField(cdf) // to designer
+ {
+ using(def sw = StringWriter())
+ {
+ Output = sw;
+ Indent = 2; // TODO: maybe we should change it dynamically?
+
+ if (isAddLine)
+ Output.WriteLine();
+ else
+ GenerateIndent();
+ GenerateField(cdf);
+
+ //def linesList =
CodeDomHelper.StringToListOfLines(sw.ToString() );
+
//_designerFileMerger.AddLines(_formCodeInfo.newFieldInsertionLine,
+ // linesList);
+
+ //_formCodeInfo.newFieldInsertionLine += linesList.Count; //
TODO : maybe we have to add additional lines
+ //Debug.Print($"_formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine) "
+ // "after adding $(cdf.Name)\n");
+ }
+ }
+
+ def RemoveField(of)
+ {
+ def loc = of.Location;
+ def line = if (Options.BlankLinesBetweenMembers) loc.Line-1 else
loc.Line;
+ _designerFileMerger.RemoveLines(line, loc.EndLine );
+
+ def lineOffset = line - loc.EndLine - 1;
+ Relocate(_designerFileIndex,line,lineOffset);
+
+ //_formCodeInfo.newFieldInsertionLine += lineOffset;
+ //Debug.Print($"_formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine) "
+ // "after removing $(of.Name)\n");
+ }
+
+ def RenameField(of,cdf)
+ {
+ using(def sw = StringWriter())
+ {
+ Output = sw;
+ Indent = 2; // TODO: maybe we should change it dynamically?
+
+ GenerateIndent();
+ GenerateField(cdf);
+
+ def linesList = CodeDomHelper.StringToListOfLines(sw.ToString()
);
+
+ def oldLoc = of.Location;
+ _designerFileMerger.ReplaceLines(oldLoc.Line, oldLoc.EndLine,
+ linesList);
+ def lineOffset = linesList.Count - (oldLoc.EndLine - oldLoc.Line
+ 1);
+ Relocate(_designerFileIndex, oldLoc.Line, lineOffset);
+
+ //_formCodeInfo.newFieldInsertionLine += lineOffset;
+ //Debug.Print($"_formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine) "
+ // "after renaming $(of.Name)->$(cdf.Name)\n");
+ }
+ }
+
+ def sortedCodedomFields = _codeDomFields.Sort(
+ fun(f1,f2) {
+ mutable res : int;
+
+ res = if(f1.UserData.Contains(typeof(Location)))
+ {
+ if(f2.UserData.Contains(typeof(Location)))
+ {
+ (f1.UserData[typeof(Location)] :> Location).CompareTo(
+ (f2.UserData[typeof(Location)] :> Location))
+ }
+ else
+ -1
+ }
+ else if(f2.UserData.Contains(typeof(Location)))
+ 1
+ else
+ -1;
+
+ /*
+ when(f1.UserData.Contains(typeof(Location)))
+ Debug.Print($"$(f1.Name) has Location =
$(f1.UserData[typeof(Location)] :> Location)\n");
+ when(f2.UserData.Contains(typeof(Location)))
+ Debug.Print($"$(f2.Name) has Location =
$(f2.UserData[typeof(Location)] :> Location)\n");
+
+ Debug.Print($"Comparing1 $(f1.Name) and $(f2.Name) res =
$res\n");
+ */
+ res
+ }
+ );
+
+ Debug.Print("codedomFields (after Sort):\n");
+ sortedCodedomFields.Iter(f => Debug.Print($" field $(f.Name)\n") );
+
+ AddRemoveRenameDispatcher(_oldFields, sortedCodedomFields,
+ GetChangeStatus,
+ AddField, RemoveField, RenameField );
+ }
+
+ protected MergeMethods(classDecl: CodeTypeDeclaration) : void
+ {
+ // DEBUG
+ Debug.Print("oldMethods:\n");
+ _oldMethods.Iter(m => Debug.Print($" method $(m.Name)") );
+
+ //Debug.Print("allMethods:\n");
+ //typeBuilder.GetMethods().Iter(m => Debug.Print($" method
$(m.Name)\n") );
+
+ Debug.Print("codedomMethods:\n");
+ _codeDomMethods.Iter(m => Debug.Print($" method $(m.Name)") );
+
+ // Process InitializeComponent
+
+ match((_oldMethods.Find(m => m.Name == "InitializeComponent" ),
+ _codeDomMethods.Find(m => m.Name == "InitializeComponent" ))
)
+ {
+ | (om, Some(cdm)) =>
+ using(def sw = StringWriter())
+ {
+ Output = sw;
+ Indent = 2; // TODO: maybe we should change it dynamically?
+
+ GenerateIndent();
+ GenerateMethod(cdm, classDecl);
+
+ def linesList =
CodeDomHelper.StringToListOfLines(sw.ToString());
+
+ match(om)
+ {
+ | Some(om) =>
+ def oldLoc = om.Location;
+ _designerFileMerger.ReplaceLines(oldLoc.Line,
oldLoc.EndLine,
+ linesList);
+ def lineOffset = linesList.Count - (oldLoc.EndLine -
oldLoc.Line + 1);
+ Relocate(_designerFileIndex, oldLoc.Line, lineOffset);
+
+ //_formCodeInfo.newFieldInsertionLine += lineOffset;
+ //Debug.Print($"_formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine) "
+ // "after renewing InitializeComponent\n");
+
+ | None => // just give up for now
+ throw ApplicationException("InitializeComponent not found
in old designer file");
+ }
+ }
+
+ | _ =>
+ throw ApplicationException("InitializeComponent not found in
CodeDom tree");
+ }
+
+ def AddMethod(cdm)
+ {
+ using(def sw = StringWriter())
+ {
+ Output = sw;
+ Indent = 2; // TODO: maybe we should change it dynamically?
+
+
+ // KLiss: alter event handler parameter names
+ foreach(param is CodeParameterDeclarationExpression in
cdm.Parameters)
+ {
+ when(param.Name == "sender" && param.Type.BaseType
== "System.Object")
+ param.Name = "_sender";
+ when(param.Name == "e" &&
param.Type.BaseType.EndsWith("EventArgs"))
+ param.Name = "_e";
+ }
+
+ // TODO: correct way to insert empty method
+
+ def statements = cdm.Statements;
+ def isMethodBodyEmpty = (statements.Count == 0);
+ when (isMethodBodyEmpty)
+ // insert ';' for generation reverse this change later
+ _ = statements.Add(CodeMethodReturnStatement() );
+
+ // if(Options.BlankLinesBetweenMembers )
+ Output.WriteLine(); // TODO : blank lines should be regulated?
+
+ GenerateMethod(cdm,classDecl);
+
+ // clear body again
+ when (isMethodBodyEmpty)
+ statements.Clear();
+
+ //def linesList =
CodeDomHelper.StringToListOfLines(sw.ToString() );
+
+ //_mainFileMerger.AddLines(_formCodeInfo.newMethodInsertionLine,
+ // linesList);
+
+ //// Add cursor position to codedom: (TODO: do it the right way)
+ //cdm.UserData[typeof(Point)] =
+ // Point(1 + Options.IndentString.Length*3,
+ // 1 + _formCodeInfo.newMethodInsertionLine +
+ // match (BracingStyle) { | Block | Indent => 2 | _ => 3
} );
+
+ //_formCodeInfo.newMethodInsertionLine += linesList.Count; //
TODO : maybe we have to add additional lines
+ //Debug.Print($"_formCodeInfo.newMethodInsertionLine =
$(_formCodeInfo.newMethodInsertionLine) "
+ // "after adding $(cdm.Name)\n");
+ }
+ }
+
+ def RemoveMethod(om)
+ {
+ // TODO : blank lines should be regulated?
+ def (line,endLine) = (om.Location.Line-1,om.Location.EndLine);
+ def removedLines = endLine - line + 1;
+ _mainFileMerger.RemoveLines(line, endLine); // TODO
+
+ // adjust all other methods
+ Relocate(_mainFileIndex,line, -removedLines);
+
+ //_formCodeInfo.newMethodInsertionLine -= removedLines;
+ //Debug.Print($"_formCodeInfo.newMethodInsertionLine =
$(_formCodeInfo.newMethodInsertionLine) "
+ // "after removing $(om.Name)\n");
+ }
+
+ def RenameMethod(om,cdm)
+ {
+ using(def sw = StringWriter())
+ {
+ Output = sw;
+ Indent = 2; // TODO: maybe we should change it dynamically?
+
+ GenerateIndent();
+ GenerateMethod(cdm,classDecl);
+
+ def linesList = CodeDomHelper.StringToListOfLines(sw.ToString()
);
+
+ def oldLoc = om.Location;
+ _designerFileMerger.ReplaceLines(oldLoc.Line, oldLoc.EndLine,
+ linesList);
+ def lineOffset = linesList.Count - (oldLoc.EndLine - oldLoc.Line
+ 1);
+ Relocate(_mainFileIndex, oldLoc.Line, lineOffset);
+
+ //_formCodeInfo.newMethodInsertionLine += lineOffset;
+ //Debug.Print($"_formCodeInfo.newMethodInsertionLine =
$(_formCodeInfo.newMethodInsertionLine)"
+ // "after renaming $(om.Name)->$(cdm.Name)\n");
+ }
+ }
+
+ AddRemoveRenameDispatcher(_oldMethods, _codeDomMethods,
+ GetChangeStatus,
+ AddMethod, RemoveMethod, RenameMethod );
+ }
+
+ protected GenerateIndent() : void
+ {
+ def output = Output;
+ def indentString = Options.IndentString;
+ repeat(Indent)
+ output.Write(indentString);
+ }
+
+ protected Relocate(fileIndex: int,
+ line: int, lineOffset: int) : void
+ {
+ if (fileIndex == _mainFileIndex)
+ {
+ foreach (_m in _oldMethods)
+ {
+ assert2(false);
+ //def loc = m.Location;
+ //when (loc.FileIndex == _mainFileIndex)
+ // m.Location = Completion.Relocate(loc, line, 0, lineOffset, 0)
+ }
+
+ foreach (m in _codeDomMethods)
+ {
+ def locRef = m.UserData[typeof(Location)];
+
+ when (locRef != null)
+ {
+ def loc = locRef :> Location;
+ when (loc.FileIndex == fileIndex)
+ {
+ def pt = m.UserData[typeof(Point)] :> Point;
+ when (pt.Y > line)
+ {
+ pt.Y += lineOffset;
+ m.UserData[typeof(Point)] = pt;
+ }
+ }
+ }
+ }
+ }
+ else // fileIndex == _designerFileIndex
+ {
+ foreach (_f in _oldFields)
+ {
+ assert2(false);
+ //def loc = f.Location;
+ //when (loc.FileIndex == fileIndex)
+ // f.Location = Completion.Relocate(loc, line, 0, lineOffset, 0)
+ }
+ }
+ }
+
+ // Removes can be everywhere, Adds only at the end
+ static protected AddRemoveRenameDispatcher[T1,T2](old_list: list[T1],
new_list: list[T2],
+ status: T1*T2->ChangeStatus,
+ addFunc : T2->void, removeFunc : T1->void, renameFunc : T1*T2->void
) : void
+ {
+ def dispatcher(old_l, new_l )
+ {
+ | (h1 :: t1, h2 :: t2) =>
+ match (status(h1,h2)) {
+ | Equal => dispatcher(t1,t2)
+ | NonEqual => { removeFunc(h1); dispatcher(t1,new_l) }
+ | Renamed => { renameFunc(h1,h2); dispatcher(t1,t2) }
+ }
+ | (_, []) =>
+ foreach (x in old_l)
+ removeFunc(x);
+
+ | ([], _) =>
+ foreach (x in new_l)
+ addFunc(x);
+ }
+
+ dispatcher(old_list, new_list)
+ }
+
+ static protected GetChangeStatus[T1,T2](oldMember: T1, codeDomMember:
T2 ) : ChangeStatus
+ where T1 : MemberBuilder where T2 : CodeTypeMember
+ {
+ //Debug.Print($"Comparing $(oldMember.Name) and
$(codeDomMember.Name)\n");
+ def oldName = codeDomMember.UserData["Name"];
+ if (oldName != null && ((oldName :> string) == oldMember.Name))
+ if (oldMember.Name != codeDomMember.Name)
+ ChangeStatus.Renamed
+ else
+ ChangeStatus.Equal
+ else
+ ChangeStatus.NonEqual
+ }
+ }
+}
=======================================
--- /dev/null
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/FormCodeDomParser.n
Wed Nov 11 12:09:20 2009
@@ -0,0 +1,81 @@
+using System;
+using System.IO;
+using System.Collections;
+using System.Collections.Generic;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.ComponentModel.Design.Serialization;
+using System.Diagnostics;
+using System.Drawing;
+using System.Reflection;
+
+using Nemerle.Assertions;
+using NC = Nemerle.Collections;
+using Nemerle.Compiler;
+using Nemerle.Compiler.Parsetree;
+using Nemerle.Compiler.Typedtree;
+using Nemerle.Completion2;
+using Nemerle.Utility;
+
+namespace Nemerle.Compiler.Utils
+{
+ // now CodeDomParser only parses files from Project.CompileUnits
+ // it is not thread-safe at the moment!
+ public class FormCodeDomParser : NemerleCodeParserBase
+ {
+ mutable _project : Project;
+ mutable _mainFileIndex : int;
+ mutable _designerFileIndex : int;
+
+
+ public CreateCodeCompileUnit(project : Project, mainFileIndex : int,
designerFileIndex : int) : CodeCompileUnit
+ {
+ // Initialization
+ _project = project;
+ base._manager = _project.Engine;
+
+ _mainFileIndex = mainFileIndex;
+ _designerFileIndex = designerFileIndex;
+
+ // Processing
+ def unit = CodeCompileUnit();
+
+ def globalImports = List();
+
+ foreach(decl in
project.CompileUnits.GetTopNamespace(mainFileIndex).Decls)
+ {
+ | Decl.Namespace as nsDecl => _ =
unit.Namespaces.Add(ProcessNamespace(nsDecl));
+ | Decl.Using as usDecl =>
globalImports.Add(usDecl.Name.ToString("."));
//unit.Imports.Add(CodeNamespaceImport());
+ | d with(bodyLoc =
project.CompileUnits.GetTopNamespace(_mainFileIndex).BodyLocation) =>
+ //TODO: VladD2: Какая-то чушь...
+ throw CodeDomSerializerException($"Assumed root Declaration of
CompileUnit is Decl.Namespace, got $d",
+
CodeLinePragma(bodyLoc.File,bodyLoc.Line));
+ }
+
+ foreach(import in globalImports)
+ _ = unit.ReferencedAssemblies.Add(import);
+
+ unit
+ }
+
+ private ProcessNamespace(decl: Decl.Namespace) : CodeNamespace
+ {
+ def res = CodeNamespace(decl.Name.ToString("."));
+
+ foreach(decl in decl.Decls)
+ match(decl)
+ {
+ | Decl.Type(ast) => _ =
res.Types.Add(ProcessTypeDeclaration(ast));
+ | Decl.Using as usDecl =>
res.Imports.Add(CodeNamespaceImport(usDecl.Name.ToString(".")));
+ | Decl.Namespace(BodyLocation = bodyLoc) =>
+ //TODO: VladD2: Какая-то чушь... Счего бы это нельзя иметь
вложенных пространств имен?
+ throw CodeDomSerializerException("Namespace declarations
cannot contain inner namespace declarations",
+
CodeLinePragma(bodyLoc.File,bodyLoc.Line));
+
+ | _ => () // Ignored
+ }
+
+ res
+ }
+ }
+}
=======================================
--- /dev/null
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/NemerleCodeDomProvider.n
Wed Nov 11 12:09:20 2009
@@ -0,0 +1,62 @@
+using System;
+using System.ComponentModel;
+using System.CodeDom.Compiler;
+
+using Nemerle.Compiler;
+
+namespace Nemerle.Compiler.Utils
+{
+ public class NemerleCodeDomProvider : CodeDomProvider
+ {
+ private provider: CodeDomProvider;
+
+ public this()
+ {
+ this(NemerleCodeProvider());
+ }
+
+ public this(prov: CodeDomProvider)
+ {
+ provider = prov;
+ }
+
+ [Obsolete("Callers should not use the ICodeParser interface.")]
+ public override CreateParser(): ICodeParser
+ {
+#pragma warning disable 618 // Obsolete
+ def parser = provider.CreateParser();
+#pragma warning restore 618
+
+ if (parser == null)
+ NemerleCodeParser();
+ else
+ parser;
+ }
+
+ [Obsolete("Callers should not use the ICodeGenerator interface.")]
+ public override CreateGenerator(): ICodeGenerator
+ {
+#pragma warning disable 618 // Obsolete
+ provider.CreateGenerator();
+#pragma warning restore 618
+ }
+
+ [Obsolete("Callers should not use the ICodeCompiler interface.")]
+ public override CreateCompiler(): ICodeCompiler
+ {
+#pragma warning disable 618 // Obsolete
+ provider.CreateCompiler();
+#pragma warning restore 618
+ }
+
+ public override FileExtension: string
+ {
+ get { provider.FileExtension; }
+ }
+
+ public override GetConverter (ty : Type) : TypeConverter
+ {
+ provider.GetConverter(ty);
+ }
+ }
+}
=======================================
--- /dev/null
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/NemerleCodeParser.n
Wed Nov 11 12:09:20 2009
@@ -0,0 +1,135 @@
+using System;
+using System.IO;
+using System.Collections;
+using System.Collections.Generic;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.ComponentModel.Design.Serialization;
+using System.Diagnostics;
+using System.Drawing;
+using System.Reflection;
+
+using Nemerle.Assertions;
+using Nemerle.Collections;
+using Nemerle.Compiler;
+using Nemerle.Compiler.Parsetree;
+using Nemerle.Compiler.Typedtree;
+using Nemerle.Completion2;
+using Nemerle.Imperative;
+using Nemerle.Text;
+using Nemerle.Utility;
+
+using System.CodeDom.CodeBinaryOperatorType;
+
+using SCG = System.Collections.Generic;
+
+namespace Nemerle.Compiler.Utils
+{
+ // now CodeDomParser only parses files from Project.CompileUnits
+ // it is not thread-safe at the moment!
+
+ //TODO: VladD2: Убрать наследование от ManagerClass. Вместо этого
использовать проект к которому подлючен разбираемый файл.
+
+ /// <summary>
+ /// Provides an implementation of the <see
cref="T:System.CodeDom.Compiler.ICodeParser"/> interface.
+ /// </summary>
+ public class NemerleCodeParser : NemerleCodeParserBase, ICodeParser
+ {
+ class Compiler : ManagerClass
+ {
+ public this ()
+ {
+ base (CompilationOptions());
+ InitCompiler ();
+ LoadExternalLibraries ();
+ }
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see
cref="T:Nemerle.Compiler.NemerleCodeParser"/> class.
+ /// </summary>
+ public this ()
+ {
+ _manager = Compiler();
+ }
+
+ // TODO: do we need to make it type-safe
+ protected mutable _currentMethod : MethodBuilder;
+
+ protected mutable _compilerInit : bool;
+
+ /// <summary>
+ /// Compiles the specified text stream into a <see
cref="T:System.CodeDom.CodeCompileUnit"/>
+ ///.</summary>
+ /// <param name="codeStream">A <see cref="T:System.IO.TextReader"/>
+ /// that is used to read the code to be parsed.</param>
+ /// <returns>
+ /// A <see cref="T:System.CodeDom.CodeCompileUnit"/> containing the
code
+ /// model produced from parsing the code.
+ /// </returns>
+ public Parse(codeStream : TextReader) : CodeCompileUnit
+ {
+ def oldMan = ManagerClass.Instance;
+ def topDecls =
+ try
+ {
+ _manager.ParsingPipeline(LexerString(_manager,
codeStream.ReadToEnd(), Location.Default))
+ }
+ finally { ManagerClass.Instance = oldMan; };
+
+ def unit = CodeCompileUnit();
+
+ mutable lastNamespace;
+ mutable codeDomNamespace;
+
+ def switchToNamespace(decl : TopDeclaration)
+ {
+ unless (decl.PName.context.CurrentNamespace.Equals(lastNamespace))
//FixMe: не надо исползовать PName он может быть пуст!
+ {
+ lastNamespace = decl.PName.context.CurrentNamespace;
+ codeDomNamespace =
ToCodeNamespace(decl.PName.context.CurrentNamespace);
+ _ = unit.Namespaces.Add(codeDomNamespace);
+ }
+ }
+
+ foreach (decl in topDecls)
+ {
+ | TopDeclaration.Class as cls =>
+
+ switchToNamespace(cls);
+ _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(cls));
+
+ | TopDeclaration.Interface as ifs =>
+
+ switchToNamespace(ifs);
+ _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(ifs));
+
+ | TopDeclaration.Enum as enm =>
+
+ switchToNamespace(enm);
+ _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(enm));
+
+ | TopDeclaration.Variant as vrt =>
+
+ switchToNamespace(vrt);
+ _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(vrt));
+
+ | TopDeclaration.VariantOption as vrto =>
+
+ switchToNamespace(vrto);
+ _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(vrto));
+
+ | TopDeclaration.Delegate as del =>
+
+ //there is no need to switch to namespace
+ switchToNamespace(del);
+ _ = codeDomNamespace.Types.Add(ToCodeTypeDelegate(del));
+
+ | _ =>
+ throw NotSupportedException($"$decl is not supported");
+ }
+
+ unit;
+ }
+ }
+}
=======================================
--- /dev/null
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDom/NemerleCodeParserBase.n
Wed Nov 11 12:09:20 2009
@@ -0,0 +1,703 @@
+using System;
+using System.IO;
+using System.Collections;
+using System.Collections.Generic;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.ComponentModel.Design.Serialization;
+using System.Diagnostics;
+using System.Drawing;
+using System.Reflection;
+
+using Nemerle.Assertions;
+using Nemerle.Collections;
+using Nemerle.Compiler;
+using Nemerle.Compiler.Parsetree;
+using Nemerle.Compiler.Typedtree;
+using Nemerle.Completion2;
+using Nemerle.Imperative;
+using Nemerle.Text;
+using Nemerle.Utility;
+
+using System.CodeDom.CodeBinaryOperatorType;
+
+namespace Nemerle.Compiler.Utils
+{
+ public class NemerleCodeParserBase
+ {
+ // now needed only for AsObject
+ protected mutable _manager : ManagerClass;
+
+ protected virtual ToCodeNamespace(ns : NamespaceTree.Node) :
CodeNamespace
+ {
+ CodeNamespace(ns.GetDisplayName());
+ }
+
+ protected virtual ToCodeTypeDelegate(del : TopDeclaration.Delegate) :
CodeTypeDelegate
+ {
+ def ty = CodeTypeDelegate(del.Name);
+
+ ty.ReturnType = ToCodeTypeReference(del.header.ParsedReturnType);
+
ty.Parameters.AddRange(del.header.ParsedParameters.Map(ToCodeParameterDeclarationExpression).NToArray());
+
+ ty;
+ }
+
+ protected virtual ToCodeTypeDeclaration(vrt :
TopDeclaration.Variant) : CodeTypeDeclaration
+ {
+ def ty = CodeTypeDeclaration(vrt.Name);
+
+ ty.IsClass = true;
+ ty.IsInterface = false;
+
ty.BaseTypes.AddRange(vrt.t_extends.Map(ToCodeTypeReference).NToArray());
+
ty.TypeParameters.AddRange(ToCodeTypeParameters(vrt.typarms).NToArray());
+ ty.Members.AddRange(vrt.decls.Map(ToCodeTypeMember).NToArray());
+
+ ty.UserData["Nemerle.TopDeclaration"] = "Variant";
+
+ ty;
+ }
+
+ protected virtual ToCodeTypeDeclaration(vrto :
TopDeclaration.VariantOption) : CodeTypeDeclaration
+ {
+ def ty = CodeTypeDeclaration(vrto.Name);
+
+ ty.IsClass = true;
+ ty.IsInterface = false;
+
//ty.BaseTypes.AddRange(vrto.t_extends.Map(ToCodeTypeReference).NToArray());
+
//ty.TypeParameters.AddRange(ToCodeTypeParameters(vrto.typarms).NToArray());
+ ty.Members.AddRange(vrto.decls.Map(ToCodeTypeMember).NToArray());
+
+ ty.UserData["Nemerle.TopDeclaration"] = "VariantOption";
+
+ ty;
+ }
+
+ protected virtual ToCodeTypeDeclaration(enm : TopDeclaration.Enum) :
CodeTypeDeclaration
+ {
+ def ty = CodeTypeDeclaration(enm.Name);
+ ty.IsClass = false;
+ ty.IsEnum = true;
+
ty.BaseTypes.AddRange(enm.t_extends.Map(ToCodeTypeReference).NToArray());
+
ty.TypeParameters.AddRange(ToCodeTypeParameters(enm.typarms).NToArray());
+ ty.Members.AddRange(enm.decls.Map(ToCodeTypeMember).NToArray());
+ ty;
+ }
+
+ protected virtual ToCodeTypeDeclaration(ifs :
TopDeclaration.Interface) : CodeTypeDeclaration
+ {
+ def ty = CodeTypeDeclaration(ifs.Name);
+ ty.IsClass = false;
+ ty.IsInterface = true;
+
ty.BaseTypes.AddRange(ifs.t_extends.Map(ToCodeTypeReference).NToArray());
+
ty.TypeParameters.AddRange(ToCodeTypeParameters(ifs.typarms).NToArray());
+ ty.Members.AddRange(ifs.methods.Map(ToCodeTypeMember).NToArray());
+ ty;
+ }
+
+ protected virtual ToCodeTypeDeclaration(cls : TopDeclaration.Class) :
CodeTypeDeclaration
+ {
+ def ty = CodeTypeDeclaration(cls.Name);
+
+ when(cls.Attributes %&& NemerleAttributes.Struct)
+ {
+ ty.IsClass = false;
+ ty.IsStruct = true;
+ }
+
+
ty.BaseTypes.AddRange(cls.t_extends.Map(ToCodeTypeReference).NToArray());
+
ty.TypeParameters.AddRange(ToCodeTypeParameters(cls.typarms).NToArray());
+ ty.Members.AddRange(cls.decls.Map(ToCodeTypeMember).NToArray());
+ ty;
+ }
+
+ private ToCodeTypeReference(typeName : string) : CodeTypeReference
+ {
+ CodeTypeReference(typeName);
+ }
+
+ protected virtual ToCodeTypeReference(expr : PExpr) : CodeTypeReference
+ {
+ ToCodeTypeReference(expr.ToString());
+ }
+
+ protected virtual ToCodeTypeParameter(tyvar : Splicable) :
CodeTypeParameter
+ {
+ CodeTypeParameter(tyvar.GetName().Id);
+ }
+
+ protected virtual ToCodeTypeParameters(typarms : Typarms) : list
[CodeTypeParameter]
+ {
+ def toCodeTypeParameter(tyvar : Splicable) : CodeTypeParameter
+ {
+ def tyParm = ToCodeTypeParameter(tyvar);
+ typarms.constraints
+ .Filter(c => c.tyvar.Equals(tyvar))
+ .Iter (c => _ =
tyParm.Constraints.Add(ToCodeTypeReference(c.ty)));
+ tyParm;
+ }
+
+ typarms.tyvars.Map(toCodeTypeParameter);
+ }
+
+ protected virtual ToMemberAttributes(attrs : NemerleAttributes) :
MemberAttributes
+ {
+ mutable memberAttrs: MemberAttributes;
+
+ when(attrs %&& NemerleAttributes.Static) memberAttrs |=
MemberAttributes.Static;
+ when(attrs %&& NemerleAttributes.Public) memberAttrs |=
MemberAttributes.Public;
+ when(attrs %&& NemerleAttributes.Private) memberAttrs |=
MemberAttributes.Private;
+
+ if(attrs %&& NemerleAttributes.Internal && attrs %&&
NemerleAttributes.Protected)
+ memberAttrs |= MemberAttributes.FamilyOrAssembly
+ else
+ {
+ when(attrs %&& NemerleAttributes.Internal) memberAttrs |=
MemberAttributes.Assembly;
+ when(attrs %&& NemerleAttributes.Protected) memberAttrs |=
MemberAttributes.Family;
+ }
+
+ when(attrs %&& NemerleAttributes.New) memberAttrs |=
MemberAttributes.New;
+ when(attrs %&& NemerleAttributes.Override) memberAttrs |=
MemberAttributes.Override;
+ when(attrs %&& NemerleAttributes.Sealed) memberAttrs |=
MemberAttributes.Final;
+
+ memberAttrs;
+ }
+
+ protected virtual ToCodeEnumOption(opt : ClassMember.EnumOption) :
CodeMemberField
+ {
+ def ext = (opt.DefinedIn :> TopDeclaration.Enum).t_extends;
+
+ def typeRef =
+ if(ext.Length>0)
+ ToCodeTypeReference(ext.Head);
+ else
+ ToCodeTypeReference("int");
+
+ CodeMemberField(typeRef, opt.Name);
+ }
+
+ protected virtual ToCodeMemberField(field : ClassMember.Field) :
CodeMemberField
+ {
+ CodeMemberField (ToCodeTypeReference (field.ty), field.Name);
+ }
+
+ protected virtual ToCodeMemberMethod(func : ClassMember.Function) :
CodeMemberMethod
+ {
+ def codeMethod =
+ match(func.Name)
+ {
+ | ".ctor" => CodeConstructor()
+ | ".cctor" => CodeTypeConstructor()
+ | "Main" when func.Attributes %&& NemerleAttributes.Static
+ => CodeEntryPointMethod()
+ | _ => CodeMemberMethod()
+ };
+
+ codeMethod.Name = func.Name;
+ codeMethod.ReturnType = ToCodeTypeReference(func.header.ReturnType);
+ //TODO:
codeMethod.ReturnTypeCustomAttributes.AddRange(???.NToArray());
+
codeMethod.Parameters.AddRange(func.header.Parameters.Map(ToCodeParameterDeclarationExpression).NToArray());
+
codeMethod.ImplementationTypes.AddRange(func.implemented.Map(ToCodeTypeReference).NToArray());
+ //TODO: codeMethod.PrivateImplementationType = ???
+
codeMethod.TypeParameters.AddRange(ToCodeTypeParameters(func.header.TypeParameters).NToArray());
+ codeMethod.Statements.AddRange(ToStatements(func.Body).NToArray());
+
+ codeMethod;
+ }
+
+ protected virtual ToCodeParameterDeclarationExpression(parm :
Parsetree.PParameter) : CodeParameterDeclarationExpression
+ {
+ def codeParam =
CodeParameterDeclarationExpression(ToCodeTypeReference(parm.Type),
parm.Name);
+
codeParam.CustomAttributes.AddRange(parm.modifiers.GetCustomAttributes().Map(ToCodeAttributeDeclaration).NToArray());
+ //codeParam.Direction = ???
+ codeParam;
+ }
+
+ protected virtual ToCodeMemberProperty(prop : ClassMember.Property) :
CodeMemberProperty
+ {
+ def codeProperty = CodeMemberProperty();
+ codeProperty.Name = prop.Name;
+ //TODO:
codeProperty.ImplementationTypes.AddRange(???(ToCodeTypeReference).NToArray());
+ //TODO: codeProperty.PrivateImplementationType = ???
+ //TODO: codeProperty.Parameters = ???
+ match (prop.get)
+ {
+ | Some (m) =>
codeProperty.GetStatements.AddRange(ToStatements(m.Body).NToArray());
+ | None => ()
+ }
+
+ match (prop.set)
+ {
+ | Some (m) =>
codeProperty.SetStatements.AddRange(ToStatements(m.Body).NToArray());
+ | None => ()
+ }
+
+ codeProperty;
+ }
+
+ protected virtual ToCodeMemberEvent(evt : ClassMember.Event) :
CodeMemberEvent
+ {
+ def codeEvent = CodeMemberEvent();
+ codeEvent.Name = evt.Name;
+ codeEvent.Type = ToCodeTypeReference(evt.ty);
+ //TODO:
codeProperty.ImplementationTypes.AddRange(???(ToCodeTypeReference).NToArray());
+ //TODO: codeProperty.PrivateImplementationType = ???
+
+ codeEvent;
+ }
+
+ protected virtual ToCodeTypeMember(member : ClassMember) :
CodeTypeMember
+ {
+ def codeMember =
+ match (member)
+ {
+ | ClassMember.TypeDeclaration as tyDecl
+ when tyDecl.td is TopDeclaration.Class =>
ToCodeTypeDeclaration(tyDecl.td :> TopDeclaration.Class);
+ | ClassMember.TypeDeclaration as tyDecl
+ when tyDecl.td is TopDeclaration.Variant =>
ToCodeTypeDeclaration(tyDecl.td :> TopDeclaration.Variant);
+ | ClassMember.TypeDeclaration as tyDecl
+ when tyDecl.td is TopDeclaration.VariantOption =>
ToCodeTypeDeclaration(tyDecl.td :> TopDeclaration.VariantOption);
+ | ClassMember.TypeDeclaration as tyDecl
+ when tyDecl.td is TopDeclaration.Delegate =>
ToCodeTypeDelegate(tyDecl.td :> TopDeclaration.Delegate);
+ | ClassMember.Field as field => ToCodeMemberField(field);
+ | ClassMember.Function as func => ToCodeMemberMethod(func);
+ | ClassMember.Property as prop => ToCodeMemberProperty(prop);
+ | ClassMember.Event as evt => ToCodeMemberEvent(evt);
+ | ClassMember.EnumOption as enm => ToCodeEnumOption(enm);
+
+ | _ => throw NotSupportedException($"$member not supported");
+ }
+
+ when(member.modifiers != null)
+ {//member.modifiers == null for TopDeclaration.Variant
+ codeMember.Attributes = ToMemberAttributes (member.Attributes);
+
codeMember.CustomAttributes.AddRange(member.modifiers.GetCustomAttributes().Map(ToCodeAttributeDeclaration).NToArray());
+ }
+
+ codeMember;
+ }
+
+ protected virtual ToCodeAttributeDeclaration(attr : PExpr) :
CodeAttributeDeclaration
+ {
+ CodeAttributeDeclaration(ToCodeTypeReference(attr));
+ }
+
+ protected ProcessTypeDeclaration(typeDecl : TopDeclaration) :
CodeTypeDeclaration
+ {
+ match(typeDecl)
+ {
+ | TopDeclaration.Class as typeDecl => CreateClass(typeDecl)
+ | _ =>
+ throw NotImplementedException("Non class top declarations aren't
supported yet")
+ }
+ }
+
+ protected CreateClass(cls : TopDeclaration.Class) : CodeTypeDeclaration
+ {
+ // creates class declaration
+ def classDecl = CodeTypeDeclaration(cls.Name);
+ classDecl.Attributes =
CodeDomHelper.GetMemberAttributes(cls.Attributes);
+ classDecl.TypeAttributes =
CodeDomHelper.GetTypeAttributes(cls.Attributes);
+ def typeBuilder = cls.TypeBuilder;
+ assert(typeBuilder != null);
+
+ foreach (baseType in typeBuilder.GetDirectSuperTypes())
+ _ = classDecl.BaseTypes.Add(ToTypeRef(baseType));
+
+ classDecl.IsClass = true;
+
+ // sets class access mofifiers
+ classDecl.IsPartial = CodeDomHelper.IsPartial(cls.Attributes);
+
+ // Set type parameters. will it work?
+ //VladD2: Думаю, для форм это на фиг не нужно.
+ //foreach (t in cls.typarms.tyvars)
+ // _ =
classDecl.TypeParameters.Add(CodeTypeParameter(t.ToString()));
+
+ def pracessPart(part : TopDeclaration.Class) : void
+ {
+ // TODO: Seems like comments went away
+ //classDecl.Comments = CodeCommentStatement();
+
+ // TODO: Figure out how to parse CustomAttributes
+ //classDecl.CustomAttributes =
cls.GetModifiers().GetCustomAttributes();
+
+ ProcessClassMembers(part.GetMembers(), classDecl);
+
+ //TODO: adds usings directives
+
+ //AddToCodeNamespace(cls, codeClass);
+
+ //TODO: Add Location ?
+ }
+
+ foreach (part is TopDeclaration.Class in typeBuilder.AstParts)
+ pracessPart(part);
+
+ classDecl
+ }
+
+ // needed cause we may want to override it in derived classes
+ protected virtual ProcessClassMembers(members : list[ClassMember],
classDecl : CodeTypeDeclaration) : void
+ {
+ foreach (m in members)
+ {
+ def codeTypeMember : CodeTypeMember =
+ match (m : ClassMember)
+ {
+ | TypeDeclaration(td) => ProcessTypeDeclaration(td)
+ | Field as field => CreateField(field)
+ | Property as prop => CreateProperty(prop)
+ | Event as vnt => CreateEvent(vnt)
+ | Function as func => CreateMethod(func)
+ | EnumOption => assert(false, "ClassMember.EnumOption
not supported yet");
+ };
+
+ // TODO: Seems like comments went away
+ //memberDecl.Comments = CodeCommentStatement();
+
+ // TODO: Figure out how to parse CustomAttributes
+ //memberDecl.CustomAttributes =
member.GetModifiers().GetCustomAttributes();
+
+ //// Add Location
+ //memberDecl.UserData.Add(typeof(Location), member.Location);
+
+ codeTypeMember.UserData["Name"] = m.Name;
+ codeTypeMember.UserData["Member"] = m;
+ codeTypeMember.Name = m.Name;
+ _ = classDecl.Members.Add(codeTypeMember);
+ }
+ }
+
+ protected virtual CreateField(field : ClassMember.Field) :
CodeMemberField
+ {
+ // GetFieldInfo() doesn't work
+ //def fieldDecl = CodeMemberField(field.GetFieldInfo().FieldType,
field.Name);
+
+ Debug.Print($"CreateField: from field $field");
+
+ // TODO: VladD2: Using of GetSystemType() is bad idea!
+ def fieldDecl = CodeMemberField(ToTypeRef(field.ty), field.Name);
+
+ fieldDecl.Attributes =
CodeDomHelper.GetMemberAttributes(field.Attributes, true);
+
+ when (field.Initializer != null)
+ fieldDecl.InitExpression = ToExpression(field.Initializer);
+
+ fieldDecl
+ }
+
+ protected virtual CreateProperty(prop : ClassMember.Property) :
CodeMemberProperty
+ {
+ Debug.Print($"CreateProperty: from $prop");
+
+ def result = CodeMemberProperty();
+ result.Attributes =
CodeDomHelper.GetMemberAttributes(prop.Attributes);
+ result.Name = prop.Name;
+
+ when(prop.get is Some(get))
+ {
+ result.HasGet = true;
+ result.Type = ToTypeRef(get.header.ReturnType);
+ _ =
result.GetStatements.AddRange(ToStatements(get.Body).NToArray())
+ }
+
+ when(prop.set is Some(set))
+ {
+ result.HasSet = true;
+ result.Type = ToTypeRef(set.header.ReturnType);
+ _ =
result.SetStatements.AddRange(ToStatements(set.Body).NToArray())
+ }
+
+ result
+ }
+
+ protected virtual CreateEvent(evt : ClassMember.Event) :
CodeMemberEvent
+ {
+ def eventDecl = CodeMemberEvent();
+ eventDecl.Attributes =
CodeDomHelper.GetMemberAttributes(evt.Attributes);
+ eventDecl.Name = evt.Name;
+ eventDecl.Type = ToTypeRef(evt.ty);
+ eventDecl
+ }
+
+ protected virtual CreateMethod(method : ClassMember.Function) :
CodeMemberMethod
+ {
+ Debug.Print($"CreateMethod : from $method");
+
+ def methodDecl : CodeMemberMethod =
+ match(method.Name)
+ {
+ | ".ctor" when method.Attributes %&& NemerleAttributes.Static =>
CodeTypeConstructor()
+ | ".ctor" =>
CodeConstructor()
+ | "Main" when method.Attributes %&& NemerleAttributes.Static =>
CodeEntryPointMethod()
+ | _ =>
CodeMemberMethod()
+ };
+
+ methodDecl.Attributes =
CodeDomHelper.GetMemberAttributes(method.Attributes, false);
+
+ //TODO: methodDecl.ImplementationTypes - how to get that
+
+ //methodDecl.Parameters
+ foreach (p in method.header.Parameters)
+ _ =
methodDecl.Parameters.Add(CodeParameterDeclarationExpression(ToTypeRef(p.Type),
p.Name));
+
+ //TODO: methodDecl.PrivateImplementationType ?
+
+ methodDecl.ReturnType = ToTypeRef(method.header.ReturnType);
+
+ // methodDecl.TypeParameters , TODO: check if it actually works
+ foreach (tp in method.header.TypeParameters.tyvars)
+ _ =
methodDecl.TypeParameters.Add(CodeTypeParameter(tp.ToString()));
+
+ //_currentMethod = method;
+ method.Builder.EnsureCompiled(); // we need PExpr & TExpr
+
methodDecl.Statements.AddRange(ToStatements(method.Builder.BodyParsed).NToArray());
+
+ //Debug.Print($" method.BodyTyped.Location (col =
$(method.BodyTyped.Location.Column), line =
$(method.BodyTyped.Location.Line))");
+
+ methodDecl
+ }
+
+
+ ToTypeRefExpression(typeInfo : Nemerle.Compiler.TypeInfo,
typeParaams : list[TyVar]) : CodeTypeReferenceExpression
+ {
+ CodeTypeReferenceExpression(ToTypeRef(typeInfo, typeParaams))
+ }
+
+ ToTypeRef(tyVar : PExpr) : CodeTypeReference
+ {
+ def cnvToCsTy(t : object)
+ {
+ t.ToString().Replace(".[", "<").Replace("[", "<").Replace("]", ">")
+ }
+ match (tyVar.TypedObject)
+ {
+ | t is TyVar => ToTypeRef(t)
+ | null => CodeTypeReference(cnvToCsTy(tyVar))
+ | t => CodeTypeReference(cnvToCsTy(t))
+ }
+ }
+
+ ToTypeRef(tyVar : TyVar) : CodeTypeReference
+ {
+ def ty = tyVar.Fix();
+
+ if (ty.IsFixed)
+ {
+ def makeTypeArgs(args) { args.MapToArray(ToTypeRef) }
+
+ match (ty)
+ {
+ | Class(tycon, args) => ToTypeRef(tycon, args)
+ | TyVarRef(tyvar) => CodeTypeReference(tyvar.Name)
+ | Fun(_from, _to) => CodeTypeReference(typeof(object)) //
HACK: Not supported by C#
+ | Tuple(args) =>
+ CodeTypeReference("Nemerle.Builtins.Tuple", makeTypeArgs(args))
+ | Array(tyVar, rank) => CodeTypeReference(ToTypeRef(tyVar),
rank)
+ | Void => CodeTypeReference(typeof(void))
+ | Ref(_tyVar)
+ | Out(_tyVar) => throw ApplicationException("Ref/Out
not supported")
+ | Intersection(_types) => CodeTypeReference(typeof(object))
+ }
+ }
+ else CodeTypeReference(typeof(object))
+ }
+
+ ToTypeRef(typeInfo : Nemerle.Compiler.TypeInfo, typeParams :
list[TyVar]) : CodeTypeReference
+ {
+ //Debug.Assert(typeInfo.TyparmsCount == 0, "typeInfo.TyparmsCount ==
0, value is $(typeInfo.TyparmsCount)"); // TODO: Add support for type
parameters!
+ //Debug.Assert(typeParams.IsEmpty, $"typeParams.IsEmpty, value is
$(typeParams.ToString())");
+
+ if (typeInfo.SystemType != null)
+ CodeTypeReference(typeInfo.SystemType.FullName,
typeParams.Map(ToTypeRef).NToArray());
+ else
+ CodeTypeReference(typeInfo.FullName,
typeParams.Map(ToTypeRef).NToArray());
+ }
+
+ protected virtual ToExpression(expr : PExpr) : CodeExpression
+ {
+ match (expr)
+ {
+ | <[ $expr1 && $expr2 ]> with op = BooleanAnd
+ | <[ $expr1 || $expr2 ]> with op = BooleanOr
+ | <[ $expr1 != $expr2 ]> with op = IdentityInequality
+ | <[ $expr1 == $expr2 ]> with op = IdentityEquality
+ | <[ $expr1 & $expr2 ]> with op = BitwiseAnd
+ | <[ $expr1 | $expr2 ]> with op = BitwiseOr
+ | <[ $expr1 + $expr2 ]> with op = Add
+ | <[ $expr1 - $expr2 ]> with op = Subtract
+ | <[ $expr1 / $expr2 ]> with op = Divide
+ | <[ $expr1 * $expr2 ]> with op = Multiply =>
+ CodeBinaryOperatorExpression(ToExpression(expr1), op,
ToExpression(expr2))
+
+ | <[ array[..$parms] ]> as ary =>
+ def tExpr = ary.TypedObject :> TExpr;
+ match (tExpr)
+ {
+ | TExpr.Array(_args, dimensions) =>
+ Debug.Assert(dimensions is [_]);
+ CodeArrayCreateExpression(
+ ToTypeRef(tExpr.MType()), parms.MapToArray(ToExpression))
+ | _ => NotSupportedExpression(ary)
+ }
+
+ | <[ $obj.$func(..$parms) ]> as call =>
+ match (call.func.TypedObject)
+ {
+ | TExpr.StaticRef(from, mem, type_parms) when mem.MemberKind
== MemberTypes.Constructor =>
+ def codeParams = parms.MapToArray(ToExpression);
+ CodeObjectCreateExpression(ToTypeRef(from.tycon,
type_parms), codeParams);
+
+ | _ =>
+ CodeMethodInvokeExpression(
+ CodeMethodReferenceExpression(ToExpression(obj),
+ func.ToString()),
+
parms.MapToArray(ToExpression));
+ }
+
+ | <[ $func(..$parms) ]> => // TODO: Add support of ctor's
+ CodeMethodInvokeExpression(
+ CodeMethodReferenceExpression(null, func.ToString()),
+ parms.MapToArray(ToExpression));
+
+ | <[ $obj.$field ]> when field.TypedObject is IField =>
+ CodeFieldReferenceExpression(ToExpression(obj),
field.TypedObject.Name);
+
+ | <[ $obj.$prop ]> when prop.TypedObject is IProperty =>
+ CodePropertyReferenceExpression(ToExpression(obj),
prop.TypedObject.Name);
+
+ | <[ $obj.$_ ]> as mem when mem.TypedObject is TExpr =>
+ match (mem.TypedObject)
+ {
+ | TExpr.StaticRef(_from, mem, type_parms) when mem.IsStatic =>
+ CodeFieldReferenceExpression(
+ ToTypeRefExpression(mem.DeclaringType, type_parms),
mem.Name)
+
+ | TExpr.MethodRef(_tObj, meth, typeParms, _notvirtual) =>
+ CodeMethodReferenceExpression(ToExpression(obj), meth.Name,
+ typeParms.MapToArray(param => ToTypeRef(param)))
+
+ | xxx =>
+ _ = xxx;
+ NotSupportedExpression(expr)
+ }
+
+ | PExpr.Ref(name) =>
CodeVariableReferenceExpression(name.ToString())
+
+ | PExpr.Literal(literal) =>
+ match (literal)
+ {
+ | Void => CodeTypeReferenceExpression("void")
+ | Null with val = null : object | String(val) | Float (val) |
Double (val)
+ | Decimal (val) | Char (val) | Bool (val)
+ => CodePrimitiveExpression(val)
+ | Integer(val, is_negative, _treat_as) =>
+ def val = val :> long;
+ def val = if (is_negative) -val else val;
+ CodePrimitiveExpression(val)
+
+ | Enum (_val : Literal.Integer, ty : TypeInfo, field : IField)
=>
+
CodeFieldReferenceExpression(CodeTypeReferenceExpression(ty.FullName),
field.Name)
+ }
+
+ | <[ $sourceExpr :> $_ ]> =>
+ def tExpr = expr.TypedObject :> TExpr.TypeConversion;
+ CodeCastExpression(ToTypeRef(tExpr.MType()),
ToExpression(sourceExpr))
+
+ | <[ base ]> => CodeBaseReferenceExpression()
+ | <[ this ]> => CodeThisReferenceExpression()
+ | <[ typeof($typeExpr) ]> =>
CodeTypeOfExpression(typeExpr.ToString()) // TODO: Test it
+ | null => CodeSnippetExpression("");
+ | PExpr.Member(_, _) => // (obj, member)
+ //TODO: VladD2: Какая-то чушь. Надо это переделать...
+ // sample: obj = System.Drawing, member = Color
+
match(_manager.CoreEnv.LookupType(expr.ToString().Split('.').ToList()))
+ {
+ | Some(ti) => CodeTypeReferenceExpression(ti.FullName);
+ | _ => NotSupportedExpression(expr);
+ }
+
+ | _ => NotSupportedExpression(expr)
+ }
+ }
+
+ NotSupportedExpression(expr : PExpr) : CodeExpression
+ {
+ Debug.WriteLine($"[Form Designer]: Not suported expression: '$expr'
($(expr.GetType().Name))");
+ CodeSnippetExpression(expr.ToString())
+ }
+
+ protected ToStatements(expr : PExpr) : IEnumerable[CodeStatement]
+ {
+ match (expr)
+ {
+ | PExpr.Sequence(exprs) =>
+ foreach (expr in exprs)
+ foreach (codeStatement in ToStatements(expr))
+ yield codeStatement;
+
+ | <[ $expr1 += $expr2 ]> =>
+ match (expr1)
+ {
+ | <[ $obj.$member ]> when member.TypedObject is IEvent =>
+ yield CodeAttachEventStatement(ToExpression(obj),
+ member.TypedObject.Name, ToExpression(expr2))
+
+ | _ =>
+ yield CodeAssignStatement(ToExpression(expr1),
ToExpression(<[ $expr1 + $expr2 ]>))
+ }
+
+ | <[ $expr1 -= $expr2 ]> =>
+ match (expr1)
+ {
+ | <[ $obj.$member ]> when member.TypedObject is IEvent =>
+ yield CodeRemoveEventStatement(ToExpression(obj),
+ member.TypedObject.Name, ToExpression(expr2))
+
+ | _ =>
+ yield CodeAssignStatement(ToExpression(expr1),
ToExpression(<[ $expr1 - $expr2 ]>))
+ }
+
+ | <[ $target = $source ]> =>
+ yield CodeAssignStatement(ToExpression(target),
ToExpression(source))
+
+ | <[ mutable $expr = $val ]> with isMutable = true
+ | <[ def $expr = $val ]> with isMutable = false =>
+
+ def (expr, tyRef) =
+ match (expr)
+ {
+ | PExpr.TypeEnforcement (expr, ty) => (expr,
ToCodeTypeReference (ty));
+ | _ => (expr, CodeTypeReference ());
+ }
+
+ def name =
+ match (expr)
+ {
+ | PExpr.Ref (name) => name.Id;
+ | _ => throw NotSupportedException($"$expr not
supported");
+ }
+
+ def statement =
+ match (val)
+ {
+ | null => CodeVariableDeclarationStatement(tyRef, name);
+ | _ => CodeVariableDeclarationStatement(tyRef, name,
ToExpression(val))
+ }
+
+ statement.UserData["mutable"] = isMutable;
+ yield statement;
+
+ | <[ when ($cond) $expr ]> =>
+ yield CodeConditionStatement(ToExpression(cond),
ToStatements(expr).NToArray())
+
+ | <[ if ($cond) $trueExpr else $falseExpr ]> =>
+ yield CodeConditionStatement(ToExpression(cond),
+ ToStatements(trueExpr).NToArray(),
ToStatements(falseExpr).NToArray())
+
+ | _ => yield CodeExpressionStatement(ToExpression(expr))
+ }
+ }
+ }
+}
=======================================
--- /dev/null
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Nemerle.Completion2/Engine/BackgroundWorks/Engine-MergeCodeCompileUnit.n
Wed Nov 11 12:09:20 2009
@@ -0,0 +1,119 @@
+using System;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+
+using Nemerle.Assertions;
+using Nemerle.Collections;
+using Nemerle.Compiler;
+using Nemerle.Compiler.Parsetree;
+using Nemerle.Imperative;
+using Nemerle.Utility;
+using Nemerle.Compiler.Utils;
+using Nemerle.Compiler.Utils.Async;
+using Nemerle.Surround;
+
+namespace Nemerle.Completion2
+{
+ public partial class Engine
+ {
+ public BeginMergeCodeCompileUnit(codeCompileUnit : CodeCompileUnit) :
MergeCodeCompileUnitAsyncRequest
+ {
+ def request = MergeCodeCompileUnitAsyncRequest(this,
codeCompileUnit, MergeCodeCompileUnit);
+ AsyncWorker.AddWork(request);
+ request
+ }
+
+ public MergeCodeCompileUnit(codeCompileUnit : CodeCompileUnit) :
array[Location * string]
+ {
+ def request = BeginMergeCodeCompileUnit(codeCompileUnit);
+ _ = request.AsyncWaitHandle.WaitOne();
+
+ when (request.Stop)
+ assert(false);
+
+ request.MergeInfo
+ }
+
+ /// Run by AsyncWorker thread!
+ /// Parse CompileUnit. Set CompileUnit to source. Update information
about outline regions.
+ private MergeCodeCompileUnit(request : AsyncRequest) : void
+ {
+ AsyncWorker.CheckCurrentThreadIsTheAsyncWorker();
+
+ surroundwith (currentAsyncRequest)
+ try
+ {
+
+ when (request.Stop)
+ return;
+
+ if (IsBuildTypesTreeInProgress)
+ AsyncWorker.AddWork(request);
+ else
+ {
+ def project = this.Project;
+
+ if (project == null)
+ {
+ _ = BeginBuildTypesTree();
+ AsyncWorker.AddWork(request);
+ }
+ else
+ {
+ def req = request :> MergeCodeCompileUnitAsyncRequest;
+
+ req.MergeInfo =
MakeMargeInfoCodeCompileUnit(req.CodeCompileUnit);
+
+ req.MarkAsCompleted();
+ }
+ }
+
+ //Debug.WriteLine($"UpdateCompileUnit 6 $(timer.Elapsed)");
timer.Reset(); timer.Start();
+ }
+ catch
+ { | e is CompilationAbortedException =>
+ def msg = $"The parse CompileUnit operation aborted at:
$(e.Message)";
+ throw CompilationAbortedException(msg, e);
+ }
+ finally
+ {
+ //AsyncWorker.AddResponse(() => _callback.SetStatusText("Update
compile unit is complete."));
+ request.MarkAsCompleted();
+ }
+ }
+
+ private MakeMargeInfoCodeCompileUnit(codeCompileUnit :
CodeCompileUnit) : array[Location * string]
+ {
+ def result = List();
+ //def codeDomGenerator = FormCodeDomGenerator();
+
+ assert(codeCompileUnit.Namespaces.Count >= 1);
+ def ns = codeCompileUnit.Namespaces[0];
+ assert(ns.Types.Count >= 1);
+ def ty = ns.Types[0];
+ def cls = ty.UserData["Member"] :> ClassMember;
+ //assert(cls != null);
+
+ def methods = ty.Members.OfType.[CodeMemberMethod]().ToArray();
+
+ def found = methods.Find(m => m.Name == "InitializeComponent"
+ && m.ReturnType.BaseType == "System.Void"
&& m.ReturnType.TypeArguments.Count == 0
+ && m.Parameters.Count == 0);
+ match (found)
+ {
+ | Some(method) =>
+ def sourseInitializeComponent = method.UserData["Member"] :>
ClassMember;
+ def loc = sourseInitializeComponent.BodyInnerLocation;
+ def text = FormCodeDomGenerator.ToString(method.Statements);
+ result.Add((loc, text));
+
+ | _ => assert(false);
+ }
+
+ result.ToArray()
+ }
+ } // end class Engine
+} // end of Nemerle.Completion2 namespace
=======================================
--- /nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/CodeDomHelper.n Sun
Jan 28 18:45:49 2007
+++ /dev/null
@@ -1,132 +0,0 @@
-using System;
-using System.CodeDom;
-using System.CodeDom.Compiler;
-using System.Collections;
-using System.IO;
-using System.Reflection;
-
-using Nemerle.Compiler;
-using Nemerle.Compiler.Typedtree;
-using Nemerle.Collections;
-using SCG = System.Collections.Generic;
-
-namespace Nemerle.Compiler.Utils
-{
- public module CodeDomHelper
- {
- public IsPartial(attrs: NemerleAttributes): bool
- {
- attrs %&& NemerleAttributes.Partial
- }
-
- public GetMemberAttributes(attrs: NemerleAttributes, field: bool =
false): MemberAttributes
- {
- mutable res: MemberAttributes;
-
- when(attrs %&& NemerleAttributes.Static) res |=
MemberAttributes.Static;
- when(attrs %&& NemerleAttributes.Public) res |=
MemberAttributes.Public;
- when(attrs %&& NemerleAttributes.Private) res |=
MemberAttributes.Private;
-
- if(attrs %&& NemerleAttributes.Internal && attrs %&&
NemerleAttributes.Protected)
- res |= MemberAttributes.FamilyOrAssembly
- else
- {
- when(attrs %&& NemerleAttributes.Internal) res |=
MemberAttributes.FamilyAndAssembly;
- when(attrs %&& NemerleAttributes.Protected) res |=
MemberAttributes.Family;
- }
-
- when(field && !(attrs %&& NemerleAttributes.Mutable)) res |=
MemberAttributes.Const;
-
- when(attrs %&& NemerleAttributes.New) res |= MemberAttributes.New;
- when(attrs %&& NemerleAttributes.Override) res |=
MemberAttributes.Override;
- when(attrs %&& NemerleAttributes.Sealed) res |=
MemberAttributes.Final;
- when(attrs %&& NemerleAttributes.Virtual) res |=
MemberAttributes.VTableMask;
-
- when(res == 0)
- {
- if(field)
- res |= MemberAttributes.Private
- else
- res |= MemberAttributes.Assembly
- }
-
- res;
- }
-
- public GetTypeAttributes(attrs: NemerleAttributes): TypeAttributes
- {
- if(attrs == NemerleAttributes.None)
- TypeAttributes.NotPublic;
- else
- {
- mutable res: TypeAttributes =
- if(attrs %&& NemerleAttributes.Public)
- TypeAttributes.Public
- else
- TypeAttributes.NotPublic;
-
- when(attrs %&& NemerleAttributes.Abstract) res |=
TypeAttributes.Abstract;
- when(attrs %&& NemerleAttributes.Sealed) res |=
TypeAttributes.Sealed;
- when(attrs %&& NemerleAttributes.SpecialName) res |=
TypeAttributes.SpecialName;
- res;
- }
- }
-
- public GetLinePragma(expr: TExpr) : CodeLinePragma
- {
- def loc = expr.Location;
- CodeLinePragma(loc.File,loc.Line)
- }
-
- public MapFilterByType[T1,T2](this collection: SCG.IEnumerable[T1]) :
list[T2]
- {
- def res = SCG.List();
- foreach(e is T2 in collection)
- res.Add(e);
-
- res.ToList()
- }
-
- public MapFilterByType[T2](this collection: IEnumerable) : list[T2]
- {
- def res = SCG.List();
- foreach(e is T2 in collection)
- res.Add(e);
-
- res.ToList()
- }
-
- public StringToListOfLines(s: string) : SCG.List[string]
- {
- def res = SCG.List();
-
- using(def sr = StringReader(s))
- for(mutable s1 = sr.ReadLine(); s1 != null; s1 = sr.ReadLine())
- res.Add(s1);
-
- res
- }
-
- // Debug output method
- public ToString(unit: CodeCompileUnit, generator: ICodeGenerator) :
string
- {
- mutable s : string = null;
- using (def sw = StringWriter())
- {
- //def codeGen = NemerleCodeGenerator() : ICodeGenerator;
- generator.GenerateCodeFromCompileUnit(unit,sw,null);
- s = sw.ToString();
- }
- s
- }
-
- public PrintMacro(the_macro: IMacro) : string
- {
- $"[Macro:\n GetName = $(the_macro.GetName())\n"
- " GetNamespace () = $(the_macro.GetNamespace ())\n"
- " Keywords = $(the_macro.Keywords)\n"
- " Usage = $(the_macro.Usage)\n";
- //" SyntaxExtension = $(the_macro.SyntaxExtension())]";
- }
- }
-}
=======================================
---
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/FormCodeDomGenerator.n
Tue Nov 10 12:44:15 2009
+++ /dev/null
@@ -1,494 +0,0 @@
-using System;
-using System.IO;
-using System.Collections;
-using System.Collections.Generic;
-using System.CodeDom;
-using System.CodeDom.Compiler;
-using System.ComponentModel.Design.Serialization;
-using System.Diagnostics;
-using System.Drawing;
-using SR = System.Reflection;
-
-using Nemerle.Assertions;
-using Nemerle.Collections;
-using Nemerle.Compiler;
-using Nemerle.Compiler.Parsetree;
-using Nemerle.Compiler.Typedtree;
-using Nemerle.Completion2;
-using Nemerle.Imperative;
-using Nemerle.Utility;
-
-namespace Nemerle.Compiler.Utils
-{
- // now FormCodeDomGenerator only parses files from Project.CompileUnits
- // it is not thread-safe at the moment!
-
- // TODO : generation of new files
- public class FormCodeDomGenerator : NemerleCodeGenerator
- {
- protected enum ChangeStatus { | Equal | NonEqual | Renamed };
-
- mutable _project : Project;
-
- mutable _mainFileIndex : int;
- mutable _designerFileIndex : int;
-
- mutable _mainFileMerger : IFileTextMerger;
- mutable _designerFileMerger : IFileTextMerger;
-
- mutable _formCodeInfo : FormCodeInfo;
-
- mutable _codeDomMethods : list[CodeMemberMethod];
- mutable _codeDomFields : list[CodeMemberField];
-
- mutable _oldFields: list[FieldBuilder];
- mutable _oldMethods: list[MethodBuilder];
-
- /*
- mutable _output : TextWriter; // changed before immediate processing
-
- protected new Output : TextWriter
- {
- get { _output }
- set { _output = value; }
- }
-
- mutable _currentFileIndex : int;
-
- protected SetMainOutput() : void
- {
- _currentFileIndex = _mainFileIndex;
- Output = _mainFile;
- }
-
- protected SetDesignerOutput() : void
- {
- _currentFileIndex = _designerFileIndex;
- Output = _designerFile;
- }
- */
-
- public MergeFormCodeFromCompileUnit([NotNull] project: Project,
- mainFilePath: string, designerFilePath: string, e: CodeCompileUnit,
- mainFileMerger : IFileTextMerger, designerFileMerger :
IFileTextMerger,
- o: CodeGeneratorOptions) : void
- {
- _project = project;
-
- _mainFileMerger = mainFileMerger;
- _designerFileMerger = designerFileMerger;
-
- _mainFileIndex = Location.GetFileIndex(mainFilePath);
- _designerFileIndex = Location.GetFileIndex(designerFilePath);
-
- _formCodeInfo = e.UserData[typeof(FormCodeInfo)] :> FormCodeInfo;
- Debug.Print($"Before merging: _formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine)\n"
- "_formCodeInfo.newMethodInsertionLine =
$(_formCodeInfo.newMethodInsertionLine)\n");
-
- Options = if (o != null) o else CodeGeneratorOptions();
-
- Debug.Assert(e.Namespaces.Count == 1,"CodeCompileUnit for a form
should contain only one namespace!");
-
- // TODO : do we need to bother about namespace Imports?
-
- Debug.Assert(e.Namespaces[0].Types.Count == 1,
- "CodeCompileUnit for a form should contain only one form class!");
-
- def nsDecls =
project.CompileUnits.GetTopNamespace(_mainFileIndex).Decls.MapFilterByType.[Decl.Namespace]();
-
- Debug.Assert(nsDecls.Length == 1,
- "Root Decl for a form CompileUnit should contain only one form
class!" );
- def nsDecl = nsDecls.Head;
-
- // TODO : Check for form class
- MergeClassDecl(e.Namespaces[0].Types[0],
- match(nsDecl.Decls.Find(_ is Decl.Type))
- { | Some(Decl.Type(ast)) => ast
- | _ => throw ApplicationException(
- "Can't find typeBuilder for the Form class
in CodeDom")
- }.TypeBuilder);
-
- _mainFileMerger.Flush();
- _designerFileMerger.Flush();
-
- Debug.Print($"After merging: _formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine)\n"
- "_formCodeInfo.newMethodInsertionLine =
$(_formCodeInfo.newMethodInsertionLine)\n");
-
- e.UserData[typeof(FormCodeInfo)] = _formCodeInfo;
- }
-
- private allDeclaredFlags : SR.BindingFlags = BindingFlags.DeclaredOnly
|
- BindingFlags.Instance |
- BindingFlags.Static |
- BindingFlags.Public |
- BindingFlags.NonPublic;
-
- protected MergeClassDecl(classDecl: CodeTypeDeclaration, typeBuilder:
TypeBuilder) : void
- {
- _oldMethods = typeBuilder.GetMembers(allDeclaredFlags).Filter(
- m => match(m.MemberKind) { | MemberKinds.Method | Constructor =>
true | _ => false }
- && !m.Name.OrdinalStartsWith("_N_field_initialiser"))
- .MapFilterByType.[MethodBuilder]();
-
- _codeDomMethods =
classDecl.Members.MapFilterByType.[CodeMemberMethod]();
-
- _oldFields =
typeBuilder.GetFields(allDeclaredFlags).MapFilterByType.[FieldBuilder]();
- _codeDomFields =
classDecl.Members.MapFilterByType.[CodeMemberField]();
-
- MergeMethods(classDecl);
- MergeFields();
- }
-
- protected MergeFields() : void
- {
- //classDecl.Members.Filter(_ is CodeMemberField).Map(_ :
CodeMemberField);
-
- // DEBUG
- Debug.Print("oldFields:\n");
- _oldFields.Iter(f => Debug.Print($" field $(f.Name)") );
-
- //Debug.Print("allFields:\n");
- //typeBuilder.GetFields().Iter(f => Debug.Print($" field
$(f.Name)\n") );
-
- Debug.Print("codedomFields:\n");
- _codeDomFields.Iter(f => Debug.Print($" field $(f.Name)") );
-
- def isAddLine = Options.BlankLinesBetweenMembers;
-
- def AddField(cdf) // to designer
- {
- using(def sw = StringWriter())
- {
- Output = sw;
- Indent = 2; // TODO: maybe we should change it dynamically?
-
- if (isAddLine)
- Output.WriteLine();
- else
- GenerateIndent();
- GenerateField(cdf);
-
- def linesList = CodeDomHelper.StringToListOfLines(sw.ToString()
);
- _designerFileMerger.AddLines(_formCodeInfo.newFieldInsertionLine,
- linesList);
-
- _formCodeInfo.newFieldInsertionLine += linesList.Count; //
TODO : maybe we have to add additional lines
- Debug.Print($"_formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine) "
- "after adding $(cdf.Name)\n");
- }
- }
-
- def RemoveField(of)
- {
- def loc = of.Location;
- def line = if (Options.BlankLinesBetweenMembers) loc.Line-1 else
loc.Line;
- _designerFileMerger.RemoveLines(line, loc.EndLine );
-
- def lineOffset = line - loc.EndLine - 1;
- Relocate(_designerFileIndex,line,lineOffset);
-
- _formCodeInfo.newFieldInsertionLine += lineOffset;
- Debug.Print($"_formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine) "
- "after removing $(of.Name)\n");
- }
-
- def RenameField(of,cdf)
- {
- using(def sw = StringWriter())
- {
- Output = sw;
- Indent = 2; // TODO: maybe we should change it dynamically?
-
- GenerateIndent();
- GenerateField(cdf);
-
- def linesList = CodeDomHelper.StringToListOfLines(sw.ToString()
);
-
- def oldLoc = of.Location;
- _designerFileMerger.ReplaceLines(oldLoc.Line, oldLoc.EndLine,
- linesList);
- def lineOffset = linesList.Count - (oldLoc.EndLine - oldLoc.Line
+ 1);
- Relocate(_designerFileIndex, oldLoc.Line, lineOffset);
-
- _formCodeInfo.newFieldInsertionLine += lineOffset;
- Debug.Print($"_formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine) "
- "after renaming $(of.Name)->$(cdf.Name)\n");
- }
- }
-
- def sortedCodedomFields = _codeDomFields.Sort(
- fun(f1,f2) {
- mutable res : int;
-
- res = if(f1.UserData.Contains(typeof(Location)))
- {
- if(f2.UserData.Contains(typeof(Location)))
- {
- (f1.UserData[typeof(Location)] :> Location).CompareTo(
- (f2.UserData[typeof(Location)] :> Location))
- }
- else
- -1
- }
- else if(f2.UserData.Contains(typeof(Location)))
- 1
- else
- -1;
-
- /*
- when(f1.UserData.Contains(typeof(Location)))
- Debug.Print($"$(f1.Name) has Location =
$(f1.UserData[typeof(Location)] :> Location)\n");
- when(f2.UserData.Contains(typeof(Location)))
- Debug.Print($"$(f2.Name) has Location =
$(f2.UserData[typeof(Location)] :> Location)\n");
-
- Debug.Print($"Comparing1 $(f1.Name) and $(f2.Name) res =
$res\n");
- */
- res
- }
- );
-
- Debug.Print("codedomFields (after Sort):\n");
- sortedCodedomFields.Iter(f => Debug.Print($" field $(f.Name)\n") );
-
- AddRemoveRenameDispatcher(_oldFields, sortedCodedomFields,
- GetChangeStatus,
- AddField, RemoveField, RenameField );
- }
-
- protected MergeMethods(classDecl: CodeTypeDeclaration) : void
- {
- // DEBUG
- Debug.Print("oldMethods:\n");
- _oldMethods.Iter(m => Debug.Print($" method $(m.Name)") );
-
- //Debug.Print("allMethods:\n");
- //typeBuilder.GetMethods().Iter(m => Debug.Print($" method
$(m.Name)\n") );
-
- Debug.Print("codedomMethods:\n");
- _codeDomMethods.Iter(m => Debug.Print($" method $(m.Name)") );
-
- // Process InitializeComponent
-
- match((_oldMethods.Find(m => m.Name == "InitializeComponent" ),
- _codeDomMethods.Find(m => m.Name == "InitializeComponent" ))
)
- {
- | (om, Some(cdm)) =>
- using(def sw = StringWriter())
- {
- Output = sw;
- Indent = 2; // TODO: maybe we should change it dynamically?
-
- GenerateIndent();
- GenerateMethod(cdm, classDecl);
-
- def linesList =
CodeDomHelper.StringToListOfLines(sw.ToString());
-
- match(om)
- {
- | Some(om) =>
- def oldLoc = om.Location;
- _designerFileMerger.ReplaceLines(oldLoc.Line,
oldLoc.EndLine,
- linesList);
- def lineOffset = linesList.Count - (oldLoc.EndLine -
oldLoc.Line + 1);
- Relocate(_designerFileIndex, oldLoc.Line, lineOffset);
-
- _formCodeInfo.newFieldInsertionLine += lineOffset;
- Debug.Print($"_formCodeInfo.newFieldInsertionLine =
$(_formCodeInfo.newFieldInsertionLine) "
- "after renewing InitializeComponent\n");
-
- | None => // just give up for now
- throw ApplicationException("InitializeComponent not found
in old designer file");
- }
- }
-
- | _ =>
- throw ApplicationException("InitializeComponent not found in
CodeDom tree");
- }
-
- def AddMethod(cdm)
- {
- using(def sw = StringWriter())
- {
- Output = sw;
- Indent = 2; // TODO: maybe we should change it dynamically?
-
-
- // KLiss: alter event handler parameter names
- foreach(param is CodeParameterDeclarationExpression in
cdm.Parameters)
- {
- when(param.Name == "sender" && param.Type.BaseType
== "System.Object")
- param.Name = "_sender";
- when(param.Name == "e" &&
param.Type.BaseType.EndsWith("EventArgs"))
- param.Name = "_e";
- }
-
- // TODO: correct way to insert empty method
-
- def statements = cdm.Statements;
- def isMethodBodyEmpty = (statements.Count == 0);
- when (isMethodBodyEmpty)
- // insert ';' for generation reverse this change later
- _ = statements.Add(CodeMethodReturnStatement() );
-
- // if(Options.BlankLinesBetweenMembers )
- Output.WriteLine(); // TODO : blank lines should be regulated?
-
- GenerateMethod(cdm,classDecl);
-
- // clear body again
- when (isMethodBodyEmpty)
- statements.Clear();
-
- def linesList = CodeDomHelper.StringToListOfLines(sw.ToString()
);
-
- _mainFileMerger.AddLines(_formCodeInfo.newMethodInsertionLine,
- linesList);
-
- // Add cursor position to codedom: (TODO: do it the right way)
- cdm.UserData[typeof(Point)] =
- Point(1 + Options.IndentString.Length*3,
- 1 + _formCodeInfo.newMethodInsertionLine +
- match (BracingStyle) { | Block | Indent => 2 | _ => 3 }
);
-
- _formCodeInfo.newMethodInsertionLine += linesList.Count; //
TODO : maybe we have to add additional lines
- Debug.Print($"_formCodeInfo.newMethodInsertionLine =
$(_formCodeInfo.newMethodInsertionLine) "
- "after adding $(cdm.Name)\n");
- }
- }
-
- def RemoveMethod(om)
- {
- // TODO : blank lines should be regulated?
- def (line,endLine) = (om.Location.Line-1,om.Location.EndLine);
- def removedLines = endLine - line + 1;
- _mainFileMerger.RemoveLines(line, endLine); // TODO
-
- // adjust all other methods
- Relocate(_mainFileIndex,line, -removedLines);
-
- _formCodeInfo.newMethodInsertionLine -= removedLines;
- Debug.Print($"_formCodeInfo.newMethodInsertionLine =
$(_formCodeInfo.newMethodInsertionLine) "
- "after removing $(om.Name)\n");
- }
-
- def RenameMethod(om,cdm)
- {
- using(def sw = StringWriter())
- {
- Output = sw;
- Indent = 2; // TODO: maybe we should change it dynamically?
-
- GenerateIndent();
- GenerateMethod(cdm,classDecl);
-
- def linesList = CodeDomHelper.StringToListOfLines(sw.ToString()
);
-
- def oldLoc = om.Location;
- _designerFileMerger.ReplaceLines(oldLoc.Line, oldLoc.EndLine,
- linesList);
- def lineOffset = linesList.Count - (oldLoc.EndLine - oldLoc.Line
+ 1);
- Relocate(_mainFileIndex, oldLoc.Line, lineOffset);
-
- _formCodeInfo.newMethodInsertionLine += lineOffset;
- Debug.Print($"_formCodeInfo.newMethodInsertionLine =
$(_formCodeInfo.newMethodInsertionLine)"
- "after renaming $(om.Name)->$(cdm.Name)\n");
- }
- }
-
- AddRemoveRenameDispatcher(_oldMethods, _codeDomMethods,
- GetChangeStatus,
- AddMethod, RemoveMethod, RenameMethod );
- }
-
- protected GenerateIndent() : void
- {
- def output = Output;
- def indentString = Options.IndentString;
- repeat(Indent)
- output.Write(indentString);
- }
-
- protected Relocate(fileIndex: int,
- line: int, lineOffset: int) : void
- {
- if (fileIndex == _mainFileIndex)
- {
- foreach (_m in _oldMethods)
- {
- assert2(false);
- //def loc = m.Location;
- //when (loc.FileIndex == _mainFileIndex)
- // m.Location = Completion.Relocate(loc, line, 0, lineOffset, 0)
- }
-
- foreach (m in _codeDomMethods)
- {
- def locRef = m.UserData[typeof(Location)];
-
- when (locRef != null)
- {
- def loc = locRef :> Location;
- when (loc.FileIndex == fileIndex)
- {
- def pt = m.UserData[typeof(Point)] :> Point;
- when (pt.Y > line)
- {
- pt.Y += lineOffset;
- m.UserData[typeof(Point)] = pt;
- }
- }
- }
- }
- }
- else // fileIndex == _designerFileIndex
- {
- foreach (_f in _oldFields)
- {
- assert2(false);
- //def loc = f.Location;
- //when (loc.FileIndex == fileIndex)
- // f.Location = Completion.Relocate(loc, line, 0, lineOffset, 0)
- }
- }
- }
-
- // Removes can be everywhere, Adds only at the end
- static protected AddRemoveRenameDispatcher[T1,T2](old_list: list[T1],
new_list: list[T2],
- status: T1*T2->ChangeStatus,
- addFunc : T2->void, removeFunc : T1->void, renameFunc : T1*T2->void
) : void
- {
- def dispatcher(old_l, new_l )
- {
- | (h1 :: t1, h2 :: t2) =>
- match (status(h1,h2)) {
- | Equal => dispatcher(t1,t2)
- | NonEqual => { removeFunc(h1); dispatcher(t1,new_l) }
- | Renamed => { renameFunc(h1,h2); dispatcher(t1,t2) }
- }
- | (_, []) =>
- foreach (x in old_l)
- removeFunc(x);
-
- | ([], _) =>
- foreach (x in new_l)
- addFunc(x);
- }
-
- dispatcher(old_list, new_list)
- }
-
- static protected GetChangeStatus[T1,T2](oldMember: T1, codeDomMember:
T2 ) : ChangeStatus
- where T1 : MemberBuilder where T2 : CodeTypeMember
- {
- //Debug.Print($"Comparing $(oldMember.Name) and
$(codeDomMember.Name)\n");
- def oldName = codeDomMember.UserData["Name"];
- if (oldName != null && ((oldName :> string) == oldMember.Name))
- if (oldMember.Name != codeDomMember.Name)
- ChangeStatus.Renamed
- else
- ChangeStatus.Equal
- else
- ChangeStatus.NonEqual
- }
- }
-}
=======================================
--- /nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/FormCodeDomParser.n
Tue Nov 10 12:44:15 2009
+++ /dev/null
@@ -1,212 +0,0 @@
-using System;
-using System.IO;
-using System.Collections;
-using System.Collections.Generic;
-using System.CodeDom;
-using System.CodeDom.Compiler;
-using System.ComponentModel.Design.Serialization;
-using System.Diagnostics;
-using System.Drawing;
-using System.Reflection;
-
-using Nemerle.Assertions;
-using NC = Nemerle.Collections;
-using Nemerle.Compiler;
-using Nemerle.Compiler.Parsetree;
-using Nemerle.Compiler.Typedtree;
-using Nemerle.Completion2;
-using Nemerle.Utility;
-
-namespace Nemerle.Compiler.Utils
-{
- // now CodeDomParser only parses files from Project.CompileUnits
- // it is not thread-safe at the moment!
- public class FormCodeDomParser : NemerleCodeParser
- {
- mutable _project : Project;
-
- mutable _mainFileIndex : int;
- mutable _designerFileIndex : int;
-
- mutable _formCodeInfo : FormCodeInfo = FormCodeInfo(-1,-1);
-
- /*
- methods and fields in generated CodeCompileUnit contain
- typeof(Location) - indicates that this member is already in file
- and
- typeof(Point) - is required by Designer
- data in UserData
-
- CodeCompileUnit itself contains typeof(FormCodeInfo) in UserData
- */
- public CreateCodeCompileUnit(project : Project, mainFileIndex : int,
designerFileIndex : int) : CodeCompileUnit
- {
- // Initialization
- _project = project;
- base._manager = _project.Engine;
-
- _mainFileIndex = mainFileIndex;
- _designerFileIndex = designerFileIndex;
-
- //// TODO: new object vs Clear
- //cachedObjs = NC.Hashtable();
-
- // Processing
- def unit = CodeCompileUnit();
-
- def globalImports = List();
-
- foreach(decl in
project.CompileUnits.GetTopNamespace(_designerFileIndex).Decls)
- {
- | Decl.Namespace as nsDecl => _ =
unit.Namespaces.Add(ProcessNamespace(nsDecl));
-
- | Decl.Using as usDecl =>
- globalImports.Add(usDecl.Name.ToString("."));
- //unit.Imports.Add(CodeNamespaceImport());
-
- | d with(bodyLoc =
project.CompileUnits.GetTopNamespace(_mainFileIndex).BodyLocation) =>
- //TODO: VladD2: Какая-то чушь...
- throw CodeDomSerializerException($"Assumed root Declaration of
CompileUnit is Decl.Namespace, got $d",
-
CodeLinePragma(bodyLoc.File,bodyLoc.Line));
- }
-
- foreach(import in globalImports)
- _ = unit.ReferencedAssemblies.Add(import);
-
- // Add FormCodeInfo
- when (_designerFileIndex != -1)
- assert(_formCodeInfo.newMethodInsertionLine != -1 &&
_formCodeInfo.newFieldInsertionLine != -1,
- "Don't know where generated fields and methods should be
placed");
-
- //TODO: VladD2: Какая-то чушь...
- unit.UserData.Add(typeof(FormCodeInfo), _formCodeInfo);
-
- /*
- Debug.Write(CodeDomHelper.ToString(unit,
- NemerleCodeGenerator()));
- Debug.Write(CodeDomHelper.ToString(unit,
-
Microsoft.CSharp.CSharpCodeProvider().CreateGenerator()));
- */
-
- unit
- }
-
- private ProcessNamespace(decl: Decl.Namespace) : CodeNamespace
- {
- def res = CodeNamespace(decl.Name.ToString("."));
-
- foreach(decl in decl.Decls)
- match(decl)
- {
- | Decl.Type(ast) =>
- assert(res.Types.Count < 2, "Form files should not contain
more than one top class declaration");
- //Debug.Write(typeDecl.Ast);
-
- InitFormCodeInfo(ast.TypeBuilder);
-
- _ = res.Types.Add(ProcessTypeDeclaration(ast));
-
- | Decl.Using as usDecl =>
-
res.Imports.Add(CodeNamespaceImport(usDecl.Name.ToString(".")));
-
- | Decl.Namespace(BodyLocation = bodyLoc) =>
- //TODO: VladD2: Какая-то чушь... Счего бы это нельзя иметь
вложенных пространств имен?
- throw CodeDomSerializerException("Namespace declarations
cannot contain inner namespace declarations",
-
CodeLinePragma(bodyLoc.File,bodyLoc.Line));
-
- | _ => () // Ignored
- }
-
- res
- }
-/*
- protected override ProcessClassMembers(members: list[IMember],
classDecl: CodeTypeDeclaration) : void
- {
- foreach (m in members)
- {
- | m is TypeBuilder =>
- _ = classDecl.Members.Add(CreateClass(m));
-
- | m is MemberBuilder when
(!m.Name.OrdinalStartsWith("_N_field_initialiser")) =>
- _ = classDecl.Members.Add(CreateMember(m));
-
- | _ =>
- () //Debug.Print($"Declaration of external member $m ignored");
- }
- }
-
- protected override CreateMember(member: MemberBuilder) : CodeTypeMember
- {
- def memberDecl = base.CreateMember(member);
- memberDecl.UserData["Name"] = member.Name;
- memberDecl
- }
-
- protected override CreateField(field: FieldBuilder) : CodeMemberField
- {
- when (field.Location.FileIndex == _designerFileIndex)
- {
- def lineAfterEnd = field.Location.EndLine+1;
- when (lineAfterEnd > _formCodeInfo.newFieldInsertionLine)
- _formCodeInfo.newFieldInsertionLine = lineAfterEnd;
- }
-
- base.CreateField(field);
- }
-
- protected override CreateMethod(method: MethodBuilder) :
CodeMemberMethod
- {
- def methodDecl = base.CreateMethod(method);
-
- if (method.Location.FileIndex == _mainFileIndex)
- {
- def lineAfterEnd = method.Location.EndLine+1;
- when (lineAfterEnd > _formCodeInfo.newMethodInsertionLine)
- _formCodeInfo.newMethodInsertionLine = lineAfterEnd;
-
- // TODO: correct positioning
- methodDecl.UserData.Add(typeof(Point),
- Point( 1+ method.BodyTyped.Location.Column,
- method.BodyTyped.Location.Line));
- }
- else when (method.Name == "InitializeComponent")
- {
- // TODO: correct region handling
- // TODO: do we need extra space?
- def lineAfterEnd = method.Location.EndLine+1;
- when (lineAfterEnd > _formCodeInfo.newFieldInsertionLine)
- _formCodeInfo.newFieldInsertionLine = lineAfterEnd;
- }
-
- methodDecl
- }
-*/
- private InitFormCodeInfo(typeBuilder: TypeBuilder) : void
- {
- // Make sure at least main and designer files are included in
PartsLocation
-
- // TODO: quite a brute approach
-
- mutable partsLocations = typeBuilder.PartsLocation;
- assert (partsLocations.Length == 2, "Form class declaration must
reside in two files: main and designer's");
-
- when (partsLocations.Head.FileIndex == _designerFileIndex)
- partsLocations = partsLocations.Reverse();// TODO
-
- assert (partsLocations.Head.FileIndex == _mainFileIndex &&
- partsLocations.Last.FileIndex == _designerFileIndex,
- "Main class is located in the wrong files!");
-
- // TODO
- _formCodeInfo.newMethodInsertionLine = partsLocations.Head.Line + 1;
- _formCodeInfo.newFieldInsertionLine = partsLocations.Last.Line + 1;
- }
-
- // process cached objects because form designer doesn't understand 'em
- //#region Cached objects related
- //
- //protected mutable cachedObjs : NC.Hashtable[string,CodeExpression];
- //
- //#endregion
- }
-}
=======================================
--- /nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/FormCodeInfo.n Fri
May 25 03:20:00 2007
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-using System.CodeDom;
-using System.Reflection;
-
-using Nemerle.Compiler;
-using Nemerle.Compiler.Typedtree;
-
-namespace Nemerle.Compiler.Utils
-{
- // This struct is inserted into CodeCompileUnit.UserData with
typeof(FormCodeInfo) key.
- public struct FormCodeInfo
- {
- // number of line in form main code file
- public mutable newMethodInsertionLine : int; // -1 indicates
uninitialized position
-
- // number of line in designer code file
- public mutable newFieldInsertionLine : int; // -1 indicates
uninitialized position
-
- public this(newMethodInsertionLine: int = -1, newFieldInsertionLine:
int = -1)
- {
- this.newMethodInsertionLine = newMethodInsertionLine;
- this.newFieldInsertionLine = newFieldInsertionLine;
- }
- }
-}
=======================================
---
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/NemerleCodeDomProvider.n
Fri Aug 24 04:46:24 2007
+++ /dev/null
@@ -1,62 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.CodeDom.Compiler;
-
-using Nemerle.Compiler;
-
-namespace Nemerle.Compiler.Utils
-{
- public class NemerleCodeDomProvider : CodeDomProvider
- {
- private provider: CodeDomProvider;
-
- public this()
- {
- this(NemerleCodeProvider());
- }
-
- public this(prov: CodeDomProvider)
- {
- provider = prov;
- }
-
- [Obsolete("Callers should not use the ICodeParser interface.")]
- public override CreateParser(): ICodeParser
- {
-#pragma warning disable 618 // Obsolete
- def parser = provider.CreateParser();
-#pragma warning restore 618
-
- if (parser == null)
- NemerleCodeParser();
- else
- parser;
- }
-
- [Obsolete("Callers should not use the ICodeGenerator interface.")]
- public override CreateGenerator(): ICodeGenerator
- {
-#pragma warning disable 618 // Obsolete
- provider.CreateGenerator();
-#pragma warning restore 618
- }
-
- [Obsolete("Callers should not use the ICodeCompiler interface.")]
- public override CreateCompiler(): ICodeCompiler
- {
-#pragma warning disable 618 // Obsolete
- provider.CreateCompiler();
-#pragma warning restore 618
- }
-
- public override FileExtension: string
- {
- get { provider.FileExtension; }
- }
-
- public override GetConverter (ty : Type) : TypeConverter
- {
- provider.GetConverter(ty);
- }
- }
-}
=======================================
--- /nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/NemerleCodeParser.n
Tue Nov 10 12:44:15 2009
+++ /dev/null
@@ -1,804 +0,0 @@
-using System;
-using System.IO;
-using System.Collections;
-using System.Collections.Generic;
-using System.CodeDom;
-using System.CodeDom.Compiler;
-using System.ComponentModel.Design.Serialization;
-using System.Diagnostics;
-using System.Drawing;
-using System.Reflection;
-
-using Nemerle.Assertions;
-using Nemerle.Collections;
-using Nemerle.Compiler;
-using Nemerle.Compiler.Parsetree;
-using Nemerle.Compiler.Typedtree;
-using Nemerle.Completion2;
-using Nemerle.Imperative;
-using Nemerle.Text;
-using Nemerle.Utility;
-
-using System.CodeDom.CodeBinaryOperatorType;
-
-using SCG = System.Collections.Generic;
-
-namespace Nemerle.Compiler.Utils
-{
- // now CodeDomParser only parses files from Project.CompileUnits
- // it is not thread-safe at the moment!
-
- //TODO: VladD2: Убрать наследование от ManagerClass. Вместо этого
использовать проект к которому подлючен разбираемый файл.
-
- /// <summary>
- /// Provides an implementation of the <see
cref="T:System.CodeDom.Compiler.ICodeParser"/> interface.
- /// </summary>
- public class NemerleCodeParser : ManagerClass, ICodeParser
- {
- /// <summary>
- /// Initializes a new instance of the <see
cref="T:Nemerle.Compiler.NemerleCodeParser"/> class.
- /// </summary>
- public this ()
- {
- base (CompilationOptions());
- InitCompiler ();
- LoadExternalLibraries ();
- }
-
- // now needed only for AsObject
- protected mutable _manager : ManagerClass;
-
- // TODO: do we need to make it type-safe
- protected mutable _currentMethod : MethodBuilder;
-
- /// <summary>
- /// Compiles the specified text stream into a <see
cref="T:System.CodeDom.CodeCompileUnit"/>
- ///.</summary>
- /// <param name="codeStream">A <see cref="T:System.IO.TextReader"/>
- /// that is used to read the code to be parsed.</param>
- /// <returns>
- /// A <see cref="T:System.CodeDom.CodeCompileUnit"/> containing the
code
- /// model produced from parsing the code.
- /// </returns>
- public Parse(codeStream: TextReader) : CodeCompileUnit
- {
- def oldMan = ManagerClass.Instance;
- def topDecls =
- try
- {
- def lexer = LexerString (this, codeStream.ReadToEnd(),
Location.Default);
- ParsingPipeline (lexer);
- }
- finally
- {
- ManagerClass.Instance = oldMan;
- }
-
- def unit = CodeCompileUnit();
-
- mutable lastNamespace;
- mutable codeDomNamespace;
-
- def switchToNamespace(decl : TopDeclaration)
- {
- unless (decl.PName.context.CurrentNamespace.Equals(lastNamespace))
//FixMe: не надо исползовать PName он может быть пуст!
- {
- lastNamespace = decl.PName.context.CurrentNamespace;
- codeDomNamespace =
ToCodeNamespace(decl.PName.context.CurrentNamespace);
- _ = unit.Namespaces.Add(codeDomNamespace);
- }
- }
-
- topDecls.Iter (fun(decl: TopDeclaration) {
- | TopDeclaration.Class as cls =>
-
- switchToNamespace(cls);
- _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(cls));
-
- | TopDeclaration.Interface as ifs =>
-
- switchToNamespace(ifs);
- _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(ifs));
-
- | TopDeclaration.Enum as enm =>
-
- switchToNamespace(enm);
- _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(enm));
-
- | TopDeclaration.Variant as vrt =>
-
- switchToNamespace(vrt);
- _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(vrt));
-
- | TopDeclaration.VariantOption as vrto =>
-
- switchToNamespace(vrto);
- _ = codeDomNamespace.Types.Add(ToCodeTypeDeclaration(vrto));
-
- | TopDeclaration.Delegate as del =>
-
- //there is no need to switch to namespace
- switchToNamespace(del);
- _ = codeDomNamespace.Types.Add(ToCodeTypeDelegate(del));
-
- | _ =>
- throw NotSupportedException($"$decl is not supported");
- });
-
- unit;
- }
-
- protected virtual ToCodeNamespace(ns : NamespaceTree.Node) :
CodeNamespace
- {
- CodeNamespace(ns.GetDisplayName());
- }
-
- protected virtual ToCodeTypeDelegate(del : TopDeclaration.Delegate) :
CodeTypeDelegate
- {
- def ty = CodeTypeDelegate(del.Name);
-
- ty.ReturnType = ToCodeTypeReference(del.header.ParsedReturnType);
-
ty.Parameters.AddRange(del.header.ParsedParameters.Map(ToCodeParameterDeclarationExpression).NToArray());
-
- ty;
- }
-
- protected virtual ToCodeTypeDeclaration(vrt :
TopDeclaration.Variant) : CodeTypeDeclaration
- {
- def ty = CodeTypeDeclaration(vrt.Name);
-
- ty.IsClass = true;
- ty.IsInterface = false;
-
ty.BaseTypes.AddRange(vrt.t_extends.Map(ToCodeTypeReference).NToArray());
-
ty.TypeParameters.AddRange(ToCodeTypeParameters(vrt.typarms).NToArray());
- ty.Members.AddRange(vrt.decls.Map(ToCodeTypeMember).NToArray());
-
- ty.UserData["Nemerle.TopDeclaration"] = "Variant";
-
- ty;
- }
-
- protected virtual ToCodeTypeDeclaration(vrto :
TopDeclaration.VariantOption) : CodeTypeDeclaration
- {
- def ty = CodeTypeDeclaration(vrto.Name);
-
- ty.IsClass = true;
- ty.IsInterface = false;
-
//ty.BaseTypes.AddRange(vrto.t_extends.Map(ToCodeTypeReference).NToArray());
-
//ty.TypeParameters.AddRange(ToCodeTypeParameters(vrto.typarms).NToArray());
- ty.Members.AddRange(vrto.decls.Map(ToCodeTypeMember).NToArray());
-
- ty.UserData["Nemerle.TopDeclaration"] = "VariantOption";
-
- ty;
- }
-
- protected virtual ToCodeTypeDeclaration(enm : TopDeclaration.Enum) :
CodeTypeDeclaration
- {
- def ty = CodeTypeDeclaration(enm.Name);
- ty.IsClass = false;
- ty.IsEnum = true;
-
ty.BaseTypes.AddRange(enm.t_extends.Map(ToCodeTypeReference).NToArray());
-
ty.TypeParameters.AddRange(ToCodeTypeParameters(enm.typarms).NToArray());
- ty.Members.AddRange(enm.decls.Map(ToCodeTypeMember).NToArray());
- ty;
- }
-
- protected virtual ToCodeTypeDeclaration(ifs :
TopDeclaration.Interface) : CodeTypeDeclaration
- {
- def ty = CodeTypeDeclaration(ifs.Name);
- ty.IsClass = false;
- ty.IsInterface = true;
-
ty.BaseTypes.AddRange(ifs.t_extends.Map(ToCodeTypeReference).NToArray());
-
ty.TypeParameters.AddRange(ToCodeTypeParameters(ifs.typarms).NToArray());
- ty.Members.AddRange(ifs.methods.Map(ToCodeTypeMember).NToArray());
- ty;
- }
-
- protected virtual ToCodeTypeDeclaration(cls : TopDeclaration.Class) :
CodeTypeDeclaration
- {
- def ty = CodeTypeDeclaration(cls.Name);
-
- when(cls.Attributes %&& NemerleAttributes.Struct)
- {
- ty.IsClass = false;
- ty.IsStruct = true;
- }
-
-
ty.BaseTypes.AddRange(cls.t_extends.Map(ToCodeTypeReference).NToArray());
-
ty.TypeParameters.AddRange(ToCodeTypeParameters(cls.typarms).NToArray());
- ty.Members.AddRange(cls.decls.Map(ToCodeTypeMember).NToArray());
- ty;
- }
-
- private ToCodeTypeReference(typeName : string) : CodeTypeReference
- {
- CodeTypeReference(typeName);
- }
-
- protected virtual ToCodeTypeReference(expr : PExpr) : CodeTypeReference
- {
- ToCodeTypeReference(expr.ToString());
- }
-
- protected virtual ToCodeTypeParameter(tyvar : Splicable) :
CodeTypeParameter
- {
- CodeTypeParameter(tyvar.GetName().Id);
- }
-
- protected virtual ToCodeTypeParameters(typarms : Typarms) : list
[CodeTypeParameter]
- {
- def toCodeTypeParameter(tyvar : Splicable) : CodeTypeParameter
- {
- def tyParm = ToCodeTypeParameter(tyvar);
- typarms.constraints
- .Filter(c => c.tyvar.Equals(tyvar))
- .Iter (c => _ =
tyParm.Constraints.Add(ToCodeTypeReference(c.ty)));
- tyParm;
- }
-
- typarms.tyvars.Map(toCodeTypeParameter);
- }
-
- protected virtual ToMemberAttributes(attrs : NemerleAttributes) :
MemberAttributes
- {
- mutable memberAttrs: MemberAttributes;
-
- when(attrs %&& NemerleAttributes.Static) memberAttrs |=
MemberAttributes.Static;
- when(attrs %&& NemerleAttributes.Public) memberAttrs |=
MemberAttributes.Public;
- when(attrs %&& NemerleAttributes.Private) memberAttrs |=
MemberAttributes.Private;
-
- if(attrs %&& NemerleAttributes.Internal && attrs %&&
NemerleAttributes.Protected)
- memberAttrs |= MemberAttributes.FamilyOrAssembly
- else
- {
- when(attrs %&& NemerleAttributes.Internal) memberAttrs |=
MemberAttributes.Assembly;
- when(attrs %&& NemerleAttributes.Protected) memberAttrs |=
MemberAttributes.Family;
- }
-
- when(attrs %&& NemerleAttributes.New) memberAttrs |=
MemberAttributes.New;
- when(attrs %&& NemerleAttributes.Override) memberAttrs |=
MemberAttributes.Override;
- when(attrs %&& NemerleAttributes.Sealed) memberAttrs |=
MemberAttributes.Final;
-
- memberAttrs;
- }
-
- protected virtual ToCodeEnumOption(opt : ClassMember.EnumOption) :
CodeMemberField
- {
- def ext = (opt.DefinedIn :> TopDeclaration.Enum).t_extends;
-
- def typeRef =
- if(ext.Length>0)
- ToCodeTypeReference(ext.Head);
- else
- ToCodeTypeReference("int");
-
- CodeMemberField(typeRef, opt.Name);
- }
-
- protected virtual ToCodeMemberField(field : ClassMember.Field) :
CodeMemberField
- {
- CodeMemberField (ToCodeTypeReference (field.ty), field.Name);
- }
-
- protected virtual ToCodeMemberMethod(func : ClassMember.Function) :
CodeMemberMethod
- {
- def codeMethod =
- match(func.Name)
- {
- | ".ctor" => CodeConstructor()
- | ".cctor" => CodeTypeConstructor()
- | "Main" when func.Attributes %&& NemerleAttributes.Static
- => CodeEntryPointMethod()
- | _ => CodeMemberMethod()
- };
-
- codeMethod.Name = func.Name;
- codeMethod.ReturnType = ToCodeTypeReference(func.header.ReturnType);
- //TODO:
codeMethod.ReturnTypeCustomAttributes.AddRange(???.NToArray());
-
codeMethod.Parameters.AddRange(func.header.Parameters.Map(ToCodeParameterDeclarationExpression).NToArray());
-
codeMethod.ImplementationTypes.AddRange(func.implemented.Map(ToCodeTypeReference).NToArray());
- //TODO: codeMethod.PrivateImplementationType = ???
-
codeMethod.TypeParameters.AddRange(ToCodeTypeParameters(func.header.TypeParameters).NToArray());
- codeMethod.Statements.AddRange(ToStatements(func.Body).NToArray());
-
- codeMethod;
- }
-
- protected virtual ToCodeParameterDeclarationExpression(parm :
Parsetree.PParameter) : CodeParameterDeclarationExpression
- {
- def codeParam =
CodeParameterDeclarationExpression(ToCodeTypeReference(parm.Type),
parm.Name);
-
codeParam.CustomAttributes.AddRange(parm.modifiers.GetCustomAttributes().Map(ToCodeAttributeDeclaration).NToArray());
- //codeParam.Direction = ???
- codeParam;
- }
-
- protected virtual ToCodeMemberProperty(prop : ClassMember.Property) :
CodeMemberProperty
- {
- def codeProperty = CodeMemberProperty();
- codeProperty.Name = prop.Name;
- //TODO:
codeProperty.ImplementationTypes.AddRange(???(ToCodeTypeReference).NToArray());
- //TODO: codeProperty.PrivateImplementationType = ???
- //TODO: codeProperty.Parameters = ???
- match (prop.get)
- {
- | Some (m) =>
codeProperty.GetStatements.AddRange(ToStatements(m.Body).NToArray());
- | None => ()
- }
-
- match (prop.set)
- {
- | Some (m) =>
codeProperty.SetStatements.AddRange(ToStatements(m.Body).NToArray());
- | None => ()
- }
-
- codeProperty;
- }
-
- protected virtual ToCodeMemberEvent(evt : ClassMember.Event) :
CodeMemberEvent
- {
- def codeEvent = CodeMemberEvent();
- codeEvent.Name = evt.Name;
- codeEvent.Type = ToCodeTypeReference(evt.ty);
- //TODO:
codeProperty.ImplementationTypes.AddRange(???(ToCodeTypeReference).NToArray());
- //TODO: codeProperty.PrivateImplementationType = ???
-
- codeEvent;
- }
-
- protected virtual ToCodeTypeMember(member : ClassMember) :
CodeTypeMember
- {
- def codeMember =
- match (member)
- {
- | ClassMember.TypeDeclaration as tyDecl
- when tyDecl.td is TopDeclaration.Class =>
ToCodeTypeDeclaration(tyDecl.td :> TopDeclaration.Class);
- | ClassMember.TypeDeclaration as tyDecl
- when tyDecl.td is TopDeclaration.Variant =>
ToCodeTypeDeclaration(tyDecl.td :> TopDeclaration.Variant);
- | ClassMember.TypeDeclaration as tyDecl
- when tyDecl.td is TopDeclaration.VariantOption =>
ToCodeTypeDeclaration(tyDecl.td :> TopDeclaration.VariantOption);
- | ClassMember.TypeDeclaration as tyDecl
- when tyDecl.td is TopDeclaration.Delegate =>
ToCodeTypeDelegate(tyDecl.td :> TopDeclaration.Delegate);
- | ClassMember.Field as field => ToCodeMemberField(field);
- | ClassMember.Function as func => ToCodeMemberMethod(func);
- | ClassMember.Property as prop => ToCodeMemberProperty(prop);
- | ClassMember.Event as evt => ToCodeMemberEvent(evt);
- | ClassMember.EnumOption as enm => ToCodeEnumOption(enm);
-
- | _ => throw NotSupportedException($"$member not supported");
- }
-
- when(member.modifiers != null)
- {//member.modifiers == null for TopDeclaration.Variant
- codeMember.Attributes = ToMemberAttributes (member.Attributes);
-
codeMember.CustomAttributes.AddRange(member.modifiers.GetCustomAttributes().Map(ToCodeAttributeDeclaration).NToArray());
- }
-
- codeMember;
- }
-
- protected virtual ToCodeAttributeDeclaration(attr : PExpr) :
CodeAttributeDeclaration
- {
- CodeAttributeDeclaration(ToCodeTypeReference(attr));
- }
-
- protected ProcessTypeDeclaration(typeDecl : TopDeclaration) :
CodeTypeDeclaration
- {
- match(typeDecl)
- {
- | TopDeclaration.Class as typeDecl => CreateClass(typeDecl)
- | _ =>
- throw NotImplementedException("Non class top declarations aren't
supported yet")
- }
- }
-
- protected CreateClass(cls : TopDeclaration.Class) : CodeTypeDeclaration
- {
- // creates class declaration
- def classDecl = CodeTypeDeclaration(cls.Name);
-
- classDecl.Attributes =
CodeDomHelper.GetMemberAttributes(cls.Attributes);
-
- foreach (baseType in cls.TypeBuilder.GetDirectSuperTypes())
- _ = classDecl.BaseTypes.Add(ToTypeRef(baseType));
-
- // TODO: Seems like comments went away
- //classDecl.Comments = CodeCommentStatement();
-
- // TODO: Figure out how to parse CustomAttributes
- //classDecl.CustomAttributes =
cls.GetModifiers().GetCustomAttributes();
-
- classDecl.IsClass = true;
-
- // sets class access mofifiers
- classDecl.IsPartial = CodeDomHelper.IsPartial(cls.Attributes);
- classDecl.TypeAttributes =
CodeDomHelper.GetTypeAttributes(cls.Attributes);
-
-
- // Set type parameters
- // will it work?
- //VladD2: Думаю, для форм это на фиг не нужно.
- foreach (t in cls.typarms.tyvars)
- _ = classDecl.TypeParameters.Add(CodeTypeParameter(t.ToString()));
-
- // adds members
- Debug.Print("ProcessClassMembers in reversed order");
- ProcessClassMembers(cls.GetMembers(), classDecl);
-
- //TODO: adds usings directives
-
- //AddToCodeNamespace(cls, codeClass);
-
- //TODO: Add Location ?
-
- classDecl
- }
-
- // needed cause we may want to override it in derived classes
- protected virtual ProcessClassMembers(members : list[ClassMember],
classDecl : CodeTypeDeclaration) : void
- {
- foreach (m in members)
- {
- def codeTypeMember : CodeTypeMember =
- match (m)
- {
- | ClassMember.TypeDeclaration(td) => ProcessTypeDeclaration(td)
- | ClassMember.Field as field => CreateField(field)
- | ClassMember.Property as prop => CreateProperty(prop)
- | ClassMember.Event as vnt => CreateEvent(vnt)
- | ClassMember.Function as func => CreateMethod(func)
- | ClassMember.EnumOption =>
assert(false, "ClassMember.EnumOption not supported yet");
- };
-
- // TODO: Seems like comments went away
- //memberDecl.Comments = CodeCommentStatement();
-
- // TODO: Figure out how to parse CustomAttributes
- //memberDecl.CustomAttributes =
member.GetModifiers().GetCustomAttributes();
-
- //// Add Location
- //memberDecl.UserData.Add(typeof(Location), member.Location);
-
- codeTypeMember.UserData["Name"] = m.Name;
- codeTypeMember.Name = m.Name;
- _ = classDecl.Members.Add(codeTypeMember);
- }
- }
-
- protected virtual CreateField(field : ClassMember.Field) :
CodeMemberField
- {
- // GetFieldInfo() doesn't work
- //def fieldDecl = CodeMemberField(field.GetFieldInfo().FieldType,
field.Name);
-
- Debug.Print($"CreateField: from field $field");
-
- // TODO: VladD2: Using of GetSystemType() is bad idea!
- def fieldDecl = CodeMemberField(ToTypeRef(field.ty), field.Name);
-
- fieldDecl.Attributes =
CodeDomHelper.GetMemberAttributes(field.Attributes, true);
-
- /*if (field.IsLiteral)
- fieldDecl.InitExpression =
CodePrimitiveExpression(field.GetValue().AsObject(
- _manager.InternalType));
- else */
-
- // temporary
- //when (field.IsInitializerPresent)
- // fieldDecl.InitExpression =
CreateExpression(field.InitializerTyped);
-
- fieldDecl
- }
-
- protected virtual CreateProperty(prop : ClassMember.Property) :
CodeMemberProperty
- {
- Debug.Print($"CreateProperty: from $prop");
-
- def result = CodeMemberProperty();
- result.Attributes =
CodeDomHelper.GetMemberAttributes(prop.Attributes);
- result.Name = prop.Name;
-
- when(prop.get is Some(get))
- {
- result.HasGet = true;
- result.Type = ToTypeRef(get.header.ReturnType);
- _ =
result.GetStatements.AddRange(ToStatements(get.Body).NToArray())
- }
-
- when(prop.set is Some(set))
- {
- result.HasSet = true;
- result.Type = ToTypeRef(set.header.ReturnType);
- _ =
result.SetStatements.AddRange(ToStatements(set.Body).NToArray())
- }
-
- result
- }
-
- protected virtual CreateEvent(evt : ClassMember.Event) :
CodeMemberEvent
- {
- def eventDecl = CodeMemberEvent();
- eventDecl.Attributes =
CodeDomHelper.GetMemberAttributes(evt.Attributes);
- eventDecl.Name = evt.Name;
- eventDecl.Type = ToTypeRef(evt.ty);
- eventDecl
- }
-
- protected virtual CreateMethod(method : ClassMember.Function) :
CodeMemberMethod
- {
- Debug.Print($"CreateMethod : from $method");
-
- def methodDecl : CodeMemberMethod =
- match(method.Name)
- {
- | ".ctor" when method.Attributes %&& NemerleAttributes.Static =>
CodeTypeConstructor()
- | ".ctor" =>
CodeConstructor()
- | "Main" when method.Attributes %&& NemerleAttributes.Static =>
CodeEntryPointMethod()
- | _ =>
CodeMemberMethod()
- };
-
- methodDecl.Attributes =
CodeDomHelper.GetMemberAttributes(method.Attributes, false);
-
- //TODO: methodDecl.ImplementationTypes - how to get that
-
- //methodDecl.Parameters
- foreach (p in method.header.Parameters)
- _ =
methodDecl.Parameters.Add(CodeParameterDeclarationExpression(ToTypeRef(p.Type),
p.Name));
-
- //TODO: methodDecl.PrivateImplementationType ?
-
- methodDecl.ReturnType = ToTypeRef(method.header.ReturnType);
-
- // methodDecl.TypeParameters , TODO: check if it actually works
- foreach (tp in method.header.TypeParameters.tyvars)
- _ =
methodDecl.TypeParameters.Add(CodeTypeParameter(tp.ToString()));
-
- //_currentMethod = method;
- method.Builder.EnsureCompiled(); // we need PExpr & TExpr
-
methodDecl.Statements.AddRange(ToStatements(method.Builder.BodyParsed).NToArray());
-
- //Debug.Print($" method.BodyTyped.Location (col =
$(method.BodyTyped.Location.Column), line =
$(method.BodyTyped.Location.Line))");
-
- methodDecl
- }
-
-
- ToTypeRefExpression(typeInfo : Nemerle.Compiler.TypeInfo,
typeParaams : list[TyVar]) : CodeTypeReferenceExpression
- {
- CodeTypeReferenceExpression(ToTypeRef(typeInfo, typeParaams))
- }
-
- ToTypeRef(tyVar : PExpr) : CodeTypeReference
- {
- def cnvToCsTy(t : object)
- {
- t.ToString().Replace(".[", "<").Replace("[", "<").Replace("]", ">")
- }
- match (tyVar.TypedObject)
- {
- | t is TyVar => ToTypeRef(t)
- | null => CodeTypeReference(cnvToCsTy(tyVar))
- | t => CodeTypeReference(cnvToCsTy(t))
- }
- }
-
- ToTypeRef(tyVar : TyVar) : CodeTypeReference
- {
- def ty = tyVar.Fix();
-
- if (ty.IsFixed)
- {
- def makeTypeArgs(args) { args.MapToArray(ToTypeRef) }
-
- match (ty)
- {
- | Class(tycon, args) => ToTypeRef(tycon, args)
- | TyVarRef(tyvar) => CodeTypeReference(tyvar.Name)
- | Fun(_from, _to) => CodeTypeReference(typeof(object)) //
HACK: Not supported by C#
- | Tuple(args) =>
- CodeTypeReference("Nemerle.Builtins.Tuple", makeTypeArgs(args))
- | Array(tyVar, rank) => CodeTypeReference(ToTypeRef(tyVar),
rank)
- | Void => CodeTypeReference(typeof(void))
- | Ref(_tyVar)
- | Out(_tyVar) => throw ApplicationException("Ref/Out
not supported")
- | Intersection(_types) => CodeTypeReference(typeof(object))
- }
- }
- else CodeTypeReference(typeof(object))
- }
-
- ToTypeRef(typeInfo : Nemerle.Compiler.TypeInfo, typeParams :
list[TyVar]) : CodeTypeReference
- {
- //Debug.Assert(typeInfo.TyparmsCount == 0, "typeInfo.TyparmsCount ==
0, value is $(typeInfo.TyparmsCount)"); // TODO: Add support for type
parameters!
- //Debug.Assert(typeParams.IsEmpty, $"typeParams.IsEmpty, value is
$(typeParams.ToString())");
-
- if (typeInfo.SystemType != null)
- CodeTypeReference(typeInfo.SystemType.FullName,
typeParams.Map(ToTypeRef).NToArray());
- else
- CodeTypeReference(typeInfo.FullName,
typeParams.Map(ToTypeRef).NToArray());
- }
-
- protected virtual ToExpression(expr : PExpr) : CodeExpression
- {
- match (expr)
- {
- | <[ $expr1 && $expr2 ]> with op = BooleanAnd
- | <[ $expr1 || $expr2 ]> with op = BooleanOr
- | <[ $expr1 != $expr2 ]> with op = IdentityInequality
- | <[ $expr1 == $expr2 ]> with op = IdentityEquality
- | <[ $expr1 & $expr2 ]> with op = BitwiseAnd
- | <[ $expr1 | $expr2 ]> with op = BitwiseOr
- | <[ $expr1 + $expr2 ]> with op = Add
- | <[ $expr1 - $expr2 ]> with op = Subtract
- | <[ $expr1 / $expr2 ]> with op = Divide
- | <[ $expr1 * $expr2 ]> with op = Multiply =>
- CodeBinaryOperatorExpression(ToExpression(expr1), op,
ToExpression(expr2))
-
- | <[ array[..$parms] ]> as ary =>
- def tExpr = ary.TypedObject :> TExpr;
- match (tExpr)
- {
- | TExpr.Array(_args, dimensions) =>
- Debug.Assert(dimensions is [_]);
- CodeArrayCreateExpression(
- ToTypeRef(tExpr.MType()), parms.MapToArray(ToExpression))
- | _ => NotSupportedExpression(ary)
- }
-
- | <[ $obj.$func(..$parms) ]> as call =>
- match (call.func.TypedObject)
- {
- | TExpr.StaticRef(from, mem, type_parms) when mem.MemberKind
== MemberTypes.Constructor =>
- def codeParams = parms.MapToArray(ToExpression);
- CodeObjectCreateExpression(ToTypeRef(from.tycon,
type_parms), codeParams);
-
- | _ =>
- CodeMethodInvokeExpression(
- CodeMethodReferenceExpression(ToExpression(obj),
- func.ToString()),
-
parms.MapToArray(ToExpression));
- }
-
- | <[ $func(..$parms) ]> => // TODO: Add support of ctor's
- CodeMethodInvokeExpression(
- CodeMethodReferenceExpression(null, func.ToString()),
- parms.MapToArray(ToExpression));
-
- | <[ $obj.$field ]> when field.TypedObject is IField =>
- CodeFieldReferenceExpression(ToExpression(obj),
field.TypedObject.Name);
-
- | <[ $obj.$prop ]> when prop.TypedObject is IProperty =>
- CodePropertyReferenceExpression(ToExpression(obj),
prop.TypedObject.Name);
-
- | <[ $obj.$_ ]> as mem when mem.TypedObject is TExpr =>
- match (mem.TypedObject)
- {
- | TExpr.StaticRef(_from, mem, type_parms) when mem.IsStatic =>
- CodeFieldReferenceExpression(
- ToTypeRefExpression(mem.DeclaringType, type_parms),
mem.Name)
-
- | TExpr.MethodRef(_tObj, meth, typeParms, _notvirtual) =>
- CodeMethodReferenceExpression(ToExpression(obj), meth.Name,
- typeParms.MapToArray(param => ToTypeRef(param)))
-
- | xxx =>
- _ = xxx;
- NotSupportedExpression(expr)
- }
-
- | PExpr.Ref(name) =>
CodeVariableReferenceExpression(name.ToString())
-
- | PExpr.Literal(literal) =>
- match (literal)
- {
- | Void => CodeTypeReferenceExpression("void")
- | Null with val = null : object | String(val) | Float (val) |
Double (val)
- | Decimal (val) | Char (val) | Bool (val)
- => CodePrimitiveExpression(val)
- | Integer(val, is_negative, _treat_as) =>
- def val = val :> long;
- def val = if (is_negative) -val else val;
- CodePrimitiveExpression(val)
-
- | Enum (_val : Literal.Integer, ty : TypeInfo, field : IField)
=>
-
CodeFieldReferenceExpression(CodeTypeReferenceExpression(ty.FullName),
field.Name)
- }
-
- | <[ $sourceExpr :> $_ ]> =>
- def tExpr = expr.TypedObject :> TExpr.TypeConversion;
- CodeCastExpression(ToTypeRef(tExpr.MType()),
ToExpression(sourceExpr))
-
- | <[ base ]> => CodeBaseReferenceExpression()
- | <[ this ]> => CodeThisReferenceExpression()
- | <[ typeof($typeExpr) ]> =>
CodeTypeOfExpression(typeExpr.ToString()) // TODO: Test it
- | null => CodeSnippetExpression("");
- | PExpr.Member(_, _) => // (obj, member)
- // sample: obj = System.Drawing, member = Color
-
match(_manager.CoreEnv.LookupType(expr.ToString().Split('.').ToList()))
- {
- | Some(ti) => CodeTypeReferenceExpression(ti.FullName);
- | _ => NotSupportedExpression(expr);
- }
-
- | _ => NotSupportedExpression(expr)
- }
- }
-
- NotSupportedExpression(expr : PExpr) : CodeExpression
- {
- Debug.WriteLine($"[Form Designer]: Not suported expression: '$expr'
($(expr.GetType().Name))");
- CodeSnippetExpression(expr.ToString())
- }
-
- protected ToStatements(expr : PExpr) : SCG.IEnumerable[CodeStatement]
- {
- match (expr)
- {
- | PExpr.Sequence(exprs) =>
- foreach (expr in exprs)
- foreach (codeStatement in ToStatements(expr))
- yield codeStatement;
-
- | <[ $expr1 += $expr2 ]> =>
- match (expr1)
- {
- | <[ $obj.$member ]> when member.TypedObject is IEvent =>
- yield CodeAttachEventStatement(ToExpression(obj),
- member.TypedObject.Name, ToExpression(expr2))
-
- | _ =>
- yield CodeAssignStatement(ToExpression(expr1),
ToExpression(<[ $expr1 + $expr2 ]>))
- }
-
- | <[ $expr1 -= $expr2 ]> =>
- match (expr1)
- {
- | <[ $obj.$member ]> when member.TypedObject is IEvent =>
- yield CodeRemoveEventStatement(ToExpression(obj),
- member.TypedObject.Name, ToExpression(expr2))
-
- | _ =>
- yield CodeAssignStatement(ToExpression(expr1),
ToExpression(<[ $expr1 - $expr2 ]>))
- }
-
- | <[ $target = $source ]> =>
- yield CodeAssignStatement(ToExpression(target),
ToExpression(source))
-
- | <[ mutable $expr = $val ]> with isMutable = true
- | <[ def $expr = $val ]> with isMutable = false =>
-
- def (expr, tyRef) =
- match (expr)
- {
- | PExpr.TypeEnforcement (expr, ty) => (expr,
ToCodeTypeReference (ty));
- | _ => (expr, CodeTypeReference ());
- }
-
- def name =
- match (expr)
- {
- | PExpr.Ref (name) => name.Id;
- | _ => throw NotSupportedException($"$expr not
supported");
- }
-
- def statement =
- match (val)
- {
- | null => CodeVariableDeclarationStatement(tyRef, name);
- | _ => CodeVariableDeclarationStatement(tyRef, name,
ToExpression(val))
- }
-
- statement.UserData["mutable"] = isMutable;
- yield statement;
-
- | <[ when ($cond) $expr ]> =>
- yield CodeConditionStatement(ToExpression(cond),
ToStatements(expr).NToArray())
-
- | <[ if ($cond) $trueExpr else $falseExpr ]> =>
- yield CodeConditionStatement(ToExpression(cond),
- ToStatements(trueExpr).NToArray(),
ToStatements(falseExpr).NToArray())
-
- | _ => yield CodeExpressionStatement(ToExpression(expr))
- }
- }
- }
-}
=======================================
---
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Async/AsyncRequestType.n
Tue Nov 10 12:44:15 2009
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Async/AsyncRequestType.n
Wed Nov 11 12:09:20 2009
@@ -25,5 +25,6 @@
| FindMethodsToOverride
| CloseProject
| CreateCodeCompileUnit
+ | MergeCodeCompileUnit
}
}
=======================================
---
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Nemerle.Compiler.Utils.csproj
Tue Nov 10 12:44:15 2009
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Nemerle.Compiler.Utils.csproj
Wed Nov 11 12:09:20 2009
@@ -114,13 +114,7 @@
<Compile Include="Nemerle.Completion2\TraceWriter.n" />
<Compile Include="Properties\AssemblyInfo.n" />
<Compile Include="AstBrowserForm.n" />
- <Compile Include="CodeDomHelper.n" />
<Compile Include="Const.n" />
- <Compile Include="FormCodeDomGenerator.n" />
- <Compile Include="FormCodeDomParser.n" />
- <Compile Include="FormCodeInfo.n" />
- <Compile Include="NemerleCodeDomProvider.n" />
- <Compile Include="NemerleCodeParser.n" />
<Compile Include="Utils.n" />
</ItemGroup>
<ItemGroup>
@@ -304,6 +298,20 @@
<ItemGroup>
<Compile
Include="Nemerle.Completion2\Engine\BackgroundWorks\Engine-CreateCodeCompileUnit.n"
/>
</ItemGroup>
+ <ItemGroup>
+ <Compile Include="CodeDom\CodeDomHelper.n" />
+ <Compile Include="CodeDom\FormCodeDomGenerator.n" />
+ <Compile Include="CodeDom\FormCodeDomParser.n" />
+ <Compile Include="CodeDom\NemerleCodeDomProvider.n" />
+ <Compile Include="CodeDom\NemerleCodeParser.n" />
+ <Compile Include="CodeDom\NemerleCodeParserBase.n" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile
Include="Async\AsyncRequest\MergeCodeCompileUnitAsyncRequest.n" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile
Include="Nemerle.Completion2\Engine\BackgroundWorks\Engine-MergeCodeCompileUnit.n"
/>
+ </ItemGroup>
<Import Project="$(Nemerle)\Nemerle.MSBuild.targets" />
<!-- To modify your build process, add your task inside one of the
targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
=======================================
---
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Nemerle.Compiler.Utils.nproj
Tue Nov 3 07:48:08 2009
+++
/nemerle/trunk/VsIntegration/Nemerle.Compiler.Utils/Nemerle.Compiler.Utils.nproj
Wed Nov 11 12:09:20 2009
@@ -8,6 +8,7 @@
<Folder Include="AstUtils\" />
<Folder Include="Async\" />
<Folder Include="Async\AsyncRequest\" />
+ <Folder Include="CodeDom\" />
<Folder Include="CompilerMessage\" />
<Folder Include="Hints\" />
<Folder Include="Nemerle.Completion2\" />
=======================================
---
/nemerle/trunk/VsIntegration/Nemerle.VisualStudio/Project/NemerleFileNodeCodeDomProvider.cs
Tue Nov 10 12:44:15 2009
+++
/nemerle/trunk/VsIntegration/Nemerle.VisualStudio/Project/NemerleFileNodeCodeDomProvider.cs
Wed Nov 11 12:09:20 2009
@@ -15,6 +15,7 @@
using NCU = Nemerle.Compiler.Utils;

using Nemerle.VisualStudio.LanguageService;
+using System.Diagnostics;

namespace Nemerle.VisualStudio.Project
{
@@ -217,45 +218,55 @@

#region Generator implementation

- public override void GenerateCodeFromCompileUnit(CodeCompileUnit e,
TextWriter w, CodeGeneratorOptions o)
- {
- if (o == null)
- o = GetCodeGeneratorOptions();
-
- if (IsFormSubType)
- {
- string mainFilePath = PathOfMainFile();
- string designerFilePath = PathOfDesignerFile();
-
- // Find designer FileNode
- NemerleDependentFileNode designerFileNode =
- _fileNode.FindChild(designerFilePath) as NemerleDependentFileNode;
-
- if (designerFileNode == null)
- throw new ApplicationException("Can't find designer file node");
-
- // Distribute changes to Form.n and Form.designer.n files
- using (RDTFileTextMerger mainMerger = new RDTFileTextMerger(_fileNode))
- using (RDTFileTextMerger designerMerger = new
RDTFileTextMerger(designerFileNode))
- {
- //ProjectInfo.FindProject(designerFilePath).Project.CompileUnits.
- ProjectInfo projectInfo = ProjectInfo.FindProject(mainFilePath);
- if (projectInfo == null)
- throw new ApplicationException("The component is not in the
project!");
-
- _codeDomGenerator.MergeFormCodeFromCompileUnit(
- projectInfo.Project,
- mainFilePath, designerFilePath,
- e, mainMerger, designerMerger, o);
- }
- }
- else
- using (StringWriter sw = new StringWriter())
- {
- (_codeDomGenerator as ICodeGenerator).GenerateCodeFromCompileUnit(e,
sw, o);
-
- UpdateGeneratedCodeFile(sw.ToString(), PathOfMainFile());
- }
+ public override void GenerateCodeFromCompileUnit(CodeCompileUnit
codeCompileUnit, TextWriter writer, CodeGeneratorOptions options)
+ {
+ if (options == null)
+ options = GetCodeGeneratorOptions();
+
+ ProjectInfo projectInfo = ProjectInfo.FindProject(PathOfMainFile());
+
+ if (projectInfo == null)
+ throw new ApplicationException("The component is not in the
project!");
+
+ var changes =
projectInfo.Engine.MergeCodeCompileUnit(codeCompileUnit);
+
+ foreach (var item in changes)
+ Trace.WriteLine(item);
+
+ //if (IsFormSubType)
+ //{
+ // string mainFilePath = PathOfMainFile();
+ // string designerFilePath = PathOfDesignerFile();
+
+ // // Find designer FileNode
+ // NemerleDependentFileNode designerFileNode =
+ // _fileNode.FindChild(designerFilePath) as
NemerleDependentFileNode;
+
+ // if (designerFileNode == null)
+ // throw new ApplicationException("Can't find designer file
node");
+
+ // // Distribute changes to Form.n and Form.designer.n files
+ // using (RDTFileTextMerger mainMerger = new
RDTFileTextMerger(_fileNode))
+ // using (RDTFileTextMerger designerMerger = new
RDTFileTextMerger(designerFileNode))
+ // {
+ //
//ProjectInfo.FindProject(designerFilePath).Project.CompileUnits.
+ // ProjectInfo projectInfo =
ProjectInfo.FindProject(mainFilePath);
+ // if (projectInfo == null)
+ // throw new ApplicationException("The component is not in the
project!");
+
+ // _codeDomGenerator.MergeFormCodeFromCompileUnit(
+ // projectInfo.Project,
+ // mainFilePath, designerFilePath,
+ // codeCompileUnit, mainMerger, designerMerger, options);
+ // }
+ //}
+ //else
+ // using (StringWriter sw = new StringWriter())
+ // {
+ //
((ICodeGenerator)_codeDomGenerator).GenerateCodeFromCompileUnit(codeCompileUnit,
sw, options);
+
+ // UpdateGeneratedCodeFile(sw.ToString(), PathOfMainFile());
+ // }
}

private CodeGeneratorOptions GetCodeGeneratorOptions()
Reply all
Reply to author
Forward
0 new messages