public ClassDiagramRoot() { bar = new DiagramToolBar (); bar.position.x = 6; bar.position.y = 60; bar.Add (new DiagramToolElement (bar, Config.TEX_TOOL_COMPOSITE, Config.TEX_TOOL_REFERENCE, new DiagramDefaultTool ())); bar.Add (new DiagramToolElement (bar, Config.TEX_TOOL_COMPOSITE, Config.TEX_TOOL_REFERENCE, new DiagramConnectTool ())); bar.Add (new DiagramToolElement (bar, Config.TEX_TOOL_COMPOSITE, Config.TEX_TOOL_REFERENCE, new DiagramConnectTool ())); bar.Add (new DiagramToolElement (bar, Config.TEX_TOOL_COMPOSITE, Config.TEX_TOOL_REFERENCE, new DiagramConnectTool ())); DiagramNode node1 = new DiagramNode (); node1.attributes.Add (new Attribute ()); node1.attributes.Add (new Attribute ()); node1.attributes.Add (new Attribute ()); DiagramNode node2 = new DiagramNode (); DiagramNode node3 = new DiagramNode (); DiagramEdge edge1 = new DiagramEdge (); edge1.SetSource (node1); edge1.SetTarget (node2); node1.edges.Add (edge1); nodes.Add (node1); nodes.Add (node2); nodes.Add (node3); classes = new ClassNode [1]; classes [0] = new ClassNode (); diagramName = "diagram name"; types = new string[]{"int", "float", "string", "bool", "Color", "Vector2", "Vector3", "Vector4", "AnimationCurve","Rect", "Texture", "Texture2D", "Object"}; }
/// <summary> /// Creates instance of class /// </summary> /// <remarks> /// Putting null by stateComponents means work with current object state /// </remarks> internal SClass( IClassInfo objectInstance, ClassNode classNode, string[] stateComponents ) { m_object = objectInstance; m_Class = classNode; defineStateMask( stateComponents ); defineStateName(); }
private IEnumerable <BaseNode> ReadNodeElements(IEnumerable <XElement> elements, ClassNode parent, IReadOnlyDictionary <string, ClassNode> classes, Type[] typeMap, ILogger logger) { Contract.Requires(elements != null); Contract.Requires(parent != null); Contract.Requires(classes != null); Contract.Requires(typeMap != null); Contract.Requires(logger != null); foreach (var element in elements) { Type nodeType = null; if (int.TryParse(element.Attribute("Type")?.Value, out var typeVal)) { if (typeVal >= 0 && typeVal < typeMap.Length) { nodeType = typeMap[typeVal]; } } if (nodeType == null) { logger.Log(LogLevel.Error, $"Skipping node with unknown type: {element.Attribute("Type")?.Value}"); logger.Log(LogLevel.Warning, element.ToString()); continue; } var node = BaseNode.CreateInstanceFromType(nodeType, false); if (node == null) { logger.Log(LogLevel.Error, $"Could not create node of type: {nodeType}"); continue; } node.Name = element.Attribute("Name")?.Value ?? string.Empty; node.Comment = element.Attribute("Comment")?.Value ?? string.Empty; node.IsHidden = element.Attribute("bHidden")?.Value.Equals("1") ?? false; // Convert the Custom node into normal hex nodes. if (node is CustomNode customNode) { int.TryParse(element.Attribute("Size")?.Value, out var size); foreach (var paddingNode in customNode.GetEquivalentNodes(size)) { yield return(paddingNode); } continue; } // ClassInstanceNode, ClassPointerNode, ClassInstanceArrayNode, ClassPointerArrayNode if (node is BaseWrapperNode baseWrapperNode) { string reference; int arrayCount = 0; if (node is BaseClassArrayNode) // ClassInstanceArrayNode, ClassPointerArrayNode { reference = element.Element("Array")?.Attribute("Name")?.Value; if (node is ClassInstanceArrayNode) { TryGetAttributeValue(element, "Total", out arrayCount, logger); } else { TryGetAttributeValue(element, "Count", out arrayCount, logger); } } else // ClassInstanceNode, ClassPointerNode { reference = element.Attribute("Pointer")?.Value ?? element.Attribute("Instance")?.Value; } if (reference == null || !classes.ContainsKey(reference)) { logger.Log(LogLevel.Error, $"Skipping node with unknown reference: {reference}"); logger.Log(LogLevel.Warning, element.ToString()); continue; } var innerClassNode = classes[reference]; if (baseWrapperNode.ShouldPerformCycleCheckForInnerNode() && !ClassUtil.IsCyclicIfClassIsAccessibleFromParent(parent, innerClassNode, project.Classes)) { logger.Log(LogLevel.Error, $"Skipping node with cycle reference: {parent.Name}->{node.Name}"); continue; } // ClassPointerNode, ClassInstanceArrayNode and ClassPointerArrayNode need to be converted to supported nodes. if (node is BaseClassArrayNode classArrayNode) // ClassInstanceArrayNode, ClassPointerArrayNode { node = classArrayNode.GetEquivalentNode(arrayCount, innerClassNode); } else if (node is ClassPointerNode classPointerNode) // ClassPointerNode { node = classPointerNode.GetEquivalentNode(innerClassNode); } else // ClassInstanceNode, ClassPointerNode { baseWrapperNode.ChangeInnerNode(innerClassNode); } } switch (node) { case VirtualMethodTableNode vtableNode: element .Elements("Function") .Select(e => new VirtualMethodNode { Name = e.Attribute("Name")?.Value ?? string.Empty, Comment = e.Attribute("Comment")?.Value ?? string.Empty, IsHidden = e.Attribute("bHidden")?.Value.Equals("1") ?? false }) .ForEach(vtableNode.AddNode); break; case BaseTextNode textNode: { TryGetAttributeValue(element, "Size", out var length, logger); textNode.Length = textNode is Utf16TextNode ? length / 2 : length; break; } case BitFieldNode bitFieldNode: { TryGetAttributeValue(element, "Size", out var bits, logger); bitFieldNode.Bits = bits * 8; break; } } yield return(node); } }
/// <summary> /// Creates the partial file for mono. /// </summary> /// <param name="lines">The lines.</param> /// <param name="rootNode">The root node.</param> /// <param name="usings">The usings.</param> /// <param name="namespaces">The namespaces.</param> /// <param name="filename">The filename.</param> private static void CreatePartialFileForMono(string[] lines, ClassNode rootNode, List<int> usings, List<int> namespaces, string filename) { List<string> output = new List<string>(); int headerEnd = CopyHeaderComment(lines, output); // Write "using" lines foreach (int i in usings) { string line = lines[i]; if (line.Contains("using")) output.Add(line.Trim(trimchars2) + ";"); else if (line.Contains("#")) output.Add(line.Trim(trimchars)); else if (string.IsNullOrEmpty(line)) output.Add(string.Empty); } output.Add(string.Empty); // Write "namespace" lines if (namespaces.Count != 1) return; // problem, more than one namespace output.Add(lines[namespaces[0]].Trim(trimchars3)); output.Add("{"); foreach (ClassNode child in rootNode.Children) WriteClassForMono(lines, child, output, 0); output.Add("}"); RemoveExtraBlankLines(output); using (TextWriter writer = new StreamWriter(filename)) { foreach (string line in output) if (line != null) writer.WriteLine(line); writer.Close(); } }
/// <summary> /// Processes the specified root. /// </summary> /// <param name="file">The filename.</param> /// <param name="root">The root.</param> internal static void Process(string file, string root) { Console.WriteLine(file); if (!File.Exists(Path.Combine(root, file))) { return; } // Load file into string array string[] lines = File.ReadAllLines(Path.Combine(root, file)); ClassNode rootNode = new ClassNode(); List <ClassNode> classNodes = new List <ClassNode>(); List <MethodNode> methodNodes = new List <MethodNode>(); List <int> namespaces = new List <int>(); List <int> usings = new List <int>(); ClassNode currentNode = rootNode; bool incomment = false; // Analyze File for (int linenbr = 0; linenbr < lines.Length; linenbr++) { if (lines[linenbr].StartsWith("#if MOSAPROJECT")) { return; // abort... already done } string trim = GetLine(lines, linenbr, ref incomment).Replace('\t', ' '); if (incomment) { continue; } trim = StripWithInDoubleQuotes(trim); int skip = 0; if (string.IsNullOrEmpty(trim)) { continue; } else if (trim.StartsWith("#")) { continue; } else if ((trim.StartsWith("extern ") || (trim.Contains(" extern "))) && !trim.Contains(" alias ")) { int start = GetPreviousBlockEnd(lines, linenbr); skip = GetNumberOfMethodDeclarationLines(lines, linenbr, false); MethodNode node = new MethodNode(currentNode, start, linenbr + skip, linenbr); methodNodes.Add(node); currentNode.Methods.Add(node); } else if (trim.StartsWith("using ") && trim.Contains(";")) { usings.Add(linenbr); } else if (trim.StartsWith("namespace ")) { namespaces.Add(linenbr); } else if (trim.Contains(" class ") || (trim.StartsWith("class ")) || trim.Contains(" struct ") || (trim.StartsWith("struct "))) { // Search backwards for the start of the class definition (might not be on the same line as class keyword) int start = GetPreviousBlockEnd(lines, linenbr); string className = GetClassName(lines, start, linenbr); // Attempt to handle #else class definitions if (className == currentNode.Name) { currentNode.OtherDeclare.Add(linenbr); continue; } // Find the last line of the class int end = GetEndOfScope(lines, linenbr); // Go up to parent while (linenbr > currentNode.End) { currentNode = currentNode.Parent; } // Child ClassNode child = new ClassNode(currentNode, start, end, linenbr); classNodes.Add(child); currentNode.Children.Add(child); currentNode = child; child.Name = className; } linenbr = linenbr + skip; // Go up to parent while (linenbr >= currentNode.End) { currentNode = currentNode.Parent; } } // Mark all partial nodes foreach (ClassNode node in classNodes) { if (node.Methods.Count != 0) { node.Partial = true; ClassNode upNode = node; do { upNode.Parent.Partial = true; upNode = upNode.Parent; } while (upNode != upNode.Parent); } } // Create partial file if (methodNodes.Count != 0) { string partialFile = Path.Combine(root, file.Insert(file.Length - 2, "Partial.")); //Console.WriteLine(partialFile); CreatePartialFile(lines, rootNode, usings, namespaces, partialFile); } // Modify source file CreateModifiedFile(lines, classNodes, methodNodes, Path.Combine(root, file)); }
void drawWindow(int id) { ClassNode clazz = (ClassNode)cuurentClassData.classes.GetValue (id); Rect boxRect = new Rect (0, 16, clazz.rect.width, clazz.rect.height - 16); GUI.Box (boxRect, ""); if ((Event.current.button == 0) && (Event.current.type == EventType.MouseDown)) { focusWidowId = id; if (mode != mode_draw) { if (refModeClass != null && refModeClass != clazz) { refModeTargetClass = clazz; } } } string iconPath = clazz.iconPath; Texture2D texIcon = null; Rect iconRect = new Rect (6, 22, 32, 32); if (iconPath != null) { texIcon = loadTexture (iconPath); } if (texIcon == null) { texIcon = texNoImage; } GUIStyle iconStyle = new GUIStyle (GUIStyle.none); iconStyle.normal.background = texIcon; if (GUI.Button (iconRect, "", iconStyle)) { string path = EditorUtility.OpenFilePanel ("Select Icon", "Assets", ""); if (path != null) { if (Application.dataPath.Length < path.Length) { path = path.Substring (Application.dataPath.Length); char[] chTrims = {'/', '\\'}; path = path.TrimStart (chTrims); clazz.iconPath = path; } } } Rect textRect = new Rect (iconRect.x + iconRect.width + 10, iconRect.y + 8, clazz.rect.width - (iconRect.x + iconRect.width + 8) - 20, 16); if (id == focusWidowId) { clazz.name = GUI.TextField (textRect, clazz.name); } else { GUI.Label (textRect, clazz.name); } float bx = clazz.rect.width - 18; if (id == focusWidowId) { GUIStyle style = new GUIStyle (GUIStyle.none); style.normal.background = texSuper; Rect btnRect = new Rect (0, 0, 16, 16); if (GUI.Button (btnRect, "", style)) { if (clazz.superClassName != null && 0 < clazz.superClassName.Length) { clazz.superClassName = null; } else { changeModeRef (clazz, mode_ref_gen); } } style.normal.background = texCompositeTool; btnRect.x += 18; if (GUI.Button (btnRect, "", style)) { changeModeRef (clazz, mode_ref_com); } style.normal.background = texReferenceTool; btnRect.x += 18; if (GUI.Button (btnRect, "", style)) { changeModeRef (clazz, mode_ref_ref); } style.normal.background = texAdd; btnRect.x += 18; if (GUI.Button (btnRect, "", style)) { clazz.attributes.Add (new Attribute ()); } style.normal.background = texRemove; btnRect.x = bx; btnRect.y = 0; if (GUI.Button (btnRect, "", style)) { System.Collections.Generic.List<ClassNode> classList = new System.Collections.Generic.List<ClassNode> (cuurentClassData.classes); classList.Remove (clazz); cuurentClassData.classes = classList.ToArray (); } } for (int index = 0; index < clazz.attributes.Count; index++) { Attribute attr = (Attribute)clazz.attributes[index]; float nwidth = 50; float twidth = 90; float y = 60 + 18 * index; Rect irect = new Rect (12, y, 16, 16); Rect nrect = new Rect (irect.x + irect.width + 4, y, nwidth, 16); Rect crect = new Rect (nrect.x + nwidth, y, 8, 16); Rect trect = new Rect (crect.x + crect.width - 10, y, twidth, 16); texIcon = null; string attrIconPath = attr.iconPath; if (attrIconPath != null) { texIcon = loadTexture (attrIconPath); } if (texIcon == null) { texIcon = texNoImage16; } GUIStyle attrIconStyle = new GUIStyle (GUIStyle.none); attrIconStyle.normal.background = texIcon; if (GUI.Button (irect, "", attrIconStyle)) { string path = EditorUtility.OpenFilePanel ("Select Icon", "Assets", ""); if (path != null) { if (Application.dataPath.Length < path.Length) { path = path.Substring (Application.dataPath.Length); char[] chTrims = {'/', '\\'}; path = path.TrimStart (chTrims); attr.iconPath = path; } } } if (id == focusWidowId) { attr.name = GUI.TextField (nrect, attr.name); GUI.Label (crect, ":"); attr.type = DrawTypeField (trect, attr.type); } else { GUI.Label (nrect, attr.name); GUI.Label (crect, ":"); DrawTypeField (trect, attr.type); //GUI.Label (trect, attr.type); } if (id == focusWidowId) { GUIStyle style = new GUIStyle (GUIStyle.none); style.normal.background = texRemoveMini; if (GUI.Button (new Rect (trect.x + trect.width - 4, y, 13, 16), "", style)) { clazz.attributes.Remove (attr); } } } int space = 12; if (0 < clazz.attributes.Count) { space = 20; } if (clazz.rect.height - boxRect.y - space < clazz.attributes.Count * 18 + iconRect.height) { clazz.rect.height = boxRect.y + clazz.attributes.Count * 18 + iconRect.height + space; } else if (0 < (clazz.rect.height - boxRect.y - space) - (clazz.attributes.Count * 18 + iconRect.height)) { clazz.rect.height = clazz.attributes.Count * 18 + iconRect.height + boxRect.y + space; } GUI.DragWindow (); }
/// <summary> /// Initializes a new instance of the <see cref="ClassNode"/> class. /// </summary> public ClassNode() { Parent = this; // trick! Start = int.MinValue; End = int.MaxValue; }
public List<MethodMirror> GetOverloads(string methodName) { List<MethodMirror> methods = new List<MethodMirror>(); string name = string.Empty; if(classNode == null) { Validity.Assert(staticCore != null); ProtoCore.DSASM.ClassTable classTable = staticCore.ClassTable; int ci = classTable.IndexOf(ClassName); if (ci != ProtoCore.DSASM.Constants.kInvalidIndex) { classNode = classTable.ClassNodes[ci]; } } ProcedureTable procedureTable = classNode.vtable; List<ProcedureNode> procList = procedureTable.procList; foreach (ProcedureNode pNode in procList) { name = pNode.name; if (name == methodName) { methods.Add(new MethodMirror(pNode)); } } return methods; }
// Constructor public ClassTree(IEnumerable<BplClass> classes) { Roots = new List<ClassNode>(); foreach (var bplClass in classes.Where(c => c.BaseClass == null).OrderBy(c => c.Name)) { var classNode = new ClassNode(bplClass); classNode.CreateChildren(bplClass.DerivedClasses); Roots.Add(classNode); } }
// If the type is an array, it returns a list of unique types in the array // corresponding to one assembly and a list of assemblies if the types belong to more than one assembly private Dictionary <string, List <string> > GetType(StackValue sv) { Dictionary <string, List <string> > asmType = new Dictionary <string, List <string> >(); if (sv.IsPointer) { ClassNode classNode = core.ClassTable.ClassNodes[sv.metaData.type]; List <string> types = new List <string>(); types.Add(classNode.name); asmType.Add(classNode.ExternLib, types); return(asmType); } else { List <string> type = new List <string>(); switch (sv.optype) { case AddressType.ArrayPointer: { //List<string> types = GetArrayTypes(sv); //return "array"; //return GetTypesHelper(types); asmType = GetArrayTypes(sv); break; } case AddressType.Int: //return "int"; type.Add("int"); asmType.Add("", type); break; case AddressType.Double: //return "double"; type.Add("double"); asmType.Add("", type); break; case AddressType.Null: //return "null"; type.Add("null"); asmType.Add("", type); break; case AddressType.Boolean: //return "bool"; type.Add("bool"); asmType.Add("", type); break; case AddressType.String: //return "string"; type.Add("string"); asmType.Add("", type); break; case AddressType.Char: //return "char"; type.Add("char"); asmType.Add("", type); break; case AddressType.FunctionPointer: //return "function pointer"; type.Add("function pointer"); asmType.Add("", type); break; default: break; } return(asmType); } }
// classScope is a global context, it tells we are in which class's scope // functionScope is telling us which function we are in. // // 1. Try to find if the target is a member function's local variable // classScope != kInvalidIndex && functionScope != kInvalidIndex; // // 2. Try to find if the target is a member variable // 2.1 In a member functions classScope != kInvalidIndex && functionScope != kInvalidIndex. // Returns member in derived class, or non-private member in base classes // // 2.2 In a global functions classScope == kInvalidIndex && functionScope != kInvalidIndex. // Returns public member in derived class, or public member in base classes // // 2.3 Otherwise, classScope == kInvalidIndex && functionScope == kInvalidIndex // Return public member in derived class, or public member in base classes public static int GetSymbolIndex(ClassNode classNode, string name, int classScope, int functionScope, int blockId, List <CodeBlock> codeblockList, out bool hasThisSymbol, out ProtoCore.DSASM.AddressType addressType) { hasThisSymbol = false; addressType = ProtoCore.DSASM.AddressType.Invalid; if (classNode.Symbols == null) { return(ProtoCore.DSASM.Constants.kInvalidIndex); } IEnumerable <SymbolNode> allSymbols = classNode.Symbols.GetNodeForName(name); if (allSymbols == null) { return(ProtoCore.DSASM.Constants.kInvalidIndex); } int myself = classNode.TypeSystem.classTable.IndexOf(classNode.Name); bool isInMemberFunctionContext = (classScope == myself) && (functionScope != ProtoCore.DSASM.Constants.kInvalidIndex); bool isInStaticFunction = isInMemberFunctionContext && classNode.ProcTable.Procedures.Count > functionScope && classNode.ProcTable.Procedures[functionScope].IsStatic; // Try for member function variables var blocks = GetAncestorBlockIdsOfBlock(blockId, codeblockList); blocks.Insert(0, blockId); Dictionary <int, SymbolNode> symbolOfBlockScope = new Dictionary <int, SymbolNode>(); foreach (var memvar in allSymbols) { if ((isInMemberFunctionContext) && (memvar.functionIndex == functionScope)) { symbolOfBlockScope[memvar.codeBlockId] = memvar; } } if (symbolOfBlockScope.Count > 0) { foreach (var blockid in blocks) { if (symbolOfBlockScope.ContainsKey(blockid)) { hasThisSymbol = true; addressType = AddressType.VarIndex; return(symbolOfBlockScope[blockid].symbolTableIndex); } } } // Try for member variables. var candidates = new List <SymbolNode>(); foreach (var memvar in allSymbols) { if (memvar.functionIndex == ProtoCore.DSASM.Constants.kGlobalScope) { candidates.Add(memvar); } } // Sort candidates descending based on their class scopes so that // we can search member variable in reverse order of hierarchy tree. candidates.Sort((lhs, rhs) => rhs.classScope.CompareTo(lhs.classScope)); hasThisSymbol = candidates.Count > 0; foreach (var symbol in candidates) { bool isAccessible = false; if (isInMemberFunctionContext) { isAccessible = (symbol.classScope == myself) || (symbol.access != ProtoCore.CompilerDefinitions.AccessModifier.Private); if (isInStaticFunction) { isAccessible = isAccessible && symbol.isStatic; } } else { isAccessible = symbol.access == ProtoCore.CompilerDefinitions.AccessModifier.Public; } if (isAccessible) { addressType = symbol.isStatic ? AddressType.StaticMemVarIndex : AddressType.MemVarIndex; return(symbol.symbolTableIndex); } } return(Constants.kInvalidIndex); }
public string GetClassTrace(StackValue val, Heap heap, int langblock, bool forPrint) { if (!formatParams.ContinueOutputTrace()) { return("..."); } RuntimeMemory rmem = MirrorTarget.rmem; Executable exe = MirrorTarget.exe; ClassTable classTable = MirrorTarget.RuntimeCore.DSExecutable.classTable; int classtype = val.metaData.type; if (classtype < 0 || (classtype >= classTable.ClassNodes.Count)) { formatParams.RestoreOutputTraceDepth(); return(string.Empty); } ClassNode classnode = classTable.ClassNodes[classtype]; if (classnode.IsImportedClass) { var helper = DLLFFIHandler.GetModuleHelper(FFILanguage.CSharp); var marshaller = helper.GetMarshaler(runtimeCore); var strRep = marshaller.GetStringValue(val); formatParams.RestoreOutputTraceDepth(); return(strRep); } else { var obj = heap.ToHeapObject <DSObject>(val); StringBuilder classtrace = new StringBuilder(); if (classnode.Symbols != null && classnode.Symbols.symbolList.Count > 0) { if (!classnode.Name.Equals("Function")) { bool firstPropertyDisplayed = false; for (int n = 0; n < obj.Count; ++n) { SymbolNode symbol = classnode.Symbols.symbolList[n]; string propName = symbol.name; if (firstPropertyDisplayed) { classtrace.Append(", "); } string propValue = ""; if (symbol.isStatic) { var staticSymbol = exe.runtimeSymbols[langblock].symbolList[symbol.symbolTableIndex]; StackValue staticProp = rmem.GetSymbolValue(staticSymbol); propValue = GetStringValue(staticProp, heap, langblock, forPrint); } else { propValue = GetStringValue(obj.GetValueFromIndex(symbol.index, runtimeCore), heap, langblock, forPrint); } classtrace.Append(string.Format("{0} = {1}", propName, propValue)); firstPropertyDisplayed = true; } } } else { var stringValues = obj.Values.Select(x => GetStringValue(x, heap, langblock, forPrint)) .ToList(); for (int n = 0; n < stringValues.Count(); ++n) { if (0 != n) { classtrace.Append(", "); } classtrace.Append(stringValues[n]); } } formatParams.RestoreOutputTraceDepth(); if (classtype >= (int)ProtoCore.PrimitiveType.MaxPrimitive) { if (forPrint) { return(string.Format("{0}{{{1}}}", classnode.Name, classtrace.ToString())); } else { string tempstr = (string.Format("{0}({1})", classnode.Name, classtrace.ToString())); return(tempstr); } } return(classtrace.ToString()); } }
private int GetSymbolIndex(string name, out int ci, ref int block, out SymbolNode symbol) { RuntimeMemory rmem = MirrorTarget.rmem; ProtoCore.DSASM.Executable exe = runtimeCore.DSExecutable; int functionIndex = Constants.kGlobalScope; ci = Constants.kInvalidIndex; int functionBlock = Constants.kGlobalScope; if (runtimeCore.DebugProps.DebugStackFrameContains(DebugProperties.StackFrameFlagOptions.FepRun)) { ci = runtimeCore.watchClassScope = rmem.CurrentStackFrame.ClassScope; functionIndex = rmem.CurrentStackFrame.FunctionScope; functionBlock = rmem.CurrentStackFrame.FunctionBlock; } // TODO Jun: 'block' is incremented only if there was no other block provided by the programmer // This is only to address NUnit issues when retrieving a global variable // Some predefined functions are hard coded in the AST so isSingleAssocBlock will never be true //if (exe.isSingleAssocBlock) //{ // ++block; //} int index = -1; if (ci != Constants.kInvalidIndex) { ClassNode classnode = runtimeCore.DSExecutable.classTable.ClassNodes[ci]; if (functionIndex != ProtoCore.DSASM.Constants.kInvalidIndex && functionBlock != runtimeCore.RunningBlock) { index = exe.runtimeSymbols[block].IndexOf(name, Constants.kGlobalScope, Constants.kGlobalScope); } if (index == Constants.kInvalidIndex) { index = classnode.Symbols.IndexOfClass(name, ci, functionIndex); } if (index != Constants.kInvalidIndex) { symbol = classnode.Symbols.symbolList[index]; return(index); } } else { bool found = runtimeCore.DSExecutable.CompleteCodeBlockDict.TryGetValue(block, out CodeBlock searchBlock); Validity.Assert(found, $"Could not find code block with codeBlockId {block}"); // To detal with the case that a language block defined in a function // // def foo() // { // [Imperative] // { // a; // } // } if (functionIndex != ProtoCore.DSASM.Constants.kInvalidIndex) { if (searchBlock.IsMyAncestorBlock(functionBlock)) { while (searchBlock.codeBlockId != functionBlock) { index = exe.runtimeSymbols[searchBlock.codeBlockId].IndexOf(name, ci, ProtoCore.DSASM.Constants.kInvalidIndex); if (index == ProtoCore.DSASM.Constants.kInvalidIndex) { searchBlock = searchBlock.parent; } else { break; } } } if (index == ProtoCore.DSASM.Constants.kInvalidIndex) { index = exe.runtimeSymbols[searchBlock.codeBlockId].IndexOf(name, ci, functionIndex); } if (index == ProtoCore.DSASM.Constants.kInvalidIndex) { index = exe.runtimeSymbols[searchBlock.codeBlockId].IndexOf(name, ci, ProtoCore.DSASM.Constants.kInvalidIndex); } } else { index = exe.runtimeSymbols[searchBlock.codeBlockId].IndexOf(name, ci, ProtoCore.DSASM.Constants.kInvalidIndex); } if (index == ProtoCore.DSASM.Constants.kInvalidIndex) { searchBlock = searchBlock.parent; while (searchBlock != null) { block = searchBlock.codeBlockId; index = exe.runtimeSymbols[searchBlock.codeBlockId].IndexOf(name, ci, ProtoCore.DSASM.Constants.kInvalidIndex); if (index != ProtoCore.DSASM.Constants.kInvalidIndex) { break; } else { searchBlock = searchBlock.parent; } } } if (index != ProtoCore.DSASM.Constants.kInvalidIndex) { block = searchBlock.codeBlockId; symbol = exe.runtimeSymbols[searchBlock.codeBlockId].symbolList[index]; return(index); } } throw new NameNotFoundException { Name = name }; //throw new NotImplementedException("{F5ACC95F-AEC9-486D-BC82-FF2CB26E7E6A}"); //@TODO(Luke): Replace this with a symbol lookup exception }
public override void VisitNestedClass(ClassNode node) { visitor.VisitNestedClass((INestedClassWithSymbols)node); }
public abstract Word Visit(ClassNode classNode);
public void Load(string filePath, ILogger logger) { var document = XDocument.Load(filePath); if (document.Root == null) { return; } Type[] typeMap = null; if (document.Root.FirstNode is XComment versionComment) { switch (versionComment.Value.Substring(0, 12).ToLower()) { case "reclass 2011": case "reclass 2013": typeMap = typeMap2013; break; case "reclass 2015": case "reclass 2016": typeMap = typeMap2016; break; default: logger.Log(LogLevel.Warning, $"Unknown file version: {versionComment.Value}"); logger.Log(LogLevel.Warning, "Defaulting to ReClass 2016."); typeMap = typeMap2016; break; } } var classes = new List <Tuple <XElement, ClassNode> >(); foreach (var element in document.Root .Elements("Class") .DistinctBy(e => e.Attribute("Name")?.Value)) { var node = new ClassNode(false) { Name = element.Attribute("Name")?.Value ?? string.Empty, AddressFormula = TransformAddressString(element.Attribute("strOffset")?.Value ?? string.Empty) }; project.AddClass(node); classes.Add(Tuple.Create(element, node)); } var classMap = classes.ToDictionary(t => t.Item2.Name, t => t.Item2); foreach (var t in classes) { ReadNodeElements( t.Item1.Elements("Node"), t.Item2, classMap, typeMap, logger ).ForEach(t.Item2.AddNode); } }
/// <summary> /// Returns the base class hierarchy for the given class /// </summary> /// <returns></returns> public List<ClassMirror> GetClassHierarchy() { List<ClassMirror> baseClasses = new List<ClassMirror>(); Validity.Assert(!string.IsNullOrEmpty(ClassName)); Validity.Assert(staticCore != null); int ci; if (classNode == null) { ProtoCore.DSASM.ClassTable classTable = staticCore.ClassTable; ci = classTable.IndexOf(ClassName); if (ci != ProtoCore.DSASM.Constants.kInvalidIndex) { classNode = classTable.ClassNodes[ci]; } } ClassNode cNode = classNode; while (cNode.baseList.Count > 0) { ci = cNode.baseList[0]; Validity.Assert(ci != ProtoCore.DSASM.Constants.kInvalidIndex); baseClasses.Add(new ClassMirror(staticCore, staticCore.ClassTable.ClassNodes[ci], this.libraryMirror)); cNode = staticCore.ClassTable.ClassNodes[ci]; } return baseClasses; }
public static void SerializeNodesToStream(Stream output, IEnumerable <BaseNode> nodes, ILogger logger) { Contract.Requires(output != null); Contract.Requires(nodes != null); Contract.Requires(Contract.ForAll(nodes, n => n != null)); Contract.Requires(logger != null); using var project = new ReClassNetProject(); void RecursiveAddClasses(BaseNode node) { ClassNode classNode = null; switch (node) { case ClassNode c1: classNode = c1; break; case BaseWrapperNode wrapperNode when wrapperNode.ResolveMostInnerNode() is ClassNode c2: classNode = c2; break; } if (classNode == null || project.ContainsClass(classNode.Uuid)) { return; } project.AddClass(classNode); foreach (var wrapperNodeChild in classNode.Nodes.OfType <BaseWrapperNode>()) { RecursiveAddClasses(wrapperNodeChild); } } var serialisationClass = new ClassNode(false) { Name = SerializationClassName }; var needsSerialisationClass = true; foreach (var node in nodes) { RecursiveAddClasses(node); if (!(node is ClassNode)) { if (needsSerialisationClass) { needsSerialisationClass = false; project.AddClass(serialisationClass); } serialisationClass.AddNode(node); } } var file = new ReClassNetFile(project); file.Save(output, logger); }
/// <summary> /// Returns the list of constructors defined for the given class /// </summary> /// <returns></returns> public List<MethodMirror> GetConstructors() { List<MethodMirror> constructors = new List<MethodMirror>(); if(classNode == null) { Validity.Assert(staticCore != null); ProtoCore.DSASM.ClassTable classTable = staticCore.ClassTable; int ci = classTable.IndexOf(ClassName); if (ci != ProtoCore.DSASM.Constants.kInvalidIndex) { classNode = classTable.ClassNodes[ci]; } } ProcedureTable procedureTable = classNode.vtable; List<ProcedureNode> procList = procedureTable.procList; foreach (ProcedureNode pNode in procList) { if (pNode.isConstructor == true) constructors.Add(new MethodMirror(pNode)); } return constructors; }
void Awake() { PlayerMeta player = BaseSaver.GetPlayer(); List <string> mages = new List <string>(new string[] { "HumanBaseMage", "EgyptBaseMage", "CthulhuBaseMage" }); List <string> scouts = new List <string>(new string[] { "HumanBaseScout", "EgyptBaseScout", "CthulhuBaseScout" }); int rM = 0; int rSc = 0; int rSo = 0; foreach (Unit unt in player.characters) { ClassNode clss = unt.GetCurrentClass(); while (clss.GetParent() != null) { clss = clss.GetParent(); } if (mages.Contains(clss.GetType().ToString())) { rM++; } else if (scouts.Contains(clss.GetType().ToString())) { rSc++; } else { rSo++; } } //rosterTxt.text = "Current Army: \nMage: " + rM.ToString() + "\nScout: " + rSc.ToString() + "\nSoldier: " + rSo.ToString(); armyPnl.transform.GetChild(0).GetChild(0).GetComponent <TextMeshProUGUI>().text = rM.ToString(); armyPnl.transform.GetChild(1).GetChild(0).GetComponent <TextMeshProUGUI>().text = rSc.ToString(); armyPnl.transform.GetChild(2).GetChild(0).GetComponent <TextMeshProUGUI>().text = rSo.ToString(); switch (player.faction) { case Unit.FactionType.Cthulhu: armyPnl.transform.GetChild(0).GetChild(2).GetComponent <Image>().sprite = glossary.GetComponent <Glossary>().cthulhuMage.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; armyPnl.transform.GetChild(1).GetChild(2).GetComponent <Image>().sprite = glossary.GetComponent <Glossary>().cthulhuScout.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; armyPnl.transform.GetChild(2).GetChild(2).GetComponent <Image>().sprite = glossary.GetComponent <Glossary>().cthulhuSoldier.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; break; case Unit.FactionType.Human: armyPnl.transform.GetChild(0).GetChild(2).GetComponent <Image>().sprite = glossary.GetComponent <Glossary>().humanMage.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; armyPnl.transform.GetChild(1).GetChild(2).GetComponent <Image>().sprite = glossary.GetComponent <Glossary>().humanScout.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; armyPnl.transform.GetChild(2).GetChild(2).GetComponent <Image>().sprite = glossary.GetComponent <Glossary>().humanSoldier.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; break; case Unit.FactionType.Egypt: armyPnl.transform.GetChild(0).GetChild(2).GetComponent <Image>().sprite = glossary.GetComponent <Glossary>().egyptMage.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; armyPnl.transform.GetChild(1).GetChild(2).GetComponent <Image>().sprite = glossary.GetComponent <Glossary>().egyptScout.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; armyPnl.transform.GetChild(2).GetChild(2).GetComponent <Image>().sprite = glossary.GetComponent <Glossary>().egyptSoldier.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; break; } panels = new GameObject[panelGroup.transform.childCount]; for (int i = 0; i < panelGroup.transform.childCount; i++) { panels[i] = panelGroup.transform.GetChild(i).gameObject; UnitProxy unt = ClassNode.ComputeClassBaseUnit(player.faction, (Unit.UnitType)i, glossary.GetComponent <Glossary>()); panels[i].transform.GetChild(1).GetComponent <Image>().sprite = unt.transform.GetChild(0).GetComponent <SpriteRenderer>().sprite; } selectableUnits = new Unit[] { Unit.BuildInitial(player.faction, Unit.UnitType.Mage, BoardProxy.PLAYER_TEAM), Unit.BuildInitial(player.faction, Unit.UnitType.Scout, BoardProxy.PLAYER_TEAM), Unit.BuildInitial(player.faction, Unit.UnitType.Soldier, BoardProxy.PLAYER_TEAM), }; for (int i = 0; i < selectableUnits.Length && i < panels.Length; i++) { RefreshPanel(panels[i], selectableUnits[i]); } selected = null; contBtn.gameObject.SetActive(false); ResetParticles(); GetComponent <Image>().color = HelperScripts.GetColorByFaction(player.faction); }
/// <summary> /// Creates the partial file for MOSA. /// </summary> /// <param name="lines">The lines.</param> /// <param name="rootNode">The root node.</param> /// <param name="usings">The usings.</param> /// <param name="namespaces">The namespaces.</param> /// <param name="filename">The filename.</param> private static void CreatePartialFileForMosa(string[] lines, ClassNode rootNode, List<int> usings, List<int> namespaces, string filename) { List<string> output = new List<string>(); // Write "using" lines foreach (int i in usings) output.Add(lines[i].Trim(trimchars2) + ";"); output.Add(string.Empty); // Write "namespace" lines if (namespaces.Count != 1) return; // problem, more than one namespace output.Add(lines[namespaces[0]].Trim(trimchars3)); output.Add("{"); foreach (ClassNode child in rootNode.Children) WriteClassForMosa(lines, child, output, 0); output.Add("}"); using (TextWriter writer = new StreamWriter(filename)) { foreach (string line in output) if (line != null) writer.WriteLine(line); writer.Close(); } }
public CentralServerNode load(SystemInfo systemInfo) { CentralServerNode centralServerNode = csnFactory.CreateExport().Value; centralServerNode.Properties = CentralServerProperties.From(systemInfo.CentralServer); DatabasesFolderNode databasesFolderNode = dfnFactory.CreateExport().Value; foreach (var database in systemInfo.Databases.OrderBy(db => db.Name)) { DatabaseNode databaseNode = dfFactory.CreateExport().Value; databaseNode.DatabaseName = database.Name; if (database.Classes != null) { foreach (var @class in database.Classes.OrderBy(c => c.Name)) { var cn = new ClassNode(@class.Name, @class.Interface, @class.ParentClasses); foreach (var f in @class.Fields.OrderBy(f => f.Name)) { var fn = new FieldNode(f.Name, f.Type); cn.Children.Add(fn); } foreach (var m in @class.Methods.OrderBy(m => m)) { var mn = new MethodNode(m); cn.Children.Add(mn); } databaseNode.Children.Add(cn); } } databasesFolderNode.Children.Add(databaseNode); } centralServerNode.Children.Add(databasesFolderNode); DataServersFolderNode dataServersFolderNode = new DataServersFolderNode(); foreach (var dataServer in systemInfo.DataServer) { DataServerNode dataServerNode = dsnFactory.CreateExport().Value; dataServerNode.Properties = DataServerProperties.From(dataServer); //DatabasesFolderNode databasesFolderNode2 = dfnFactory.CreateExport().Value; //connectionService.DatabasesChanged += delegate(object s, EventArgs e) //{ // databasesFolderNode2.Children.Clear(); // foreach (string database in connectionService.Databases) // { // DatabaseNode databaseNode = new DatabaseNode(database); // databasesFolderNode2.Children.Add(databaseNode); // } //}; //foreach (string database in databasesList) //{ // DatabaseNode databaseNode = new DatabaseNode(database); // databasesFolderNode2.Children.Add(databaseNode); //} //dataServerNode.Children.Add(databasesFolderNode2); dataServersFolderNode.Children.Add(dataServerNode); } centralServerNode.Children.Add(dataServersFolderNode); return(centralServerNode); }
private void changeModeDraw() { wantsMouseMove = false; //Debug.Log ("changeModeDraw" + " wantsMouseMove=" + wantsMouseMove); refModeClass = null; refModeTargetClass = null; mode = mode_draw; }
public void Load(Stream input, ILogger logger) { Contract.Requires(input != null); Contract.Requires(logger != null); using (var archive = new ZipArchive(input, ZipArchiveMode.Read)) { var dataEntry = archive.GetEntry(DataFileName); if (dataEntry == null) { throw new FormatException(); } using (var entryStream = dataEntry.Open()) { var document = XDocument.Load(entryStream); if (document.Root?.Element(XmlClassesElement) == null) { throw new FormatException("The data has not the correct format."); } uint.TryParse(document.Root.Attribute(XmlVersionAttribute)?.Value, out var fileVersion); if ((fileVersion & FileVersionCriticalMask) > (FileVersion & FileVersionCriticalMask)) { throw new FormatException($"The file version is unsupported. A newer {Constants.ApplicationName} version is required to read it."); } var platform = document.Root.Attribute(XmlPlatformAttribute)?.Value; if (platform != Constants.Platform) { logger.Log(LogLevel.Warning, $"The platform of the file ({platform}) doesn't match the program platform ({Constants.Platform})."); } var customDataElement = document.Root.Element(XmlCustomDataElement); if (customDataElement != null) { project.CustomData.Deserialize(customDataElement); } var typeMappingElement = document.Root.Element(XmlTypeMappingElement); if (typeMappingElement != null) { project.TypeMapping.Deserialize(typeMappingElement); } var enumsElement = document.Root.Element(XmlEnumsElement); if (enumsElement != null) { foreach (var enumElement in enumsElement.Elements(XmlEnumElement)) { var name = enumElement.Attribute(XmlNameAttribute)?.Value ?? string.Empty; var useFlagsMode = (bool?)enumElement.Attribute(XmlFlagsAttribute) ?? false; var size = enumElement.Attribute(XmlSizeAttribute).GetEnumValue <EnumMetaData.UnderlyingTypeSize>(); var values = new Dictionary <string, long>(); foreach (var itemElement in enumElement.Elements(XmlItemElement)) { var itemName = itemElement.Attribute(XmlNameAttribute)?.Value ?? string.Empty; var itemValue = (long?)itemElement.Attribute(XmlValueAttribute) ?? 0L; values.Add(itemName, itemValue); } var @enum = new EnumMetaData { Name = name }; @enum.SetData(useFlagsMode, size, values); project.AddEnum(@enum); } } var classes = new List <Tuple <XElement, ClassNode> >(); var classesElement = document.Root.Element(XmlClassesElement); if (classesElement != null) { foreach (var element in classesElement .Elements(XmlClassElement) .DistinctBy(e => e.Attribute(XmlUuidAttribute)?.Value)) { var node = new ClassNode(false) { Uuid = NodeUuid.FromBase64String(element.Attribute(XmlUuidAttribute)?.Value, true), Name = element.Attribute(XmlNameAttribute)?.Value ?? string.Empty, Comment = element.Attribute(XmlCommentAttribute)?.Value ?? string.Empty, AddressFormula = element.Attribute(XmlAddressAttribute)?.Value ?? string.Empty }; if (!project.ContainsClass(node.Uuid)) { project.AddClass(node); classes.Add(Tuple.Create(element, node)); } } } foreach (var t in classes) { var nodes = t.Item1.Elements(XmlNodeElement) .Select(e => CreateNodeFromElement(e, t.Item2, logger)) .Where(n => n != null); foreach (var node in nodes) { t.Item2.AddNode(node); } } } } }
public void Accept(ClassNode node) { node.VisitChildren(this); }
private IEnumerable <BaseNode> ReadNodeElements(IEnumerable <XElement> elements, ClassNode parent, IReadOnlyDictionary <string, ClassNode> classes, ILogger logger) { Contract.Requires(elements != null); Contract.Requires(Contract.ForAll(elements, e => e != null)); Contract.Requires(parent != null); Contract.Requires(logger != null); foreach (var element in elements) { Type nodeType = null; if (int.TryParse(element.Attribute("Type")?.Value, out var typeVal)) { if (typeVal >= 0 && typeVal < typeMap.Length) { nodeType = typeMap[typeVal]; } } if (nodeType == null) { logger.Log(LogLevel.Error, $"Skipping node with unknown type: {element.Attribute("Type")?.Value}"); logger.Log(LogLevel.Warning, element.ToString()); continue; } var node = BaseNode.CreateInstanceFromType(nodeType, false); if (node == null) { logger.Log(LogLevel.Error, $"Could not create node of type: {nodeType}"); continue; } node.Name = element.Attribute("Name")?.Value ?? string.Empty; node.Comment = element.Attribute("Comments")?.Value ?? string.Empty; // ClassInstanceNode, ClassPointerNode if (node is BaseWrapperNode wrapperNode) { var pointToClassId = element.Attribute("PointToClass")?.Value; if (pointToClassId == null || !classes.ContainsKey(pointToClassId)) { logger.Log(LogLevel.Error, $"Skipping node with unknown reference: {pointToClassId}"); logger.Log(LogLevel.Warning, element.ToString()); continue; } var innerClassNode = classes[pointToClassId]; if (wrapperNode.ShouldPerformCycleCheckForInnerNode() && !ClassUtil.IsCyclicIfClassIsAccessibleFromParent(parent, innerClassNode, project.Classes)) { logger.Log(LogLevel.Error, $"Skipping node with cycle reference: {parent.Name}->{node.Name}"); continue; } if (node is ClassPointerNode classPointerNode) { node = classPointerNode.GetEquivalentNode(innerClassNode); } else // ClassInstanceNode { wrapperNode.ChangeInnerNode(innerClassNode); } } yield return(node); } }
public MethodNode(ClassNode classNode, int start, int end, int declare) { ClassNode = classNode; Declare = declare; Start = start; End = end; }
//public ClassMirror() //{ //} public ClassMirror(ProtoCore.Type type, ProtoCore.Core core) { if (core != null) { ClassName = type.Name; if (classNode == null) { ProtoCore.DSASM.ClassTable classTable = core.ClassTable; classNode = classTable.ClassNodes[type.UID]; } libraryMirror = new LibraryMirror(classNode.ExternLib, core); } }
/// <summary> /// Writes the class for mono. /// </summary> /// <param name="lines">The lines.</param> /// <param name="currentNode">The current node.</param> /// <param name="output">The output.</param> /// <param name="depth">The depth.</param> private static void WriteClassForMono(string[] lines, ClassNode currentNode, List<string> output, int depth) { if (!currentNode.Partial) return; string tabs = "".PadLeft(20, '\t').Substring(0, depth + 1); // Write class declaration output.Add(tabs + GetDeclaration(lines, currentNode.Start, currentNode.Declare)); output.Add(tabs + "{"); // Write method declarations foreach (MethodNode method in currentNode.Methods) { string extra = string.Empty; // bool endif = false; for (int i = method.Start; i <= method.End; i++) { string line = lines[i]; string trim = line.TrimStart(trimchars); if (trim.StartsWith("//")) continue; if (trim.StartsWith("#")) { // if (trim.Contains("#endif")) // endif = false; // else // if (trim.Contains("#if")) // endif = true; output.Add(trim); } else output.Add(tabs + '\t' + trim); } //if (endif) // output.Add("#endif"); } output.Add(string.Empty); foreach (ClassNode child in currentNode.Children) WriteClassForMono(lines, child, output, depth + 1); output.Add(tabs + "}"); }
//public ClassMirror(string className) //{ // ClassName = className; //} internal ClassMirror(ProtoCore.Core core, ProtoCore.DSASM.ClassNode classNode, LibraryMirror libraryMirror) : base(core) { ClassName = classNode.name; this.libraryMirror = libraryMirror; this.classNode = classNode; }
public void Visit(ClassNode node) { // we're good }
public ClassMirror(string className, ProtoCore.Core core) : base(core) { if (core == null) return; ClassName = className; if (classNode == null) { ProtoCore.DSASM.ClassTable classTable = core.ClassTable; int ci = classTable.IndexOf(ClassName); if (ci != ProtoCore.DSASM.Constants.kInvalidIndex) { classNode = classTable.ClassNodes[ci]; } } libraryMirror = new LibraryMirror(classNode.ExternLib, core); }
private void classesView_ClassSelected(object sender, ClassNode node) { memoryViewControl.ClassNode = node; memoryViewControl.Invalidate(); }
/// <summary> /// Get the super class of this class /// </summary> /// <returns></returns> public ClassMirror GetSuperClass() { Validity.Assert(!string.IsNullOrEmpty(ClassName)); Validity.Assert(staticCore != null); int ci; if (classNode == null) { ProtoCore.DSASM.ClassTable classTable = staticCore.ClassTable; ci = classTable.IndexOf(ClassName); if (ci != ProtoCore.DSASM.Constants.kInvalidIndex) { classNode = classTable.ClassNodes[ci]; } } ci = classNode.baseList[0]; Validity.Assert(ci != ProtoCore.DSASM.Constants.kInvalidIndex); return new ClassMirror(staticCore, staticCore.ClassTable.ClassNodes[ci], this.libraryMirror); }
public void TestArrayGetCommonSuperType() { String code = @" class A {} class B extends A {} class C extends B {} tAAA = {A.A(), A.A(), A.A()}; tAAB = {A.A(), A.A(), B.B()}; tAAC = {A.A(), A.A(), C.C()}; tABA = {A.A(), B.B(), A.A()}; tABB = {A.A(), B.B(), B.B()}; tABC = {A.A(), B.B(), C.C()}; tACA = {A.A(), C.C(), A.A()}; tACB = {A.A(), C.C(), B.B()}; tACC = {A.A(), C.C(), C.C()}; //--- tBAA = {B.B(), A.A(), A.A()}; tBAB = {B.B(), A.A(), B.B()}; tBAC = {B.B(), A.A(), C.C()}; tBBA = {B.B(), B.B(), A.A()}; tBBB = {B.B(), B.B(), B.B()}; tBBC = {B.B(), B.B(), C.C()}; tBCA = {B.B(), C.C(), A.A()}; tBCB = {B.B(), C.C(), B.B()}; tBCC = {B.B(), C.C(), C.C()}; //--- tCAA = {C.C(), A.A(), A.A()}; tCAB = {C.C(), A.A(), B.B()}; tCAC = {C.C(), A.A(), C.C()}; tCBA = {C.C(), B.B(), A.A()}; tCBB = {C.C(), B.B(), B.B()}; tCBC = {C.C(), B.B(), C.C()}; tCCA = {C.C(), C.C(), A.A()}; tCCB = {C.C(), C.C(), B.B()}; tCCC = {C.C(), C.C(), C.C()}; "; ProtoScript.Runners.ProtoScriptRunner fsr = new ProtoScript.Runners.ProtoScriptRunner(); ProtoCore.RuntimeCore runtimeCore = null; ExecutionMirror mirror = fsr.Execute(code, core, out runtimeCore); StackValue svAAA = mirror.GetRawFirstValue("tAAA"); ClassNode superAAA = ArrayUtils.GetGreatestCommonSubclassForArray(svAAA, runtimeCore); Assert.IsTrue(superAAA.Name == "A"); StackValue svAAB = mirror.GetRawFirstValue("tAAB"); ClassNode superAAB = ArrayUtils.GetGreatestCommonSubclassForArray(svAAB, runtimeCore); Assert.IsTrue(superAAB.Name == "A"); StackValue svAAC = mirror.GetRawFirstValue("tAAC"); ClassNode superAAC = ArrayUtils.GetGreatestCommonSubclassForArray(svAAC, runtimeCore); Assert.IsTrue(superAAC.Name == "A"); StackValue svABA = mirror.GetRawFirstValue("tABA"); ClassNode superABA = ArrayUtils.GetGreatestCommonSubclassForArray(svABA, runtimeCore); Assert.IsTrue(superABA.Name == "A"); StackValue svABB = mirror.GetRawFirstValue("tABB"); ClassNode superABB = ArrayUtils.GetGreatestCommonSubclassForArray(svABB, runtimeCore); Assert.IsTrue(superABB.Name == "A"); StackValue svABC = mirror.GetRawFirstValue("tABC"); ClassNode superABC = ArrayUtils.GetGreatestCommonSubclassForArray(svABC, runtimeCore); Assert.IsTrue(superABC.Name == "A"); StackValue svACA = mirror.GetRawFirstValue("tACA"); ClassNode superACA = ArrayUtils.GetGreatestCommonSubclassForArray(svACA, runtimeCore); Assert.IsTrue(superACA.Name == "A"); StackValue svACB = mirror.GetRawFirstValue("tACB"); ClassNode superACB = ArrayUtils.GetGreatestCommonSubclassForArray(svACB, runtimeCore); Assert.IsTrue(superACB.Name == "A"); StackValue svACC = mirror.GetRawFirstValue("tACC"); ClassNode superACC = ArrayUtils.GetGreatestCommonSubclassForArray(svACC, runtimeCore); Assert.IsTrue(superACC.Name == "A"); //---- StackValue svBAA = mirror.GetRawFirstValue("tBAA"); ClassNode superBAA = ArrayUtils.GetGreatestCommonSubclassForArray(svBAA, runtimeCore); Assert.IsTrue(superBAA.Name == "A"); StackValue svBAB = mirror.GetRawFirstValue("tBAB"); ClassNode superBAB = ArrayUtils.GetGreatestCommonSubclassForArray(svBAB, runtimeCore); Assert.IsTrue(superBAB.Name == "A"); StackValue svBAC = mirror.GetRawFirstValue("tBAC"); ClassNode superBAC = ArrayUtils.GetGreatestCommonSubclassForArray(svBAC, runtimeCore); Assert.IsTrue(superBAC.Name == "A"); StackValue svBBA = mirror.GetRawFirstValue("tBBA"); ClassNode superBBA = ArrayUtils.GetGreatestCommonSubclassForArray(svBBA, runtimeCore); Assert.IsTrue(superBBA.Name == "A"); StackValue svBBB = mirror.GetRawFirstValue("tBBB"); ClassNode superBBB = ArrayUtils.GetGreatestCommonSubclassForArray(svBBB, runtimeCore); Assert.IsTrue(superBBB.Name == "B"); StackValue svBBC = mirror.GetRawFirstValue("tBBC"); ClassNode superBBC = ArrayUtils.GetGreatestCommonSubclassForArray(svBBC, runtimeCore); Assert.IsTrue(superBBC.Name == "B"); StackValue svBCA = mirror.GetRawFirstValue("tBCA"); ClassNode superBCA = ArrayUtils.GetGreatestCommonSubclassForArray(svBCA, runtimeCore); Assert.IsTrue(superBCA.Name == "A"); StackValue svBCB = mirror.GetRawFirstValue("tBCB"); ClassNode superBCB = ArrayUtils.GetGreatestCommonSubclassForArray(svBCB, runtimeCore); Assert.IsTrue(superBCB.Name == "B"); StackValue svBCC = mirror.GetRawFirstValue("tBCC"); ClassNode superBCC = ArrayUtils.GetGreatestCommonSubclassForArray(svBCC, runtimeCore); Assert.IsTrue(superBCC.Name == "B"); //---- StackValue svCAA = mirror.GetRawFirstValue("tCAA"); ClassNode superCAA = ArrayUtils.GetGreatestCommonSubclassForArray(svCAA, runtimeCore); Assert.IsTrue(superCAA.Name == "A"); StackValue svCAB = mirror.GetRawFirstValue("tCAB"); ClassNode superCAB = ArrayUtils.GetGreatestCommonSubclassForArray(svCAB, runtimeCore); Assert.IsTrue(superCAB.Name == "A"); StackValue svCAC = mirror.GetRawFirstValue("tCAC"); ClassNode superCAC = ArrayUtils.GetGreatestCommonSubclassForArray(svCAC, runtimeCore); Assert.IsTrue(superCAC.Name == "A"); StackValue svCBA = mirror.GetRawFirstValue("tCBA"); ClassNode superCBA = ArrayUtils.GetGreatestCommonSubclassForArray(svCBA, runtimeCore); Assert.IsTrue(superCBA.Name == "A"); StackValue svCBB = mirror.GetRawFirstValue("tCBB"); ClassNode superCBB = ArrayUtils.GetGreatestCommonSubclassForArray(svCBB, runtimeCore); Assert.IsTrue(superCBB.Name == "B"); StackValue svCBC = mirror.GetRawFirstValue("tCBC"); ClassNode superCBC = ArrayUtils.GetGreatestCommonSubclassForArray(svCBC, runtimeCore); Assert.IsTrue(superCBC.Name == "B"); StackValue svCCA = mirror.GetRawFirstValue("tCCA"); ClassNode superCCA = ArrayUtils.GetGreatestCommonSubclassForArray(svCCA, runtimeCore); Assert.IsTrue(superCCA.Name == "A"); StackValue svCCB = mirror.GetRawFirstValue("tCCB"); ClassNode superCCB = ArrayUtils.GetGreatestCommonSubclassForArray(svCCB, runtimeCore); Assert.IsTrue(superCCB.Name == "B"); StackValue svCCC = mirror.GetRawFirstValue("tCCC"); ClassNode superCCC = ArrayUtils.GetGreatestCommonSubclassForArray(svCCC, runtimeCore); Assert.IsTrue(superCCC.Name == "C"); }
/// <summary> /// Returns the list of class properties of this class /// </summary> /// <returns> symbol nodes</returns> public List<PropertyMirror> GetProperties() { List<PropertyMirror> properties = new List<PropertyMirror>(); Dictionary<string, ProcedureNode> setterMap = new Dictionary<string, ProcedureNode>(); string name = string.Empty; if (classNode == null) { Validity.Assert(staticCore != null); ProtoCore.DSASM.ClassTable classTable = staticCore.ClassTable; int ci = classTable.IndexOf(ClassName); if (ci != ProtoCore.DSASM.Constants.kInvalidIndex) { classNode = classTable.ClassNodes[ci]; } } ProcedureTable procedureTable = classNode.vtable; List<ProcedureNode> procList = procedureTable.procList; string getterPrefix = ProtoCore.DSASM.Constants.kGetterPrefix; string setterPrefix = ProtoCore.DSASM.Constants.kSetterPrefix; foreach (ProcedureNode pNode in procList) { name = pNode.name; if (name.Contains(getterPrefix) && pNode.argInfoList.Count == 0 ) { properties.Add(new PropertyMirror(pNode)); } else if (name.Contains(setterPrefix) && pNode.argInfoList.Count == 1 && !pNode.isAutoGeneratedThisProc) { if (setterMap.ContainsKey(name)) { ProcedureNode proc = setterMap[name]; if (proc.argTypeList[0].UID == (int)ProtoCore.PrimitiveType.kTypeVar && pNode.argTypeList[0].UID != (int)ProtoCore.PrimitiveType.kTypeVar) { setterMap.Remove(name); setterMap.Add(name, pNode); } } else { setterMap.Add(name, pNode); } } } foreach (var kvp in setterMap) { properties.Add(new PropertyMirror(kvp.Value, true)); } return properties; }
public void Defect_TestArrayGetCommonSuperType() { String code = @" class A{}; class B extends A{}; class C extends A{}; class D extends C{}; a =A.A(); b = B.B(); c = C.C(); d = D.D(); //ba:A = B.B(); //ca:A = C.C(); //dc:C = D.D(); tABC = { a, b, c }; tABD = { a, b, d }; tACD = { a, c, d }; tBCD = { b, c, d }; tAB = { a, b }; tAD = { a, d }; tBC = { b, c }; tBD = { b, d }; tCD = { c, d }; "; ProtoScript.Runners.ProtoScriptRunner fsr = new ProtoScript.Runners.ProtoScriptRunner(); ProtoCore.RuntimeCore runtimeCore = null; ExecutionMirror mirror = fsr.Execute(code, core, out runtimeCore); StackValue svABC = mirror.GetRawFirstValue("tABC"); ClassNode superABC = ArrayUtils.GetGreatestCommonSubclassForArray(svABC, runtimeCore); Assert.IsTrue(superABC.Name == "A"); StackValue svABD = mirror.GetRawFirstValue("tABD"); ClassNode superABD = ArrayUtils.GetGreatestCommonSubclassForArray(svABD, runtimeCore); Assert.IsTrue(superABD.Name == "A"); StackValue svACD = mirror.GetRawFirstValue("tACD"); ClassNode superACD = ArrayUtils.GetGreatestCommonSubclassForArray(svACD, runtimeCore); Assert.IsTrue(superABD.Name == "A"); StackValue svBCD = mirror.GetRawFirstValue("tBCD"); ClassNode superBCD = ArrayUtils.GetGreatestCommonSubclassForArray(svBCD, runtimeCore); Assert.IsTrue(superBCD.Name == "A"); StackValue svAB = mirror.GetRawFirstValue("tAB"); ClassNode superAB = ArrayUtils.GetGreatestCommonSubclassForArray(svAB, runtimeCore); Assert.IsTrue(superAB.Name == "A"); StackValue svAD = mirror.GetRawFirstValue("tAD"); ClassNode superAD = ArrayUtils.GetGreatestCommonSubclassForArray(svAD, runtimeCore); Assert.IsTrue(superAD.Name == "A"); StackValue svBC = mirror.GetRawFirstValue("tBC"); ClassNode superBC = ArrayUtils.GetGreatestCommonSubclassForArray(svBC, runtimeCore); Assert.IsTrue(superBC.Name == "A"); StackValue svBD = mirror.GetRawFirstValue("tBD"); ClassNode superBD = ArrayUtils.GetGreatestCommonSubclassForArray(svBD, runtimeCore); Assert.IsTrue(superBD.Name == "A"); StackValue svCD = mirror.GetRawFirstValue("tCD"); ClassNode superCD = ArrayUtils.GetGreatestCommonSubclassForArray(svCD, runtimeCore); Assert.IsTrue(superCD.Name == "C"); }
/// <summary> /// Returns the list of function properties of the class only /// </summary> /// <returns> function nodes </returns> public List<MethodMirror> GetFunctions() { List<MethodMirror> methods = new List<MethodMirror>(); string name = string.Empty; if(classNode == null) { Validity.Assert(staticCore != null); ProtoCore.DSASM.ClassTable classTable = staticCore.ClassTable; int ci = classTable.IndexOf(ClassName); if (ci != ProtoCore.DSASM.Constants.kInvalidIndex) { classNode = classTable.ClassNodes[ci]; } } ProcedureTable procedureTable = classNode.vtable; List<ProcedureNode> procList = procedureTable.procList; foreach (ProcedureNode pNode in procList) { name = pNode.name; if (!pNode.isAssocOperator && !pNode.isAutoGenerated && !pNode.isAutoGeneratedThisProc && !pNode.isConstructor) { methods.Add(new MethodMirror(pNode)); } } return methods; }
public void Visit(ClassNode node) { // invalid! ignore IsValid = false; }
public MethodMirror GetDeclaredMethod(string methodName, List<ProtoCore.Type> argumentTypes) { if (classNode == null) { Validity.Assert(staticCore != null); ProtoCore.DSASM.ClassTable classTable = staticCore.ClassTable; int ci = classTable.IndexOf(ClassName); if (ci != ProtoCore.DSASM.Constants.kInvalidIndex) { classNode = classTable.ClassNodes[ci]; } } ProcedureTable procedureTable = classNode.vtable; List<ProcedureNode> procList = procedureTable.procList; return StaticMirror.FindMethod(methodName, argumentTypes, procList); }
public void SetTypeSystem() { Validity.Assert(null == classTable); if (null != classTable) { return; } classTable = new DSASM.ClassTable(); classTable.Reserve((int)PrimitiveType.kMaxPrimitives); ClassNode cnode; cnode = new ClassNode { name = DSDefinitions.Keyword.Array, size = 0, rank = 5, symbols = null, vtable = null, typeSystem = this }; /*cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); * cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); * cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); * cnode.coerceTypes.Add((int)PrimitiveType.kTypeChar, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); * cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); */ cnode.classId = (int)PrimitiveType.kTypeArray; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeArray); // // cnode = new ClassNode { name = DSDefinitions.Keyword.Double, size = 0, rank = 4, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceDoubleToIntScore); cnode.classId = (int)PrimitiveType.kTypeDouble; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeDouble); // // cnode = new ClassNode { name = DSDefinitions.Keyword.Int, size = 0, rank = 3, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceIntToDoubleScore); cnode.classId = (int)PrimitiveType.kTypeInt; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeInt); // // cnode = new ClassNode { name = DSDefinitions.Keyword.Bool, size = 0, rank = 2, symbols = null, vtable = null, typeSystem = this }; // if convert operator to method call, without the following statement // a = true + 1 will fail, because _add expects two integers //cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeBool; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeBool); // // cnode = new ClassNode { name = DSDefinitions.Keyword.Char, size = 0, rank = 1, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeChar; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeChar); // // cnode = new ClassNode { name = DSDefinitions.Keyword.String, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeString; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeString); // // cnode = new ClassNode { name = DSDefinitions.Keyword.Var, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; /*cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); * cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); * cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); * cnode.coerceTypes.Add((int)PrimitiveType.kTypeChar, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); * cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);*/ cnode.classId = (int)PrimitiveType.kTypeVar; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeVar); // // cnode = new ClassNode { name = DSDefinitions.Keyword.Null, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeChar, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeNull; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeNull); // // cnode = new ClassNode { name = DSDefinitions.Keyword.Void, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.classId = (int)PrimitiveType.kTypeVoid; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeVoid); // // cnode = new ClassNode { name = "hostentityid", size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.classId = (int)PrimitiveType.kTypeHostEntityID; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeHostEntityID); // // cnode = new ClassNode { name = "pointer_reserved", size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; // if convert operator to method call, without the following statement, // a = b.c + d.e will fail, b.c and d.e are resolved as pointer and _add method requires two integer cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypePointer; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypePointer); // // cnode = new ClassNode { name = DSDefinitions.Keyword.FunctionPointer, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore); cnode.classId = (int)PrimitiveType.kTypeFunctionPointer; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeFunctionPointer); // // cnode = new ClassNode { name = "return_reserved", size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this }; cnode.classId = (int)PrimitiveType.kTypeReturn; classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeReturn); }
/// <summary> /// Processes the specified root. /// </summary> /// <param name="file">The filename.</param> /// <param name="root">The root.</param> internal static void Process(string file, string root) { Console.WriteLine(file); if (!File.Exists(Path.Combine(root, file))) return; // Load file into string array string[] lines = File.ReadAllLines(Path.Combine(root, file)); ClassNode rootNode = new ClassNode(); List<ClassNode> classNodes = new List<ClassNode>(); List<MethodNode> methodNodes = new List<MethodNode>(); List<int> namespaces = new List<int>(); List<int> usings = new List<int>(); ClassNode currentNode = rootNode; bool incomment = false; // Analyze File for (int linenbr = 0; linenbr < lines.Length; linenbr++) { string trim = GetLine(lines, linenbr, ref incomment).Replace('\t', ' '); if (incomment) continue; trim = StripWithInDoubleQuotes(trim); int skip = 0; if (string.IsNullOrEmpty(trim)) continue; else if (trim.StartsWith("#")) continue; else if ((trim.StartsWith("extern ") || (trim.Contains(" extern "))) && !trim.Contains(" alias ")) { int start = GetPreviousBlockEnd(lines, linenbr); skip = GetNumberOfMethodDeclarationLines(lines, linenbr, false); MethodNode node = new MethodNode(currentNode, start, linenbr + skip, linenbr); methodNodes.Add(node); currentNode.Methods.Add(node); } else if (trim.StartsWith("using ") && trim.Contains(";")) { usings.Add(linenbr); } else if (trim.StartsWith("namespace ")) { namespaces.Add(linenbr); } else if (trim.Contains(" class ") || (trim.StartsWith("class ")) || trim.Contains(" struct ") || (trim.StartsWith("struct "))) { // Search backwards for the start of the class definition (might not be on the same line as class keyword) int start = GetPreviousBlockEnd(lines, linenbr); string className = GetClassName(lines, start, linenbr); // Attempt to handle #else class definitions if (className == currentNode.Name) { currentNode.OtherDeclare.Add(linenbr); continue; } // Find the last line of the class int end = GetEndOfScope(lines, linenbr); // Go up to parent while (linenbr > currentNode.End) currentNode = currentNode.Parent; // Child ClassNode child = new ClassNode(currentNode, start, end, linenbr); classNodes.Add(child); currentNode.Children.Add(child); currentNode = child; child.Name = className; } linenbr = linenbr + skip; // Go up to parent while (linenbr >= currentNode.End) currentNode = currentNode.Parent; } // Mark all partial nodes foreach (ClassNode node in classNodes) if (node.Methods.Count != 0) { node.Partial = true; ClassNode upNode = node; do { upNode.Parent.Partial = true; upNode = upNode.Parent; } while (upNode != upNode.Parent); } // Create partial file if (methodNodes.Count != 0) { File.Copy(Path.Combine(root, file), Path.Combine(root, Path.GetFileNameWithoutExtension(file) + ".Original.cs")); string partialMosaFile = Path.Combine(root, file.Insert(file.Length - 2, "Mosa.Partial.")); Console.WriteLine(">" + Path.GetFileName(partialMosaFile)); CreatePartialFileForMosa(lines, rootNode, usings, namespaces, partialMosaFile); string partialMonoFile = Path.Combine(root, file.Insert(file.Length - 2, "Partial.")); Console.WriteLine(">" + Path.GetFileName(partialMonoFile)); CreatePartialFileForMono(lines, rootNode, usings, namespaces, partialMonoFile); // Modify source file CreateModifiedFile(lines, classNodes, methodNodes, Path.Combine(root, file)); } }
public static bool CheckInvalidArrayCoersion(FunctionEndPoint fep, List <StackValue> reducedSVs, ClassTable classTable, RuntimeCore runtimeCore, bool allowArrayPromotion) { for (int i = 0; i < reducedSVs.Count; i++) { Type typ = fep.FormalParams[i]; if (typ.UID == (int)ProtoCore.PrimitiveType.kInvalidType) { return(true); } if (!typ.IsIndexable) { continue; //It wasn't an array param, skip } //Compute the type of target param if (!allowArrayPromotion) { Validity.Assert(reducedSVs[i].IsArray, "This should be an array otherwise this shouldn't have passed previous tests"); } if (!allowArrayPromotion) { if (typ.rank != ArrayUtils.GetMaxRankForArray(reducedSVs[i], runtimeCore) && typ.rank != DSASM.Constants.kArbitraryRank) { return(true); //Invalid co-ercsion } } else { if (typ.rank < ArrayUtils.GetMaxRankForArray(reducedSVs[i], runtimeCore) && typ.rank != DSASM.Constants.kArbitraryRank) { return(true); //Invalid co-ercsion } } Dictionary <ClassNode, int> arrayTypes = ArrayUtils.GetTypeStatisticsForArray(reducedSVs[i], runtimeCore); ClassNode cn = null; if (arrayTypes.Count == 0) { //This was an empty array Validity.Assert(cn == null, "If it was an empty array, there shouldn't be a type node"); cn = runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeNull]; } else if (arrayTypes.Count == 1) { //UGLY, get the key out of the array types, of which there is only one foreach (ClassNode key in arrayTypes.Keys) { cn = key; } } else if (arrayTypes.Count > 1) { ClassNode commonBaseType = ArrayUtils.GetGreatestCommonSubclassForArray(reducedSVs[i], runtimeCore); if (commonBaseType == null) { throw new ProtoCore.Exceptions.ReplicationCaseNotCurrentlySupported("Array with no common superclass not yet supported: {0C644179-14F5-4172-8EF8-A2F3739901B2}"); } cn = commonBaseType; //From now on perform tests on the commmon base type } ClassNode argTypeNode = classTable.ClassNodes[typ.UID]; //cn now represents the class node of the argument //argTypeNode represents the class node of the argument bool isNotExactTypeMatch = cn != argTypeNode; bool argumentsNotNull = cn != runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeNull]; bool recievingTypeNotAVar = argTypeNode != runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeVar]; bool isNotConvertible = !cn.ConvertibleTo(typ.UID); //bool isCalleeVar = cn == core.classTable.list[(int) PrimitiveType.kTypeVar]; //Is it an invalid conversion? if (isNotExactTypeMatch && argumentsNotNull && recievingTypeNotAVar && isNotConvertible) // && !isCalleeVar) { return(true); //It's an invalid coersion } } return(false); }
internal void CreateChildren(IEnumerable<BplClass> bplClasses) { foreach (var bplClass in bplClasses.OrderBy(c => c.Name)) { var classNode = new ClassNode(bplClass); Children.Add(classNode); classNode.CreateChildren(bplClass.DerivedClasses); } }
/// <summary> /// Outputs the C++ code for the given class to the <see cref="TextWriter"/> instance. /// </summary> /// <param name="writer">The writer to output to.</param> /// <param name="class">The class to output.</param> /// <param name="classes">The list of all available classes.</param> /// <param name="logger">The logger.</param> private void WriteClass(IndentedTextWriter writer, ClassNode @class, IEnumerable <ClassNode> classes, ILogger logger) { Contract.Requires(writer != null); Contract.Requires(@class != null); Contract.Requires(classes != null); writer.Write("class "); writer.Write(@class.Name); var skipFirstMember = false; if (@class.Nodes.FirstOrDefault() is ClassInstanceNode inheritedFromNode) { skipFirstMember = true; writer.Write(" : public "); writer.Write(inheritedFromNode.InnerNode.Name); } if (!string.IsNullOrEmpty(@class.Comment)) { writer.Write(" // "); writer.Write(@class.Comment); } writer.WriteLine(); writer.WriteLine("{"); writer.WriteLine("public:"); writer.Indent++; var nodes = @class.Nodes .Skip(skipFirstMember ? 1 : 0) .WhereNot(n => n is FunctionNode); WriteNodes(writer, nodes, logger); var vTableNodes = @class.Nodes.OfType <VirtualMethodTableNode>().ToList(); if (vTableNodes.Any()) { writer.WriteLine(); var virtualMethodNodes = vTableNodes .SelectMany(vt => vt.Nodes) .OfType <VirtualMethodNode>(); foreach (var node in virtualMethodNodes) { writer.Write("virtual void "); writer.Write(node.MethodName); writer.WriteLine("();"); } } var functionNodes = classes .SelectMany(c2 => c2.Nodes) .OfType <FunctionNode>() .Where(f => f.BelongsToClass == @class) .ToList(); if (functionNodes.Any()) { writer.WriteLine(); foreach (var node in functionNodes) { writer.Write(node.Signature); writer.WriteLine("{ }"); } } writer.Indent--; writer.Write("}; //Size: 0x"); writer.WriteLine($"{@class.MemorySize:X04}"); writer.WriteLine($"static_assert(sizeof({@class.Name}) == 0x{@class.MemorySize:X});"); }
private void changeModeRef(ClassNode clazz, int refType) { wantsMouseMove = true; //Debug.Log ("changeModeRef" + " wantsMouseMove=" + wantsMouseMove); refModeClass = clazz; mode = refType; }
private static IEnumerable <BaseNode> ReadNodeRows(IEnumerable <DataRow> rows, ClassNode parent, IReadOnlyDictionary <int, ClassNode> classes, IReadOnlyDictionary <int, VirtualMethodTableNode> vtables, ILogger logger) { Contract.Requires(rows != null); Contract.Requires(parent != null); Contract.Requires(logger != null); foreach (var row in rows) { Type nodeType = null; var typeVal = Convert.ToInt32(row["type"]); if (typeVal >= 0 && typeVal < typeMap.Length) { nodeType = typeMap[typeVal]; } if (nodeType == null) { logger.Log(LogLevel.Error, $"Skipping node with unknown type: {row["type"]}"); logger.Log(LogLevel.Warning, string.Join(",", row.ItemArray)); continue; } var node = BaseNode.CreateInstanceFromType(nodeType, false); if (node == null) { logger.Log(LogLevel.Error, $"Could not create node of type: {nodeType}"); continue; } node.Name = Convert.ToString(row["variable"]); node.Comment = Convert.ToString(row["comment"]); // ClassInstanceNode, ClassPointerNode if (node is BaseWrapperNode wrapperNode) { var reference = Convert.ToInt32(row["ref"]); if (!classes.ContainsKey(reference)) { if (!vtables.TryGetValue(reference, out var vtableNode)) { logger.Log(LogLevel.Error, $"Skipping node with unknown reference: {row["ref"]}"); logger.Log(LogLevel.Warning, string.Join(",", row.ItemArray)); continue; } yield return(vtableNode); continue; } var innerClassNode = classes[reference]; if (wrapperNode.ShouldPerformCycleCheckForInnerNode() && !ClassUtil.IsCyclicIfClassIsAccessibleFromParent(parent, innerClassNode, classes.Values)) { logger.Log(LogLevel.Error, $"Skipping node with cycle reference: {parent.Name}->{node.Name}"); continue; } if (node is ClassPointerNode classPointerNode) { node = classPointerNode.GetEquivalentNode(innerClassNode); } else { wrapperNode.ChangeInnerNode(innerClassNode); } } if (node is BaseTextNode textNode) { textNode.Length = Math.Max(IntPtr.Size, Convert.ToInt32(row["length"])); } yield return(node); } }
protected override void OnGUIimpl() { Event e = Event.current; switch (e.type) { case EventType.keyDown: { if (mode != mode_draw) { changeModeDraw (); } break; } case EventType.MouseMove: { Repaint (); break; } } GameObject gameObject = Selection.activeGameObject; if (!gameObject) { GUI.Label (new Rect (20, 20, 300, 100), "ClassDiagramRoot is not found."); return; } ClassDiagramRoot classData = gameObject.GetComponent<ClassDiagramRoot> (); if (!classData) { GUI.Label (new Rect (20, 20, 300, 100), "Select ClassDiagramRoot."); return; } if (cuurentClassData != classData) { focusClass = null; focusWidowId = -1; mode = mode_draw; refModeClass = null; refModeTargetClass = null; } cuurentClassData = classData; if (mode == mode_draw) { if ((Event.current.button == 0) && (Event.current.type == EventType.MouseDown)) { focusWidowId = -1; focusClass = null; } } if (GUI.Button (new Rect (10, 35, 25, 18), "+")) { System.Collections.Generic.List<ClassNode> classList = new System.Collections.Generic.List<ClassNode> (classData.classes); ClassNode newClass = new ClassNode (); { string newName = newClass.name; int size = classData.classes.Length; if (0 < size) { string nameTemp = newName; int index = 1; while (true) { bool exist = false; foreach (ClassNode c in classList) { if (c.name == nameTemp) { exist = true; break; } } if (exist) { nameTemp = newName + " " + index; index ++; } else { newName = nameTemp; break; } } } newClass.name = newName; } { Rect newRect = new Rect (newClass.rect); int size = classData.classes.Length; if (0 < size) { while (true) { bool exist = false; foreach (ClassNode c in classList) { if (c.rect.x == newRect.x && c.rect.y == newRect.y) { exist = true; break; } } if (exist) { newRect.x += 20; newRect.y += 20; } else { break; } } } newClass.rect = newRect; } classList.Add (newClass); cuurentClassData.classes = classList.ToArray (); } GUIStyle windowStyle = new GUIStyle (GUIStyle.none); BeginWindows (); for (int index = 0; index < cuurentClassData.classes.Length; index++) { ClassNode clazz = (ClassNode)cuurentClassData.classes.GetValue (index); clazz.rect = GUI.Window (index, clazz.rect, drawWindow, "", windowStyle); if (focusWidowId == index) { focusClass = clazz; } if (clazz.superClassName != null) { ClassNode target = clazz.GetSuperClassNode (cuurentClassData); Rect clazzRect = new Rect (clazz.rect.x, clazz.rect.y + 16, clazz.rect.width, clazz.rect.height - 16); if (target != null) { drawLine (clazzRect , new Rect (target.rect.x, target.rect.y + 16, target.rect.width, target.rect.height - 16), new Color (0.3f, 0.4f, 0.7f), false, null, texTriangle); } else { if (clazz.superClassName != null && 0 < clazz.superClassName.Length) { drawLine (clazzRect , new Rect (clazzRect.x, clazzRect.y - 50, clazzRect.width, clazzRect.height), new Color (0.3f, 0.4f, 0.7f), true, null, texTriangle); } } } } EndWindows (); if (mode != mode_draw) { Vector2 mouse = Event.current.mousePosition; drawLine (new Rect (refModeClass.rect.x, refModeClass.rect.y + 16, refModeClass.rect.width, refModeClass.rect.height - 16) , new Rect (mouse.x - 5, mouse.y - 5, 5, 5), new Color (0.3f, 0.4f, 0.7f), true, GetSrcAnchorTex (), GetDestAnchorTex ()); if (refModeTargetClass != null) { switch (mode) { case mode_ref_gen:{ refModeClass.superClassName = refModeTargetClass.name; break; } case mode_ref_com:{ break; } case mode_ref_ref:{ break; } } changeModeDraw (); } } }
public void Load(string filePath, ILogger logger) { using (var connection = new SQLiteConnection($"Data Source={filePath}")) { connection.Open(); var classes = new Dictionary <int, ClassNode>(); var vtables = new Dictionary <int, VirtualMethodTableNode>(); foreach (var row in Query(connection, "SELECT tbl_name FROM sqlite_master WHERE tbl_name LIKE 'class%'")) { var id = Convert.ToInt32(row["tbl_name"].ToString().Substring(5)); var classRow = Query(connection, $"SELECT variable, comment FROM class{id} WHERE type = 2 LIMIT 1").FirstOrDefault(); if (classRow == null) { continue; } // Skip the vtable classes. if (classRow["variable"].ToString() == "VTABLE") { var vtableNode = new VirtualMethodTableNode(); Query(connection, $"SELECT variable, comment FROM class{id} WHERE type = 16") .Select(e => new VirtualMethodNode { Name = Convert.ToString(e["variable"]), Comment = Convert.ToString(e["comment"]) }) .ForEach(vtableNode.AddNode); foreach (var method in vtableNode.Nodes.Where(m => m.Name == "void function()")) { method.Name = string.Empty; } vtables.Add(id, vtableNode); continue; } var node = new ClassNode(false) { Name = classRow["variable"].ToString(), Comment = classRow["comment"].ToString() }; project.AddClass(node); classes.Add(id, node); } foreach (var kv in classes) { ReadNodeRows( Query(connection, $"SELECT variable, comment, type, length, ref FROM class{kv.Key} WHERE type != 2"), kv.Value, classes, vtables, logger ).ForEach(kv.Value.AddNode); } } }
/// <summary> /// Writes the class for Mosa. /// </summary> /// <param name="lines">The lines.</param> /// <param name="currentNode">The current node.</param> /// <param name="output">The output.</param> /// <param name="depth">The depth.</param> private static void WriteClassForMosa(string[] lines, ClassNode currentNode, List<string> output, int depth) { if (!currentNode.Partial) return; string tabs = "".PadLeft(20, '\t').Substring(0, depth + 1); // Write class declaration output.Add(tabs + GetDeclaration(lines, currentNode.Start, currentNode.Declare)); output.Add(tabs + "{"); // Write method declarations foreach (MethodNode method in currentNode.Methods) { string extra = string.Empty; for (int i = method.Declare; i <= method.End; i++) { string line = lines[i]; string trim = line.TrimStart(trimchars); if ((trim.StartsWith("[")) && (trim.EndsWith("]"))) continue; if (trim.StartsWith("//")) continue; line = StripDLLBrackets(line); line = " " + line.Replace("\t", " "); line = line.Replace(" extern ", " "); line = line.Trim(trimchars); bool semicolon = line.Contains(";"); if (semicolon) line = line.Replace(";", string.Empty); if ((line == "get") || (line == "set")) extra = "\t"; if (!string.IsNullOrEmpty(line)) { output.Add(tabs + extra + "\t" + line); } if (semicolon) { output.Add(tabs + extra + "\t{"); output.Add(tabs + extra + "\t\tthrow new System.NotImplementedException();"); output.Add(tabs + extra + "\t}"); extra = string.Empty; } } } output.Add(string.Empty); foreach (ClassNode child in currentNode.Children) WriteClassForMosa(lines, child, output, depth + 1); output.Add(tabs + "}"); }
private void BuilderType(InterfaceNode type, NamespaceNode nspace) { DDW.ClassNode cls = new ClassNode(new Token(TokenID.Public)); cls.Modifiers = Modifier.Public; cls.BaseClasses.Add(new TypeNode(new IdentifierExpression("Peanut.Mappings.DataObject", new Token(TokenID.Typeof)))); foreach (AttributeNode attr in type.Attributes) { cls.Attributes.Add(attr); } mTableName = GetTableName(type); mClassName = type.Name.Identifier.Substring(1, type.Name.Identifier.Length - 1); cls.Name = new IdentifierExpression(mClassName, new Token(TokenID.String | TokenID.Public)); cls.IsPartial = true; nspace.Classes.Add(cls); StringBuilder sb = new StringBuilder(); sb.AppendLine("///<summary>"); sb.AppendLine("///Peanut Generator Copyright @ FanJianHan 2010-2013"); sb.AppendLine("///website:http://www.ikende.com"); if (!string.IsNullOrEmpty(type.Comment)) { sb.AppendLine(type.Comment); } StringReader sr = new StringReader(type.DocComment); string value = sr.ReadLine(); while (value != null) { if (value.IndexOf("summary>") == -1) { sb.AppendLine(value); } value = sr.ReadLine(); } sb.AppendLine("///</summary>"); cls.DocComment = sb.ToString(); foreach (InterfacePropertyNode property in type.Properties) { string propertyname = property.Names[0].GenericIdentifier; string fieldname = GetFieldName(property); FieldNode field = new FieldNode(new Token(TokenID.False)); field.Modifiers = Modifier.Private; QualifiedIdentifierExpression name = new QualifiedIdentifierExpression(new Token(TokenID.String)); name.Expressions.Add(new IdentifierExpression("m" + property.Names[0].GenericIdentifier, new Token(TokenID.String))); field.Names.Add(name); field.Type = property.Type; cls.Fields.Add(field); IType fieldtype = new TypeNode(new IdentifierExpression("Peanut.FieldInfo<" + ((TypeNode)property.Type).GenericIdentifier + ">", new Token(TokenID.Typeof))); field = new FieldNode(new Token(TokenID.False)); field.Modifiers = Modifier.Public | Modifier.Static; NodeCollection <ArgumentNode> args = new NodeCollection <ArgumentNode>(); args.Add(new ArgumentNode(new Token(TokenID.String))); args.Add(new ArgumentNode(new Token(TokenID.String))); args[0].Expression = new StringPrimitive(mTableName, new Token(TokenID.String)); args[1].Expression = new StringPrimitive(fieldname, new Token(TokenID.String)); name = new QualifiedIdentifierExpression(new Token(TokenID.String)); name.Expressions.Add(new AssignmentExpression(TokenID.Equal, new IdentifierExpression(propertyname.Substring(0, 1).ToLower() + propertyname.Substring(1, propertyname.Length - 1) , new Token(TokenID.String)), new ObjectCreationExpression(fieldtype, args, new Token(TokenID.New)))); field.Names.Add(name); field.Type = fieldtype; cls.Fields.Add(field); PropertyNode pn = new PropertyNode(new Token(TokenID.Newline)); foreach (AttributeNode attr in property.Attributes) { pn.Attributes.Add(attr); } pn.Names = property.Names; pn.Modifiers = Modifier.Public | Modifier.Virtual; pn.Type = property.Type; pn.Setter = new AccessorNode(true, new Token(TokenID.Newline)); pn.Setter.Kind = "set"; ExpressionStatement setvalue = new ExpressionStatement( new AssignmentExpression(TokenID.Equal, new IdentifierExpression("m" + property.Names[0].GenericIdentifier, new Token(TokenID.String)) , new IdentifierExpression("value", new Token(TokenID.String))) ); pn.Setter.StatementBlock.Statements.Add(setvalue); args = new NodeCollection <ArgumentNode>(); args.Add(new ArgumentNode(new Token(TokenID.String))); args[0].Expression = new StringPrimitive(propertyname, new Token(TokenID.String)); QualifiedIdentifierExpression invoke = new QualifiedIdentifierExpression(new Token(TokenID.String)); invoke.Expressions.Add(new IdentifierExpression("EntityState", new Token(TokenID.String))); invoke.Expressions.Add(new InvocationExpression(new IdentifierExpression("FieldChange", new Token(TokenID.Default)), args)); setvalue = new ExpressionStatement(invoke); pn.Setter.StatementBlock.Statements.Add(setvalue); pn.Getter = new AccessorNode(true, new Token(TokenID.Newline)); pn.Getter.Kind = "get"; ReturnStatement rs = new ReturnStatement(new Token(TokenID.Return)); rs.ReturnValue = new IdentifierExpression("m" + property.Names[0].GenericIdentifier, new Token(TokenID.String)); pn.Getter.StatementBlock.Statements.Add(rs); sb = new StringBuilder(); sb.AppendLine("///<summary>"); sb.AppendLine("///Type:" + ((TypeNode)property.Type).GenericIdentifier); if (!string.IsNullOrEmpty(property.Comment)) { sb.AppendLine(type.Comment); } sr = new StringReader(property.DocComment); value = sr.ReadLine(); while (value != null) { if (value.IndexOf("summary>") == -1) { sb.AppendLine(value); } value = sr.ReadLine(); } sb.AppendLine("///</summary>"); pn.DocComment = sb.ToString(); cls.Properties.Add(pn); } //CodeTypeDeclaration entity = new CodeTypeDeclaration(mClassName); //CodeCommentStatement comm; //cns.Types.Add(entity); //comm = new CodeCommentStatement("<summary>"); //comm.Comment.DocComment = true; //entity.Comments.Add(comm); //comm = new CodeCommentStatement("Peanut Generator Copyright © FanJianHan 2010-2013"); //comm.Comment.DocComment = true; //entity.Comments.Add(comm); //comm = new CodeCommentStatement("website:http://www.ikende.com"); //comm.Comment.DocComment = true; //entity.Comments.Add(comm); //if (!string.IsNullOrEmpty(type.Comment)) //{ // comm = new CodeCommentStatement(type.Comment); // comm.Comment.DocComment = true; // entity.Comments.Add(comm); //} //StringReader sr = new StringReader(type.DocComment); //string value = sr.ReadLine(); //while (value != null) //{ // if (value.IndexOf("summary>") == -1) // { // comm = new CodeCommentStatement(value.Replace("///", "")); // comm.Comment.DocComment = true; // entity.Comments.Add(comm); // } // value = sr.ReadLine(); //} //comm = new CodeCommentStatement("</summary>"); //comm.Comment.DocComment = true; //entity.Comments.Add(comm); //// } //entity.BaseTypes.Add(new CodeTypeReference("Peanut.Mappings.DataObject")); //entity.BaseTypes.Add(new CodeTypeReference(type.Name.Identifier)); //entity.Attributes = MemberAttributes.Public; //entity.IsPartial = true; //entity.CustomAttributes.Add(new CodeAttributeDeclaration("Serializable")); //entity.IsClass = true; //foreach (AttributeNode aitem in type.Attributes) //{ // CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(aitem.Name.GenericIdentifier); // entity.CustomAttributes.Add(attribute); // if (attribute.Name.ToLower() == "table") // { // if (aitem.Arguments.Count > 0) // { // DDW.StringPrimitive pe = (DDW.StringPrimitive)aitem.Arguments[0].Expression; // if (pe != null) // { // mTableName = pe.Value.ToString(); // } // else // { // mTableName = mClassName; // } // attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(mTableName))); // } // else // { // mTableName = mClassName; // } // } //} //foreach (InterfacePropertyNode mitem in type.Properties) //{ // BuilderProperty(entity, mitem); //} }
/// <summary> /// Initializes a new instance of the <see cref="ClassNode"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="start">The start.</param> /// <param name="end">The end.</param> /// <param name="declare">The declare.</param> public ClassNode(ClassNode parent, int start, int end, int declare) { Parent = parent; Start = start; End = end; Declare = declare; }
public bool DoesTypeDeepMatch(List <StackValue> formalParameters, RuntimeCore runtimeCore) { if (formalParameters.Count != FormalParams.Length) { return(false); } for (int i = 0; i < FormalParams.Length; i++) { if (FormalParams[i].IsIndexable != formalParameters[i].IsArray) { return(false); } if (FormalParams[i].IsIndexable && formalParameters[i].IsArray) { if (FormalParams[i].rank != ArrayUtils.GetMaxRankForArray(formalParameters[i], runtimeCore) && FormalParams[i].rank != DSASM.Constants.kArbitraryRank) { return(false); } Type typ = FormalParams[i]; Dictionary <ClassNode, int> arrayTypes = ArrayUtils.GetTypeStatisticsForArray(formalParameters[i], runtimeCore); ClassNode cn = null; if (arrayTypes.Count == 0) { //This was an empty array Validity.Assert(cn == null, "If it was an empty array, there shouldn't be a type node"); cn = runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeNull]; } else if (arrayTypes.Count == 1) { //UGLY, get the key out of the array types, of which there is only one foreach (ClassNode key in arrayTypes.Keys) { cn = key; } } else if (arrayTypes.Count > 1) { ClassNode commonBaseType = ArrayUtils.GetGreatestCommonSubclassForArray(formalParameters[i], runtimeCore); if (commonBaseType == null) { throw new ProtoCore.Exceptions.ReplicationCaseNotCurrentlySupported( string.Format(Resources.ArrayWithNotSupported, "{0C644179-14F5-4172-8EF8-A2F3739901B2}")); } cn = commonBaseType; //From now on perform tests on the commmon base type } ClassNode argTypeNode = runtimeCore.DSExecutable.classTable.ClassNodes[typ.UID]; //cn now represents the class node of the argument //argTypeNode represents the class node of the argument //TODO(Jun)This is worrying test //Disable var as exact match, otherwise resolution between double and var will fail if (cn != argTypeNode && cn != runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeNull] && argTypeNode != runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeVar]) { return(false); } //if (coersionScore != (int)ProcedureDistance.kExactMatchScore) // return false; continue; } if (FormalParams[i].UID != formalParameters[i].metaData.type) { return(false); } } return(true); }
/// <summary> /// Processes the specified root. /// </summary> /// <param name="file">The filename.</param> /// <param name="root">The root.</param> internal static void Process(Options options, string source) { string filename = Path.GetFileName(source); string originalFile = source.Insert(source.Length - 3, ".Original"); string mosaFile = source.Insert(source.Length - 3, ".Mosa"); string monoFile = source.Insert(source.Length - 3, ".Internal"); bool same = CompareFile.Compare(Path.Combine(options.Source, source), Path.Combine(options.Destination, originalFile)); //Console.WriteLine("# " + filename); if (!File.Exists(Path.Combine(options.Source, source))) { Console.WriteLine("0> " + filename); if (options.UpdateOnChange) { File.Delete(Path.Combine(options.Destination, source)); File.Delete(Path.Combine(options.Destination, originalFile)); File.Delete(Path.Combine(options.Destination, mosaFile)); File.Delete(Path.Combine(options.Destination, monoFile)); } return; } string[] lines = File.ReadAllLines(Path.Combine(options.Source, source)); ClassNode rootNode = new ClassNode(); List<ClassNode> classNodes = new List<ClassNode>(); List<MethodNode> methodNodes = new List<MethodNode>(); List<int> namespaces = new List<int>(); List<int> usings = new List<int>(); ClassNode currentNode = rootNode; bool incomment = false; // Analyze File for (int linenbr = 0; linenbr < lines.Length; linenbr++) { string trim = GetLine(lines, linenbr, ref incomment).Replace('\t', ' '); if (incomment) continue; trim = StripWithInDoubleQuotes(trim); int skip = 0; if (string.IsNullOrEmpty(trim)) continue; else if (trim.StartsWith("#")) continue; else if ((trim.StartsWith("extern ") || (trim.Contains(" extern "))) && !trim.Contains(" alias ")) { int start = GetPreviousBlockEnd(lines, linenbr); skip = GetNumberOfMethodDeclarationLines(lines, linenbr, false); MethodNode node = new MethodNode(currentNode, start, linenbr + skip, linenbr); methodNodes.Add(node); currentNode.Methods.Add(node); } else if (trim.StartsWith("using ") && trim.Contains(";")) { usings.Add(linenbr); } else if (trim.StartsWith("namespace ")) { namespaces.Add(linenbr); } else if (trim.Contains(" class ") || (trim.StartsWith("class ")) || trim.Contains(" struct ") || (trim.StartsWith("struct "))) { // Search backwards for the start of the class definition (might not be on the same line as class keyword) int start = GetPreviousBlockEnd(lines, linenbr); string className = GetClassName(lines, start, linenbr); // Attempt to handle #else class definitions if (className == currentNode.Name) { currentNode.OtherDeclare.Add(linenbr); continue; } // Find the last line of the class int end = GetEndOfScope(lines, linenbr); // Go up to parent while (linenbr > currentNode.End) currentNode = currentNode.Parent; // Child ClassNode child = new ClassNode(currentNode, start, end, linenbr); classNodes.Add(child); currentNode.Children.Add(child); currentNode = child; child.Name = className; } linenbr = linenbr + skip; // Go up to parent while (linenbr >= currentNode.End) currentNode = currentNode.Parent; } // Mark all partial nodes foreach (ClassNode node in classNodes) if (node.Methods.Count != 0) { node.Partial = true; ClassNode upNode = node; do { upNode.Parent.Partial = true; upNode = upNode.Parent; } while (upNode != upNode.Parent); } Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(options.Destination, source))); if (methodNodes.Count != 0) { if (options.CreateOriginalFile && !same) { Console.WriteLine("1> " + originalFile); File.Copy(Path.Combine(options.Source, source), Path.Combine(options.Destination, originalFile), true); } ExpandUsing(lines, usings); if (options.CreateMosaFile) { if (!File.Exists(Path.Combine(options.Destination, mosaFile)) || (options.UpdateOnChange && !same)) { Console.WriteLine("2> " + mosaFile); CreatePartialFileForMosa(lines, rootNode, usings, namespaces, Path.Combine(options.Destination, mosaFile)); } } if (options.CreateMonoFile) { if (!File.Exists(Path.Combine(options.Destination, monoFile)) || (options.UpdateOnChange && !same)) { Console.WriteLine("3> " + monoFile); CreatePartialFileForMono(lines, rootNode, usings, namespaces, Path.Combine(options.Destination, monoFile)); } } if (options.UpdateOnChange && !same) { Console.WriteLine("4> " + source); CreateModifiedFile(lines, classNodes, methodNodes, Path.Combine(options.Destination, source)); } } else { same = CompareFile.Compare(Path.Combine(options.Source, source), Path.Combine(options.Destination, source)); if (options.UpdateOnChange && !same) { Console.WriteLine("5> " + source); File.Copy(Path.Combine(options.Source, source), Path.Combine(options.Destination, source), true); File.Delete(Path.Combine(options.Destination, originalFile)); File.Delete(Path.Combine(options.Destination, mosaFile)); File.Delete(Path.Combine(options.Destination, monoFile)); } } }
private void EmitClassSerializer(ClassNode cnode, StringBuilder sb) { var nodeToBuf = new Dictionary <PropNode, string>(); int tempNum = 0; sb.AppendLine("func (d *" + cnode.Name + ") Serialize(w io.Writer) error {"); sb.AppendLine(" var err error"); foreach (PropNode node in cnode.childNodes) { if (node.Flags == "proto") { sb.AppendLine(" buf" + tempNum + ", err := proto.Marshal(d." + GetUpperName(node.Name) + ")"); sb.AppendLine(" if err != nil { return err }"); if (node.FlagsOpt != null) { sb.AppendLine(" d." + GetUpperName(node.FlagsOpt) + " = int32(len(buf" + tempNum + "))"); } nodeToBuf[node] = "buf" + tempNum; tempNum++; } } foreach (PropNode node in cnode.childNodes) { if (node.Flags == "const") { continue; } else if (node.Flags == "boolmarshal") { sb.AppendLine(" err = rwu.WriteBool(w, d." + GetUpperName(node.Name) + ")"); } else if (node.Flags == "steamidmarshal") { sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, d." + GetUpperName(node.Name) + ")"); } else if (node.Flags == "protomask") { sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, EMsg(uint32(d." + GetUpperName(node.Name) + ") | ProtoMask))"); } else if (node.Flags == "protomaskgc") { sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, EMsg(uint32(d." + GetUpperName(node.Name) + ") | ProtoMask))"); } else if (node.Flags == "proto") { sb.AppendLine(" _, err = w.Write(" + nodeToBuf[node] + ")"); } else { sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, d." + GetUpperName(node.Name) + ")"); } if (node != cnode.childNodes[cnode.childNodes.Count - 1]) { sb.AppendLine(" if err != nil { return err }"); } } sb.AppendLine(" return err"); sb.AppendLine("}"); sb.AppendLine(); }
/// <summary> /// Creates the partial file for MOSA. /// </summary> /// <param name="lines">The lines.</param> /// <param name="rootNode">The root node.</param> /// <param name="usings">The usings.</param> /// <param name="namespaces">The namespaces.</param> /// <param name="filename">The filename.</param> private static void CreatePartialFileForMosa(string[] lines, ClassNode rootNode, List<int> usings, List<int> namespaces, string filename) { List<string> output = new List<string>(); output.Add("/*"); output.Add(" * (c) 2010 MOSA - The Managed Operating System Alliance"); output.Add(" *"); output.Add(" * Licensed under the terms of the New BSD License."); output.Add(" *"); output.Add(" * Authors:"); output.Add(" * Phil Garcia (tgiphil) <*****@*****.**>"); output.Add(" *"); output.Add(" */"); output.Add(string.Empty); // Write "using" lines foreach (int i in usings) { string line = lines[i]; if (line.Contains("using")) output.Add(line.Trim(trimchars2) + ";"); else if (line.Contains("#")) output.Add(line.Trim(trimchars)); else if (string.IsNullOrEmpty(line)) output.Add(string.Empty); } output.Add(string.Empty); // Write "namespace" lines if (namespaces.Count != 1) return; // problem, more than one namespace output.Add(lines[namespaces[0]].Trim(trimchars3)); output.Add("{"); foreach (ClassNode child in rootNode.Children) WriteClassForMosa(lines, child, output, 0); output.Add("}"); RemoveExtraBlankLines(output); using (TextWriter writer = new StreamWriter(filename)) { foreach (string line in output) if (line != null) writer.WriteLine(line); writer.Close(); } }
private void EmitClassDeserializer(ClassNode cnode, StringBuilder sb) { int tempNum = 0; sb.AppendLine("func (d *" + cnode.Name + ") Deserialize(r io.Reader) error {"); sb.AppendLine(" var err error"); foreach (PropNode node in cnode.childNodes) { if (node.Flags == "const") { continue; } else if (node.Flags == "boolmarshal") { sb.AppendLine(" d." + GetUpperName(node.Name) + ", err = rwu.ReadBool(r)"); } else if (node.Flags == "steamidmarshal") { sb.AppendLine(" t" + tempNum + ", err := rwu.ReadUint64(r)"); sb.AppendLine(" if err != nil { return err }"); sb.AppendLine(" d." + GetUpperName(node.Name) + " = steamid.SteamId(t" + tempNum + ")"); tempNum++; continue; } else if (node.Flags == "protomask") { string type = EmitType(node.Type); if (enumTypes.ContainsKey(type)) { type = enumTypes[type]; } sb.AppendLine(" t" + tempNum + ", err := rwu.Read" + GetUpperName(type) + "(r)"); sb.AppendLine(" if err != nil { return err }"); sb.AppendLine(" d." + GetUpperName(node.Name) + " = EMsg(uint32(t" + tempNum + ") & EMsgMask)"); tempNum++; continue; } else if (node.Flags == "protomaskgc") { sb.AppendLine(" t" + tempNum + ", err := rwu.Read" + GetUpperName(EmitType(node.Type)) + "(r)"); sb.AppendLine(" if err != nil { return err }"); sb.AppendLine(" d." + GetUpperName(node.Name) + " = uint32(t" + tempNum + ") & EMsgMask"); tempNum++; continue; } else if (node.Flags == "proto") { sb.AppendLine(" buf" + tempNum + " := make([]byte, d." + GetUpperName(node.FlagsOpt) + ", d." + GetUpperName(node.FlagsOpt) + ")"); sb.AppendLine(" _, err = io.ReadFull(r, buf" + tempNum + ")"); sb.AppendLine(" if err != nil { return err }"); sb.AppendLine(" err = proto.Unmarshal(buf" + tempNum + ", d." + GetUpperName(node.Name) + ")"); tempNum++; } else { string type = EmitType(node.Type); if (!String.IsNullOrEmpty(node.FlagsOpt)) { sb.AppendLine(" err = binary.Read(r, binary.LittleEndian, d." + GetUpperName(node.Name) + ")"); } else if (!enumTypes.ContainsKey(type)) { sb.AppendLine(" d." + GetUpperName(node.Name) + ", err = rwu.Read" + GetUpperName(type) + "(r)"); } else { sb.AppendLine(" t" + tempNum + ", err := rwu.Read" + GetUpperName(enumTypes[type]) + "(r)"); if (node != cnode.childNodes[cnode.childNodes.Count - 1]) { sb.AppendLine(" if err != nil { return err }"); } sb.AppendLine(" d." + GetUpperName(node.Name) + " = " + type + "(t" + tempNum + ")"); tempNum++; continue; } } if (node != cnode.childNodes[cnode.childNodes.Count - 1]) { sb.AppendLine(" if err != nil { return err }"); } } sb.AppendLine(" return err"); sb.AppendLine("}"); sb.AppendLine(); }
/// <summary> /// Creates instance of class /// </summary> internal SClass( IClassInfo objectInstance, ClassNode classNode ) : this( objectInstance, classNode, null ) { }
/// <summary> /// Writes the class. /// </summary> /// <param name="lines">The lines.</param> /// <param name="currentNode">The current node.</param> /// <param name="output">The output.</param> /// <param name="depth">The depth.</param> private static void WriteClass(string[] lines, ClassNode currentNode, List <string> output, int depth) { if (!currentNode.Partial) { return; } string tabs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t".Substring(0, depth + 1); // Write class declaration output.Add(tabs + GetDeclaration(lines, currentNode.Start, currentNode.Declare)); output.Add(tabs + "{"); // Write method declarations foreach (MethodNode method in currentNode.Methods) { string extra = string.Empty; for (int i = method.Declare; i <= method.End; i++) { string line = lines[i]; string trim = line.TrimStart(trimchars); if ((trim.StartsWith("[")) && (trim.EndsWith("]"))) { continue; } if (trim.StartsWith("//")) { continue; } line = StripDLLBrackets(line); line = " " + line.Replace("\t", " "); line = line.Replace(" extern ", " "); line = line.Trim(trimchars); bool semicolon = line.Contains(";"); if (semicolon) { line = line.Replace(";", string.Empty); } if ((line == "get") || (line == "set")) { extra = "\t"; } if (!string.IsNullOrEmpty(line)) { output.Add(tabs + extra + "\t" + line); } if (semicolon) { output.Add(tabs + extra + "\t{"); output.Add(tabs + extra + "\t\tthrow new System.NotImplementedException();"); output.Add(tabs + extra + "\t}"); extra = string.Empty; } } } output.Add(string.Empty); foreach (ClassNode child in currentNode.Children) { WriteClass(lines, child, output, depth + 1); } output.Add(tabs + "}"); }