diff options
Diffstat (limited to 'src')
29 files changed, 957 insertions, 648 deletions
diff --git a/src/core/common/Rtti.cpp b/src/core/common/Rtti.cpp index 6849a0e..acc98a7 100644 --- a/src/core/common/Rtti.cpp +++ b/src/core/common/Rtti.cpp @@ -147,6 +147,17 @@ bool Rtti::setIsOneOf(const RttiSet &s1, const RttiSet &s2) return false; } +RttiSet Rtti::setIntersection(const RttiSet &s1, const RttiSet &s2) +{ + RttiSet res; + for (const Rtti *t1 : s1) { + if (t1->isOneOf(s2)) { + res.insert(t1); + } + } + return res; +} + bool Rtti::composedOf(const Rtti &other) const { initialize(); diff --git a/src/core/common/Rtti.hpp b/src/core/common/Rtti.hpp index 05cc728..f371494 100644 --- a/src/core/common/Rtti.hpp +++ b/src/core/common/Rtti.hpp @@ -403,6 +403,17 @@ public: static bool setIsOneOf(const RttiSet &s1, const RttiSet &s2); /** + * Calculates the intersection of two RttiSets. Only the elements of s1 + * which are at least one element in s2 are returned. + * + * @param s1 is the first set. For each type in this set we check whether + * it is one of the types in s2, only those elements are returned. + * @param s2 is the second set. + * @return s1 restricted to the types in s2. + */ + static RttiSet setIntersection(const RttiSet &s1, const RttiSet &s2); + + /** * Returns true if an instance of this type may have references to the other * given type. This mechanism is used to prune impossible paths when * resolving objects of a certain type by name in an object graph. diff --git a/src/core/common/Utils.hpp b/src/core/common/Utils.hpp index f6f5225..a88c716 100644 --- a/src/core/common/Utils.hpp +++ b/src/core/common/Utils.hpp @@ -73,10 +73,7 @@ public: /** * Returns true if the given character is a whitespace character. */ - static bool isLinebreak(const char c) - { - return (c == '\n') || (c == '\r'); - } + static bool isLinebreak(const char c) { return (c == '\n') || (c == '\r'); } /** * Removes whitespace at the beginning and the end of the given string. @@ -93,11 +90,12 @@ public: * @param s is the container that should be trimmed. * @param f is a function that returns true for values that should be * removed. - * @return start and end index. Note that "end" points at the character beyond - * the end, thus "end" minus "start" + * @return start and end index. Note that "end" points at the character + * beyond the end, thus "end" minus "start" */ template <class T, class Filter> - static std::pair<size_t, size_t> trim(const T &s, Filter f) { + static std::pair<size_t, size_t> trim(const T &s, Filter f) + { size_t start = 0; for (size_t i = 0; i < s.size(); i++) { if (!f(s[i])) { @@ -181,6 +179,18 @@ public: * lowercase. */ static std::string extractFileExtension(const std::string &filename); + + /** + * Hash functional to be used for enum classes. + * See http://stackoverflow.com/a/24847480/2188211 + */ + struct EnumHash { + template <typename T> + std::size_t operator()(T t) const + { + return static_cast<std::size_t>(t); + } + }; }; } diff --git a/src/core/managed/Managed.hpp b/src/core/managed/Managed.hpp index 8b594ea..cb7104b 100644 --- a/src/core/managed/Managed.hpp +++ b/src/core/managed/Managed.hpp @@ -91,7 +91,7 @@ public: * @return a reference at the underlying Manager object which manages this * particular Managed instance. */ - Manager &getManager() { return mgr; } + Manager &getManager() const { return mgr; } /** * Returns the unique identifier (UID) of this object. Valid UIDs are diff --git a/src/core/model/Document.cpp b/src/core/model/Document.cpp index f22ccd6..f452695 100644 --- a/src/core/model/Document.cpp +++ b/src/core/model/Document.cpp @@ -25,7 +25,6 @@ #include <core/common/RttiBuilder.hpp> namespace ousia { -namespace model { /* Class DocumentEntity */ @@ -720,24 +719,23 @@ bool Document::hasChild(Handle<StructureNode> s) const } return false; } -} /* Type registrations */ namespace RttiTypes { -const Rtti Document = RttiBuilder<model::Document>("Document") +const Rtti Document = RttiBuilder<ousia::Document>("Document") .parent(&Node) .composedOf({&AnnotationEntity, &StructuredEntity}); const Rtti StructureNode = - RttiBuilder<model::StructureNode>("StructureNode").parent(&Node); + RttiBuilder<ousia::StructureNode>("StructureNode").parent(&Node); const Rtti StructuredEntity = - RttiBuilder<model::StructuredEntity>("StructuredEntity") + RttiBuilder<ousia::StructuredEntity>("StructuredEntity") .parent(&StructureNode) .composedOf({&StructuredEntity, &DocumentPrimitive, &Anchor}); -const Rtti DocumentPrimitive = RttiBuilder<model::DocumentPrimitive>( +const Rtti DocumentPrimitive = RttiBuilder<ousia::DocumentPrimitive>( "DocumentPrimitive").parent(&StructureNode); -const Rtti Anchor = RttiBuilder<model::Anchor>("Anchor").parent(&StructureNode); +const Rtti Anchor = RttiBuilder<ousia::Anchor>("Anchor").parent(&StructureNode); const Rtti AnnotationEntity = - RttiBuilder<model::AnnotationEntity>("AnnotationEntity") + RttiBuilder<ousia::AnnotationEntity>("AnnotationEntity") .parent(&Node) .composedOf({&StructuredEntity, &DocumentPrimitive, &Anchor}); } diff --git a/src/core/model/Document.hpp b/src/core/model/Document.hpp index 97bbb60..9ea2d6e 100644 --- a/src/core/model/Document.hpp +++ b/src/core/model/Document.hpp @@ -121,9 +121,6 @@ namespace ousia { // Forward declarations class Rtti; - -namespace model { - class Document; class StructureNode; class StructuredEntity; @@ -889,7 +886,6 @@ public: */ bool hasChild(Handle<StructureNode> s) const; }; -} namespace RttiTypes { extern const Rtti Document; diff --git a/src/core/model/Domain.cpp b/src/core/model/Domain.cpp index 3c4b64c..360aa83 100644 --- a/src/core/model/Domain.cpp +++ b/src/core/model/Domain.cpp @@ -24,7 +24,6 @@ #include "Domain.hpp" namespace ousia { -namespace model { /* Class FieldDescriptor */ @@ -545,21 +544,21 @@ Rooted<AnnotationClass> Domain::createAnnotationClass( return Rooted<AnnotationClass>{new AnnotationClass( getManager(), std::move(name), this, attributesDescriptor)}; } -} + /* Type registrations */ namespace RttiTypes { const Rtti FieldDescriptor = - RttiBuilder<model::FieldDescriptor>("FieldDescriptor").parent(&Node); + RttiBuilder<ousia::FieldDescriptor>("FieldDescriptor").parent(&Node); const Rtti Descriptor = - RttiBuilder<model::Descriptor>("Descriptor").parent(&Node); + RttiBuilder<ousia::Descriptor>("Descriptor").parent(&Node); const Rtti StructuredClass = - RttiBuilder<model::StructuredClass>("StructuredClass") + RttiBuilder<ousia::StructuredClass>("StructuredClass") .parent(&Descriptor) .composedOf(&FieldDescriptor); const Rtti AnnotationClass = - RttiBuilder<model::AnnotationClass>("AnnotationClass").parent(&Descriptor); -const Rtti Domain = RttiBuilder<model::Domain>("Domain") + RttiBuilder<ousia::AnnotationClass>("AnnotationClass").parent(&Descriptor); +const Rtti Domain = RttiBuilder<ousia::Domain>("Domain") .parent(&Node) .composedOf({&StructuredClass, &AnnotationClass}); } diff --git a/src/core/model/Domain.hpp b/src/core/model/Domain.hpp index ef228b1..541a428 100644 --- a/src/core/model/Domain.hpp +++ b/src/core/model/Domain.hpp @@ -212,10 +212,6 @@ namespace ousia { // Forward declarations class Rtti; - -namespace model { - -// Forward declarations class Descriptor; class StructuredClass; class Domain; @@ -1085,7 +1081,6 @@ public: typesystems.insert(typesystems.end(), ts.begin(), ts.end()); } }; -} namespace RttiTypes { diff --git a/src/core/model/Project.cpp b/src/core/model/Project.cpp index a0f1f08..a298ffc 100644 --- a/src/core/model/Project.cpp +++ b/src/core/model/Project.cpp @@ -25,10 +25,9 @@ namespace ousia { -namespace model { - -Project::Project(Manager &mgr) +Project::Project(Manager &mgr, Registry ®istry) : Node(mgr), + registry(registry), systemTypesystem(acquire(new SystemTypesystem(mgr))), documents(this) { @@ -69,10 +68,9 @@ void Project::addDocument(Handle<Document> document) } const NodeVector<Document> &Project::getDocuments() const { return documents; } -} namespace RttiTypes { -const Rtti Project = RttiBuilder<model::Project>("Project") +const Rtti Project = RttiBuilder<ousia::Project>("Project") .parent(&Node) .composedOf(&Document) .composedOf(&SystemTypesystem); diff --git a/src/core/model/Project.hpp b/src/core/model/Project.hpp index 4e2a43b..2c50f49 100644 --- a/src/core/model/Project.hpp +++ b/src/core/model/Project.hpp @@ -28,6 +28,8 @@ #ifndef _OUSIA_PROJECT_HPP_ #define _OUSIA_PROJECT_HPP_ +#include <core/resource/ResourceManager.hpp> + #include "Node.hpp" namespace ousia { @@ -35,9 +37,8 @@ namespace ousia { // Forward declarations class Logger; class Rtti; - -namespace model { - +class Registry; +class ParserContext; class SystemTypesystem; class Typesystem; class Document; @@ -51,6 +52,11 @@ class Domain; class Project : public Node { private: /** + * Reference at the internally used Registry instance. + */ + Registry ®istry; + + /** * Private instance of the system typesystem which is distributed as a * reference to all child typesystems. */ @@ -61,6 +67,11 @@ private: */ NodeVector<Document> documents; + /** + * ResourceManager used to manage all resources used by the project. + */ + ResourceManager resourceManager; + protected: /** * Validates the project and all parts it consists of. @@ -74,8 +85,10 @@ public: * Constructor of the Project class. * * @param mgr is the manager instance used for managing this Node. + * @param registry is the registry instance that should be used for locating + * files and finding parsers for these files. */ - Project(Manager &mgr); + Project(Manager &mgr, Registry ®istry); /** * Returns a reference to the internal system typesystem. @@ -123,7 +136,6 @@ public: */ const NodeVector<Document> &getDocuments() const; }; -} namespace RttiTypes { /** diff --git a/src/core/model/Typesystem.cpp b/src/core/model/Typesystem.cpp index f26363c..5f8f613 100644 --- a/src/core/model/Typesystem.cpp +++ b/src/core/model/Typesystem.cpp @@ -23,7 +23,6 @@ #include <core/common/VariantConverter.hpp> namespace ousia { -namespace model { /* Class Type */ @@ -562,31 +561,31 @@ SystemTypesystem::SystemTypesystem(Manager &mgr) addType(doubleType); addType(boolType); } -} + /* RTTI type registrations */ namespace RttiTypes { -const Rtti Type = RttiBuilder<model::Type>("Type").parent(&Node); +const Rtti Type = RttiBuilder<ousia::Type>("Type").parent(&Node); const Rtti StringType = - RttiBuilder<model::StringType>("StringType").parent(&Type); -const Rtti IntType = RttiBuilder<model::IntType>("IntType").parent(&Type); + RttiBuilder<ousia::StringType>("StringType").parent(&Type); +const Rtti IntType = RttiBuilder<ousia::IntType>("IntType").parent(&Type); const Rtti DoubleType = - RttiBuilder<model::DoubleType>("DoubleType").parent(&Type); -const Rtti BoolType = RttiBuilder<model::BoolType>("BoolType").parent(&Type); -const Rtti EnumType = RttiBuilder<model::EnumType>("EnumType").parent(&Type); + RttiBuilder<ousia::DoubleType>("DoubleType").parent(&Type); +const Rtti BoolType = RttiBuilder<ousia::BoolType>("BoolType").parent(&Type); +const Rtti EnumType = RttiBuilder<ousia::EnumType>("EnumType").parent(&Type); const Rtti StructType = - RttiBuilder<model::StructType>("StructType").parent(&Type).composedOf(&Attribute); -const Rtti ArrayType = RttiBuilder<model::ArrayType>("ArrayType").parent(&Type); + RttiBuilder<ousia::StructType>("StructType").parent(&Type).composedOf(&Attribute); +const Rtti ArrayType = RttiBuilder<ousia::ArrayType>("ArrayType").parent(&Type); const Rtti UnknownType = - RttiBuilder<model::UnknownType>("UnknownType").parent(&Type); -const Rtti Constant = RttiBuilder<model::Constant>("Constant").parent(&Node); -const Rtti Attribute = RttiBuilder<model::Attribute>("Attribute").parent(&Node); + RttiBuilder<ousia::UnknownType>("UnknownType").parent(&Type); +const Rtti Constant = RttiBuilder<ousia::Constant>("Constant").parent(&Node); +const Rtti Attribute = RttiBuilder<ousia::Attribute>("Attribute").parent(&Node); const Rtti Typesystem = - RttiBuilder<model::Typesystem>("Typesystem").parent(&Node).composedOf( + RttiBuilder<ousia::Typesystem>("Typesystem").parent(&Node).composedOf( {&StringType, &IntType, &DoubleType, &BoolType, &EnumType, &StructType, &Constant}); const Rtti SystemTypesystem = - RttiBuilder<model::SystemTypesystem> ("SystemTypesystem").parent(&Typesystem); + RttiBuilder<ousia::SystemTypesystem> ("SystemTypesystem").parent(&Typesystem); } } diff --git a/src/core/model/Typesystem.hpp b/src/core/model/Typesystem.hpp index e0aa81e..1405ed6 100644 --- a/src/core/model/Typesystem.hpp +++ b/src/core/model/Typesystem.hpp @@ -42,10 +42,6 @@ namespace ousia { // Forward declarations class Rtti; - -namespace model { - -// Forward declarations class Typesystem; class SystemTypesystem; @@ -1131,7 +1127,6 @@ public: */ Rooted<BoolType> getBoolType() { return boolType; } }; -} /* RTTI type registrations */ diff --git a/src/core/parser/ParserContext.cpp b/src/core/parser/ParserContext.cpp index fa26c59..0a75fdf 100644 --- a/src/core/parser/ParserContext.cpp +++ b/src/core/parser/ParserContext.cpp @@ -22,15 +22,28 @@ namespace ousia { /* Class ParserContext */ -ParserContext::ParserContext(ParserScope &scope, Registry ®istry, - Logger &logger, Manager &manager, - Handle<model::Project> project) - : scope(scope), - registry(registry), - logger(logger), - manager(manager), - project(project) +ParserContext::ParserContext(Handle<Project> project, ParserScope &scope, + SourceId sourceId, Logger &logger) + : project(project), scope(scope), sourceId(sourceId), logger(logger) { } + +ParserContext::ParserContext(Handle<Project> project, ParserScope &scope, + Logger &logger) + : project(project), scope(scope), sourceId(InvalidSourceId), logger(logger) +{ +} + +ParserContext ParserContext::clone(ParserScope &scope, SourceId sourceId) const +{ + return ParserContext{project, scope, sourceId, logger}; +} + +ParserContext ParserContext::clone(SourceId sourceId) const +{ + return ParserContext{project, scope, sourceId, logger}; +} + +Manager &ParserContext::getManager() const { return project->getManager(); } } diff --git a/src/core/parser/ParserContext.hpp b/src/core/parser/ParserContext.hpp index bb64600..c44222f 100644 --- a/src/core/parser/ParserContext.hpp +++ b/src/core/parser/ParserContext.hpp @@ -28,64 +28,128 @@ #ifndef _OUSIA_PARSER_CONTEXT_HPP_ #define _OUSIA_PARSER_CONTEXT_HPP_ +#include <core/common/Location.hpp> #include <core/managed/Managed.hpp> -#include <core/model/Node.hpp> #include <core/model/Project.hpp> +#include "ParserScope.hpp" + namespace ousia { // Forward declaration class Logger; -class ParserScope; -class Registry; /** - * Struct containing the objects that are passed to a parser instance. + * Class containing the objects that are passed to a parser instance. */ -struct ParserContext { +class ParserContext { +private: /** - * Reference to the ParserScope instance that should be used within the parser. + * Project instance into which the new content should be parsed. */ - ParserScope &scope; + Rooted<Project> project; /** - * Reference to the Registry instance that should be used within the parser. + * Reference to the ParserScope instance that should be used within the + * parser. */ - Registry ®istry; + ParserScope &scope; /** - * Reference to the Logger the parser should log any messages to. + * SourceId is the ID of the resource that is currently being processed. */ - Logger &logger; + SourceId sourceId; /** - * Reference to the Manager the parser should append nodes to. + * Reference to the Logger the parser should log any messages to. */ - Manager &manager; + Logger &logger; +public: /** - * Project instance into which the new content should be parsed. + * Constructor of the ParserContext class. + * + * @param project is the project into which the content should be parsed. + * @param scope is a reference to the ParserScope instance that should be + * used to lookup names. + * @param sourceId is a SourceId instance specifying the source the parser + * is reading from. + * @param logger is a reference to the Logger instance that should be used + * to log error messages and warnings that occur while parsing the document. */ - Rooted<model::Project> project; + ParserContext(Handle<Project> project, ParserScope &scope, + SourceId sourceId, Logger &logger); /** - * Constructor of the ParserContext class. + * Constructor of the ParserContext class with the sourceId being set + * to the InvalidSourceId value. * + * @param project is the project into which the content should be parsed. * @param scope is a reference to the ParserScope instance that should be * used to lookup names. - * @param registry is a reference at the Registry class, which allows to - * obtain references at parsers for other formats or script engine - * implementations. * @param logger is a reference to the Logger instance that should be used * to log error messages and warnings that occur while parsing the document. - * @param manager is a Reference to the Manager the parser should append - * nodes to. - * @param project is the project into which the content should be parsed. */ - ParserContext(ParserScope &scope, Registry ®istry, Logger &logger, - Manager &manager, Handle<model::Project> project); -}; + ParserContext(Handle<Project> project, ParserScope &scope, + Logger &logger); + + /** + * Clones the ParserContext instance but exchanges the ParserScope instance + * and the source id. + * + * @param scope is a reference at the new ParserScope instance. + * @param sourceId is the source id the parser is reading from. + * @return a copy of this ParserContext with exchanged scope and source id. + */ + ParserContext clone(ParserScope &scope, SourceId sourceId) const; + /** + * Clones the ParserContext instance but exchanges the source id. + * + * @param sourceId is the source id the parser is reading from. + * @return a copy of this ParserContext with exchanged source id. + */ + ParserContext clone(SourceId sourceId) const; + + /** + * Returns a handle pointing at the Project node. + * + * @return a project node handle. + */ + Rooted<Project> getProject() const { return project; } + + /** + * Returns a reference pointing at the current ParserScope instance. + * + * @return a reference at the parser scope object that should be used during + * the parsing process. + */ + ParserScope &getScope() const { return scope; } + + /** + * Returns a reference pointing at the current LoggerInstance. + * + * @return a reference at LoggerInstance to which all error messages should + * be logged. + */ + Logger &getLogger() const { return logger; } + + /** + * Returns a reference pointing at the manager instance that should be used + * when creating new Managed objects. + * + * @return a reference pointing at the underlying Manager instance. + */ + Manager &getManager() const; + + /** + * Returns the SourceId instance which specifies the source file the parser + * is currently reading from. + * + * @return the current source id. + */ + SourceId getSourceId() const { return sourceId; } +}; } #endif /* _OUSIA_PARSER_CONTEXT_HPP_ */ diff --git a/src/core/parser/ParserScope.hpp b/src/core/parser/ParserScope.hpp index a759738..c1369dd 100644 --- a/src/core/parser/ParserScope.hpp +++ b/src/core/parser/ParserScope.hpp @@ -41,7 +41,6 @@ namespace ousia { // Forward declaration class CharReader; -class Registry; class Logger; class ParserScope; diff --git a/src/core/parser/ParserStack.cpp b/src/core/parser/ParserStack.cpp index 3792ee8..02b142a 100644 --- a/src/core/parser/ParserStack.cpp +++ b/src/core/parser/ParserStack.cpp @@ -22,6 +22,7 @@ #include <core/common/Utils.hpp> #include <core/common/Exceptions.hpp> +#include <core/model/Project.hpp> namespace ousia { @@ -74,7 +75,7 @@ HandlerInstance HandlerDescriptor::create(const ParserContext &ctx, } // Canonicalize the arguments - arguments.validateMap(args, ctx.logger, true); + arguments.validateMap(args, ctx.getLogger(), true); h->start(args); return HandlerInstance(h, this); diff --git a/src/core/parser/ParserStack.hpp b/src/core/parser/ParserStack.hpp index 6296dff..031ce68 100644 --- a/src/core/parser/ParserStack.hpp +++ b/src/core/parser/ParserStack.hpp @@ -139,15 +139,13 @@ public: const std::string &name() { return handlerData.name; } - ParserScope &scope() { return handlerData.ctx.scope; } + ParserScope &scope() { return handlerData.ctx.getScope(); } - Registry ®istry() { return handlerData.ctx.registry; } + Manager &manager() { return handlerData.ctx.getManager(); } - Manager &manager() { return handlerData.ctx.manager; } + Logger &logger() { return handlerData.ctx.getLogger(); } - Logger &logger() { return handlerData.ctx.logger; } - - Rooted<model::Project> project() { return handlerData.ctx.project; } + Rooted<Project> project() { return handlerData.ctx.getProject(); } State state() { return handlerData.state; } @@ -322,11 +320,6 @@ private: std::stack<HandlerInstance> stack; /** - * Reference at some user defined data. - */ - void *userData; - - /** * Used internally to get all expected command names for the given state * (does not work if the current Handler instance allows arbitrary * children). This function is used to build error messages. @@ -345,9 +338,8 @@ public: * corresponding HandlerDescriptor instances. */ ParserStack(ParserContext &ctx, - const std::multimap<std::string, HandlerDescriptor> &handlers, - void *userData = nullptr) - : ctx(ctx), handlers(handlers), userData(userData){}; + const std::multimap<std::string, HandlerDescriptor> &handlers) + : ctx(ctx), handlers(handlers){}; /** * Returns the state the ParserStack instance currently is in. @@ -425,13 +417,6 @@ public: * @return a reference to the parser context. */ ParserContext &getContext() { return ctx; } - - /** - * Returns the user defined data. - * - * @return the userData pointer that was given in the constructor. - */ - void *getUserData() { return userData; } }; } diff --git a/src/core/resource/Resource.cpp b/src/core/resource/Resource.cpp index 349c82a..ff3c77f 100644 --- a/src/core/resource/Resource.cpp +++ b/src/core/resource/Resource.cpp @@ -16,11 +16,39 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include <core/common/Utils.hpp> + #include "Resource.hpp" #include "ResourceLocator.hpp" namespace ousia { +/* Helper functions for the internal maps */ + +static std::unordered_map<ResourceType, std::string, Utils::EnumHash> reverseMap( + const std::unordered_map<std::string, ResourceType> &m) +{ + std::unordered_map<ResourceType, std::string, Utils::EnumHash> res; + for (auto e : m) { + res.emplace(e.second, e.first); + } + return res; +} + +/* Internal maps */ + +static const std::unordered_map<std::string, ResourceType> + NAME_RESOURCE_TYPE_MAP{{"document", ResourceType::DOCUMENT}, + {"domain", ResourceType::DOMAIN_DESC}, + {"typesystem", ResourceType::TYPESYSTEM}, + {"attributes", ResourceType::ATTRIBUTES}, + {"stylesheet", ResourceType::STYLESHEET}, + {"script", ResourceType::SCRIPT}, + {"data", ResourceType::DATA}}; + +static const std::unordered_map<ResourceType, std::string, Utils::EnumHash> + RESOURCE_TYPE_NAME_MAP = reverseMap(NAME_RESOURCE_TYPE_MAP); + /* Class Resource */ Resource::Resource() @@ -39,6 +67,32 @@ std::unique_ptr<std::istream> Resource::stream() const return locator->stream(location); } +std::string Resource::getResourceTypeName(ResourceType resourceType) +{ + auto it = RESOURCE_TYPE_NAME_MAP.find(resourceType); + if (it != RESOURCE_TYPE_NAME_MAP.end()) { + return it->second; + } + return "unknown"; +} + +ResourceType Resource::getResourceTypeByName(const std::string &name) +{ + std::string normName = Utils::toLower(name); + auto it = NAME_RESOURCE_TYPE_MAP.find(normName); + if (it != NAME_RESOURCE_TYPE_MAP.end()) { + return it->second; + } + return ResourceType::UNKNOWN; +} + +/* Operators */ + +std::ostream &operator<<(std::ostream &os, ResourceType resourceType) +{ + return os << Resource::getResourceTypeName(resourceType); +} + /* NullResource instance */ const Resource NullResource{}; diff --git a/src/core/resource/Resource.hpp b/src/core/resource/Resource.hpp index 1934029..63ed591 100644 --- a/src/core/resource/Resource.hpp +++ b/src/core/resource/Resource.hpp @@ -30,6 +30,7 @@ #include <map> #include <memory> +#include <ostream> #include <string> namespace ousia { @@ -169,9 +170,36 @@ public: * a resource. */ const std::string &getLocation() const { return location; } + + /** + * Returns the name of the given resource type. + * + * @param resourceType is the ResourceType of which the human readable name + * should be returned. + * @return the human readable name of the ResourceType. + */ + static std::string getResourceTypeName(ResourceType resourceType); + + /** + * Returns a resourceType by its name or ResourceType::UNKNOWN if the name + * is invalid. + * + * @param name is the name of the resource type. The name is converted to + * lowercase. + */ + static ResourceType getResourceTypeByName(const std::string &name); }; /** + * Operator used for streaming the name of ResourceType instances. + * + * @param os is the output stream. + * @param resourceType is the type that should be serialized. + * @return the output stream. + */ +std::ostream& operator<<(std::ostream &os, ResourceType resourceType); + +/** * Invalid resource instance. */ extern const Resource NullResource; diff --git a/src/core/resource/ResourceManager.cpp b/src/core/resource/ResourceManager.cpp index 184a16d..03fd65b 100644 --- a/src/core/resource/ResourceManager.cpp +++ b/src/core/resource/ResourceManager.cpp @@ -25,33 +25,17 @@ #include <core/common/SourceContextReader.hpp> #include <core/common/Utils.hpp> #include <core/model/Node.hpp> -#include <core/parser/ParserContext.hpp> +#include <core/model/Project.hpp> #include <core/parser/Parser.hpp> +#include <core/parser/ParserContext.hpp> +#include <core/parser/ParserScope.hpp> #include <core/Registry.hpp> #include "ResourceManager.hpp" -#include "ResourceUtils.hpp" +#include "ResourceRequest.hpp" namespace ousia { -/* Static helper functions */ - -static void logUnsopportedType(Logger &logger, Resource &resource, - const RttiSet &supportedTypes) -{ - // Build a list containing the expected type names - std::vector<std::string> expected; - for (const Rtti *supportedType : supportedTypes) { - expected.push_back(supportedType->name); - } - - // Log the actual error message - logger.error( - std::string("Expected the file \"") + resource.getLocation() + - std::string("\" to define one of the following internal types ") + - Utils::join(expected, ", ", "{", "}")); -} - /* Class ResourceManager */ SourceId ResourceManager::allocateSourceId(const Resource &resource) @@ -86,39 +70,14 @@ void ResourceManager::purgeResource(SourceId sourceId) contextReaders.erase(sourceId); } -Rooted<Node> ResourceManager::parse(ParserContext &ctx, Resource &resource, - const std::string &mimetype, - const RttiSet &supportedTypes) +Rooted<Node> ResourceManager::parse(Registry ®istry, ParserContext &ctx, + const ResourceRequest &req, ParseMode mode) { - // Try to deduce the mimetype of no mimetype was given - std::string mime = mimetype; - if (mime.empty()) { - mime = ctx.registry.getMimetypeForFilename(resource.getLocation()); - if (mime.empty()) { - ctx.logger.error(std::string("Filename \"") + - resource.getLocation() + - std::string( - "\" has an unknown file extension. Explicitly " - "specify a mimetype.")); - return nullptr; - } - } - - // Fetch a parser for the mimetype - const std::pair<Parser *, RttiSet> &parserDescr = - ctx.registry.getParserForMimetype(mime); - Parser *parser = parserDescr.first; - - // Make sure a parser was found - if (!parser) { - ctx.logger.error(std::string("Cannot parse files of type \"") + mime + - std::string("\"")); - return nullptr; - } - - // Make sure the parser returns at least one of the supported types - if (!Rtti::setIsOneOf(parserDescr.second, supportedTypes)) { - logUnsopportedType(ctx.logger, resource, supportedTypes); + // Locate the resource relative to the old resource, abort if this did not + // work + Resource resource; + if (!req.locate(registry, ctx.getLogger(), resource, + getResource(ctx.getSourceId()))) { return nullptr; } @@ -129,16 +88,31 @@ Rooted<Node> ResourceManager::parse(ParserContext &ctx, Resource &resource, Rooted<Node> node; try { // Set the current source id in the logger instance - GuardedLogger logger(ctx.logger, SourceLocation{sourceId}); - - // Fetch the input stream and create a char reader - std::unique_ptr<std::istream> is = resource.stream(); - CharReader reader(*is, sourceId); - - // Actually parse the input stream - node = parser->parse(reader, ctx); + { + GuardedLogger logger(ctx.getLogger(), SourceLocation{sourceId}); + + // Fetch the input stream and create a char reader + std::unique_ptr<std::istream> is = resource.stream(); + CharReader reader(*is, sourceId); + + // Actually parse the input stream, distinguish the LINK and the + // INCLUDE + // mode + switch (mode) { + case ParseMode::LINK: { + ParserScope scope; // New empty parser scope instance + ParserContext childCtx = ctx.clone(scope, sourceId); + node = req.getParser()->parse(reader, childCtx); + } + case ParseMode::INCLUDE: { + ParserContext childCtx = ctx.clone(sourceId); + node = req.getParser()->parse(reader, childCtx); + } + } + } if (node == nullptr) { - throw LoggableException{"Internal error: Parser returned null."}; + throw LoggableException{"File \"" + resource.getLocation() + + "\" cannot be parsed."}; } } catch (LoggableException ex) { @@ -146,17 +120,66 @@ Rooted<Node> ResourceManager::parse(ParserContext &ctx, Resource &resource, purgeResource(sourceId); // Log the exception and return nullptr - ctx.logger.log(ex); + ctx.getLogger().log(ex); return nullptr; } - // Store the parsed node along with the sourceId - storeNode(sourceId, node); + // Store the parsed node along with the sourceId, if we are in the LINK mode + if (mode == ParseMode::LINK) { + storeNode(sourceId, node); + } // Return the parsed node return node; } +Rooted<Node> ResourceManager::link(Registry ®istry, ParserContext &ctx, + const std::string &path, + const std::string &mimetype, + const std::string &rel, + const RttiSet &supportedTypes) +{ + ResourceRequest req{path, mimetype, rel, supportedTypes}; + if (req.deduce(registry, ctx.getLogger())) { + return parse(registry, ctx, req, ParseMode::LINK); + } + return nullptr; +} + +Rooted<Node> ResourceManager::include(Registry ®istry, ParserContext &ctx, + const std::string &path, + const std::string &mimetype, + const std::string &rel, + const RttiSet &supportedTypes) +{ + ResourceRequest req{path, mimetype, rel, supportedTypes}; + if (req.deduce(registry, ctx.getLogger())) { + return parse(registry, ctx, req, ParseMode::INCLUDE); + } + return nullptr; +} + +SourceContext ResourceManager::readContext(const SourceLocation &location, + size_t maxContextLength) +{ + const Resource &resource = getResource(location.getSourceId()); + if (resource.isValid()) { + // Fetch a char reader for the resource + std::unique_ptr<std::istream> is = resource.stream(); + CharReader reader{*is, location.getSourceId()}; + + // Return the context + return contextReaders[location.getSourceId()].readContext( + reader, location, maxContextLength, resource.getLocation()); + } + return SourceContext{}; +} + +SourceContext ResourceManager::readContext(const SourceLocation &location) +{ + return readContext(location, SourceContextReader::MAX_MAX_CONTEXT_LENGTH); +} + SourceId ResourceManager::getSourceId(const std::string &location) { auto it = locations.find(location); @@ -187,7 +210,7 @@ Rooted<Node> ResourceManager::getNode(Manager &mgr, SourceId sourceId) { auto it = nodes.find(sourceId); if (it != nodes.end()) { - Managed *managed = mgr.getManaged(sourceId); + Managed *managed = mgr.getManaged(it->second); if (managed != nullptr) { return dynamic_cast<Node *>(managed); } else { @@ -206,86 +229,5 @@ Rooted<Node> ResourceManager::getNode(Manager &mgr, const Resource &resource) { return getNode(mgr, getSourceId(resource)); } - -Rooted<Node> ResourceManager::link(ParserContext &ctx, const std::string &path, - const std::string &mimetype, - const std::string &rel, - const RttiSet &supportedTypes, - const Resource &relativeTo) -{ - // Try to deduce the ResourceType - ResourceType resourceType = - ResourceUtils::deduceResourceType(rel, supportedTypes, ctx.logger); - - // Lookup the resource for given path and resource type - Resource resource; - if (!ctx.registry.locateResource(resource, path, resourceType, - relativeTo)) { - ctx.logger.error("File \"" + path + "\" not found."); - return nullptr; - } - - // Try to shrink the set of supportedTypes - RttiSet types = ResourceUtils::limitRttiTypes(supportedTypes, rel); - - // Check whether the resource has already been parsed - Rooted<Node> node = getNode(ctx.manager, resource); - if (node == nullptr) { - // Node has not already been parsed, parse it now - node = parse(ctx, resource, mimetype, supportedTypes); - - // Abort if parsing failed - if (node == nullptr) { - return nullptr; - } - } - - // Make sure the node has one of the supported types - if (!node->type().isOneOf(supportedTypes)) { - logUnsopportedType(ctx.logger, resource, supportedTypes); - return nullptr; - } - - return node; -} - -Rooted<Node> ResourceManager::link(ParserContext &ctx, const std::string &path, - const std::string &mimetype, - const std::string &rel, - const RttiSet &supportedTypes, - SourceId relativeTo) -{ - // Fetch the resource corresponding to the source id, make sure it is valid - const Resource &relativeResource = getResource(relativeTo); - if (!relativeResource.isValid()) { - ctx.logger.fatalError("Internal error: Invalid SourceId supplied."); - return nullptr; - } - - // Continue with the usual include routine - return link(ctx, path, mimetype, rel, supportedTypes, relativeResource); -} - -SourceContext ResourceManager::readContext(const SourceLocation &location, - size_t maxContextLength) -{ - const Resource &resource = getResource(location.getSourceId()); - if (resource.isValid()) { - // Fetch a char reader for the resource - std::unique_ptr<std::istream> is = resource.stream(); - CharReader reader{*is, location.getSourceId()}; - - // Return the context - return contextReaders[location.getSourceId()].readContext( - reader, location, maxContextLength, resource.getLocation()); - } - return SourceContext{}; -} - -SourceContext ResourceManager::readContext(const SourceLocation &location) -{ - return readContext(location, SourceContextReader::MAX_MAX_CONTEXT_LENGTH); -} - } diff --git a/src/core/resource/ResourceManager.hpp b/src/core/resource/ResourceManager.hpp index 221e2cc..6cb3249 100644 --- a/src/core/resource/ResourceManager.hpp +++ b/src/core/resource/ResourceManager.hpp @@ -34,6 +34,7 @@ #include <core/common/Location.hpp> #include <core/common/Rtti.hpp> +#include <core/common/SourceContextReader.hpp> #include <core/managed/Managed.hpp> #include "Resource.hpp" @@ -41,8 +42,11 @@ namespace ousia { // Forward declarations +class Registry; class Node; +class Parser; class ParserContext; +class ResourceRequest; extern const Resource NullResource; /** @@ -51,6 +55,12 @@ extern const Resource NullResource; * and returns references for those resources that already have been parsed. */ class ResourceManager { +public: + /** + * Used internally to set the mode of the Parse function. + */ + enum class ParseMode { LINK, INCLUDE }; + private: /** * Next SourceId to be used. @@ -105,25 +115,113 @@ private: void purgeResource(SourceId sourceId); /** - * Used internally to parse the given resource. + * Used internally to parse the given resource. Can either operate in the + * "link" or the "include" mode. In the latter case the ParserScope instance + * inside the ParserContext is exchanged with an empty one. + * + * @param registry is the registry that should be used to locate the + * resource. + * @param ctx is the context that should be passed to the parser. + * @param req is a ResourceRequest instance that contains all information + * about the requested resource. + * @param mode describes whether the file should be included or linked. + * @return the parsed node or nullptr if something goes wrong. + */ + Rooted<Node> parse(Registry ®istry, ParserContext &ctx, + const ResourceRequest &req, ParseMode mode); + +public: + /** + * Resolves the reference to the file specified by the given path and -- if + * this has not already happened -- parses the file. The parser that is + * called is provided a new ParserContext instance with an empty ParserScope + * which allows the Node instance returned by the parser to be cached. Logs + * any problem in the logger instance of the given ParserContext. + * + * @param registry is the registry instance that should be used to lookup + * the parser instances and to locate the resources. + * @param ctx is the context from which the Logger instance will be looked + * up. This context instance is not directly passed to the Parser, the + * ParserScope instance is replaced with a new one. The sourceId specified + * in the context instance will be used as relative location for looking up + * the new resource. + * @param mimetype is the mimetype of the resource that should be parsed + * (may be empty, in which case the mimetype is deduced from the file + * extension) + * @param rel is a "relation string" supplied by the user which specifies + * the relationship of the specified resource. + * @param supportedTypes contains the types of the returned Node the caller + * can deal with. Note that only the types the parser claims to return are + * checked, not the actual result. + * @return the parsed node or nullptr if something goes wrong. + */ + Rooted<Node> link(Registry ®istry, ParserContext &ctx, + const std::string &path, const std::string &mimetype = "", + const std::string &rel = "", + const RttiSet &supportedTypes = RttiSet{}); + + /** + * Resolves the reference to the file specified by the given path and parses + * the file using the provided context. As the result of the "include" + * function depends on the ParserScope inside the provided ParserContext + * instance, the resource has to be parsed every time this function is + * called. This contasts the behaviour of the "link" function, which creates + * a new ParserScope and thus guarantees reproducible results. Logs any + * problem in the logger instance of the given ParserContext. * - * @param ctx is the context from the Registry and the Logger instance will - * be looked up. - * @param resource is the resource from which the input stream should be - * obtained. + * @param registry is the registry instance that should be used to lookup + * the parser instances and to locate the resources. + * @param ctx is the context from which the Logger instance will be looked + * up. The sourceId specified in the context instance will be used as + * relative location for looking up the new resource. + * @param path is the requested path of the file that should be included. * @param mimetype is the mimetype of the resource that should be parsed * (may be empty, in which case the mimetype is deduced from the file * extension) + * @param rel is a "relation string" supplied by the user which specifies + * the relationship of the specified resource. * @param supportedTypes contains the types of the returned Node the caller * can deal with. Note that only the types the parser claims to return are * checked, not the actual result. * @return the parsed node or nullptr if something goes wrong. */ - Rooted<Node> parse(ParserContext &ctx, Resource &resource, - const std::string &mimetype, - const RttiSet &supportedTypes); + Rooted<Node> include(Registry ®istry, ParserContext &ctx, + const std::string &path, + const std::string &mimetype = "", + const std::string &rel = "", + const RttiSet &supportedTypes = RttiSet{}); + + /** + * Creates and returns a SourceContext structure containing information + * about the given SourceLocation (such as line and column number). Throws + * a LoggableException if an irrecoverable error occurs while looking up the + * context (such as a no longer existing resource). + * + * @param location is the SourceLocation for which context information + * should be retrieved. This method is used by the Logger class to print + * pretty messages. + * @param maxContextLength is the maximum length in character of context + * that should be extracted. + * @return a valid SourceContext if a valid SourceLocation was given or an + * invalid SourceContext if the location is invalid. + */ + SourceContext readContext(const SourceLocation &location, + size_t maxContextLength); + /** + * Creates and returns a SourceContext structure containing information + * about the given SourceLocation (such as line and column number). Throws + * a LoggableException if an irrecoverable error occurs while looking up the + * context (such as a no longer existing resource). Does not limit the + * context length. + * + * @param location is the SourceLocation for which context information + * should be retrieved. This method is used by the Logger class to print + * pretty messages. + * @return a valid SourceContext if a valid SourceLocation was given or an + * invalid SourceContext if the location is invalid. + */ + SourceContext readContext(const SourceLocation &location); -public: /** * Returns the sourceId for the given location string. * @@ -188,63 +286,6 @@ public: * @return the Node instance corresponding to the given resource. */ Rooted<Node> getNode(Manager &mgr, const Resource &resource); - - /** - * Resolves the reference to the file specified by the given path and -- if - * this has not already happened -- parses the file. Logs any problem in - * the logger instance of the given ParserContext. - * - * @param ctx is the context from the Registry and the Logger instance will - * be looked up. - * @param path is the path to the file that should be included. - * @param mimetype is the mimetype the file was included with. If no - * mimetype is given, the path must have an extension that is known by - */ - Rooted<Node> link(ParserContext &ctx, const std::string &path, - const std::string &mimetype = "", - const std::string &rel = "", - const RttiSet &supportedTypes = RttiSet{}, - const Resource &relativeTo = NullResource); - - /** - * Resolves the reference to the file specified by the given path and -- if - * this has not already happened -- parses the file. Logs any problem in - * the logger instance of the given ParserContext. - */ - Rooted<Node> link(ParserContext &ctx, const std::string &path, - const std::string &mimetype, const std::string &rel, - const RttiSet &supportedTypes, SourceId relativeTo); - - /** - * Creates and returns a SourceContext structure containing information - * about the given SourceLocation (such as line and column number). Throws - * a LoggableException if an irrecoverable error occurs while looking up the - * context (such as a no longer existing resource). - * - * @param location is the SourceLocation for which context information - * should be retrieved. This method is used by the Logger class to print - * pretty messages. - * @param maxContextLength is the maximum length in character of context - * that should be extracted. - * @return a valid SourceContext if a valid SourceLocation was given or an - * invalid SourceContext if the location is invalid. - */ - SourceContext readContext(const SourceLocation &location, - size_t maxContextLength); - /** - * Creates and returns a SourceContext structure containing information - * about the given SourceLocation (such as line and column number). Throws - * a LoggableException if an irrecoverable error occurs while looking up the - * context (such as a no longer existing resource). Does not limit the - * context length. - * - * @param location is the SourceLocation for which context information - * should be retrieved. This method is used by the Logger class to print - * pretty messages. - * @return a valid SourceContext if a valid SourceLocation was given or an - * invalid SourceContext if the location is invalid. - */ - SourceContext readContext(const SourceLocation &location); }; } diff --git a/src/core/resource/ResourceRequest.cpp b/src/core/resource/ResourceRequest.cpp new file mode 100644 index 0000000..b047082 --- /dev/null +++ b/src/core/resource/ResourceRequest.cpp @@ -0,0 +1,238 @@ +/* + Ousía + Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +#include <string> + +#include <core/common/Logger.hpp> +#include <core/common/Rtti.hpp> +#include <core/common/Utils.hpp> +#include <core/resource/Resource.hpp> +#include <core/resource/Resource.hpp> +#include <core/Registry.hpp> + +#include "ResourceRequest.hpp" + +namespace ousia { + +namespace RttiTypes { +extern const Rtti Document; +extern const Rtti Domain; +extern const Rtti Node; +extern const Rtti Typesystem; +} + +/** + * Map mapping from Rtti pointers to the corresponding ResourceType. + */ +static const std::unordered_map<const Rtti *, ResourceType> + RTTI_RESOURCE_TYPE_MAP{{&RttiTypes::Document, ResourceType::DOCUMENT}, + {&RttiTypes::Domain, ResourceType::DOMAIN_DESC}, + {&RttiTypes::Typesystem, ResourceType::TYPESYSTEM}}; + +/** + * Function used internally to build a set with all currently supported + * ResourceType instances. + * + * @param supportedTypes are all supported types. + * @return a set containing all ResourceTypes that can be used for these + * RTTI descriptors. + */ +static const std::unordered_set<ResourceType, Utils::EnumHash> +supportedResourceTypes(const RttiSet &supportedTypes) +{ + std::unordered_set<ResourceType, Utils::EnumHash> res; + for (const Rtti *supportedType : supportedTypes) { + auto it = RTTI_RESOURCE_TYPE_MAP.find(supportedType); + if (it != RTTI_RESOURCE_TYPE_MAP.end()) { + res.insert(it->second); + } + } + return res; +} + +/** + * Converts a set of supported RTTI descriptors to a string describing the + * corresponding ResourceTypes. + * + * @param supportedTypes are all supported types. + * @return a string containing all corresponding resource types. + */ +static std::string supportedResourceTypesString(const RttiSet &supportedTypes) +{ + return Utils::join(supportedResourceTypes(supportedTypes), ", ", "{", "}"); +} + +/** + * Tries to deduce the resource type from the given set of supported types. + * Returns ResourceType::UNKNOWN if there are ambiguities. + * + * @param supportedTypes are all supported types. + * @return the deduced ResourceType or ResourceType::UNKNOWN if there was an + * ambiguity. + */ +static ResourceType deduceResourceType(const RttiSet &supportedTypes) +{ + ResourceType resourceType = ResourceType::UNKNOWN; + for (const Rtti *supportedType : supportedTypes) { + auto it = RTTI_RESOURCE_TYPE_MAP.find(supportedType); + if (it != RTTI_RESOURCE_TYPE_MAP.end()) { + // Preven ambiguity + if (resourceType != ResourceType::UNKNOWN && + resourceType != it->second) { + resourceType = ResourceType::UNKNOWN; + break; + } + resourceType = it->second; + } + } + return resourceType; +} + +/** + * Function used to limit the supportedTypes to those that correspond to the + * ResourceType. + * + * @param resourceType is the type of the resource type that is going to be + * included. + * @param supportedTypes are all supported types. + * @return a restricted set of supportedTypes that correspond to the + * resourceType. + */ +static RttiSet limitSupportedTypes(ResourceType resourceType, + const RttiSet &supportedTypes) +{ + // Calculate the expected types + RttiSet expectedTypes; + for (auto entry : RTTI_RESOURCE_TYPE_MAP) { + if (entry.second == resourceType) { + expectedTypes.insert(entry.first); + } + } + + // Restrict the supported types to the expected types + return Rtti::setIntersection(supportedTypes, expectedTypes); +} + +/* Class ResourceRequest */ + +ResourceRequest::ResourceRequest(const std::string &path, + const std::string &mimetype, + const std::string &rel, + const RttiSet &supportedTypes) + : path(path), + mimetype(mimetype), + rel(rel), + supportedTypes(supportedTypes), + resourceType(ResourceType::UNKNOWN), + parser(nullptr) +{ +} + +bool ResourceRequest::deduce(Registry ®istry, Logger &logger) +{ + bool ok = true; + + // Try to deduce the mimetype if none was given + if (mimetype.empty()) { + mimetype = registry.getMimetypeForFilename(path); + if (mimetype.empty()) { + logger.error(std::string("Filename \"") + path + + std::string( + "\" has an unknown file extension. Explicitly " + "specify a mimetype.")); + ok = false; + } + } + + // Find a parser for the mimetype + if (!mimetype.empty()) { + auto parserDescr = registry.getParserForMimetype(mimetype); + parser = parserDescr.first; + parserTypes = parserDescr.second; + + // Make sure a valid parser was returned, and if yes, whether the + // parser is allows to run here + if (!parser) { + logger.error(std::string("Cannot parse files of type \"") + + mimetype + std::string("\"")); + ok = false; + } else if (!Rtti::setIsOneOf(parserTypes, supportedTypes)) { + logger.error(std::string("Resource of type \"") + mimetype + + std::string("\" cannot be included here!")); + ok = false; + } + } + + // Limit the supportedTypes to those returned by the parser + supportedTypes = Rtti::setIntersection(supportedTypes, parserTypes); + if (supportedTypes.empty()) { + logger.error(std::string("Cannot include or link a file of type \"") + + mimetype + std::string("\" here!")); + ok = false; + } + + // Try to deduce the ResourceType from the "rel" string + if (!rel.empty()) { + resourceType = Resource::getResourceTypeByName(rel); + if (resourceType == ResourceType::UNKNOWN) { + logger.error(std::string("Unknown relation \"") + rel + + std::string("\", expected one of ") + + supportedResourceTypesString(supportedTypes)); + ok = false; + } + } + + // Try to deduce the ResourceType from the supportedTypes + if (resourceType == ResourceType::UNKNOWN) { + resourceType = deduceResourceType(supportedTypes); + } + + // Further limit the supportedTypes to those types that correspond to the + // specified resource type. + if (resourceType != ResourceType::UNKNOWN) { + supportedTypes = limitSupportedTypes(resourceType, supportedTypes); + if (supportedTypes.empty()) { + logger.error( + std::string("File of type \"") + mimetype + + std::string("\" cannot be included with relationship ") + + Resource::getResourceTypeName(resourceType)); + ok = false; + } + } else { + // Issue a warning if the resource type is unknown + logger.warning(std::string( + "Ambiguous resource relationship, consider " + "specifying one of ") + + supportedResourceTypesString(supportedTypes) + + std::string(" as \"rel\" attribute")); + } + + return ok; +} + +bool ResourceRequest::locate(Registry ®istry, Logger &logger, + Resource &resource, + const Resource &relativeTo) const +{ + if (!registry.locateResource(resource, path, resourceType, relativeTo)) { + logger.error(std::string("File not found: ") + path); + return false; + } + return true; +} +} + diff --git a/src/core/resource/ResourceRequest.hpp b/src/core/resource/ResourceRequest.hpp new file mode 100644 index 0000000..9d5728f --- /dev/null +++ b/src/core/resource/ResourceRequest.hpp @@ -0,0 +1,197 @@ +/* + Ousía + Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * @file ResourceRequest.hpp + * + * Defines the ResourceRequest class used by the ResourceManager to deduce as + * much information as possible about a resource that was included by the user. + * + * @author Andreas Stöckel (astoecke@techfak.uni-bielefeld.de) + */ + +#ifndef _OUSIA_RESOURCE_REQUEST_HPP_ +#define _OUSIA_RESOURCE_REQUEST_HPP_ + +#include <string> + +#include <core/common/Rtti.hpp> +#include <core/resource/Resource.hpp> + +namespace ousia { + +// Forward declarations +class Logger; +class Parser; +class Registry; + +/** + * The ResourceRequest class contains user provided data about a Resource that + * should be opened and parsed. The ResourceRequest class can then be used to + * deduce missing information about the resource and finally to locate the + * Resource in the filesystem and to find a parser that is capable of parsing + * the Resource. + */ +class ResourceRequest { +private: + /** + * Requested path of the file that should be included. + */ + std::string path; + + /** + * Mimetype of the resource that should be parsed. + */ + std::string mimetype; + + /** + * Relation string specifing the relationship of the resource within the + * document it is included in. + */ + std::string rel; + + /** + * Specifies the types of the Node that may result from the resource once it + * has been parsed. + */ + RttiSet supportedTypes; + + /** + * Types the parser is expected to return. + */ + RttiSet parserTypes; + + /** + * ResourceType as deduced from the user provided values. + */ + ResourceType resourceType; + + /** + * Pointer at the Parser instance that may be used to parse the resource. + */ + Parser *parser; + +public: + /** + * Constructor of the ResourceRequest class. Takes the user provided data + * about the resource request. + * + * @param path is the requested path of the file that should be included. + * @param mimetype is the mimetype of the resource that should be parsed + * (may be empty, in which case the mimetype is deduced from the file + * extension) + * @param rel is a "relation string" supplied by the user which specifies + * the relationship of the specified resource within the document it is + * included in. + * @param supportedTypes specifies the types of the Node that may result + * from the resource once it has been parsed. This value is not directly + * provided by the user, but by the calling code. + */ + ResourceRequest(const std::string &path, const std::string &mimetype, + const std::string &rel, const RttiSet &supportedTypes); + + /** + * Tries to deduce all possible information and produces log messages for + * the user. + * + * @param registry from which registered parsers, mimetypes and file + * extensions are looked up. + * @param logger is the logger instance to which errors or warnings are + * logged. + * @return true if a parser has been found that could potentially be used to + * parse the file. + */ + bool deduce(Registry ®istry, Logger &logger); + + /** + * Tries to locate the specified resource. + * + * @param registry from which registered parsers, mimetypes and file + * extensions are looked up. + * @param logger is the logger instance to which errors or warnings are + * logged. + * @param resource is the Resource descriptor that should be filled with the + * actual location. + * @param relativeTo is another resource relative to which the Resource + * should be looked up. + * @return true if a resource was found, false otherwise. Equivalent to + * the value of resource.isValid(). + */ + bool locate(Registry ®istry, Logger &logger, Resource &resource, + const Resource &relativeTo = NullResource) const; + + /** + * Returns the requested path of the file that should be included. + * + * @param path given by the user (not the location of an actually found + * resource). + */ + const std::string &getPath() const { return path; } + + /** + * Returns the mimetype of the resource that should be parsed. + * + * @return the deduced mimetype. + */ + const std::string &getMimetype() const { return mimetype; } + + /** + * Returns the relation string which specifies the relationship of the + * resource within the document it is included in. + * + * @return the deduced relation string. + */ + const std::string &getRel() const { return rel; } + + /** + * Returns the types of the Node that may result from the resource once it + * has been parsed. Restricted to the types that may actually returned by + * the parser. + * + * @return the deduced supported types. + */ + const RttiSet &getSupportedTypes() const { return supportedTypes; } + + /** + * Returns the ResourceType as deduced from the user provided values. + * + * @return deduced ResourceType or ResourceType::UNKNOWN if none could be + * deduced. + */ + ResourceType getResourceType() const { return resourceType; } + + /** + * Returns the parser that was deduced according to the given resource + * descriptors. + * + * @return the pointer at the parser instance or nullptr if none was found. + */ + Parser *getParser() const { return parser; } + + /** + * Returns the types the parser may return or an empty set if no parser was + * found. + * + * @return the types the parser may return. + */ + RttiSet getParserTypes() const { return parserTypes; } +}; +} + +#endif /* _OUSIA_RESOURCE_REQUEST_HPP_ */ + diff --git a/src/core/resource/ResourceUtils.cpp b/src/core/resource/ResourceUtils.cpp deleted file mode 100644 index 7c42716..0000000 --- a/src/core/resource/ResourceUtils.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* - Ousía - Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. -*/ - -#include <core/common/Logger.hpp> -#include <core/common/Rtti.hpp> -#include <core/common/Utils.hpp> - -#include "ResourceUtils.hpp" - -namespace ousia { - -namespace RttiTypes { -extern const Rtti Document; -extern const Rtti Domain; -extern const Rtti Node; -extern const Rtti Typesystem; -} - -/** - * Map mapping from relations (the "rel" attribute in includes) to the - * corresponding ResourceType. - */ -static const std::unordered_map<std::string, ResourceType> RelResourceTypeMap{ - {"document", ResourceType::DOCUMENT}, - {"domain", ResourceType::DOMAIN_DESC}, - {"typesystem", ResourceType::TYPESYSTEM}}; - -/** - * Map mapping from relations to the corresponding Rtti descriptor. - */ -static const std::unordered_map<std::string, const Rtti *> RelRttiTypeMap{ - {"document", &RttiTypes::Document}, - {"domain", &RttiTypes::Domain}, - {"typesystem", &RttiTypes::Typesystem}}; - -/** - * Map mapping from Rtti pointers to the corresponding ResourceType. - */ -static const std::unordered_map<const Rtti *, ResourceType> RttiResourceTypeMap{ - {&RttiTypes::Document, ResourceType::DOCUMENT}, - {&RttiTypes::Domain, ResourceType::DOMAIN_DESC}, - {&RttiTypes::Typesystem, ResourceType::TYPESYSTEM}}; - -ResourceType ResourceUtils::deduceResourceType(const std::string &rel, - const RttiSet &supportedTypes, - Logger &logger) -{ - ResourceType res; - - // Try to deduce the ResourceType from the "rel" attribute - res = deduceResourceType(rel, logger); - - // If this did not work, try to deduce the ResourceType from the - // supportedTypes supplied by the Parser instance. - if (res == ResourceType::UNKNOWN) { - res = deduceResourceType(supportedTypes, logger); - } - if (res == ResourceType::UNKNOWN) { - logger.note( - "Ambigous resource type, consider specifying the \"rel\" " - "attribute"); - } - return res; -} - -ResourceType ResourceUtils::deduceResourceType(const std::string &rel, - Logger &logger) -{ - std::string s = Utils::toLower(rel); - if (!s.empty()) { - auto it = RelResourceTypeMap.find(s); - if (it != RelResourceTypeMap.end()) { - return it->second; - } else { - logger.error(std::string("Unknown relation \"") + rel + - std::string("\"")); - } - } - return ResourceType::UNKNOWN; -} - -ResourceType ResourceUtils::deduceResourceType(const RttiSet &supportedTypes, - Logger &logger) -{ - if (supportedTypes.size() == 1U) { - auto it = RttiResourceTypeMap.find(*supportedTypes.begin()); - if (it != RttiResourceTypeMap.end()) { - return it->second; - } - } - return ResourceType::UNKNOWN; -} - -const Rtti *ResourceUtils::deduceRttiType(const std::string &rel) -{ - std::string s = Utils::toLower(rel); - if (!s.empty()) { - auto it = RelRttiTypeMap.find(s); - if (it != RelRttiTypeMap.end()) { - return it->second; - } - } - return &RttiTypes::Node; -} - -RttiSet ResourceUtils::limitRttiTypes(const RttiSet &supportedTypes, - const std::string &rel) -{ - return limitRttiTypes(supportedTypes, deduceRttiType(rel)); -} - -RttiSet ResourceUtils::limitRttiTypes(const RttiSet &supportedTypes, - const Rtti *type) -{ - RttiSet res; - for (const Rtti *supportedType : supportedTypes) { - if (supportedType->isa(*type)) { - res.insert(supportedType); - } - } - return res; -} -} diff --git a/src/core/resource/ResourceUtils.hpp b/src/core/resource/ResourceUtils.hpp deleted file mode 100644 index 13f9251..0000000 --- a/src/core/resource/ResourceUtils.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - Ousía - Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. -*/ - -/** - * @file ResourceUtils.hpp - * - * Contains the ResourceUtils class which defines a set of static utility - * functions for dealing with Resources and ResourceTypes. - * - * @author Andreas Stöckel (astoecke@techfak.uni-bielefeld.de) - */ - -#ifndef _OUSIA_RESOURCE_UTILS_HPP_ -#define _OUSIA_RESOURCE_UTILS_HPP_ - -#include <string> - -#include <core/common/Rtti.hpp> - -#include "Resource.hpp" - -namespace ousia { - -/** - * Class containing static utility functions for dealing with Resources and - * ResourceTypes. - */ -class ResourceUtils { -public: - /** - * Function used to deduce the resource type from a given "relation" string - * and a set of RTTI types into which the resource should be converted by a - * parser. - * - * @param rel is a relation string which specifies the type of the resource. - * May be empty. - * @param supportedTypes is a set of RTTI types into which the resource - * should be converted by a parser. Set may be empty. - * @param logger is the Logger instance to which errors should be logged. - * @return a ResourceType specifier. - */ - static ResourceType deduceResourceType(const std::string &rel, - const RttiSet &supportedTypes, - Logger &logger); - - /** - * Function used to deduce the resource type from a given "relation" string. - * - * @param rel is a relation string which specifies the type of the resource. - * May be empty. - * @param logger is the Logger instance to which errors should be logged - * (e.g. if the relation string is invalid). - * @return a ResourceType specifier. - */ - static ResourceType deduceResourceType(const std::string &rel, - Logger &logger); - - /** - * Function used to deduce the resource type from a set of RTTI types into - * which the resource should be converted by a parser. - * - * @param supportedTypes is a set of RTTI types into which the resource - * should be converted by a parser. Set may be empty. - * @param logger is the Logger instance to which errors should be logged. - * @return a ResourceType specifier. - */ - static ResourceType deduceResourceType(const RttiSet &supportedTypes, - Logger &logger); - - /** - * Transforms the given relation string to the corresponding RttiType. - * - * @param rel is a relation string which specifies the type of the resource. - * May be empty. - * @return a pointer at the corresponding Rtti instance or a pointer at the - * Rtti descriptor of the Node class (the most general Node type) if the - * given relation type is unknown. - */ - static const Rtti *deduceRttiType(const std::string &rel); - - /** - * Reduces the number of types supported by a parser as the type of a - * resource to the intersection of the given supported types and the RTTI - * type associated with the given relation string. - * - * @param supportedTypes is a set of RTTI types into which the resource - * should be converted by a parser. Set may be empty. - * @param rel is a relation string which specifies the type of the resource. - * @return the supported type set limited to those types that can actually - * be returned according to the given relation string. - */ - static RttiSet limitRttiTypes(const RttiSet &supportedTypes, - const std::string &rel); - - /** - * Reduces the number of types supported by a parser as the type of a - * resource to the intersection of the given supported types and the RTTI - * type associated with the given relation string. - * - * @param supportedTypes is a set of RTTI types into which the resource - * should be converted by a parser. Set may be empty. - * @param type is the type that is to be expected from the parser. - * @return the supported type set limited to those types that can actually - * be returned according to the given relation string (form an isa - * relationship with the given type). - */ - static RttiSet limitRttiTypes(const RttiSet &supportedTypes, - const Rtti *type); -}; -} - -#endif /* _OUSIA_RESOURCE_UTILS_HPP_ */ - diff --git a/src/plugins/css/CSSParser.cpp b/src/plugins/css/CSSParser.cpp index 8cb41ea..cf92d32 100644 --- a/src/plugins/css/CSSParser.cpp +++ b/src/plugins/css/CSSParser.cpp @@ -79,7 +79,7 @@ Rooted<Node> CSSParser::doParse(CharReader &reader, ParserContext &ctx) CodeTokenizer tokenizer{reader, CSS_ROOT, CSS_DESCRIPTORS}; tokenizer.ignoreComments = true; tokenizer.ignoreLinebreaks = true; - Rooted<SelectorNode> root = {new SelectorNode{ctx.manager, "root"}}; + Rooted<SelectorNode> root = {new SelectorNode{ctx.getManager(), "root"}}; parseDocument(root, tokenizer, ctx); return root; } @@ -165,7 +165,7 @@ std::pair<Rooted<SelectorNode>, Rooted<SelectorNode>> CSSParser::parseSelector( auto tuple = parseSelector(tokenizer, ctx); // then we establish the DESCENDANT relationship s->getEdges().push_back( - new SelectorNode::SelectorEdge(ctx.manager, tuple.first)); + new SelectorNode::SelectorEdge(ctx.getManager(), tuple.first)); // and we return this node as well as the leaf. return std::make_pair(s, tuple.second); } @@ -177,7 +177,7 @@ std::pair<Rooted<SelectorNode>, Rooted<SelectorNode>> CSSParser::parseSelector( auto tuple = parseSelector(tokenizer, ctx); // then we establish the DESCENDANT relationship s->getEdges().push_back(new SelectorNode::SelectorEdge( - ctx.manager, tuple.first, + ctx.getManager(), tuple.first, SelectionOperator::DIRECT_DESCENDANT)); // and we return this node as well as the leaf. return std::make_pair(s, tuple.second); @@ -198,7 +198,7 @@ Rooted<SelectorNode> CSSParser::parsePrimitiveSelector(CodeTokenizer &tokenizer, const std::string name = t.content; if (!tokenizer.peek(t)) { // if we are at the end, we just return this selector with its name. - Rooted<SelectorNode> n{new SelectorNode(ctx.manager, name)}; + Rooted<SelectorNode> n{new SelectorNode(ctx.getManager(), name)}; return n; } @@ -219,7 +219,7 @@ Rooted<SelectorNode> CSSParser::parsePrimitiveSelector(CodeTokenizer &tokenizer, if (!expect(PAREN_OPEN, tokenizer, t, false, ctx)) { // if we don't have any, we return here. Rooted<SelectorNode> n{new SelectorNode( - ctx.manager, name, {pseudo_select_name, isGenerative})}; + ctx.getManager(), name, {pseudo_select_name, isGenerative})}; return n; } // parse the argument list. @@ -227,18 +227,18 @@ Rooted<SelectorNode> CSSParser::parsePrimitiveSelector(CodeTokenizer &tokenizer, // we require at least one argument, if parantheses are used // XXX args.push_back(VariantReader::parseGeneric(tokenizer.getInput(), - ctx.logger, + ctx.getLogger(), {',', ')'}).second); while (expect(COMMA, tokenizer, t, false, ctx)) { // as long as we find commas we expect new arguments. args.push_back( VariantReader::parseGeneric( - tokenizer.getInput(), ctx.logger, {',', ')'}).second); + tokenizer.getInput(), ctx.getLogger(), {',', ')'}).second); } expect(PAREN_CLOSE, tokenizer, t, true, ctx); // and we return with the finished Selector. Rooted<SelectorNode> n{new SelectorNode( - ctx.manager, name, {pseudo_select_name, args, isGenerative})}; + ctx.getManager(), name, {pseudo_select_name, args, isGenerative})}; return n; } case HASH: { @@ -250,7 +250,7 @@ Rooted<SelectorNode> CSSParser::parsePrimitiveSelector(CodeTokenizer &tokenizer, Variant::arrayType args{Variant(t.content.c_str())}; // and we return the finished Selector Rooted<SelectorNode> n{ - new SelectorNode(ctx.manager, name, {"has_id", args, false})}; + new SelectorNode(ctx.getManager(), name, {"has_id", args, false})}; return n; } case BRACKET_OPEN: { @@ -270,7 +270,7 @@ Rooted<SelectorNode> CSSParser::parsePrimitiveSelector(CodeTokenizer &tokenizer, expect(BRACKET_CLOSE, tokenizer, t, true, ctx); // and then we can return the result. Rooted<SelectorNode> n{new SelectorNode( - ctx.manager, name, {"has_attribute", args, false})}; + ctx.getManager(), name, {"has_attribute", args, false})}; return n; } else { // with an equals sign we have a has_value PseudoSelector and @@ -281,14 +281,14 @@ Rooted<SelectorNode> CSSParser::parsePrimitiveSelector(CodeTokenizer &tokenizer, expect(BRACKET_CLOSE, tokenizer, t, true, ctx); // and then we can return the result. Rooted<SelectorNode> n{new SelectorNode( - ctx.manager, name, {"has_value", args, false})}; + ctx.getManager(), name, {"has_value", args, false})}; return n; } } default: // everything else is not part of the Selector anymore. tokenizer.resetPeek(); - Rooted<SelectorNode> n{new SelectorNode(ctx.manager, name)}; + Rooted<SelectorNode> n{new SelectorNode(ctx.getManager(), name)}; return n; } } @@ -296,7 +296,7 @@ Rooted<SelectorNode> CSSParser::parsePrimitiveSelector(CodeTokenizer &tokenizer, Rooted<RuleSet> CSSParser::parseRuleSet(CodeTokenizer &tokenizer, ParserContext &ctx) { - Rooted<RuleSet> ruleSet{new RuleSet(ctx.manager)}; + Rooted<RuleSet> ruleSet{new RuleSet(ctx.getManager())}; // if we have no ruleset content, we return an empty ruleset. Token t; if (!expect(CURLY_OPEN, tokenizer, t, false, ctx)) { @@ -332,7 +332,7 @@ bool CSSParser::parseRule(CodeTokenizer &tokenizer, ParserContext &ctx, expect(COLON, tokenizer, t, true, ctx); // then the value // TODO: Resolve key for appropriate parsing function here. - value = VariantReader::parseGeneric(tokenizer.getInput(), ctx.logger, + value = VariantReader::parseGeneric(tokenizer.getInput(), ctx.getLogger(), {';'}).second; // and a ; expect(SEMICOLON, tokenizer, t, true, ctx); diff --git a/src/plugins/html/DemoOutput.cpp b/src/plugins/html/DemoOutput.cpp index a3d1b84..503c104 100644 --- a/src/plugins/html/DemoOutput.cpp +++ b/src/plugins/html/DemoOutput.cpp @@ -27,7 +27,7 @@ namespace ousia { namespace html { -void DemoHTMLTransformer::writeHTML(Handle<model::Document> doc, +void DemoHTMLTransformer::writeHTML(Handle<Document> doc, std::ostream &out, bool pretty) { Manager &mgr = doc->getManager(); @@ -66,7 +66,7 @@ void DemoHTMLTransformer::writeHTML(Handle<model::Document> doc, } // extract the book root node. - Rooted<model::StructuredEntity> root = doc->getRoot(); + Rooted<StructuredEntity> root = doc->getRoot(); if (root->getDescriptor()->getName() != "book") { throw OusiaException("The given documents root is no book node!"); } @@ -98,7 +98,7 @@ SectionType getSectionType(const std::string &name) } Rooted<xml::Element> DemoHTMLTransformer::transformSection( - Handle<xml::Element> parent, Handle<model::StructuredEntity> section, + Handle<xml::Element> parent, Handle<StructuredEntity> section, AnnoMap &startMap, AnnoMap &endMap) { Manager &mgr = section->getManager(); @@ -115,8 +115,8 @@ Rooted<xml::Element> DemoHTMLTransformer::transformSection( // check if we have a heading. if (section->hasField("heading") && section->getField("heading").size() > 0) { - Handle<model::StructuredEntity> heading = - section->getField("heading")[0].cast<model::StructuredEntity>(); + Handle<StructuredEntity> heading = + section->getField("heading")[0].cast<StructuredEntity>(); std::string headingclass; switch (type) { case SectionType::BOOK: @@ -149,7 +149,7 @@ Rooted<xml::Element> DemoHTMLTransformer::transformSection( if (!n->isa(RttiTypes::StructuredEntity)) { continue; } - Handle<model::StructuredEntity> s = n.cast<model::StructuredEntity>(); + Handle<StructuredEntity> s = n.cast<StructuredEntity>(); /* * Strictly speaking this is the wrong mechanism, because we would have * to make an "isa" call here because we can not rely on our knowledge @@ -174,7 +174,7 @@ Rooted<xml::Element> DemoHTMLTransformer::transformSection( } Rooted<xml::Element> DemoHTMLTransformer::transformList( - Handle<xml::Element> parent, Handle<model::StructuredEntity> list, + Handle<xml::Element> parent, Handle<StructuredEntity> list, AnnoMap &startMap, AnnoMap &endMap) { Manager &mgr = list->getManager(); @@ -183,8 +183,8 @@ Rooted<xml::Element> DemoHTMLTransformer::transformList( Rooted<xml::Element> l{new xml::Element{mgr, parent, listclass}}; // iterate through list items. for (auto &it : list->getField()) { - Handle<model::StructuredEntity> item = - it.cast<model::StructuredEntity>(); + Handle<StructuredEntity> item = + it.cast<StructuredEntity>(); std::string itDescrName = item->getDescriptor()->getName(); if (itDescrName == "item") { // create the list item. @@ -203,10 +203,10 @@ Rooted<xml::Element> DemoHTMLTransformer::transformList( return l; } -typedef std::stack<Rooted<model::AnnotationEntity>> AnnoStack; +typedef std::stack<Rooted<AnnotationEntity>> AnnoStack; static Rooted<xml::Element> openAnnotation( - Manager &mgr, AnnoStack &opened, Handle<model::AnnotationEntity> entity, + Manager &mgr, AnnoStack &opened, Handle<AnnotationEntity> entity, Handle<xml::Element> current) { // we push the newly opened entity on top of the stack. @@ -225,7 +225,7 @@ static Rooted<xml::Element> openAnnotation( } Rooted<xml::Element> DemoHTMLTransformer::transformParagraph( - Handle<xml::Element> parent, Handle<model::StructuredEntity> par, + Handle<xml::Element> parent, Handle<StructuredEntity> par, AnnoMap &startMap, AnnoMap &endMap) { Manager &mgr = par->getManager(); @@ -234,8 +234,8 @@ Rooted<xml::Element> DemoHTMLTransformer::transformParagraph( // check if we have a heading. if (par->hasField("heading") && par->getField("heading").size() > 0) { - Handle<model::StructuredEntity> heading = - par->getField("heading")[0].cast<model::StructuredEntity>(); + Handle<StructuredEntity> heading = + par->getField("heading")[0].cast<StructuredEntity>(); // put the heading in a strong xml::Element. Rooted<xml::Element> strong{new xml::Element{mgr, p, "strong"}}; p->addChild(strong); @@ -281,7 +281,7 @@ Rooted<xml::Element> DemoHTMLTransformer::transformParagraph( * be re-opened. */ AnnoStack tmp; - Rooted<model::AnnotationEntity> closed = opened.top(); + Rooted<AnnotationEntity> closed = opened.top(); current = current->getParent(); opened.pop(); while (closed->getEnd()->getName() != n->getName()) { @@ -313,12 +313,12 @@ Rooted<xml::Element> DemoHTMLTransformer::transformParagraph( if (!n->isa(RttiTypes::StructuredEntity)) { continue; } - Handle<model::StructuredEntity> t = n.cast<model::StructuredEntity>(); + Handle<StructuredEntity> t = n.cast<StructuredEntity>(); std::string childDescriptorName = t->getDescriptor()->getName(); if (childDescriptorName == "text") { - Handle<model::DocumentPrimitive> primitive = - t->getField()[0].cast<model::DocumentPrimitive>(); + Handle<DocumentPrimitive> primitive = + t->getField()[0].cast<DocumentPrimitive>(); if (primitive.isNull()) { throw OusiaException("Text field is not primitive!"); } diff --git a/src/plugins/html/DemoOutput.hpp b/src/plugins/html/DemoOutput.hpp index b755aac..67b7494 100644 --- a/src/plugins/html/DemoOutput.hpp +++ b/src/plugins/html/DemoOutput.hpp @@ -39,7 +39,7 @@ namespace ousia { namespace html { -typedef std::map<std::string, Rooted<model::AnnotationEntity>> AnnoMap; +typedef std::map<std::string, Rooted<AnnotationEntity>> AnnoMap; class DemoHTMLTransformer { private: @@ -50,14 +50,14 @@ private: * called recursively. */ Rooted<xml::Element> transformSection(Handle<xml::Element> parent, - Handle<model::StructuredEntity> sec, + Handle<StructuredEntity> sec, AnnoMap &startMap, AnnoMap &endMap); /** * This transforms a list entity, namely ul and ol to an XHTML element. * For each item, the transformParagraph function is called. */ Rooted<xml::Element> transformList(Handle<xml::Element> parent, - Handle<model::StructuredEntity> list, + Handle<StructuredEntity> list, AnnoMap &startMap, AnnoMap &endMap); /** * This transforms a paragraph-like entity, namely heading, item and @@ -65,7 +65,7 @@ private: * contained. For anchor handling we require the AnnoMaps. */ Rooted<xml::Element> transformParagraph(Handle<xml::Element> parent, - Handle<model::StructuredEntity> par, + Handle<StructuredEntity> par, AnnoMap &startMap, AnnoMap &endMap); public: @@ -89,7 +89,7 @@ public: * @param pretty is a flag that manipulates whether newlines and tabs are * used. */ - void writeHTML(Handle<model::Document> doc, std::ostream &out, + void writeHTML(Handle<Document> doc, std::ostream &out, bool pretty = true); }; } diff --git a/src/plugins/xml/XmlParser.cpp b/src/plugins/xml/XmlParser.cpp index 78d9df8..17bc470 100644 --- a/src/plugins/xml/XmlParser.cpp +++ b/src/plugins/xml/XmlParser.cpp @@ -32,8 +32,6 @@ namespace ousia { -using namespace ousia::model; - /* Document structure */ static const State STATE_DOCUMENT = 0; static const State STATE_HEAD = 1; @@ -235,24 +233,18 @@ public: /* Adapter Expat -> ParserStack */ -struct XMLParserUserData { - SourceId sourceId; -}; - static SourceLocation syncLoggerPosition(XML_Parser p) { // Fetch the parser stack and the associated user data ParserStack *stack = static_cast<ParserStack *>(XML_GetUserData(p)); - XMLParserUserData *ud = - static_cast<XMLParserUserData *>(stack->getUserData()); // Fetch the current location in the XML file size_t offs = XML_GetCurrentByteIndex(p); // Build the source location and update the default location of the current // logger instance - SourceLocation loc{ud->sourceId, offs}; - stack->getContext().logger.setDefaultLocation(loc); + SourceLocation loc{stack->getContext().getSourceId(), offs}; + stack->getContext().getLogger().setDefaultLocation(loc); return loc; } @@ -269,7 +261,7 @@ static void xmlStartElementHandler(void *p, const XML_Char *name, while (*attr) { const std::string key{*(attr++)}; std::pair<bool, Variant> value = VariantReader::parseGenericString( - *(attr++), stack->getContext().logger); + *(attr++), stack->getContext().getLogger()); args.emplace(std::make_pair(key, value.second)); } stack->start(std::string(name), args, loc); @@ -305,10 +297,7 @@ Rooted<Node> XmlParser::doParse(CharReader &reader, ParserContext &ctx) // Create the parser stack instance and pass the reference to the state // machine descriptor - XMLParserUserData data; - data.sourceId = reader.getSourceId(); - - ParserStack stack{ctx, XML_HANDLERS, &data}; + ParserStack stack{ctx, XML_HANDLERS}; XML_SetUserData(&p, &stack); XML_UseParserAsHandlerArg(&p); |