private bool templateContainsVar(IResource list)
 {
     if (list != null && !list.isLiteral())
     {
         IEnumerator <IResource> nodes = list.AsList().GetEnumerator();
         while (nodes.MoveNext())
         {
             IResource node = nodes.Current;
             if (node.hasProperty(RDF.PropertyType, SP.ClassNamedGraph))
             {
                 INamedGraph namedGraph = (INamedGraph)node.As(typeof(NamedGraphImpl));
                 foreach (IElement element in namedGraph.getElements())
                 {
                     if (element is ITriple)
                     {
                         if (containsVar((ITriple)element))
                         {
                             return(true);
                         }
                     }
                 }
             }
             else
             {
                 if (containsVar((ITripleTemplate)node.As(typeof(TripleTemplateImpl))))
                 {
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
예제 #2
0
        /// <summary>
        /// Starts YComp on a free TCP port in the range 4242-4251.
        /// </summary>
        /// <param name="graph">The named graph to be displayed.</param>
        /// <param name="layout">Sets the layouter in YComp.
        ///     Can be one of:
        ///     - Random
        ///     - Hierarchic
        ///     - Organic
        ///     - Orthogonal
        ///     - Circular
        ///     - Tree
        ///     - Diagonal
        ///     - Incremental Hierarchic
        ///     - Compilergraph
        /// </param>
        /// <param name="dumpInfo">Sets the dump information setting colors, shapes,
        ///     excluded types, etc.</param>
        /// <returns>An YCompClient object, or null on error.</returns>
        public static YCompClient CreateYCompClient(INamedGraph graph, String layout, DumpInfo dumpInfo)
        {
            int ycompPort = GetFreeTCPPort();

            if (ycompPort < 0)
            {
                Console.WriteLine("Didn't find a free TCP port in the range 4242-4251!");
                return(null);
            }
            try
            {
                Process.Start("ycomp", "-p " + ycompPort);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unable to start ycomp: " + e.ToString());
                return(null);
            }

            try
            {
                return(new YCompClient(graph, layout, 20000, ycompPort, dumpInfo));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to connect to YComp at port " + ycompPort + ": " + ex.Message);
                return(null);
            }
        }
예제 #3
0
        public string ToString(object data, INamedGraph graph, params object[] additionalData)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(ToString(debuggingEvent));
            sb.Append(" ");

            switch (debuggingEvent)
            {
            case SubruleDebuggingEvent.Add:
            case SubruleDebuggingEvent.Rem:
            case SubruleDebuggingEvent.Emit:
            case SubruleDebuggingEvent.Halt:
            case SubruleDebuggingEvent.Highlight:
            {
                string message = (string)data;
                sb.Append("\"");
                sb.Append(message);
                sb.Append("\"");
                for (int i = 0; i < additionalData.Length; ++i)
                {
                    sb.Append(" ");
                    sb.Append(EmitHelper.Clip(EmitHelper.ToStringAutomatic(additionalData[i], graph, false, null, null), 120));
                }
                break;
            }

            case SubruleDebuggingEvent.Match:
            {
                IMatches matches = (IMatches)data;
                sb.Append(matches.Producer.PackagePrefixedName);
                break;
            }

            case SubruleDebuggingEvent.New:
            case SubruleDebuggingEvent.Delete:
            case SubruleDebuggingEvent.Retype:
            case SubruleDebuggingEvent.SetAttributes:
            {
                IGraphElement elem = (IGraphElement)data;
                sb.Append(graph.GetElementName(elem));
                sb.Append(":");
                sb.Append(elem.Type.Name);
                if (additionalData.Length > 0)
                {
                    sb.Append(".");     // the attribute name
                    sb.Append((string)additionalData[0]);
                }
                break;
            }

            default:
                return("INTERNAL FAILURE, unknown SubruleDebuggingConfigurationRule");
            }

            sb.Append(" triggers ");
            sb.Append(ToString());

            return(sb.ToString());
        }
예제 #4
0
        /**
         * Creates a new NamedGraph element as a blank node in a given Model.
         * @param model  the Model to generate the NamedGraph in
         * @param graphNameNode  the URI resource of the graph name
         * @param elements  the elements in the NamedGraph
         * @return a new NamedGraph
         */
        public static INamedGraph createNamedGraph(SpinProcessor model, INode graphNameNode, IResource elements)
        {
            INamedGraph result = (INamedGraph)model.CreateResource(SP.ClassNamedGraph).As(typeof(NamedGraphImpl));

            result.AddProperty(SP.PropertyGraphNameNode, graphNameNode);
            result.AddProperty(SP.PropertyElements, elements);
            return(result);
        }
예제 #5
0
        /// <summary>
        /// type needed for enum, otherwise null ok
        /// graph needed for node/edge in set/map, otherwise null ok
        /// </summary>
        public static String ToString(object value, AttributeType type, INamedGraph graph)
        {
            switch (type.Kind)
            {
            case AttributeKind.ByteAttr:
                return(((sbyte)value).ToString() + "Y");

            case AttributeKind.ShortAttr:
                return(((short)value).ToString() + "S");

            case AttributeKind.IntegerAttr:
                return(((int)value).ToString());

            case AttributeKind.LongAttr:
                return(((long)value).ToString() + "L");

            case AttributeKind.BooleanAttr:
                return(((bool)value).ToString());

            case AttributeKind.StringAttr:
                if (value == null)
                {
                    return("\"\"");
                }
                if (((string)value).IndexOf('\"') != -1)
                {
                    return("\'" + ((string)value) + "\'");
                }
                else
                {
                    return("\"" + ((string)value) + "\"");
                }

            case AttributeKind.FloatAttr:
                return(((float)value).ToString(System.Globalization.CultureInfo.InvariantCulture) + "f");

            case AttributeKind.DoubleAttr:
                return(((double)value).ToString(System.Globalization.CultureInfo.InvariantCulture));

            case AttributeKind.ObjectAttr:
                Console.WriteLine("Warning: Exporting non-null attribute of object type to null");
                return("null");

            case AttributeKind.GraphAttr:
                Console.WriteLine("Warning: Exporting non-null attribute of graph type to null");
                return("null");

            case AttributeKind.EnumAttr:
                return(type.EnumType.Name + "::" + type.EnumType[(int)value].Name);

            case AttributeKind.NodeAttr:
            case AttributeKind.EdgeAttr:
                return(graph.GetElementName((IGraphElement)value));

            default:
                throw new Exception("Unsupported attribute kind in export");
            }
        }
예제 #6
0
        /// <summary>
        /// Exports the given graph to the file given by the stream writer in grs format.
        /// Any errors will be reported by exception.
        /// Returns the graph export context of the main graph.
        /// </summary>
        /// <param name="graph">The graph to export. Must be a named graph.</param>
        /// <param name="sw">The stream writer of the file to export into. The stream writer is not closed automatically.</param>
        /// <param name="modelPathPrefix">Path to the model.</param>
        /// <param name="nonewgraph">If true, the new graph command is not emitted.</param>
        /// <param name="typesToAttributesToSkip">Gives a dictionary with type names containing a dictionary with attribute names that are not to be emitted</param>
        public static MainGraphExportContext ExportYouMustCloseStreamWriter(INamedGraph graph, StreamWriter sw, string modelPathPrefix, bool noNewGraph, Dictionary <String, Dictionary <String, String> > typesToAttributesToSkip)
        {
            MainGraphExportContext mainGraphContext = new MainGraphExportContext(graph);

            mainGraphContext.graphToContext[mainGraphContext.graph] = mainGraphContext;
            mainGraphContext.nameToContext[mainGraphContext.name]   = mainGraphContext;
            mainGraphContext.modelPathPrefix = modelPathPrefix;
            mainGraphContext.noNewGraph      = noNewGraph;
            if (typesToAttributesToSkip != null)
            {
                mainGraphContext.typesToAttributesToSkip = new Dictionary <string, Dictionary <string, string> >();
                foreach (KeyValuePair <String, Dictionary <String, String> > typeContainingAttributeToSkip in typesToAttributesToSkip)
                {
                    mainGraphContext.typesToAttributesToSkip.Add(typeContainingAttributeToSkip.Key, new Dictionary <string, string>());
                    foreach (KeyValuePair <String, String> attributeToSkip in typeContainingAttributeToSkip.Value)
                    {
                        mainGraphContext.typesToAttributesToSkip[typeContainingAttributeToSkip.Key].Add(attributeToSkip.Key, null);
                    }
                }
            }

            sw.WriteLine("# begin of graph \"{0}\" saved by GrsExport", mainGraphContext.name);
            sw.WriteLine();

            bool subgraphAdded = ExportSingleGraph(mainGraphContext, mainGraphContext, sw);

            if (subgraphAdded)
            {
restart:
                foreach (KeyValuePair <string, GraphExportContext> kvp in mainGraphContext.nameToContext)
                {
                    GraphExportContext context = kvp.Value;
                    if (!context.isExported)
                    {
                        subgraphAdded = ExportSingleGraph(mainGraphContext, context, sw);
                        if (subgraphAdded)
                        {
                            goto restart;
                        }
                    }
                }

                foreach (KeyValuePair <string, GraphExportContext> kvp in mainGraphContext.nameToContext)
                {
                    GraphExportContext context = kvp.Value;
                    EmitSubgraphAttributes(mainGraphContext, context, sw);
                }

                sw.WriteLine("in \"" + mainGraphContext.name + "\""); // after import in main graph
            }

            sw.WriteLine("# end of graph \"{0}\" saved by GrsExport", mainGraphContext.name);
            sw.WriteLine();

            return(mainGraphContext);
        }
예제 #7
0
        public void CreateNamedFromSpec(string grgFilename, string graphName, String statisticsPath,
                                        ProcessSpecFlags flags, List <String> externalAssemblies, int capacity,
                                        out INamedGraph newGraph, out IActions newActions)
        {
            LGSPGraph   graph;
            LGSPActions actions;

            CreateFromSpec(grgFilename, graphName, statisticsPath, flags, externalAssemblies, true, capacity, out graph, out actions);
            newGraph   = (LGSPNamedGraph)graph;
            newActions = actions;
        }
예제 #8
0
        public void ReturnFromGraph(IGraph oldGraph)
        {
            INamedGraph newGraph = (INamedGraph)subOutEnv.Graph;

            foreach (RecordingState recordingState in recordings.Values)
            {
                recordingState.writer.WriteLine("in \"" + recordingState.mainExportContext.graphToContext[newGraph].name + "\" # due to return, before: " + oldGraph.Name);
            }

            graph = newGraph;
        }
예제 #9
0
        public ShellGraphProcessingEnvironment(INamedGraph graph, String backendFilename, String[] backendParameters, String modelFilename)
        {
            LGSPNamedGraph Graph = (LGSPNamedGraph)graph;

            DumpInfo           = new DumpInfo(Graph.GetElementName);
            SubruleDebugConfig = new SubruleDebuggingConfiguration();
            BackendFilename    = backendFilename;
            BackendParameters  = backendParameters;
            ModelFilename      = modelFilename;
            ProcEnv            = new LGSPGraphProcessingEnvironment(Graph, null);
            NameToSubgraph.Add(Graph.Name, Graph);
        }
예제 #10
0
        ////////////////////////////////////////////////////////////////////////

        public void SwitchToGraph(IGraph newGraph)
        {
            IGraph oldGraph = subOutEnv.Graph;

            foreach (RecordingState recordingState in recordings.Values)
            {
                AddSubgraphsAsNeeded((INamedGraph)newGraph, recordingState);

                recordingState.writer.WriteLine("in \"" + recordingState.mainExportContext.graphToContext[(INamedGraph)newGraph].name + "\" # due to switch, before: " + oldGraph.Name);
            }

            graph = (INamedGraph)newGraph;
        }
예제 #11
0
 public static bool AddSubgraphAsNeeded(MainGraphExportContext mainGraphContext,
                                        INamedGraph graph)
 {
     if (graph != null && !mainGraphContext.graphToContext.ContainsKey(graph))
     {
         GraphExportContext subgraphContext = new GraphExportContext(mainGraphContext, graph);
         mainGraphContext.graphToContext[graph] = subgraphContext;
         mainGraphContext.nameToContext[subgraphContext.name] = subgraphContext;
         return(true);
     }
     else
     {
         return(false);
     }
 }
예제 #12
0
 public GraphExportContext(MainGraphExportContext mainGraphContext, INamedGraph graph)
 {
     this.graph = graph;
     this.mainGraphContext = mainGraphContext ?? (MainGraphExportContext)this;
     if(this.mainGraphContext.nameToContext.ContainsKey(graph.Name))
     {
         int id = 0;
         while(this.mainGraphContext.nameToContext.ContainsKey(graph.Name + "_" + id.ToString()))
         {
             ++id;
         }
         this.name = graph.Name + "_" + id.ToString();
     }
     else
         this.name = graph.Name;
 }
예제 #13
0
 public GraphExportContext(MainGraphExportContext mainGraphContext, INamedGraph graph)
 {
     this.graph            = graph;
     this.mainGraphContext = mainGraphContext ?? (MainGraphExportContext)this;
     if (this.mainGraphContext.nameToContext.ContainsKey(graph.Name))
     {
         int id = 0;
         while (this.mainGraphContext.nameToContext.ContainsKey(graph.Name + "_" + id.ToString()))
         {
             ++id;
         }
         this.name = graph.Name + "_" + id.ToString();
     }
     else
     {
         this.name = graph.Name;
     }
 }
예제 #14
0
        /// <summary>
        /// Exports the given graph to the file given by the stream writer in grs format.
        /// Any errors will be reported by exception.
        /// Returns the graph export context of the main graph.
        /// </summary>
        /// <param name="graph">The graph to export. Must be a named graph.</param>
        /// <param name="sw">The stream writer of the file to export into. The stream writer is not closed automatically.</param>
        /// <param name="modelPathPrefix">Path to the model.</param>
        public static MainGraphExportContext ExportYouMustCloseStreamWriter(INamedGraph graph, StreamWriter sw, string modelPathPrefix)
        {
            MainGraphExportContext mainGraphContext = new MainGraphExportContext(graph);

            mainGraphContext.graphToContext[mainGraphContext.graph] = mainGraphContext;
            mainGraphContext.nameToContext[mainGraphContext.name]   = mainGraphContext;
            mainGraphContext.modelPathPrefix = modelPathPrefix;

            sw.WriteLine("# begin of graph \"{0}\" saved by GrsExport", mainGraphContext.name);
            sw.WriteLine();

            bool subgraphAdded = ExportSingleGraph(mainGraphContext, mainGraphContext, sw);

            if (subgraphAdded)
            {
restart:
                foreach (KeyValuePair <string, GraphExportContext> kvp in mainGraphContext.nameToContext)
                {
                    GraphExportContext context = kvp.Value;
                    if (!context.isExported)
                    {
                        subgraphAdded = ExportSingleGraph(mainGraphContext, context, sw);
                        if (subgraphAdded)
                        {
                            goto restart;
                        }
                    }
                }

                foreach (KeyValuePair <string, GraphExportContext> kvp in mainGraphContext.nameToContext)
                {
                    GraphExportContext context = kvp.Value;
                    EmitSubgraphAttributes(mainGraphContext, context, sw);
                }

                sw.WriteLine("in \"" + mainGraphContext.name + "\""); // after import in main graph
            }

            sw.WriteLine("# end of graph \"{0}\" saved by GrsExport", mainGraphContext.name);
            sw.WriteLine();

            return(mainGraphContext);
        }
예제 #15
0
        /// <summary>
        /// Creates a new YCompClient instance and connects to the local YComp server.
        /// If it is not available a SocketException is thrown
        /// </summary>
        public YCompClient(INamedGraph graph, String layoutModule, int connectionTimeout, int port, DumpInfo dumpInfo)
        {
            this.graph    = graph;
            this.dumpInfo = dumpInfo;

            int startTime = Environment.TickCount;

            do
            {
                try
                {
                    ycompClient = new TcpClient("localhost", port);
                }
                catch (SocketException)
                {
                    ycompClient = null;
                    Thread.Sleep(1000);
                }
            } while(ycompClient == null && Environment.TickCount - startTime < connectionTimeout);

            if (ycompClient == null)
            {
                throw new Exception("Connection timeout!");
            }

            ycompStream = new YCompStream(ycompClient);

            SetLayout(layoutModule);

            NormalNodeRealizer  = GetNodeRealizer(GrColor.Yellow, GrColor.DarkYellow, GrColor.Black, GrNodeShape.Box);
            MatchedNodeRealizer = GetNodeRealizer(GrColor.Khaki, GrColor.DarkYellow, GrColor.Black, GrNodeShape.Box);
            NewNodeRealizer     = GetNodeRealizer(GrColor.LightRed, GrColor.DarkYellow, GrColor.Black, GrNodeShape.Box);
            DeletedNodeRealizer = GetNodeRealizer(GrColor.LightGrey, GrColor.DarkYellow, GrColor.Black, GrNodeShape.Box);

            NormalEdgeRealizer  = GetEdgeRealizer(GrColor.DarkYellow, GrColor.Black, 1, GrLineStyle.Continuous);
            MatchedEdgeRealizer = GetEdgeRealizer(GrColor.DarkYellow, GrColor.Black, 2, GrLineStyle.Continuous);
            NewEdgeRealizer     = GetEdgeRealizer(GrColor.LightRed, GrColor.Black, 2, GrLineStyle.Continuous);
            DeletedEdgeRealizer = GetEdgeRealizer(GrColor.LightGrey, GrColor.Black, 2, GrLineStyle.Continuous);

            dumpInfo.OnNodeTypeAppearanceChanged += new NodeTypeAppearanceChangedHandler(OnNodeTypeAppearanceChanged);
            dumpInfo.OnEdgeTypeAppearanceChanged += new EdgeTypeAppearanceChangedHandler(OnEdgeTypeAppearanceChanged);
            dumpInfo.OnTypeInfotagsChanged       += new TypeInfotagsChangedHandler(OnTypeInfotagsChanged);
        }
예제 #16
0
파일: Porter.cs 프로젝트: jblomer/GrGen.NET
        /// <summary>
        /// Exports the given named graph to a file with the given filename.
        /// The format is determined by the file extension.
        /// Currently available are: .grs/.grsi or .gxl or .xmi.
        /// Optionally suffixed by .gz; in this case they are saved gzipped.
        /// Any errors will be reported by exception.
        /// </summary>
        /// <param name="graph">The named graph to export.
        /// The .grs/.grsi exporter is exporting the names/including the names; import will return a named graph again.
        /// The .gxl exporter is exporting without the names, which is equivalent of calling the non-named graph export.</param>
        /// The .xmi exporter is using the names as xmi ids.</param>
        /// <param name="filenameParameters">The names of the files to be exported.
        /// The first must be a filename, the following may be used for giving export parameters
        /// (in fact currently no exporter supports multiple files).</param>
        public static void Export(INamedGraph graph, List <String> filenameParameters)
        {
            String       first  = ListGet(filenameParameters, 0);
            StreamWriter writer = null;

            if (first.EndsWith(".gz", StringComparison.InvariantCultureIgnoreCase))
            {
                FileStream filewriter = new FileStream(first, FileMode.OpenOrCreate, FileAccess.Write);
                writer = new StreamWriter(new GZipStream(filewriter, CompressionMode.Compress));
                first  = first.Substring(0, first.Length - 3);
            }
            else
            {
                writer = new StreamWriter(first);
            }

            using (writer)
            {
                if (first.EndsWith(".gxl", StringComparison.InvariantCultureIgnoreCase))
                {
                    GXLExport.Export(graph, writer);
                }
                else if (first.EndsWith(".grs", StringComparison.InvariantCultureIgnoreCase) ||
                         first.EndsWith(".grsi", StringComparison.InvariantCultureIgnoreCase))
                {
                    GRSExport.Export(graph, writer);
                }
                else if (first.EndsWith(".xmi", StringComparison.InvariantCultureIgnoreCase))
                {
                    XMIExport.Export(graph, writer);
                }
                else if (first.EndsWith(".grg", StringComparison.InvariantCultureIgnoreCase))
                {
                    GRGExport.Export(graph, writer);
                }
                else
                {
                    throw new NotSupportedException("File format not supported");
                }
            }
        }
예제 #17
0
        /// <summary>
        /// Creates a new YCompClient instance and connects to the local YComp server.
        /// If it is not available a SocketException is thrown
        /// </summary>
        public YCompClient(INamedGraph graph, String layoutModule, int connectionTimeout, int port,
                           DumpInfo dumpInfo, ElementRealizers realizers, Dictionary <string, IObject> nameToClassObject)
        {
            this.graph    = graph;
            this.dumpInfo = dumpInfo;

            int startTime = Environment.TickCount;

            do
            {
                try
                {
                    ycompClient = new TcpClient("localhost", port);
                }
                catch (SocketException)
                {
                    ycompClient = null;
                    Thread.Sleep(1000);
                }
            }while(ycompClient == null && Environment.TickCount - startTime < connectionTimeout);

            if (ycompClient == null)
            {
                throw new Exception("Connection timeout!");
            }

            ycompStream = new YCompStream(ycompClient);

            SetLayout(layoutModule);

            dumpInfo.OnNodeTypeAppearanceChanged += new NodeTypeAppearanceChangedHandler(OnNodeTypeAppearanceChanged);
            dumpInfo.OnEdgeTypeAppearanceChanged += new EdgeTypeAppearanceChangedHandler(OnEdgeTypeAppearanceChanged);
            dumpInfo.OnTypeInfotagsChanged       += new TypeInfotagsChangedHandler(OnTypeInfotagsChanged);

            this.realizers = realizers;
            realizers.RegisterYComp(this);

            this.nameToClassObject = nameToClassObject;
            // TODO: Add group related events
        }
예제 #18
0
파일: Porter.cs 프로젝트: jblomer/GrGen.NET
        /// <summary>
        /// Exports the given named graph to a file with the given filename.
        /// The format is determined by the file extension. 
        /// Currently available are: .grs/.grsi or .gxl or .xmi.
        /// Optionally suffixed by .gz; in this case they are saved gzipped.
        /// Any errors will be reported by exception.
        /// </summary>
        /// <param name="graph">The named graph to export.
        /// The .grs/.grsi exporter is exporting the names/including the names; import will return a named graph again.
        /// The .gxl exporter is exporting without the names, which is equivalent of calling the non-named graph export.</param>
        /// The .xmi exporter is using the names as xmi ids.</param>
        /// <param name="filenameParameters">The names of the files to be exported.
        /// The first must be a filename, the following may be used for giving export parameters
        /// (in fact currently no exporter supports multiple files).</param>
        public static void Export(INamedGraph graph, List<String> filenameParameters)
        {
            String first = ListGet(filenameParameters, 0);
            StreamWriter writer = null;
            if(first.EndsWith(".gz", StringComparison.InvariantCultureIgnoreCase))
            {
                FileStream filewriter = new FileStream(first, FileMode.OpenOrCreate, FileAccess.Write);
                writer = new StreamWriter(new GZipStream(filewriter, CompressionMode.Compress));
                first = first.Substring(0, first.Length - 3);
            }
            else
            {
                writer = new StreamWriter(first);
            }

            using(writer)
            {
                if(first.EndsWith(".gxl", StringComparison.InvariantCultureIgnoreCase))
                {
                    GXLExport.Export(graph, writer);
                }
                else if(first.EndsWith(".grs", StringComparison.InvariantCultureIgnoreCase)
                    || first.EndsWith(".grsi", StringComparison.InvariantCultureIgnoreCase))
                {
                    GRSExport.Export(graph, writer);
                }
                else if(first.EndsWith(".xmi", StringComparison.InvariantCultureIgnoreCase))
                {
                    XMIExport.Export(graph, writer);
                }
                else if(first.EndsWith(".grg", StringComparison.InvariantCultureIgnoreCase))
                {
                    GRGExport.Export(graph, writer);
                }
                else
                    throw new NotSupportedException("File format not supported");
            }
        }
예제 #19
0
        public static void EmitObjectCreation(MainGraphExportContext mainGraphContext,
                                              ObjectType objType, IObject obj, INamedGraph graph, StreamWriter sw, StringBuilder deferredInits)
        {
            sw.Write("new {0}@(% = \"{1}\"", objType.PackagePrefixedName, mainGraphContext.GetOrAssignPersistentName(obj));
            foreach (AttributeType attrType in objType.AttributeTypes)
            {
                if (IsInternalClassObjectUsedInAttribute(attrType))
                {
                    continue;
                }

                sw.Write(", {0} = ", attrType.Name);
                EmitAttribute(mainGraphContext, attrType, obj.GetAttribute(attrType.Name), graph, sw, deferredInits);
            }
            sw.Write(")");
            ++mainGraphContext.numInternalClassObjects;

            foreach (AttributeType attrType in objType.AttributeTypes)
            {
                if (!IsInternalClassObjectUsedInAttribute(attrType))
                {
                    continue;
                }

                object       value      = obj.GetAttribute(attrType.Name);
                MemoryStream memStream  = new MemoryStream();
                StreamWriter deferredSw = new StreamWriter(memStream);
                EmitAttributeInitialization(mainGraphContext, obj, attrType, value, graph, deferredSw);
                deferredSw.Flush();
                memStream.Seek(0, SeekOrigin.Begin);
                byte[] buffer   = new byte[memStream.Length];
                int    read     = memStream.Read(buffer, 0, (int)memStream.Length);
                String deferred = System.Text.Encoding.UTF8.GetString(buffer);
                deferredInits.Append(deferred);
            }
        }
예제 #20
0
        private static bool AddSubgraphsAsNeeded(INamedGraph potentialNewGraph, RecordingState recordingState)
        {
            bool wasAdded = GRSExport.AddSubgraphAsNeeded(recordingState.mainExportContext, potentialNewGraph);

            if (wasAdded)
            {
restart:
                foreach (KeyValuePair <string, GraphExportContext> kvp in recordingState.mainExportContext.nameToContext)
                {
                    GraphExportContext context = kvp.Value;
                    if (!context.isExported)
                    {
                        wasAdded = GRSExport.ExportSingleGraph(recordingState.mainExportContext, context, recordingState.writer);
                        if (wasAdded)
                        {
                            goto restart;
                        }
                    }
                }
                AddGraphAttributes(recordingState.mainExportContext, recordingState.writer);
                return(true);
            }
            return(false);
        }
예제 #21
0
        /// <summary>
        /// Handles translating NamedGraph patterns into
        /// </summary>
        /// <param name="pattern"></param>
        public virtual void PrintEnhancedSPARQL(INamedGraph pattern)
        {
            // creates a mapping for the graph node
            IResource nameNode = pattern.getNameNode();

            _currentGraphContext.Push(nameNode);
            if (nameNode.isUri())
            {
                Dataset.SetActiveGraph(nameNode.Uri);
            }
            else
            {
                // TODO find a better way to set those
                Dataset.SetActiveGraph(Dataset.DefaultGraphUris);
            }
            if (CurrentSparqlContext == SparqlContext.QueryContext)
            {
                if (nameNode.isUri())
                {
                    if (!Dataset.HasGraph(nameNode.Uri))
                    {
                        _graphMaps.Add(nameNode, String.Empty);
                    }
                    else
                    {
                        CreateGraphMapping(nameNode);
                    }
                }
                else
                {
                    CreateGraphMapping(nameNode);
                }
            }
            else
            {
                print("GRAPH ");
                if (nameNode.isUri())
                {
                    if (CurrentSparqlContext == SparqlContext.InsertTemplateContext)
                    {
                        print("<" + Dataset.Configuration.GetTripleAdditionsMonitorUri(nameNode.Uri).ToString() + ">");
                    }
                    else
                    {
                        print("<" + Dataset.Configuration.GetTripleRemovalsMonitorUri(nameNode.Uri).ToString() + ">");
                    }
                }
                else
                {
                    // TODO add the pattern to the additiontriple of the variable
                    printVariable(nameNode.getString(SP.PropertyVarName));
                }
                print("{");
                println(1);
            }
            PrintEnhancedSPARQL(pattern.getResource(SP.PropertyElements));
            if (CurrentSparqlContext != SparqlContext.QueryContext)
            {
                println(-1);
                print("}");
            }
            _currentGraphContext.Pop();
        }
예제 #22
0
 protected void Export(INamedGraph graph)
 {
     ExportYouMustCloseStreamWriter(graph, writer, "");
 }
예제 #23
0
        protected bool printTemplates(ISparqlPrinter p, INode predicate, String keyword, bool force, IResource graphIRI)
        {
            IResource resource = getResource(predicate);

            if (resource == null)
            {
                return(false);
            }
            List <IResource> nodes = resource.AsList();

            if (nodes.Count > 0 || force)
            {
                if (keyword != null)
                {
                    p.printIndentation(p.getIndentation());
                    p.printKeyword(keyword);
                }
                p.print(" {");
                p.println();
                if (graphIRI != null)
                { // Legacy triple
                    p.setIndentation(p.getIndentation() + 1);
                    p.printIndentation(p.getIndentation());
                    p.printKeyword("GRAPH");
                    p.print(" ");
                    printVarOrResource(p, graphIRI);
                    p.print(" {");
                    p.println();
                }
                foreach (IResource node in nodes)
                {
                    p.printIndentation(p.getIndentation() + 1);
                    if (node.canAs(SP.ClassNamedGraph))
                    {
                        INamedGraph namedGraph = (INamedGraph)node.As(typeof(NamedGraphImpl));
                        p.setIndentation(p.getIndentation() + 1);
                        p.setNamedBNodeMode(true);
                        namedGraph.Print(p);
                        p.setNamedBNodeMode(false);
                        p.setIndentation(p.getIndentation() - 1);
                    }
                    else
                    {
                        ITripleTemplate template = (ITripleTemplate)node.As(typeof(TripleTemplateImpl));
                        template.Print(p);
                    }
                    p.print(" .");
                    p.println();
                }
                if (graphIRI != null)
                {
                    p.printIndentation(p.getIndentation());
                    p.setIndentation(p.getIndentation() - 1);
                    p.print("}");
                    p.println();
                }
                p.printIndentation(p.getIndentation());
                p.print("}");
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #24
0
 /// <summary>
 /// Emits the attribute value as code
 /// for an attribute of the given type with the given value into the stream writer
 /// </summary>
 public static void EmitAttribute(AttributeType attrType, object value, INamedGraph graph, StreamWriter sw)
 {
     if (attrType.Kind == AttributeKind.SetAttr)
     {
         IDictionary set = (IDictionary)value;
         sw.Write("{0}{{", attrType.GetKindName());
         bool first = true;
         foreach (DictionaryEntry entry in set)
         {
             if (first)
             {
                 sw.Write(ToString(entry.Key, attrType.ValueType, graph)); first = false;
             }
             else
             {
                 sw.Write("," + ToString(entry.Key, attrType.ValueType, graph));
             }
         }
         sw.Write("}");
     }
     else if (attrType.Kind == AttributeKind.MapAttr)
     {
         IDictionary map = (IDictionary)value;
         sw.Write("{0}{{", attrType.GetKindName());
         bool first = true;
         foreach (DictionaryEntry entry in map)
         {
             if (first)
             {
                 sw.Write(ToString(entry.Key, attrType.KeyType, graph)
                          + "->" + ToString(entry.Value, attrType.ValueType, graph)); first = false;
             }
             else
             {
                 sw.Write("," + ToString(entry.Key, attrType.KeyType, graph)
                          + "->" + ToString(entry.Value, attrType.ValueType, graph));
             }
         }
         sw.Write("}");
     }
     else if (attrType.Kind == AttributeKind.ArrayAttr)
     {
         IList array = (IList)value;
         sw.Write("{0}[", attrType.GetKindName());
         bool first = true;
         foreach (object entry in array)
         {
             if (first)
             {
                 sw.Write(ToString(entry, attrType.ValueType, graph)); first = false;
             }
             else
             {
                 sw.Write("," + ToString(entry, attrType.ValueType, graph));
             }
         }
         sw.Write("]");
     }
     else if (attrType.Kind == AttributeKind.DequeAttr)
     {
         IDeque deque = (IDeque)value;
         sw.Write("{0}]", attrType.GetKindName());
         bool first = true;
         foreach (object entry in deque)
         {
             if (first)
             {
                 sw.Write(ToString(entry, attrType.ValueType, graph)); first = false;
             }
             else
             {
                 sw.Write("," + ToString(entry, attrType.ValueType, graph));
             }
         }
         sw.Write("[");
     }
     else
     {
         sw.Write("{0}", ToString(value, attrType, graph));
     }
 }
예제 #25
0
 /// <summary>
 /// Exports the given graph to a GRG file with the given filename.
 /// Any errors will be reported by exception.
 /// </summary>
 /// <param name="graph">The graph to export. Must be a named graph.</param>
 /// <param name="exportFilename">The filename for the exported file.</param>
 public static void Export(INamedGraph graph, String exportFilename)
 {
     using (GRGExport export = new GRGExport(exportFilename))
         export.Export(graph);
 }
예제 #26
0
 /// <summary>
 /// Create a recorder
 /// </summary>
 /// <param name="graph">The named graph whose changes are to be recorded</param>
 /// <param name="subOutEnv">The subaction and output environment receiving some of the action events, may be null if only graph changes are requested</param>
 public Recorder(INamedGraph graph, ISubactionAndOutputAdditionEnvironment subOutEnv)
 {
     Initialize(graph, subOutEnv);
 }
예제 #27
0
 /// <summary>
 /// Emits the attribute value as code
 /// for an attribute of the given type with the given value into the stream writer
 /// Main graph context is needed to get access to the graph -> env dictionary.
 /// </summary>
 public static void EmitAttribute(MainGraphExportContext mainGraphContext,
     AttributeType attrType, object value, INamedGraph graph, StreamWriter sw)
 {
     if(attrType.Kind==AttributeKind.SetAttr)
     {
         IDictionary set=(IDictionary)value;
         sw.Write("{0}{{", attrType.GetKindName());
         bool first = true;
         foreach(DictionaryEntry entry in set)
         {
             if(first) { sw.Write(ToString(mainGraphContext, entry.Key, attrType.ValueType, graph)); first = false; }
             else { sw.Write("," + ToString(mainGraphContext, entry.Key, attrType.ValueType, graph)); }
         }
         sw.Write("}");
     }
     else if(attrType.Kind==AttributeKind.MapAttr)
     {
         IDictionary map=(IDictionary)value;
         sw.Write("{0}{{", attrType.GetKindName());
         bool first = true;
         foreach(DictionaryEntry entry in map)
         {
             if(first) { sw.Write(ToString(mainGraphContext, entry.Key, attrType.KeyType, graph)
                 + "->" + ToString(mainGraphContext, entry.Value, attrType.ValueType, graph)); first = false;
             }
             else { sw.Write("," + ToString(mainGraphContext, entry.Key, attrType.KeyType, graph)
                 + "->" + ToString(mainGraphContext, entry.Value, attrType.ValueType, graph)); }
         }
         sw.Write("}");
     }
     else if(attrType.Kind == AttributeKind.ArrayAttr)
     {
         IList array = (IList)value;
         sw.Write("{0}[", attrType.GetKindName());
         bool first = true;
         foreach(object entry in array)
         {
             if(first) { sw.Write(ToString(mainGraphContext, entry, attrType.ValueType, graph)); first = false; }
             else { sw.Write("," + ToString(mainGraphContext, entry, attrType.ValueType, graph)); }
         }
         sw.Write("]");
     }
     else if(attrType.Kind == AttributeKind.DequeAttr)
     {
         IDeque deque = (IDeque)value;
         sw.Write("{0}]", attrType.GetKindName());
         bool first = true;
         foreach(object entry in deque)
         {
             if(first) { sw.Write(ToString(mainGraphContext, entry, attrType.ValueType, graph)); first = false; }
             else { sw.Write("," + ToString(mainGraphContext, entry, attrType.ValueType, graph)); }
         }
         sw.Write("[");
     }
     else
     {
         sw.Write("{0}", ToString(mainGraphContext, value, attrType, graph));
     }
 }
예제 #28
0
 public static bool AddSubgraphAsNeeded(MainGraphExportContext mainGraphContext, 
     INamedGraph graph)
 {
     if(graph!=null && !mainGraphContext.graphToContext.ContainsKey(graph))
     {
         GraphExportContext subgraphContext = new GraphExportContext(mainGraphContext, graph);
         mainGraphContext.graphToContext[graph] = subgraphContext;
         mainGraphContext.nameToContext[subgraphContext.name] = subgraphContext;
         return true;
     }
     else
         return false;
 }
예제 #29
0
        public string ToString(object data, INamedGraph graph, params object[] additionalData)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(ToString(debuggingEvent));
            sb.Append(" ");

            switch(debuggingEvent)
            {
                case SubruleDebuggingEvent.Add:
                case SubruleDebuggingEvent.Rem:
                case SubruleDebuggingEvent.Emit:
                case SubruleDebuggingEvent.Halt:
                case SubruleDebuggingEvent.Highlight:
                    {
                        string message = (string)data;
                        sb.Append("\"");
                        sb.Append(message);
                        sb.Append("\"");
                        for(int i = 0; i < additionalData.Length; ++i)
                        {
                            sb.Append(" ");
                            sb.Append(EmitHelper.Clip(EmitHelper.ToStringAutomatic(additionalData[i], graph), 120));
                        }
                        break;
                    }
                case SubruleDebuggingEvent.Match:
                    {
                        IMatches matches = (IMatches)data;
                        sb.Append(matches.Producer.PackagePrefixedName);
                        break;
                    }
                case SubruleDebuggingEvent.New:
                case SubruleDebuggingEvent.Delete:
                case SubruleDebuggingEvent.Retype:
                case SubruleDebuggingEvent.SetAttributes:
                    {
                        IGraphElement elem = (IGraphElement)data;
                        sb.Append(graph.GetElementName(elem));
                        sb.Append(":");
                        sb.Append(elem.Type.Name);
                        if(additionalData.Length > 0)
                        {
                            sb.Append("."); // the attribute name
                            sb.Append((string)additionalData[0]);
                        }
                        break;
                    }
                default:
                    return "INTERNAL FAILURE, unknown SubruleDebuggingConfigurationRule";
            }

            sb.Append(" triggers ");
            sb.Append(ToString());

            return sb.ToString();
        }
예제 #30
0
 /// <summary>
 /// Uploads the graph to YComp, updates the display and makes a synchonisation
 /// </summary>
 void UploadGraph(INamedGraph graph)
 {
     foreach(INode node in graph.Nodes)
         ycompClient.AddNode(node);
     foreach(IEdge edge in graph.Edges)
         ycompClient.AddEdge(edge);
     ycompClient.UpdateDisplay();
     ycompClient.Sync();
 }
예제 #31
0
        /// <summary>
        /// Unregisters the events previously registered with RegisterLibGrEvents()
        /// </summary>
        void UnregisterLibGrEvents(INamedGraph graph)
        {
            graph.OnNodeAdded -= DebugNodeAdded;
            graph.OnEdgeAdded -= DebugEdgeAdded;
            graph.OnRemovingNode -= DebugDeletingNode;
            graph.OnRemovingEdge -= DebugDeletingEdge;
            graph.OnClearingGraph -= DebugClearingGraph;
            graph.OnChangedNodeAttribute -= DebugChangedNodeAttribute;
            graph.OnChangedEdgeAttribute -= DebugChangedEdgeAttribute;
            graph.OnRetypingNode -= DebugRetypingElement;
            graph.OnRetypingEdge -= DebugRetypingElement;
            graph.OnSettingAddedNodeNames -= DebugSettingAddedNodeNames;
            graph.OnSettingAddedEdgeNames -= DebugSettingAddedEdgeNames;

            shellProcEnv.ProcEnv.OnMatched -= DebugMatched;
            shellProcEnv.ProcEnv.OnRewritingNextMatch -= DebugNextMatch;
            shellProcEnv.ProcEnv.OnFinished -= DebugFinished;

            shellProcEnv.ProcEnv.OnSwitchingToSubgraph -= DebugSwitchToGraph;
            shellProcEnv.ProcEnv.OnReturnedFromSubgraph -= DebugReturnedFromGraph;

            shellProcEnv.ProcEnv.OnDebugEnter -= DebugEnter;
            shellProcEnv.ProcEnv.OnDebugExit -= DebugExit;
            shellProcEnv.ProcEnv.OnDebugEmit -= DebugEmit;
            shellProcEnv.ProcEnv.OnDebugHalt -= DebugHalt;
            shellProcEnv.ProcEnv.OnDebugHighlight -= DebugHighlight;

            shellProcEnv.ProcEnv.OnEntereringSequence -= DebugEnteringSequence;
            shellProcEnv.ProcEnv.OnExitingSequence -= DebugExitingSequence;
            shellProcEnv.ProcEnv.OnEndOfIteration -= DebugEndOfIteration;
        }
예제 #32
0
 /// <summary>
 /// Exports the given graph to a GRS file with the given filename.
 /// Any errors will be reported by exception.
 /// </summary>
 /// <param name="graph">The graph to export. Must be a named graph.</param>
 /// <param name="exportFilename">The filename for the exported file.</param>
 public static void Export(INamedGraph graph, String exportFilename)
 {
     using(GRSExport export = new GRSExport(exportFilename))
         export.Export(graph);
 }
예제 #33
0
 public MainGraphExportContext(INamedGraph graph)
     : base(null, graph)
 {
 }
예제 #34
0
 /// <summary>
 /// Type needed for enum, otherwise null ok.
 /// Graph needed for node/edge, otherwise null ok.
 /// Main graph context needed to get access to the graph -> env dictionary for subgraph.
 /// </summary>
 public static String ToString(MainGraphExportContext mainGraphContext,
     object value, AttributeType type, INamedGraph graph)
 {
     switch(type.Kind)
     {
     case AttributeKind.ByteAttr:
         return ((sbyte)value).ToString()+"Y";
     case AttributeKind.ShortAttr:
         return ((short)value).ToString()+"S";
     case AttributeKind.IntegerAttr:
         return ((int)value).ToString();
     case AttributeKind.LongAttr:
         return ((long)value).ToString()+"L";
     case AttributeKind.BooleanAttr:
         return ((bool)value).ToString();
     case AttributeKind.StringAttr:
         if(value == null) return "\"\"";
         else return "\"" + ((string)value).Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
     case AttributeKind.FloatAttr:
         return ((float)value).ToString(System.Globalization.CultureInfo.InvariantCulture)+"f";
     case AttributeKind.DoubleAttr:
         return ((double)value).ToString(System.Globalization.CultureInfo.InvariantCulture);
     case AttributeKind.ObjectAttr:
         return graph.Model.Serialize(value, type, graph);
     case AttributeKind.GraphAttr:
         if(value != null && mainGraphContext != null && mainGraphContext.graphToContext != null)
             return "\"" + mainGraphContext.graphToContext[(INamedGraph)value].name + "\"";
         else
             return "null";
     case AttributeKind.EnumAttr:
         return type.EnumType.PackagePrefixedName + "::" + type.EnumType[(int)value].Name;
     case AttributeKind.NodeAttr:
     case AttributeKind.EdgeAttr:
         if(value != null)
             return "\"" + graph.GetElementName((IGraphElement)value) + "\"";
         else
             return "null";
     default:
         throw new Exception("Unsupported attribute kind in export");
     }
 }
예제 #35
0
        public void ReturnFromGraph(IGraph oldGraph)
        {
            INamedGraph newGraph = (INamedGraph)subOutEnv.Graph;
            foreach(RecordingState recordingState in recordings.Values)
                recordingState.writer.WriteLine("in \"" + recordingState.mainExportContext.graphToContext[newGraph].name + "\" # due to return, before: " + oldGraph.Name);

            graph = newGraph;
        }
예제 #36
0
        /// <summary>
        /// Exports the given graph to the file given by the stream writer in grs format.
        /// Any errors will be reported by exception.
        /// Returns the graph export context of the main graph.
        /// </summary>
        /// <param name="graph">The graph to export. Must be a named graph.</param>
        /// <param name="sw">The stream writer of the file to export into. The stream writer is not closed automatically.</param>
        /// <param name="modelPathPrefix">Path to the model.</param>
        public static MainGraphExportContext ExportYouMustCloseStreamWriter(INamedGraph graph, StreamWriter sw, string modelPathPrefix)
        {
            MainGraphExportContext mainGraphContext = new MainGraphExportContext(graph);
            mainGraphContext.graphToContext[mainGraphContext.graph] = mainGraphContext;
            mainGraphContext.nameToContext[mainGraphContext.name] = mainGraphContext;
            mainGraphContext.modelPathPrefix = modelPathPrefix;

            sw.WriteLine("# begin of graph \"{0}\" saved by GrsExport", mainGraphContext.name);
            sw.WriteLine();

            bool subgraphAdded = ExportSingleGraph(mainGraphContext, mainGraphContext, sw);

            if(subgraphAdded)
            {
restart:
                foreach(KeyValuePair<string, GraphExportContext> kvp in mainGraphContext.nameToContext)
                {
                    GraphExportContext context = kvp.Value;
                    if(!context.isExported)
                    {
                        subgraphAdded = ExportSingleGraph(mainGraphContext, context, sw);
                        if(subgraphAdded)
                            goto restart;
                    }
                }

                foreach(KeyValuePair<string, GraphExportContext> kvp in mainGraphContext.nameToContext)
                {
                    GraphExportContext context = kvp.Value;
                    EmitSubgraphAttributes(mainGraphContext, context, sw);
                }

                sw.WriteLine("in \"" + mainGraphContext.name + "\""); // after import in main graph
            }

            sw.WriteLine("# end of graph \"{0}\" saved by GrsExport", mainGraphContext.name);
            sw.WriteLine();

            return mainGraphContext;
        }
예제 #37
0
        ////////////////////////////////////////////////////////////////////////

        public void SwitchToGraph(IGraph newGraph)
        {
            IGraph oldGraph = subOutEnv.Graph;

            foreach(RecordingState recordingState in recordings.Values)
            {
                AddSubgraphsAsNeeded((INamedGraph)newGraph, recordingState);

                recordingState.writer.WriteLine("in \"" + recordingState.mainExportContext.graphToContext[(INamedGraph)newGraph].name + "\" # due to switch, before: " + oldGraph.Name);
            }

            graph = (INamedGraph)newGraph;
        }
예제 #38
0
        private void ParseNewSubgraphCommand()
        {
            // add new graph graphname
            Match(TokenKind.ADD);
            Match(TokenKind.NEW);
            Match(TokenKind.GRAPH);
            String graphName = ParseText();

            graph = (INamedGraph)graph.CreateEmptyEquivalent(graphName);
            nameToSubgraph.Add(graphName, graph);
        }
예제 #39
0
 /// <summary>
 /// Initializes a recorder after creation, needed if actions are selected later
 /// </summary>
 /// <param name="graph">The named graph whose changes are to be recorded</param>
 /// <param name="subOutEnv">The subaction and output environment receiving some of the action events, may be null if only graph changes are requested</param>
 public void Initialize(INamedGraph graph, ISubactionAndOutputAdditionEnvironment subOutEnv)
 {
     this.graph     = graph;
     this.subOutEnv = subOutEnv;
 }
예제 #40
0
 protected void Export(INamedGraph graph)
 {
     ExportYouMustCloseStreamWriter(graph, writer, "");
 }
예제 #41
0
 /// <summary>
 /// Emits the node/edge attribute initialization code in graph exporting
 /// for an attribute of the given type with the given value into the stream writer
 /// </summary>
 private static void EmitAttributeInitialization(IGraphElement elem, AttributeType attrType, object value, INamedGraph graph, String op, StreamWriter sw)
 {
     sw.Write("\t\t\t{0}.{1} {2} ", EscapeName(graph.GetElementName(elem)), attrType.Name, op);
     EmitAttribute(attrType, value, graph, sw);
     sw.WriteLine(";");
 }
예제 #42
0
 /// <summary>
 /// Exports the given graph to the file given by the stream writer in grs format.
 /// Any errors will be reported by exception.
 /// </summary>
 /// <param name="graph">The graph to export. Must be a named graph.</param>
 /// <param name="writer">The stream writer to export to.</param>
 public static void Export(INamedGraph graph, StreamWriter writer)
 {
     using(GRSExport export = new GRSExport(writer))
         export.Export(graph);
 }
예제 #43
0
 /// <summary>
 /// Initializes a recorder after creation, needed if actions are selected later
 /// </summary>
 /// <param name="graph">The named graph whose changes are to be recorded</param>
 /// <param name="subOutEnv">The subaction and output environment receiving some of the action events, may be null if only graph changes are requested</param>
 public void Initialize(INamedGraph graph, ISubactionAndOutputAdditionEnvironment subOutEnv)
 {
     this.graph = graph;
     this.subOutEnv = subOutEnv;
 }
예제 #44
0
 public void CreateNamedFromSpec(string grgFilename, string graphName, String statisticsPath, 
     ProcessSpecFlags flags, List<String> externalAssemblies, int capacity,
     out INamedGraph newGraph, out IActions newActions)
 {
     LGSPGraph graph;
     LGSPActions actions;
     CreateFromSpec(grgFilename, graphName, statisticsPath, flags, externalAssemblies, true, capacity, out graph, out actions);
     newGraph = (LGSPNamedGraph)graph;
     newActions = actions;
 }
예제 #45
0
 /// <summary>
 /// Exports the given graph to the file given by the stream writer in grg format, i.e. as GrGen rule.
 /// Any errors will be reported by exception.
 /// </summary>
 /// <param name="graph">The graph to export. Must be a named graph.</param>
 /// <param name="writer">The stream writer to export to.</param>
 public static void Export(INamedGraph graph, StreamWriter writer)
 {
     using (GRGExport export = new GRGExport(writer))
         export.Export(graph);
 }
예제 #46
0
        /// <summary>
        /// Exports the given graph to the file given by the stream writer in grg format, i.e. as GrGen rule.
        /// Any errors will be reported by exception.
        /// </summary>
        /// <param name="graph">The graph to export. Must be a NamedGraph.</param>
        /// <param name="sw">The stream writer of the file to export into. The stream writer is not closed automatically.</param>
        public static void ExportYouMustCloseStreamWriter(INamedGraph graph, StreamWriter sw, string modelPathPrefix)
        {
            // we traverse the graph in one pass, directly writing a creating rule,
            // and writing a matching test to a helper stream which is appended at the end to the primary stream
            using(Stream stream = new MemoryStream())
            {
                using(StreamWriter sw2 = new StreamWriter(stream))
                {
                    sw.WriteLine("// graph \"{0}\" saved by GrgExport, as creating rule and matching test", graph.Name);
                    sw.WriteLine();

                    sw.WriteLine("using " + graph.Model.ModelName + ";");
                    sw.WriteLine();

                    sw.Write("rule createGraph\n");
                    sw.Write("{\n");
                    sw.Write("\treplace {\n");

                    sw2.Write("test matchGraph\n");
                    sw2.Write("{\n");

                    // emit nodes
                    int numNodes = 0;
                    foreach (INode node in graph.Nodes)
                    {
                        String nodeName = EscapeName(graph.GetElementName(node));
                        sw.Write("\t\t{0}:{1};\n", nodeName, node.Type.Name);
                        sw2.Write("\t{0}:{1};\n", nodeName, node.Type.Name);
                        numNodes++;
                    }
                    sw.WriteLine("\t\t// total number of nodes: {0}", numNodes);
                    sw.WriteLine();
                    sw2.WriteLine("\t// total number of nodes: {0}", numNodes);
                    sw2.WriteLine();

                    // emit node attributes
                    sw.Write("\t\teval {\n");
                    sw.Write("\tif {\n");
                    foreach(INode node in graph.Nodes)
                    {
                        foreach(AttributeType attrType in node.Type.AttributeTypes)
                        {
                            object value = node.GetAttribute(attrType.Name);
                            // TODO: Add support for null values, as the default initializers could assign non-null values!
                            if(value != null) {
                                EmitAttributeInitialization(node, attrType, value, graph, "=", sw);
                                EmitAttributeInitialization(node, attrType, value, graph, "==", sw2);
                            }
                        }
                    }
                    sw.Write("\t\t}\n");
                    sw.WriteLine();
                    sw2.Write("\t}\n");
                    sw2.WriteLine();

                    // emit edges
                    int numEdges = 0;
                    foreach (INode node in graph.Nodes)
                    {
                        foreach (IEdge edge in node.Outgoing)
                        {
                            String sourceName = EscapeName(graph.GetElementName(edge.Source));
                            String edgeName = EscapeName(graph.GetElementName(edge));
                            String targetName = EscapeName(graph.GetElementName(edge.Target));
                            sw.Write("\t\t{0} -{1}:{2} -> {3};\n",
                                sourceName, edgeName, edge.Type.Name, targetName);
                            sw2.Write("\t{0} -{1}:{2} -> {3};\n",
                                sourceName, edgeName, edge.Type.Name, targetName);
                            numEdges++;
                        }
                    }
                    sw.WriteLine("\t\t// total number of edges: {0}", numEdges);
                    sw.WriteLine();
                    sw2.WriteLine("\t// total number of edges: {0}", numEdges);
                    sw2.WriteLine();

                    // emit edge attributes
                    sw.Write("\t\teval {\n");
                    sw2.Write("\teval {\n");
                    foreach(INode node in graph.Nodes)
                    {
                        foreach(IEdge edge in node.Outgoing)
                        {
                            foreach(AttributeType attrType in edge.Type.AttributeTypes)
                            {
                                object value = edge.GetAttribute(attrType.Name);
                                // TODO: Add support for null values, as the default initializers could assign non-null values!
                                if(value != null) {
                                    EmitAttributeInitialization(edge, attrType, value, graph, "=", sw);
                                    EmitAttributeInitialization(edge, attrType, value, graph, "==", sw2);
                                }
                            }
                        }
                    }
                    sw.Write("\t\t}\n");
                    sw2.Write("\t}\n");

                    sw.Write("\t}\n");
                    sw.Write("}\n");

                    //sw2.WriteLine("\nnegative { pattern; .; -->; } // no additional node and no additional edge allowed");
                    sw2.Write("}\n");

                    sw.WriteLine();
                    sw2.WriteLine();

                    // I'm sure now that M$ gave the task of designing the .NET library
                    // to the most incompetent of the incompetent it could find on its campus
                    // while C# is better than Java, the class library is just annoying
                    sw2.Flush();
                    stream.Seek(0, SeekOrigin.Begin);
                    StreamReader reader = new StreamReader(stream);
                    string str = reader.ReadToEnd();
                    sw.WriteLine(str); // sw already contains creating rule, now write matching test
                }
            }
        }
예제 #47
0
        /// <summary>
        /// Exports the given graph to the file given by the stream writer in grg format, i.e. as GrGen rule.
        /// Any errors will be reported by exception.
        /// </summary>
        /// <param name="graph">The graph to export. Must be a NamedGraph.</param>
        /// <param name="sw">The stream writer of the file to export into. The stream writer is not closed automatically.</param>
        public static void ExportYouMustCloseStreamWriter(INamedGraph graph, StreamWriter sw, string modelPathPrefix)
        {
            // we traverse the graph in one pass, directly writing a creating rule,
            // and writing a matching test to a helper stream which is appended at the end to the primary stream
            using (Stream stream = new MemoryStream())
            {
                using (StreamWriter sw2 = new StreamWriter(stream))
                {
                    sw.WriteLine("// graph \"{0}\" saved by GrgExport, as creating rule and matching test", graph.Name);
                    sw.WriteLine();

                    sw.WriteLine("using " + graph.Model.ModelName + ";");
                    sw.WriteLine();

                    sw.Write("rule createGraph\n");
                    sw.Write("{\n");
                    sw.Write("\treplace {\n");

                    sw2.Write("test matchGraph\n");
                    sw2.Write("{\n");

                    // emit nodes
                    int numNodes = 0;
                    foreach (INode node in graph.Nodes)
                    {
                        String nodeName = EscapeName(graph.GetElementName(node));
                        sw.Write("\t\t{0}:{1};\n", nodeName, node.Type.Name);
                        sw2.Write("\t{0}:{1};\n", nodeName, node.Type.Name);
                        numNodes++;
                    }
                    sw.WriteLine("\t\t// total number of nodes: {0}", numNodes);
                    sw.WriteLine();
                    sw2.WriteLine("\t// total number of nodes: {0}", numNodes);
                    sw2.WriteLine();

                    // emit node attributes
                    sw.Write("\t\teval {\n");
                    sw.Write("\tif {\n");
                    foreach (INode node in graph.Nodes)
                    {
                        foreach (AttributeType attrType in node.Type.AttributeTypes)
                        {
                            object value = node.GetAttribute(attrType.Name);
                            // TODO: Add support for null values, as the default initializers could assign non-null values!
                            if (value != null)
                            {
                                EmitAttributeInitialization(node, attrType, value, graph, "=", sw);
                                EmitAttributeInitialization(node, attrType, value, graph, "==", sw2);
                            }
                        }
                    }
                    sw.Write("\t\t}\n");
                    sw.WriteLine();
                    sw2.Write("\t}\n");
                    sw2.WriteLine();

                    // emit edges
                    int numEdges = 0;
                    foreach (INode node in graph.Nodes)
                    {
                        foreach (IEdge edge in node.Outgoing)
                        {
                            String sourceName = EscapeName(graph.GetElementName(edge.Source));
                            String edgeName   = EscapeName(graph.GetElementName(edge));
                            String targetName = EscapeName(graph.GetElementName(edge.Target));
                            sw.Write("\t\t{0} -{1}:{2} -> {3};\n",
                                     sourceName, edgeName, edge.Type.Name, targetName);
                            sw2.Write("\t{0} -{1}:{2} -> {3};\n",
                                      sourceName, edgeName, edge.Type.Name, targetName);
                            numEdges++;
                        }
                    }
                    sw.WriteLine("\t\t// total number of edges: {0}", numEdges);
                    sw.WriteLine();
                    sw2.WriteLine("\t// total number of edges: {0}", numEdges);
                    sw2.WriteLine();

                    // emit edge attributes
                    sw.Write("\t\teval {\n");
                    sw2.Write("\teval {\n");
                    foreach (INode node in graph.Nodes)
                    {
                        foreach (IEdge edge in node.Outgoing)
                        {
                            foreach (AttributeType attrType in edge.Type.AttributeTypes)
                            {
                                object value = edge.GetAttribute(attrType.Name);
                                // TODO: Add support for null values, as the default initializers could assign non-null values!
                                if (value != null)
                                {
                                    EmitAttributeInitialization(edge, attrType, value, graph, "=", sw);
                                    EmitAttributeInitialization(edge, attrType, value, graph, "==", sw2);
                                }
                            }
                        }
                    }
                    sw.Write("\t\t}\n");
                    sw2.Write("\t}\n");

                    sw.Write("\t}\n");
                    sw.Write("}\n");

                    //sw2.WriteLine("\nnegative { pattern; .; -->; } // no additional node and no additional edge allowed");
                    sw2.Write("}\n");

                    sw.WriteLine();
                    sw2.WriteLine();

                    // I'm sure now that M$ gave the task of designing the .NET library
                    // to the most incompetent of the incompetent it could find on its campus
                    // while C# is better than Java, the class library is just annoying
                    sw2.Flush();
                    stream.Seek(0, SeekOrigin.Begin);
                    StreamReader reader = new StreamReader(stream);
                    string       str    = reader.ReadToEnd();
                    sw.WriteLine(str); // sw already contains creating rule, now write matching test
                }
            }
        }
예제 #48
0
 /// <summary>
 /// type needed for enum, otherwise null ok
 /// graph needed for node/edge in set/map, otherwise null ok
 /// </summary>
 public static String ToString(object value, AttributeType type, INamedGraph graph)
 {
     switch(type.Kind)
     {
     case AttributeKind.ByteAttr:
         return ((sbyte)value).ToString()+"Y";
     case AttributeKind.ShortAttr:
         return ((short)value).ToString()+"S";
     case AttributeKind.IntegerAttr:
         return ((int)value).ToString();
     case AttributeKind.LongAttr:
         return ((long)value).ToString()+"L";
     case AttributeKind.BooleanAttr:
         return ((bool)value).ToString();
     case AttributeKind.StringAttr:
         if(value == null) return "\"\"";
         if(((string)value).IndexOf('\"') != -1) return "\'" + ((string)value) + "\'";
         else return "\"" + ((string)value) + "\"";
     case AttributeKind.FloatAttr:
         return ((float)value).ToString(System.Globalization.CultureInfo.InvariantCulture)+"f";
     case AttributeKind.DoubleAttr:
         return ((double)value).ToString(System.Globalization.CultureInfo.InvariantCulture);
     case AttributeKind.ObjectAttr:
         Console.WriteLine("Warning: Exporting non-null attribute of object type to null");
         return "null";
     case AttributeKind.GraphAttr:
         Console.WriteLine("Warning: Exporting non-null attribute of graph type to null");
         return "null";
     case AttributeKind.EnumAttr:
         return type.EnumType.Name + "::" + type.EnumType[(int)value].Name;
     case AttributeKind.NodeAttr:
     case AttributeKind.EdgeAttr:
         return graph.GetElementName((IGraphElement)value);
     default:
         throw new Exception("Unsupported attribute kind in export");
     }
 }
예제 #49
0
 private static bool AddSubgraphsAsNeeded(INamedGraph potentialNewGraph, RecordingState recordingState)
 {
     bool wasAdded = GRSExport.AddSubgraphAsNeeded(recordingState.mainExportContext, potentialNewGraph);
     if(wasAdded)
     {
     restart:
         foreach(KeyValuePair<string, GraphExportContext> kvp in recordingState.mainExportContext.nameToContext)
         {
             GraphExportContext context = kvp.Value;
             if(!context.isExported)
             {
                 wasAdded = GRSExport.ExportSingleGraph(recordingState.mainExportContext, context, recordingState.writer);
                 if(wasAdded)
                     goto restart;
             }
         }
         AddGraphAttributes(recordingState.mainExportContext, recordingState.writer);
         return true;
     }
     return false;
 }
예제 #50
0
 /// <summary>
 /// Dumps the named graph with a given graph dumper and default dump style.
 /// </summary>
 /// <param name="namedGraph">The named graph to be dumped.</param>
 /// <param name="dumper">The graph dumper to be used.</param>
 public static void Dump(INamedGraph namedGraph, IDumper dumper)
 {
     DumpMatch(namedGraph, dumper, new DumpInfo(namedGraph.GetElementName), null, 0);
 }
예제 #51
0
        /// <summary>
        /// Creates a new YCompClient instance and connects to the local YComp server.
        /// If it is not available a SocketException is thrown
        /// </summary>
        public YCompClient(INamedGraph graph, String layoutModule, int connectionTimeout, int port, DumpInfo dumpInfo, ElementRealizers realizers)
        {
            this.graph = graph;
            this.dumpInfo = dumpInfo;

            int startTime = Environment.TickCount;

            do
            {
                try
                {
                    ycompClient = new TcpClient("localhost", port);
                }
                catch(SocketException)
                {
                    ycompClient = null;
                    Thread.Sleep(1000);
                }
            } while(ycompClient == null && Environment.TickCount - startTime < connectionTimeout);

            if(ycompClient == null)
                throw new Exception("Connection timeout!");

            ycompStream = new YCompStream(ycompClient);

            SetLayout(layoutModule);

            dumpInfo.OnNodeTypeAppearanceChanged += new NodeTypeAppearanceChangedHandler(OnNodeTypeAppearanceChanged);
            dumpInfo.OnEdgeTypeAppearanceChanged += new EdgeTypeAppearanceChangedHandler(OnEdgeTypeAppearanceChanged);
            dumpInfo.OnTypeInfotagsChanged += new TypeInfotagsChangedHandler(OnTypeInfotagsChanged);

            this.realizers = realizers;
            realizers.RegisterYComp(this);

            // TODO: Add group related events
        }
예제 #52
0
        //////////////////////////////////////////////////////////////////////////////////////////////

        public static IGraphElement GetGraphElement(INamedGraph graph, string name, int threadId)
        {
            return graph.GetGraphElement(name);
        }
예제 #53
0
 /// <summary>
 /// Creates a new YCompClient instance and connects to the local YComp server.
 /// If it is not available a SocketException is thrown
 /// </summary>
 public YCompClient(INamedGraph graph, String layoutModule, int connectionTimeout, int port)
     : this(graph, layoutModule, connectionTimeout, port, new DumpInfo(graph.GetElementName))
 {
 }
예제 #54
0
 public static IEdge GetEdge(INamedGraph graph, string name, int threadId)
 {
     return graph.GetEdge(name);
 }
예제 #55
0
 /// <summary>
 /// Create a recorder
 /// </summary>
 /// <param name="graph">The named graph whose changes are to be recorded</param>
 /// <param name="subOutEnv">The subaction and output environment receiving some of the action events, may be null if only graph changes are requested</param>
 public Recorder(INamedGraph graph, ISubactionAndOutputAdditionEnvironment subOutEnv)
 {
     Initialize(graph, subOutEnv);
 }
예제 #56
0
 public static IEdge GetEdge(INamedGraph graph, string name, IActionExecutionEnvironment actionEnv, int threadId)
 {
     ++actionEnv.PerformanceInfo.SearchStepsPerThread[threadId];
     return graph.GetEdge(name);
 }
예제 #57
0
 private void ParseSwitchToSubgraph()
 {
     Match(TokenKind.IN);
     graph = ParseGraph();
 }
예제 #58
0
 /// <summary>
 /// Emits the node/edge attribute initialization code in graph exporting
 /// for an attribute of the given type with the given value into the stream writer
 /// </summary>
 private static void EmitAttributeInitialization(IGraphElement elem, AttributeType attrType, object value, INamedGraph graph, String op, StreamWriter sw)
 {
     sw.Write("\t\t\t{0}.{1} {2} ", EscapeName(graph.GetElementName(elem)), attrType.Name, op);
     EmitAttribute(attrType, value, graph, sw);
     sw.WriteLine(";");
 }
예제 #59
0
        private void ParseNewGraphCommand()
        {
            // new graph filename (graphname)?
            Match(TokenKind.NEW);
            Match(TokenKind.GRAPH);
            String modelFilename = MatchFilePath();
            String graphName = "";
            if(LookaheadText())
                graphName = ParseText();

            if(modelOverride!=null)
                modelFilename = modelOverride;
            else
                modelFilename += ".gm";

            // estimate a line creating one node or edge to 50 bytes
            int capacity = (int)(fileSize / 50);
            String capacityStr = "capacity=" + capacity.ToString();

            if(model!=null)
                graph = backend.CreateNamedGraph(model, graphName, capacityStr);
            else 
            {
                if(modelFilename.EndsWith(".grg"))
                    backend.CreateNamedFromSpec(modelFilename, graphName, null, ProcessSpecFlags.UseNoExistingFiles, new List<String>(), capacity,
                        out graph, out actions);
                else
                    graph = backend.CreateNamedGraph(modelFilename, graphName, capacityStr);
            }

            nameToSubgraph.Add(graph.Name, graph);
        }
예제 #60
0
 /// <summary>
 /// Emits the node/edge attribute initialization code in graph exporting
 /// for an attribute of the given type with the given value into the stream writer.
 /// </summary>
 private static void EmitAttributeInitialization(MainGraphExportContext mainGraphContext,
     AttributeType attrType, object value, INamedGraph graph, StreamWriter sw)
 {
     sw.Write(", {0} = ", attrType.Name);
     EmitAttribute(mainGraphContext, attrType, value, graph, sw);
 }