From 6decad0b8e7e369bd8215f31a45dd3eae982d2a9 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Wed, 21 Jan 2015 01:17:49 +0100 Subject: Some further refactoring -- renamed Scope to ParserScope, got rid of parser namespace, added new functionality to RegistryClass, wrote documentation, added function for extracting file extensions to Utils --- src/core/common/Utils.cpp | 23 +++++++++++++++++++++++ src/core/common/Utils.hpp | 20 ++++++++++++++++++++ 2 files changed, 43 insertions(+) (limited to 'src/core/common') diff --git a/src/core/common/Utils.cpp b/src/core/common/Utils.cpp index 5fde29c..c8fcdc6 100644 --- a/src/core/common/Utils.cpp +++ b/src/core/common/Utils.cpp @@ -17,7 +17,9 @@ */ #include +#include #include +#include #include "Utils.hpp" @@ -74,5 +76,26 @@ std::vector Utils::split(const std::string &s, char delim) return res; } +std::string Utils::toLower(std::string s) +{ + std::transform(s.begin(), s.end(), s.begin(), tolower); + return s; +} + +std::string Utils::extractFileExtension(const std::string &filename) +{ + size_t n = 0; + for (ssize_t i = filename.size() - 1; i >= 0; i--) { + if (filename[i] == '/' || filename[i] == '\\') { + return std::string{}; + } + if (filename[i] == '.') { + return toLower(filename.substr(i + 1, n)); + } + n++; + } + return std::string{}; +} + } diff --git a/src/core/common/Utils.hpp b/src/core/common/Utils.hpp index 1f7f142..22e0fd3 100644 --- a/src/core/common/Utils.hpp +++ b/src/core/common/Utils.hpp @@ -114,6 +114,26 @@ public: * @return a vector of strings containing the splitted sub-strings. */ static std::vector split(const std::string &s, char delim); + + /** + * Converts the given string to lowercase (only works for ANSI characters). + * + * @param s is the string that should be converted to lowercase. + * @return s in lowercase. + */ + static std::string toLower(std::string s); + + /** + * Reads the file extension of the given filename. + * + * @param filename is the filename from which the extension should be + * extracted. + * @return the extension, excluding any leading dot. The extension is + * defined as the substring after the last dot in the given string, if the + * dot is after a slash or backslash. The extension is converted to + * lowercase. + */ + static std::string extractFileExtension(const std::string &filename); }; } -- cgit v1.2.3 From 8e7be30a309ccd84684033ea854c574b32282495 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Thu, 22 Jan 2015 02:42:29 +0100 Subject: Added Location.cpp (empty, but verifies that the header has no errors) --- CMakeLists.txt | 1 + src/core/common/Location.cpp | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 src/core/common/Location.cpp (limited to 'src/core/common') diff --git a/CMakeLists.txt b/CMakeLists.txt index 2b8efc8..bcba476 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -125,6 +125,7 @@ ADD_LIBRARY(ousia_core src/core/common/Exceptions src/core/common/Function src/core/common/Logger + src/core/common/Location src/core/common/Number src/core/common/Property src/core/common/Rtti diff --git a/src/core/common/Location.cpp b/src/core/common/Location.cpp new file mode 100644 index 0000000..6f9250a --- /dev/null +++ b/src/core/common/Location.cpp @@ -0,0 +1,23 @@ +/* + 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 . +*/ + +#include "Location.hpp" + +namespace ousia { +} + -- cgit v1.2.3 From 9b9c7439b6cb1b711901ad49cd4855e1b0964652 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Thu, 22 Jan 2015 02:49:09 +0100 Subject: Backup --- src/core/common/Location.hpp | 375 ++++++++++++++++++++++++++++------ src/core/parser/ParserContext.hpp | 4 +- src/core/resource/ResourceManager.cpp | 252 +++++++++++++++++++++++ src/core/resource/ResourceManager.hpp | 152 ++++++++++++++ 4 files changed, 722 insertions(+), 61 deletions(-) create mode 100644 src/core/resource/ResourceManager.cpp create mode 100644 src/core/resource/ResourceManager.hpp (limited to 'src/core/common') diff --git a/src/core/common/Location.hpp b/src/core/common/Location.hpp index 39e1011..f3a30b2 100644 --- a/src/core/common/Location.hpp +++ b/src/core/common/Location.hpp @@ -16,91 +16,310 @@ along with this program. If not, see . */ +/** + * @file Location.hpp + * + * Types used for describing positions, ranges and excerpts of source files used + * for describing log messages. + * + * @author Andreas Stöckel (astoecke@techfak.uni-bielefeld.de) + */ + #ifndef _OUSIA_LOCATION_HPP_ #define _OUSIA_LOCATION_HPP_ +#include +#include #include namespace ousia { /** - * Struct representing a location within a source file. A position is defined by - * a byte offset (which is always reproducable), a line number and a column - * number (which may differ depending on the encoding used). + * Type used for referencing a source file currently opened in a Project. + */ +using SourceId = uint32_t; + +/** + * Type used for specifying an offset within a source file. + */ +using SourceOffset = uint32_t; + +/** + * Maximum value for a SourceOffset. As SourceOffset is a 32 Bit unsigned + * integer, the maximum value is 2^32-1, which means that 4 GiB are addressable + * by SourceOffset. */ -struct SourceLocation { +constexpr SourceOffset SourceOffsetMax = + std::numeric_limits::max(); + +/** + * Function for clamping a size_t to a valid SourceOffset value. + * + * @param pos is the size_t value that should be converted to a SourceOffset + * value. If pos is larger than the maximum value that can be represented by + * SourceOffset, the result is set to this maximum value, which is interpreted + * as "invalid" by functions dealing with the SourceOffset type. + * @return the clamped position value. + */ +inline SourceOffset clampToSourcePosition(size_t pos) +{ + return pos > SourceOffsetMax ? SourceOffsetMax : pos; +} + +/** + * Class specifying a position within an (unspecified) source file. + */ +class SourcePosition { +private: /** - * Current line, starting with one. + * Offset position in bytes relative to the start of the document. */ - int line; + SourceOffset pos; +public: /** - * Current column, starting with one. + * Default constructor of the SourcePosition class. Sets the position to + * SourceOffsetMax and thus marks the SourcePosition as invalid. */ - int column; + SourcePosition() : pos(SourceOffsetMax) {} /** - * Current byte offset. + * Creates a new SourcePosition instance with the given byte offset. */ - size_t offs; + SourcePosition(size_t pos) : pos(clampToSourcePosition(pos)) {} /** - * Default constructor of the SourceLocation struct, initializes all - * memebers with zero. + * Sets the position of the SourcePosition value to the given value. Clamps + * the given size_t to the valid range. + * + * @param pos is the position value that should be set. */ - SourceLocation() : line(0), column(0), offs(0) {} + void setPosition(size_t pos) { this->pos = clampToSourcePosition(pos); } /** - * Creates a new SourceLocation struct with only a line and no column. + * Returns the position value. Only use the value if "valid" returns true. * - * @param line is the line number. - * @param column is the column number. + * @return the current position. */ - SourceLocation(int line) : line(line), column(0), offs(0) {} + SourceOffset getPosition() const { return pos; } /** - * Creates a new SourceLocation struct with a line and column. + * Returns true if the source position is valid, false otherwise. Invalid + * positions are set to the maximum representable number. * - * @param line is the line number. - * @param column is the column number. + * @return true if the SourcePosition instance is value, false otherwise. */ - SourceLocation(int line, int column) : line(line), column(column), offs(0) + bool isValid() { return pos != SourceOffsetMax; } +}; + +/** + * The SourceRange class represents a range within an (unspecified) source file. + */ +class SourceRange { +private: + /** + * Start byte offset. + */ + SourcePosition start; + + /** + * End byte offset. + */ + SourcePosition end; + +public: + /** + * Default constructor. Creates an invalid range. + */ + SourceRange(){}; + + /** + * Constructor for a zero-length range. + * + * @param pos is the byte offset at which the SourceRange instance should be + * located. + */ + SourceRange(SourcePosition pos) : start(pos), end(pos) {} + + /** + * Constructor of a SourceRange instance. + * + * @param start is the byte offset of the first character in the range + * (start is inclusive). + * @param end points at the end of the range (end is non-inclusive). + */ + SourceRange(SourcePosition start, SourcePosition end) + : start(start), end(end) { } /** - * Creates a new SourceLocation struct with a line, column and byte offset. + * Sets the start of the SourceRange value to the given value. This + * operation might render the SourceRange invalid (if the given position is + * larger than the end position). + * + * @param pos is the start position value that should be set. + */ + void setStart(SourcePosition pos) { this->start = pos; } + + /** + * Sets the end of the SourceRange value to the given value. This operation + * might render the SourceRange invalid (if the given position is smaller + * than the start position). * - * @param line is the line number. - * @param column is the column number. - * @param offs is the byte offset. + * @param pos is the end position that should be set. */ - SourceLocation(int line, int column, size_t offs) - : line(line), column(column), offs(offs) + void setEnd(SourcePosition pos) { this->end = pos; } + + /** + * Sets the start and end of the SourceRange value to the given values. + * This operation might render the SourceRange invalid (if the given end + * position is smaller than the start position). + * + * @param start is the start position that should be set. + * @param end is the end position that should be set. + */ + void setRange(SourcePosition start, SourcePosition end) { + this->start = start; + this->end = end; } /** - * Returns true, if the line number is valid, false otherwise. + * Makes the Range represent a zero-length range that is located at the + * given position. The given position should be interpreted as being located + * "between the character just before the start offset and the start + * offset". * - * @return true for valid line numbers. + * @param pos is the position to which start and end should be set. */ - bool hasLine() const { return line > 0; } + void setPosition(SourcePosition pos) + { + this->start = pos; + this->end = pos; + } /** - * Returns true, if the column number is valid, false otherwise. + * Returns the start position of the SourceRange instance. * - * @return true for valid column numbers. + * @return the start offset in bytes. */ - bool hasColumn() const { return column > 0; } + SourceOffset getStart() const { return start.getPosition(); } /** - * Returns true, if the position is valid, false otherwise. This function is - * equivalent to the hasLine() function. + * Returns the end position of the SourceRange instance. * - * @return true if the Position struct is valid. + * @return the end offset in bytes (non-inclusive). */ - bool valid() const { return hasLine(); } + SourceOffset getEnd() const { return end.getPosition(); } + + /** + * Returns a copy of the underlying SourcePosition instance representing the + * start position. + * + * @return a copy of the start SourcePosition instance. + */ + SourcePosition getStartPosition() const { return start; } + + /** + * Returns a copy of the underlying SourcePosition instance representing the + * end position. + * + * @return a copy of the end SourcePosition instance. + */ + SourcePosition getEndPosition() const { return end; } + + /** + * Returns the length of the range. A range may have a zero value length, in + * which case it should be interpreted as "between the character before + * the start offset and the start offset". The returned value is only valid + * if the isValid() method returns true! + * + * @return the length of the range in bytes. + */ + size_t getLength() const { return end.getPosition() - start.getPosition(); } + + /** + * Returns true if this range is actually valid. This is the case if the + * start position is smaller or equal to the end position and start and end + * position themself are valid. + * + * @return true if the Range is valid. + */ + bool isValid() + { + return start.isValid() && end.isValid() && + start.getPosition() <= end.getPosition(); + } +}; + +/** + * The SourceLocation class describes a range within a specific source file. + */ +class SourceLocation : public SourceRange { +private: + /** + * Id of the source file. + */ + SourceId sourceId; + +public: + /** + * Constructor, binds the SourceLocation to the given source file. + * + * @param sourceId is the sourceId to which the SourceLocation instance + * should be bound. The sourceId cannot be overriden after construction. + */ + SourceLocation(SourceId sourceId) : sourceId(sourceId){}; + + /** + * Constructor for a zero-length range. + * + * @param sourceId is the sourceId to which the SourceLocation instance + * should be bound. The sourceId cannot be overriden after construction. + * @param pos is the byte offset at which the SourceRange instance should be + * located. + */ + SourceLocation(SourceId sourceId, SourcePosition pos) + : SourceRange(pos), sourceId(sourceId) + { + } + + /** + * Constructor of a SourceRange instance. + * + * @param sourceId is the sourceId to which the SourceLocation instance + * should be bound. The sourceId cannot be overriden after construction. + * @param start is the byte offset of the first character in the range + * (start is inclusive). + * @param end points at the end of the range (end is non-inclusive). + */ + SourceLocation(SourceId sourceId, SourcePosition start, SourcePosition end) + : SourceRange(start, end), sourceId(sourceId) + { + } + + /** + * Constructor of a SourceRange instance. + * + * @param sourceId is the sourceId to which the SourceLocation instance + * should be bound. The sourceId cannot be overriden after construction. + * @param start is the byte offset of the first character in the range + * (start is inclusive). + * @param end points at the end of the range (end is non-inclusive). + */ + SourceLocation(SourceId sourceId, const SourceRange &range) + : SourceRange(range), sourceId(sourceId) + { + } + + /** + * Returns the id of the source file this SourceLocation instance is bound + * to. + * + * @return the id of the source file this instance is bound to. + */ + SourceId getSourceId() { return sourceId; } }; /** @@ -108,6 +327,37 @@ struct SourceLocation { * messages. */ struct SourceContext { + /** + * Underlying source range (contains the byte start and end offsets in + * bytes). + */ + SourceRange range; + + /** + * Name of the underlying resource. + */ + std::string filename; + + /** + * Start line, starting with one. + */ + int startLine; + + /** + * Start column, starting with one. + */ + int startColumn; + + /** + * End line, starting with one. + */ + int endLine; + + /** + * End column, starting with one. + */ + int endColumn; + /** * Set to the content of the current line. */ @@ -119,6 +369,12 @@ struct SourceContext { */ int relPos; + /** + * Relative length (in characters) within that line. May end beyond the + * text given in the context. + */ + int relLen; + /** * Set to true if the beginning of the line has been truncated (because * the reader position is too far away from the actual position of the @@ -134,39 +390,40 @@ struct SourceContext { bool truncatedEnd; /** - * Default constructor, initializes all members with zero values. + * Default constructor, initializes primitive members with zero values. */ SourceContext() - : text(), relPos(0), truncatedStart(false), truncatedEnd(false) + : startLine(0), + startColumn(0), + endLine(0), + endColumn(0), + relPos(0), + relLen(0), + truncatedStart(false), + truncatedEnd(false) { } /** - * Constructor of the SourceContext class. + * Returns true the context text is not empty. * - * @param text is the current line the text cursor is at. - * @param relPos is the relative position of the text cursor within that - * line. - * @param truncatedStart specifies whether the text was truncated at the - * beginning. - * @param truncatedEnd specifies whether the text was truncated at the - * end. - */ - SourceContext(std::string text, size_t relPos, bool truncatedStart, - bool truncatedEnd) - : text(std::move(text)), - relPos(relPos), - truncatedStart(truncatedStart), - truncatedEnd(truncatedEnd) - { - } + * @return true if the context is valid and e.g. should be printed. + */ + bool isValid() const { return range.isValid() && hasLine() && hasColumn(); } /** - * Returns true the context text is not empty. + * Returns true, if the start line number is valid, false otherwise. * - * @return true if the context is valid and e.g. should be printed. + * @return true for valid line numbers. + */ + bool hasLine() const { return startLine > 0; } + + /** + * Returns true, if the start column number is valid, false otherwise. + * + * @return true for valid column numbers. */ - bool valid() const { return !text.empty(); } + bool hasColumn() const { return startColumn > 0; } }; /** diff --git a/src/core/parser/ParserContext.hpp b/src/core/parser/ParserContext.hpp index 88d1f52..bb64600 100644 --- a/src/core/parser/ParserContext.hpp +++ b/src/core/parser/ParserContext.hpp @@ -71,8 +71,8 @@ struct ParserContext { /** * Constructor of the ParserContext class. * - * @param scope is a reference to the ParserScope instance that should be used to - * lookup names. + * @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. diff --git a/src/core/resource/ResourceManager.cpp b/src/core/resource/ResourceManager.cpp new file mode 100644 index 0000000..563fc12 --- /dev/null +++ b/src/core/resource/ResourceManager.cpp @@ -0,0 +1,252 @@ +/* + 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 . +*/ + +#include +#include +#include +#include +#include +#include + +#include "Resource.hpp" +#include "ResourceManager.hpp" + +namespace ousia { + +/* Deduction of the ResourceType */ + +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 RelResourceTypeMap{ + {"document", ResourceType::DOCUMENT}, + {"domain", ResourceType::DOMAIN_DESC}, + {"typesystem", ResourceType::TYPESYSTEM}}; + +/** + * Map mapping from Rtti pointers to the corresponding ResourceType. + */ +static const std::unordered_map RttiResourceTypeMap{ + {&RttiTypes::Document, ResourceType::DOCUMENT}, + {&RttiTypes::Domain, ResourceType::DOMAIN_DESC}, + {&RttiTypes::Typesystem, ResourceType::TYPESYSTEM}}; + +static ResourceType relToResourceType(const std::string &rel, Logger &logger) +{ + std::string s = Utils::toLowercase(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; +} + +static ResourceType supportedTypesToResourceType(const RttiSet &supportedTypes) +{ + if (supportedTypes.size() == 1U) { + auto it = RttiResourceTypeMap.find(supportedTypes[0]); + if (it != RelResourceTypeMap.end()) { + return it->second; + } + } + return ResourceType::UNKNOWN; +} + +static ResourceType deduceResourceType(const std::string &rel, + const RttiSet &supportedTypes, + Logger &logger) +{ + ResourceType res; + + // Try to deduce the ResourceType from the "rel" attribute + res = relToResourceType(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 = supportedTypesToResourceType(supportedTypes); + } + if (res == ResourceType::UNKNOWN) { + logger.note( + "Ambigous resource type, consider specifying the \"rel\" " + "attribute"); + } + return res; +} + +/* Functions for reducing the set of supported types */ + +/** + * Map mapping from relations (the "rel" attribute in includes) to the + * corresponding RttiType + */ +static const std::unordered_map RelRttiTypeMap{ + {"document", &RttiTypes::DOCUMENT}, + {"domain", &RttiTypes::DOMAIN}, + {"typesystem", &RttiTypes::TYPESYSTEM}}; + +static Rtti *relToRttiType(const std::string &rel) +{ + std::string s = Utils::toLowercase(rel); + if (!s.empty()) { + auto it = RelRttiTypeMap.find(s); + if (it != RelRttiTypeMap.end()) { + return it->second; + } + } + return &ResourceType::Node; +} + +static RttiType shrinkSupportedTypes(const RttiSet &supportedTypes, + const std::string &rel) +{ + RttiSet types; + RttiType *type = relToRttiType(rel); + for (RttiType *supportedType : supportedTypes) { + if (supportedType->isa(type)) { + types.insert(supportedType); + } + } + return types; +} + +/* Class ResourceManager */ + +Rooted ResourceManager::link(ParserContext &ctx, Resource &resource, + const std::string &mimetype, + const RttiSet &supportedTypes) +{ + +} + +Rooted 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 = + 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 = shrinkSupportedTypes(supportedTypes, rel); + + // Check whether the resource has already been parsed + Rooted node = nullptr; + auto it = locations.find(res.getLocation()); + if (it != locations.end()) { + node = + } + = link(ctx, resource, mimetype, types); + + // Try to deduce the mimetype + std::string mime = mimetype; + if (mime.empty()) { + // Fetch the file extension + std::string ext = Utils::extractFileExtension(path); + if (ext.empty()) { + ctx.logger.error( + std::string("Specified filename \"") + path + + std::string( + "\" has no extension and no mimetype (\"type\" " + "attribute) was given instead.")); + return nullptr; + } + + // Fetch the mimetype for the extension + mime = ctx.registry.getMimetypeForExtension(ext); + if (mime.empty()) { + ctx.logger.error(std::string("Unknown file extension \"") + ext + + std::string("\"")); + return nullptr; + } + } + + // Fetch a parser for the mimetype + const std::pair parser = + ctx.registry.getParserForMimetype(mime); + + // Make sure a parser was found + if (!parser->first) { + ctx.logger.error(std::string("Cannot parse files of type \"") + mime + + std::string("\"")); + } + + // Make sure the parser returns one of the supported types +} + +Rooted 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 include(ctx, path, mimetype, rel, supportedTypes, relativeResource); +} + +const Resource &getResource(SourceId sourceId) const +{ + if (sourceId < resources.size()) { + return resources[sourceId]; + } + return NullResource; +} + +SourceContext ResourceManager::buildContext(const SourceLocation &location) +{ + SourceContext res; + + // TODO + + return res; +} +}; +} + +#endif /* _OUSIA_RESOURCE_MANAGER_HPP_ */ + diff --git a/src/core/resource/ResourceManager.hpp b/src/core/resource/ResourceManager.hpp new file mode 100644 index 0000000..809fd55 --- /dev/null +++ b/src/core/resource/ResourceManager.hpp @@ -0,0 +1,152 @@ +/* + 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 . +*/ + +/** + * @file ResourceManager.hpp + * + * Defines the ResourceManager class which is responsible for keeping track of + * already included resources and to retrieve CharReader instance for not-yet + * parsed resources. + * + * @author Andreas Stöckel (astoecke@techfak.uni-bielefeld.de) + */ + +#ifndef _OUSIA_RESOURCE_MANAGER_HPP_ +#define _OUSIA_RESOURCE_MANAGER_HPP_ + +#include +#include + +#include +#include + +namespace ousia { + +// Forward declarations +class Node; +class ParserContext; +class Resource; +class RttiSet; +extern const Resource NullResource; + +/** + * The ResourceManager class is responsible for keepking track of all included + * resources. It retrieves CharReader instances for not-yet parsed resources + * and returns references for those resources that already have been parsed. + */ +class ResourceManager { +private: + /** + * Vector used for mapping SourceId instances to the underlying resource. + */ + std::vector resources; + + /** + * Index pointing at the next free entry in the resources list. + */ + SourceId nextFreeSourceId = 0; + + /** + * Map between Resource locations and the corresponding SourceId. + */ + std::unordered_map locations; + + /** + * Map between a SourceId and the corresponding (if available) parsed node + * uid (this resembles weak references to the Node instance). + */ + std::unordered_map nodes; + + /** + * Cache used for translating byte offsets to line numbers. Maps from a + * SourceId onto a list of (sorted) SourceOffsets. The index in the list + * corresponds to the line number. + */ + std::unordered_map> lineNumberCache; + + + Rooted getCachedNode(SourceId id); + + Rooted getCachedNode(const std::string &location); + + SourceId getSourceId(const std::string &location); + + /** + * Used internally to either parse a resource or retrieve it from the + * internal cache of already parsed resources. + */ + Rooted link(ParserContext &ctx, Resource &resource, const std::string &mimetype, + const RttiSet &supportedTypes); + + +public: + /** + * 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 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 link(ParserContext &ctx, const std::string &path, + const std::string &mimetype, const std::string &rel, + const RttiSet &supportedTypes, SourceId relativeTo); + + /** + * Returns a Resource instance for the given SourceId. + * + * @param sourceId is the id of the Resource instance that should be + * returned. + * @return the Resource instance corresponding to the given sourceId. If the + * sourceId is invalid, the returned Resource will be invalid (a reference + * at NullResource). + */ + const Resource &getResource(SourceId sourceId) const; + + /** + * 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. + * @return a valid SourceContext if a valid SourceLocation was given or an + * invalid SourceContext if the location is invalid. + */ + SourceContext buildContext(const SourceLocation &location); +}; +} + +#endif /* _OUSIA_RESOURCE_MANAGER_HPP_ */ + -- cgit v1.2.3 From ef59091033b3f69dd01df009f21927b8ad81f5a9 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 00:30:44 +0100 Subject: Improved documentation and added "isOneOf" function to Rtti class. --- src/core/common/Rtti.cpp | 11 +++++++++++ src/core/common/Rtti.hpp | 11 +++++++++++ 2 files changed, 22 insertions(+) (limited to 'src/core/common') diff --git a/src/core/common/Rtti.cpp b/src/core/common/Rtti.cpp index 1213669..668e418 100644 --- a/src/core/common/Rtti.cpp +++ b/src/core/common/Rtti.cpp @@ -125,6 +125,17 @@ bool Rtti::isa(const Rtti &other) const return parents.count(&other) > 0; } +bool Rtii::isOneOf(const RttiSet &others) const +{ + initialize(); + for (const Rtti *other: others) { + if (parents.count(other) > 0) { + return true; + } + } + return false; +} + bool Rtti::composedOf(const Rtti &other) const { initialize(); diff --git a/src/core/common/Rtti.hpp b/src/core/common/Rtti.hpp index fa2692f..53043e2 100644 --- a/src/core/common/Rtti.hpp +++ b/src/core/common/Rtti.hpp @@ -378,9 +378,20 @@ public: * * @param other is the other type for which the relation to this type * should be checked. + * @return true if this type (directly or indirectly) has the given other + * type as parent or equals the other type. */ bool isa(const Rtti &other) const; + /** + * Returns true if this Rtti instance is one of the given types. + * + * @param others is a set of other types to be checked. + * @return true if this type (directly or indirectly) has once of the given + * other types as parent or equals one of the other types. + */ + bool isOneOf(const RttiSet &others) const; + /** * 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 -- cgit v1.2.3 From 1179bad0732e09b1bcae5fd77b62c4e7116d6d73 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 00:32:17 +0100 Subject: Renamed SourceOffset max to InvalidSourceOffset, introduced InvalidSourceId, made sourceId in SourceLocation mutable --- src/core/common/Location.hpp | 52 ++++++++++++++++++++++++++++++++------------ 1 file changed, 38 insertions(+), 14 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/Location.hpp b/src/core/common/Location.hpp index f3a30b2..ae50e91 100644 --- a/src/core/common/Location.hpp +++ b/src/core/common/Location.hpp @@ -39,6 +39,11 @@ namespace ousia { */ using SourceId = uint32_t; +/** + * Maximum value for a SourceId. Indicates invalid entries. + */ +constexpr SourceId InvalidSourceId = std::numeric_limits::max(); + /** * Type used for specifying an offset within a source file. */ @@ -49,7 +54,7 @@ using SourceOffset = uint32_t; * integer, the maximum value is 2^32-1, which means that 4 GiB are addressable * by SourceOffset. */ -constexpr SourceOffset SourceOffsetMax = +constexpr SourceOffset InvalidSourceOffset = std::numeric_limits::max(); /** @@ -63,7 +68,7 @@ constexpr SourceOffset SourceOffsetMax = */ inline SourceOffset clampToSourcePosition(size_t pos) { - return pos > SourceOffsetMax ? SourceOffsetMax : pos; + return pos > InvalidSourceOffset ? InvalidSourceOffset : pos; } /** @@ -79,9 +84,9 @@ private: public: /** * Default constructor of the SourcePosition class. Sets the position to - * SourceOffsetMax and thus marks the SourcePosition as invalid. + * InvalidSourceOffset and thus marks the SourcePosition as invalid. */ - SourcePosition() : pos(SourceOffsetMax) {} + SourcePosition() : pos(InvalidSourceOffset) {} /** * Creates a new SourcePosition instance with the given byte offset. @@ -109,7 +114,7 @@ public: * * @return true if the SourcePosition instance is value, false otherwise. */ - bool isValid() { return pos != SourceOffsetMax; } + bool isValid() { return pos != InvalidSourceOffset; } }; /** @@ -261,22 +266,25 @@ private: /** * Id of the source file. */ - SourceId sourceId; + SourceId sourceId = InvalidSourceId; public: + /** + * Default constructor. + */ + SourceLocation(){}; + /** * Constructor, binds the SourceLocation to the given source file. * - * @param sourceId is the sourceId to which the SourceLocation instance - * should be bound. The sourceId cannot be overriden after construction. + * @param sourceId specifies the file this location refers to. */ SourceLocation(SourceId sourceId) : sourceId(sourceId){}; /** * Constructor for a zero-length range. * - * @param sourceId is the sourceId to which the SourceLocation instance - * should be bound. The sourceId cannot be overriden after construction. + * @param sourceId specifies the file this location refers to. * @param pos is the byte offset at which the SourceRange instance should be * located. */ @@ -288,8 +296,7 @@ public: /** * Constructor of a SourceRange instance. * - * @param sourceId is the sourceId to which the SourceLocation instance - * should be bound. The sourceId cannot be overriden after construction. + * @param sourceId specifies the file this location refers to. * @param start is the byte offset of the first character in the range * (start is inclusive). * @param end points at the end of the range (end is non-inclusive). @@ -302,8 +309,7 @@ public: /** * Constructor of a SourceRange instance. * - * @param sourceId is the sourceId to which the SourceLocation instance - * should be bound. The sourceId cannot be overriden after construction. + * @param sourceId specifies the file this location refers to. * @param start is the byte offset of the first character in the range * (start is inclusive). * @param end points at the end of the range (end is non-inclusive). @@ -313,6 +319,13 @@ public: { } + /** + * Sets the source id to the given value. + * + * @param sourceId specifies the file this location refers to. + */ + void setSourceId(SourceId sourceId) { this->sourceId = sourceId; } + /** * Returns the id of the source file this SourceLocation instance is bound * to. @@ -320,6 +333,17 @@ public: * @return the id of the source file this instance is bound to. */ SourceId getSourceId() { return sourceId; } + + /** + * Returns true if this location is actually valid. This is the case if + * the underlying range is valid and the source id is valid. + * + * @return true if the Range is valid. + */ + bool isValid() + { + return SourceRange::isValid() && sourceId != InvalidSourceId; + } }; /** -- cgit v1.2.3 From c7aab61b7cf2b824f168507d9a693b375df0515b Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 00:34:01 +0100 Subject: Improved SourceLocation --- src/core/common/Location.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/Location.hpp b/src/core/common/Location.hpp index ae50e91..4ce01a8 100644 --- a/src/core/common/Location.hpp +++ b/src/core/common/Location.hpp @@ -266,13 +266,13 @@ private: /** * Id of the source file. */ - SourceId sourceId = InvalidSourceId; + SourceId sourceId; public: /** * Default constructor. */ - SourceLocation(){}; + SourceLocation() : sourceId(InvalidSourceId) {}; /** * Constructor, binds the SourceLocation to the given source file. -- cgit v1.2.3 From 5eaeae92ccf209194bced39d888c5a0e527a9c1a Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 01:25:55 +0100 Subject: Started to adapt CharReader --- src/core/common/CharReader.cpp | 209 +++++++---------------------------------- src/core/common/CharReader.hpp | 164 +++++++++----------------------- 2 files changed, 77 insertions(+), 296 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/CharReader.cpp b/src/core/common/CharReader.cpp index 6966b97..b0bbade 100644 --- a/src/core/common/CharReader.cpp +++ b/src/core/common/CharReader.cpp @@ -376,44 +376,33 @@ bool Buffer::fetch(CursorId cursor, char &c) return fetchCharacter(cursor, c, false); } -/* CharReader::Cursor class */ - -void CharReader::Cursor::assign(std::shared_ptr buffer, - CharReader::Cursor &cursor) -{ - // Copy the cursor position - buffer->copyCursor(cursor.cursor, this->cursor); - - // Copy the state - line = cursor.line; - column = cursor.column; -} - /* CharReader class */ -CharReader::CharReader(std::shared_ptr buffer, size_t line, - size_t column) +CharReader::CharReader(std::shared_ptr buffer, SourceId sourceId, + size_t offs) : buffer(buffer), - readCursor(buffer->createCursor(), line, column), - peekCursor(buffer->createCursor(), line, column), - coherent(true) + readCursor(buffer->createCursor()), + peekCursor(buffer->createCursor()), + coherent(true), + sourceId(sourceId), + offs(offs) { } -CharReader::CharReader(const std::string &str, size_t line, size_t column) - : CharReader(std::shared_ptr{new Buffer{str}}, line, column) +CharReader::CharReader(const std::string &str, SourceId sourceId, size_t offs) + : CharReader(std::shared_ptr{new Buffer{str}}, sourceId, offs) { } -CharReader::CharReader(std::istream &istream, size_t line, size_t column) - : CharReader(std::shared_ptr{new Buffer{istream}}, line, column) +CharReader::CharReader(std::istream &istream, SourceId sourceId, size_t offs) + : CharReader(std::shared_ptr{new Buffer{istream}}, sourceId, offs) { } CharReader::~CharReader() { - buffer->deleteCursor(readCursor.cursor); - buffer->deleteCursor(peekCursor.cursor); + buffer->deleteCursor(readCursor); + buffer->deleteCursor(peekCursor); } bool CharReader::readAtCursor(Cursor &cursor, char &c) @@ -437,18 +426,6 @@ bool CharReader::readAtCursor(Cursor &cursor, char &c) } } } - - // Count lines and columns - if (c == '\n') { - // A linebreak was reached, go to the next line - cursor.line++; - cursor.column = 1; - } else { - // Ignore UTF-8 continuation bytes - if (!((c & 0x80) && !(c & 0x40))) { - cursor.column++; - } - } return true; } @@ -456,7 +433,7 @@ bool CharReader::peek(char &c) { // If the reader was coherent, update the peek cursor state if (coherent) { - peekCursor.assign(buffer, readCursor); + buffer->copyCursor(readCursor, peekCursor); coherent = false; } @@ -471,12 +448,8 @@ bool CharReader::read(char &c) // Set the peek position to the current read position, if reading was not // coherent - if (!coherent) { - peekCursor.assign(buffer, readCursor); - coherent = true; - } else { - buffer->copyCursor(readCursor.cursor, peekCursor.cursor); - } + buffer->copyCursor(readCursor, peekCursor); + coherent = true; // Return the result of the read function return res; @@ -485,7 +458,7 @@ bool CharReader::read(char &c) void CharReader::resetPeek() { if (!coherent) { - peekCursor.assign(buffer, readCursor); + buffer->copyCursor(readCursor, peekCursor); coherent = true; } } @@ -493,7 +466,7 @@ void CharReader::resetPeek() void CharReader::consumePeek() { if (!coherent) { - readCursor.assign(buffer, peekCursor); + buffer->copyCursor(peekCursor, readCursor); coherent = true; } } @@ -513,7 +486,8 @@ bool CharReader::consumeWhitespace() CharReaderFork CharReader::fork() { - return CharReaderFork(buffer, readCursor, peekCursor, coherent); + return CharReaderFork(buffer, readCursor, peekCursor, sourceId, offs, + coherent); } size_t CharReader::readRaw(char *buf, size_t size) @@ -528,155 +502,38 @@ size_t CharReader::readRaw(char *buf, size_t size) return res; } -SourceContext CharReader::getContextAt(ssize_t maxSize, - Buffer::CursorId referenceCursor) -{ - // Clone the given read cursor - Buffer::CursorId cur = buffer->createCursor(referenceCursor); - - // Fetch the start position of the search - ssize_t offs = buffer->offset(cur); - ssize_t start = offs; - ssize_t end = offs; - char c; - - // Search the beginning of the line with the last non-whitespace character - bool hadNonWhitespace = false; - bool foundBegin = false; - for (ssize_t i = 0; i < maxSize; i++) { - // Fetch the character at the current position - if (buffer->fetch(cur, c)) { - // Abort, at linebreaks if we found a non-linebreak character - hadNonWhitespace = hadNonWhitespace || !Utils::isWhitespace(c); - if (hadNonWhitespace && (c == '\n' || c == '\r')) { - buffer->moveCursor(cur, 1); - start++; - foundBegin = true; - break; - } - } - if (buffer->moveCursor(cur, -1) == 0) { - foundBegin = true; - break; - } else { - // Update the start position and the hadNonWhitespace flag - start--; - } - } - - // Search the end of the line - buffer->moveCursor(cur, offs - start); - bool foundEnd = false; - for (ssize_t i = 0; i < maxSize; i++) { - // Increment the end counter if a character was read, abort if the end - // of the stream has been reached - if (buffer->read(cur, c)) { - end++; - } else { - foundEnd = true; - break; - } - - // Abort on linebreak characters - if (c == '\n' || c == '\r') { - foundEnd = true; - break; - } - } - - // Calculate the truncated start and end position and limit the number of - // characters to the maximum number of characters - ssize_t tStart = start; - ssize_t tEnd = end; - if (tEnd - tStart > maxSize) { - tStart = std::max(offs - maxSize / 2, tStart); - tEnd = tStart + maxSize; - } - - // Try to go to the calculated start position and fetch the actual start - // position - ssize_t aStart = end + buffer->moveCursor(cur, tStart - end); - if (aStart > tStart) { - tEnd = tEnd + (aStart - tStart); - tStart = aStart; - } - - // Read one line - std::stringstream ss; - size_t relPos = 0; - for (ssize_t i = tStart; i < tEnd; i++) { - if (buffer->read(cur, c)) { - // Break once a linebreak is reached - if (c == '\n' || c == '\r') { - break; - } - - // Add the current character to the output - ss << c; - - // Increment the string-relative offset as long as the original - // offset is not reached in the for loop - if (i < offs) { - relPos++; - } - } - } - - // Delete the newly created cursor - buffer->deleteCursor(cur); - - return SourceContext{ss.str(), relPos, !foundBegin || tStart != start, - !foundEnd || tEnd != end}; -} - -SourceContext CharReader::getContextAtOffs(ssize_t maxSize, size_t offs) -{ - // Create a new cursor and calculate how far it has to be moved to reach - // the position specified in the location instance - Buffer::CursorId cur = buffer->createCursor(); - ssize_t moveOffs = offs - buffer->offset(cur); - - // Try to move the cursor to the specified position and read the context - SourceContext res; - if (buffer->moveCursor(cur, moveOffs) == moveOffs) { - res = getContextAt(60, cur); - } - - // Delete the read cursor - buffer->deleteCursor(cur); - return res; -} +bool CharReader::atEnd() const { return buffer->atEnd(readCursor.cursor); } -SourceContext CharReader::getContext(ssize_t maxSize) +size_t CharReader::getOffset() const { - return getContextAt(maxSize, readCursor.cursor); + return buffer->offset(readCursor.cursor) + offs; } -SourceContext CharReader::contextCallback(const SourceLocation &location, - void *data) +SourceLocation CharReader::getLocation() const { - return static_cast(data)->getContextAtOffs(60, location.offs); + return SourceLocation{sourceId, getOffset()}; } /* Class CharReaderFork */ CharReaderFork::CharReaderFork(std::shared_ptr buffer, - CharReader::Cursor &parentReadCursor, - CharReader::Cursor &parentPeekCursor, + Buffer::CursorId parentReadCursor, + Buffer::CursorId parentPeekCursor, + SourceContextCallback sourceId, size_t offs, bool coherent) - : CharReader(buffer, 1, 1), + : CharReader(buffer, sourceId, offs), parentReadCursor(parentReadCursor), parentPeekCursor(parentPeekCursor) { - readCursor.assign(buffer, parentReadCursor); - peekCursor.assign(buffer, parentPeekCursor); + buffer->copyCursor(parentReadCursor, readCursor); + buffer->copyCursor(parentPeekCursor, peekCursor); this->coherent = coherent; } void CharReaderFork::commit() { - parentReadCursor.assign(buffer, readCursor); - parentPeekCursor.assign(buffer, peekCursor); + buffer->copyCursor(readCursor, parentReadCursor); + buffer->copyCursor(peekCursor, parentPeekCursor); } } diff --git a/src/core/common/CharReader.hpp b/src/core/common/CharReader.hpp index 134d9d9..0957e97 100644 --- a/src/core/common/CharReader.hpp +++ b/src/core/common/CharReader.hpp @@ -355,54 +355,10 @@ class CharReaderFork; /** * Used within parsers for convenient access to single characters in an input * stream or buffer. It allows reading and peeking single characters from a - * buffer. Additionally it counts the current column/row (with correct handling - * for UTF-8) and contains an internal state machine that handles the detection - * of linebreaks and converts these to a single '\n'. + * buffer. Additionally it contains an internal state machine that handles the + * detection of linebreaks and converts these to a single '\n'. */ class CharReader { -protected: - /** - * Internally used cursor structure for managing the read and the peek - * cursor. - */ - struct Cursor { - /** - * Corresponding cursor in the underlying buffer instance. - */ - const Buffer::CursorId cursor; - - /** - * Current line the cursor is in. - */ - int line; - - /** - * Current column the cursor is in. - */ - int column; - - /** - * Constructor of the Cursor class. - * - * @param cursor is the underlying cursor in the Buffer instance. - * @param line is the line at which the cursor is positioned. - * @param column is the column at which the cursor is positioned. - */ - Cursor(Buffer::CursorId cursor, int line, int column) - : cursor(cursor), line(line), column(column) - { - } - - /** - * Assigns one cursor to another. - * - * @param buffer is the underlying buffer instance the internal cursor - * belongs to. - * @param cursor is the cursor from which the state should be copied. - */ - void assign(std::shared_ptr buffer, Cursor &cursor); - }; - private: /** * Substitutes "\r", "\n\r", "\r\n" with a single "\n". @@ -421,29 +377,7 @@ private: * @return true if a character was read, false if the end of the stream has * been reached. */ - bool readAtCursor(Cursor &cursor, char &c); - - /** - * Returns the line the given cursor currently is in, but at most the - * given number of characters in the form of a Context structure. - * - * @param maxSize is the maximum length of the extracted context - * @param referenceCursor is a cursor in the internal buffer pointing at the - * location at which the context should be read. - */ - SourceContext getContextAt(ssize_t maxSize, - Buffer::CursorId referenceCursor); - - /** - * Returns the line the at the given byte offset, but at most the - * given number of characters in the form of a Context structure. - * - * @param maxSize is the maximum length of the extracted context - * @param offs is the byte offset for which the context should be read. - * @return the context at the specified position or an empty (invalid) - * context if the context could not be read. - */ - SourceContext getContextAtOffs(ssize_t maxSize, size_t offs); + bool readAtCursor(Buffer::CursorId &cursor, char &c); protected: /** @@ -454,12 +388,12 @@ protected: /** * Cursor used for reading. */ - Cursor readCursor; + Buffer::CursorId readCursor; /** * Cursor used for peeking. */ - Cursor peekCursor; + Buffer::CursorId peekCursor; /** * Set to true as long the underlying Buffer cursor is at the same position @@ -468,34 +402,51 @@ protected: */ bool coherent; + /** + * Id of the underlying source file. + */ + SourceId sourceId; + + /** + * Offset to be added to the underlying buffer byte positions. + */ + size_t offs; + /** * Protected constructor of the CharReader base class. Creates new read * and peek cursors for the given buffer. * * @param buffer is a reference to the underlying Buffer class responsible * for allowing to read from a single input stream from multiple locations. + * @param sourceId is the ID of the underlying source file. + * @param offs is the byte offset at which the char reader should start + * counting. */ - CharReader(std::shared_ptr buffer, size_t line, size_t column); + CharReader(std::shared_ptr buffer, SourceId sourceId, size_t offs); public: /** * Creates a new CharReader instance from a string. * * @param str is a string containing the input data. - * @param line is the start line. - * @param column is the start column. + * @param sourceId is the ID of the underlying source file. + * @param offs is the byte offset at which the char reader should start + * counting. */ - CharReader(const std::string &str, size_t line = 1, size_t column = 1); + CharReader(const std::string &str, SourceId sourceId = InvalidSourceId, + size_t offs = 0); /** * Creates a new CharReader instance for an input stream. * * @param istream is the input stream from which incomming data should be * read. - * @param line is the start line. - * @param column is the start column. + * @param sourceId is the ID of the underlying source file. + * @param offs is the byte offset at which the char reader should start + * counting. */ - CharReader(std::istream &istream, size_t line = 1, size_t column = 1); + CharReader(std::istream &istream, SourceId sourceId = InvalidSourceId, + size_t offs = 0); /** * Deletes the used cursors from the underlying buffer instance. @@ -572,56 +523,27 @@ public: size_t readRaw(char *buf, size_t size); /** - * Returns true if there are no more characters as the stream was - * closed. + * Returns true if there are no more characters as the stream was closed. * * @return true if there is no more data. */ - bool atEnd() const { return buffer->atEnd(readCursor.cursor); } + bool atEnd() const; /** * Returns the offset of the read cursor in bytes. - */ - size_t getOffset() const { return buffer->offset(readCursor.cursor); } - - /** - * Returns the line number the read cursor currently is at. - */ - int getLine() const { return readCursor.line; } - - /** - * Returns the column the read cursor currently is at. - */ - int getColumn() const { return readCursor.column; } - - /** - * Returns the current position of the read cursor (line and column). - */ - SourceLocation getLocation() const - { - return SourceLocation(getLine(), getColumn(), getOffset()); - } - - /** - * Returns the line the read cursor currently is in, but at most the - * given number of characters in the form of a Context structure. * - * @param maxSize is the maximum length of the extracted context + * @return the offset of the read cursor in bytes. */ - SourceContext getContext(ssize_t maxSize = 60); + size_t getOffset() const; /** - * Function that can be used to provide the context for a certain source - * location. A pointer to this function can be supplied to a Logger instance - * in the pushFile() method. The data should be set to a pointer to the - * CharReader instance. + * Returns a SourceLocation object describing the exact position (including + * the source file) of the read cursor. * - * @param location is the location for which the context should be returned. - * Only the "offs" field within the location is used. - * @param data is a pointer pointing at a CharReader instance. + * @return a SourceLocation object at the position of the current read + * cursor. */ - static SourceContext contextCallback(const SourceLocation &location, - void *data); + SourceLocation getLocation() const; }; /** @@ -637,12 +559,12 @@ private: /** * The reader cursor of the underlying CharReader instance. */ - CharReader::Cursor &parentReadCursor; + Buffer::CursorId parentReadCursor; /** * The peek cursor of the underlying CharReader instance. */ - CharReader::Cursor &parentPeekCursor; + Buffer::CursorId parentPeekCursor; /** * Constructor of the CharReaderFork class. @@ -650,12 +572,14 @@ private: * @param buffer is a reference at the parent Buffer instance. * @param parentPeekCursor is a reference at the parent read cursor. * @param parentPeekCursor is a reference at the parent peek cursor. + * @param location is the current location. * @param coherent specifies whether the char reader cursors are initialized * coherently. */ CharReaderFork(std::shared_ptr buffer, - CharReader::Cursor &parentReadCursor, - CharReader::Cursor &parentPeekCursor, bool coherent); + Buffer::CursorId &parentReadCursor, + Buffer::CursorId &parentPeekCursor, + SourceContextCallback sourceId, size_t offs, bool coherent); public: /** -- cgit v1.2.3 From 45a3d085b86e4d761a30718d05be40d4640ba63f Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 12:08:15 +0100 Subject: Adapted LoggableException according to new SourceLocation class. --- src/core/common/Exceptions.cpp | 16 ---------------- src/core/common/Exceptions.hpp | 26 +++++++++++++++----------- 2 files changed, 15 insertions(+), 27 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/Exceptions.cpp b/src/core/common/Exceptions.cpp index e368b5a..caba7cc 100644 --- a/src/core/common/Exceptions.cpp +++ b/src/core/common/Exceptions.cpp @@ -22,21 +22,5 @@ namespace ousia { -/* Class LoggableException */ - -std::string LoggableException::formatMessage(const std::string &msg, - const SourceLocation &loc) -{ - std::stringstream ss; - ss << "error "; - if (loc.hasLine()) { - ss << "at line " << loc.line << ", "; - if (loc.hasColumn()) { - ss << "column " << loc.column << " "; - } - } - ss << "with message: " << msg; - return ss.str(); -} } diff --git a/src/core/common/Exceptions.hpp b/src/core/common/Exceptions.hpp index 2a88427..0be33b3 100644 --- a/src/core/common/Exceptions.hpp +++ b/src/core/common/Exceptions.hpp @@ -77,14 +77,6 @@ public: * makes it simple to handle non-recoverable errors in the code. */ class LoggableException : public OusiaException { -private: - /** - * Function used internally to build the formated message that should be - * reported to the runtime environment. - */ - static std::string formatMessage(const std::string &msg, - const SourceLocation &loc); - public: /** * Reported error message. @@ -104,7 +96,7 @@ public: */ LoggableException(std::string msg, SourceLocation loc = SourceLocation{}) - : OusiaException(formatMessage(msg, loc)), + : OusiaException(msg), msg(std::move(msg)), loc(std::move(loc)) { @@ -128,14 +120,26 @@ public: * Constructor of LoggableException for arbitrary position objects. * * @param msg is the actual log message. - * @param loc is a reference to a variable with position and context data. + * @param loc is a reference to a variable with location data. */ template - LoggableException(std::string msg, LocationType &loc) + LoggableException(std::string msg, const LocationType &loc) : LoggableException(std::move(msg), loc.getLocation()) { } + /** + * Constructor of LoggableException for arbitrary position objects. + * + * @param msg is the actual log message. + * @param loc is a pointe to a variable with location data. + */ + template + LoggableException(std::string msg, const LocationType *loc) + : LoggableException(std::move(msg), loc->getLocation()) + { + } + /** * Returns the position at which the exception occured in the text. * -- cgit v1.2.3 From 6dbb4d19a860937ec1c78df01b1371272e1de8de Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 12:08:42 +0100 Subject: Improved SourceLocation class. --- src/core/common/Location.cpp | 9 +++++++++ src/core/common/Location.hpp | 29 +++++++++++++++++++++++++---- 2 files changed, 34 insertions(+), 4 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/Location.cpp b/src/core/common/Location.cpp index 6f9250a..7a75347 100644 --- a/src/core/common/Location.cpp +++ b/src/core/common/Location.cpp @@ -19,5 +19,14 @@ #include "Location.hpp" namespace ousia { + +/* Global Functions */ + +const SourceLocation NullSourceLocation; + +void SourceContext NullSourceContextCallback(const SourceLocation &location) +{ + return SourceContext{}; +} } diff --git a/src/core/common/Location.hpp b/src/core/common/Location.hpp index 4ce01a8..57892cc 100644 --- a/src/core/common/Location.hpp +++ b/src/core/common/Location.hpp @@ -29,6 +29,7 @@ #define _OUSIA_LOCATION_HPP_ #include +#include #include #include @@ -272,7 +273,7 @@ public: /** * Default constructor. */ - SourceLocation() : sourceId(InvalidSourceId) {}; + SourceLocation() : sourceId(InvalidSourceId){}; /** * Constructor, binds the SourceLocation to the given source file. @@ -346,6 +347,11 @@ public: } }; +/** + * NullSourceLocation is an empty SourceLocation instance. + */ +extern const SourceLocation NullSourceLocation; + /** * Represents the context of a SourceLocation instance. Used to build error * messages. @@ -435,6 +441,11 @@ struct SourceContext { */ bool isValid() const { return range.isValid() && hasLine() && hasColumn(); } + /** + * Returns true if a valid (non-empty) filename is set. + */ + bool hasFile() const { return !filename.empty(); } + /** * Returns true, if the start line number is valid, false otherwise. * @@ -455,10 +466,20 @@ struct SourceContext { * location. * * @param location is the location for which the context should be looked up. - * @param data is used defined data associated with the callback. + * @return the corresponding SourceContext. */ -using SourceContextCallback = SourceContext (*)(const SourceLocation &location, - void *data); +using SourceContextCallback = + std::function; + +/** + * Function to be used as default value for the SourceContextCallback. Returns + * an invalid SourceContext. + * + * @param location is the location for which the context should be looked up. + * @return an empty, invalid SourceContext. + */ +void SourceContext NullSourceContextCallback(const SourceLocation &location); + } #endif /* _OUSIA_LOCATION_HPP_ */ -- cgit v1.2.3 From a7e40c1f1572b05e9608e0ed43ac54c1f7e7d84b Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 12:09:14 +0100 Subject: Adapted Logger class --- src/core/common/Logger.cpp | 168 +++++++++++------ src/core/common/Logger.hpp | 447 +++++++++++++++++++++++---------------------- 2 files changed, 336 insertions(+), 279 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/Logger.cpp b/src/core/common/Logger.cpp index fa4b5c8..9f070f9 100644 --- a/src/core/common/Logger.cpp +++ b/src/core/common/Logger.cpp @@ -27,10 +27,11 @@ namespace ousia { /* Class Logger */ void Logger::log(Severity severity, const std::string &msg, - const SourceLocation &loc) + const SourceLocation &loc, + MessageMode mode = MessageMode::DEFAULT) { // Assemble the message and pass it through the filter, then process it - Message message { severity, std::move(msg), loc }; + Message message{severity, std::move(msg), loc, mode}; if (filterMessage(message)) { processMessage(message); } @@ -42,30 +43,37 @@ LoggerFork Logger::fork() { return LoggerFork(this); } void LoggerFork::processMessage(const Message &msg) { - calls.push_back(Call(CallType::MESSAGE, messages.size())); + calls.emplace_back(CallType::MESSAGE, messages.size()); messages.push_back(msg); } -void LoggerFork::processPushFile(const File &file) +void LoggerFork::processPushDefaultLocation(const SourceLocation &loc) { - calls.push_back(Call(CallType::PUSH_FILE, files.size())); - files.push_back(file); + calls.emplace_back(CallType::PUSH_LOCATION, locations.size()); + locations.push_back(loc); } -void LoggerFork::processPopFile() +void LoggerFork::processPopDefaultLocation() { - calls.push_back(Call(CallType::POP_FILE, 0)); + calls.emplace_back(CallType::POP_LOCATION, 0); } void LoggerFork::processSetDefaultLocation(const SourceLocation &loc) { - // Check whether setDefaultLocation was called immediately before, if yes, - // simply override the data - if (!calls.empty() && calls.back().type == CallType::SET_DEFAULT_LOCATION) { - locations.back() = loc; + calls.emplace_back(CallType : SET_LOCATION, locations.size()); + locations.push_back(loc); +} + +void LoggerFork::processSetSourceContextCallback( + SourceContextCallback sourceContextCallback) +{ + // Check whether setSourceContextCallback was called immediately before, + // if yes, simply override the data + if (!calls.empty() && calls.back().type == CallType::SET_CONTEXT_CALLBACK) { + callbacks.back() = loc; } else { - calls.push_back(Call(CallType::SET_DEFAULT_LOCATION, locations.size())); - locations.push_back(loc); + calls.emplace_back(CallType::SET_CONTEXT_CALLBACK, callbacks.size()); + callbacks.emplace_back(sourceContextCallback); } } @@ -73,45 +81,91 @@ void LoggerFork::purge() { calls.clear(); messages.clear(); - files.clear(); locations.clear(); + callbacks.clear(); } void LoggerFork::commit() { for (const Call &call : calls) { switch (call.type) { - case CallType::MESSAGE: { + case CallType::MESSAGE: if (parent->filterMessage(messages[call.dataIdx])) { parent->processMessage(messages[call.dataIdx]); } break; - } - case CallType::PUSH_FILE: { - parent->processPushFile(files[call.dataIdx]); + case CallType::PUSH_LOCATION: + parent->processPushDefaultLocation(locations[call.dataIdx]); break; - } - case CallType::POP_FILE: - parent->processPopFile(); + case CallType::POP_LOCATION: + parent->processPopDefaultLocation(); break; - case CallType::SET_DEFAULT_LOCATION: + case CallType::SET_LOCATION: parent->processSetDefaultLocation(locations[call.dataIdx]); break; + case CallType::SET_CONTEXT_CALLBACK: + parent->processSetSourceContextCallback( + callbacks[call.dataIdx]); + break; } } purge(); } -/* Class ConcreteLogger */ +/* Class ScopedLogger */ + +ScopedLogger::ScopedLogger(Logger &parent, SourceLocation loc = SourceLocation{}) + : Logger(), parent(parent), depth(0) +{ + pushDefaultLocation(loc); +} + +ScopedLogger::~ScopedLogger() +{ + while (depth > 0) { + popDefaultLocation(); + } +} + +void ScopedLogger::processMessage(const Message &msg) +{ + parent.processMessage(msg); +} + +bool ScopedLogger::filterMessage(const Message &msg) +{ + return parent.filterMessage(msg); +} + +void ScopedLogger::processPushDefaultLocation(const SourceLocation &loc) +{ + parent.processPushDefaultLocation(loc); + depth++; +} + +void ScopedLogger::processPopDefaultLocation() +{ + depth--; + parent.processPopDefaultLocation(); +} -static const Logger::File EMPTY_FILE{"", SourceLocation{}, nullptr, nullptr}; +void ScopedLogger::processSetDefaultLocation(const SourceLocation &loc) +{ + parent.processSetDefaultLocation(loc); +} -void ConcreteLogger::processPushFile(const File &file) +void ScopedLogger::processSetSourceContextCallback( + SourceContextCallback sourceContextCallback) { - files.push_back(file); + parent.processSetContextCallback(sourceContextCallback); } -void ConcreteLogger::processPopFile() { files.pop_back(); } +/* Class ConcreteLogger */ + +ConcreteLogger(Severity minSeverity = Severity::DEFAULT_MIN_SEVERITY) + : minSeverity(minSeverity), sourceContextCallback(NullSourceContextCallback) +{ +} bool ConcreteLogger::filterMessage(const Message &msg) { @@ -126,40 +180,38 @@ bool ConcreteLogger::filterMessage(const Message &msg) return sev >= static_cast(minSeverity); } -void ConcreteLogger::processSetDefaultLocation(const SourceLocation &loc) -{ - defaultLocation = loc; +void ConcreteLogger::processPushDefaultLocation(const SourceLocation &loc) { + locations.emplace_back(loc); } -const Logger::File &ConcreteLogger::currentFile() const -{ - if (!files.empty()) { - return files.back(); +void ConcreteLogger::processPopDefaultLocation() { + if (!locations.empty()) { + locations.pop_back(); } - return EMPTY_FILE; } -const std::string &ConcreteLogger::currentFilename() const +void ConcreteLogger::processSetDefaultLocation(const SourceLocation &loc) { - return currentFile().file; + if (!locations.empty()) { + locations.back() = loc; + } else { + locations.emplace_back(loc); + } } const SourceLocation &ConcreteLogger::messageLocation(const Message &msg) const { if (msg.loc.valid()) { return msg.loc; + } else if (!locatios.empty()) { + return locations.back(); } - return defaultLocation; + return NullSourceLocation; } SourceContext ConcreteLogger::messageContext(const Message &msg) const { - const Logger::File &file = currentFile(); - const SourceLocation &loc = messageLocation(msg); - if (file.ctxCallback && loc.valid()) { - return file.ctxCallback(loc, file.ctxCallbackData); - } - return SourceContext{}; + return sourceContextCallback(messageLocation(msg)); } Severity ConcreteLogger::getMaxEncounteredSeverity() @@ -193,6 +245,11 @@ bool ConcreteLogger::hasError() getSeverityCount(Severity::FATAL_ERROR) > 0; } +bool ConcreteLogger::hasFatalError() +{ + return getSeverityCount(Severity::FATAL_ERROR) > 0; +} + /* Class TerminalLogger */ void TerminalLogger::processMessage(const Message &msg) @@ -200,29 +257,26 @@ void TerminalLogger::processMessage(const Message &msg) Terminal t(useColor); // Fetch filename, position and context - const std::string filename = currentFilename(); - const SourceLocation pos = messageLocation(msg); const SourceContext ctx = messageContext(msg); // Print the file name - bool hasFile = !filename.empty(); - if (hasFile) { - os << t.bright() << filename << t.reset(); + if (ctx.hasFile()) { + os << t.bright() << ctx.filename << t.reset(); } // Print line and column number - if (pos.hasLine()) { + if (ctx.hasLine()) { if (hasFile) { os << ':'; } - os << t.bright() << pos.line << t.reset(); - if (pos.hasColumn()) { - os << ':' << pos.column; + os << t.bright() << ctx.startLine << t.reset(); + if (ctx.hasColumn()) { + os << ':' << ctx.startColumn; } } // Print the optional seperator - if (hasFile || pos.hasLine()) { + if (ctx.hasFile() || ctx.hasLine()) { os << ": "; } @@ -249,7 +303,7 @@ void TerminalLogger::processMessage(const Message &msg) os << msg.msg << std::endl; // Print the error message context if available - if (ctx.valid()) { +/* if (ctx.valid()) { size_t relPos = ctx.relPos; if (ctx.truncatedStart) { os << "[...] "; @@ -272,7 +326,7 @@ void TerminalLogger::processMessage(const Message &msg) } } os << t.color(Terminal::GREEN) << '^' << t.reset() << std::endl; - } + }*/ } } diff --git a/src/core/common/Logger.hpp b/src/core/common/Logger.hpp index 767d8ab..092bd3a 100644 --- a/src/core/common/Logger.hpp +++ b/src/core/common/Logger.hpp @@ -73,6 +73,40 @@ enum class Severity : uint8_t { FATAL_ERROR = 4 }; +/** + * Enum signifying how the message should be displayed. MessageMode constants + * can be combined using the bitwise or (|) operator. + */ +enum class MessageMode : uint8_t { + /** + * Default display mode. + */ + DEFAULT = 0, + + /** + * Do not display a context. + */ + NO_CONTEXT = 1, + + /** + * Do not display a file backtrace. + */ + NO_TRACE = 2 +}; + +/** + * Bitwise or for the MessageMode class. + * + * @param a is the first MessageMode. + * @param b is the second MessageMode. + * @return the two message modes combined using bitwise or. + */ +inline MessageMode operator|(MessageMode a, MessageMode b) +{ + return static_cast(static_cast(a) | + static_cast(b)); +} + // Forward declaration class LoggerFork; class ScopedLogger; @@ -91,51 +125,6 @@ public: friend LoggerFork; friend ScopedLogger; - /** - * Describes a file inclusion. - */ - struct File { - /** - * Current filename. - */ - std::string file; - - /** - * Location at which the file was included. - */ - SourceLocation loc; - - /** - * Callback used to retrieve the context for a certain location - */ - SourceContextCallback ctxCallback; - - /** - * Data to be passed to the callback. - */ - void *ctxCallbackData; - - /** - * Constructor of the Scope struct. - * - * @param type is the type of - * @param file is the name of the current file. - * @param loc is the location at which the file was included. - * @param ctxCallback is the callback function that should be called - * for looking up the context belonging to a SourceLocation instance. - * @param ctxCallbackData is additional data that should be passed to - * the callback function. - */ - File(std::string file, SourceLocation loc, - SourceContextCallback ctxCallback, void *ctxCallbackData) - : file(std::move(file)), - loc(loc), - ctxCallback(ctxCallback), - ctxCallbackData(ctxCallbackData) - { - } - }; - /** * The message struct represents a single log message and all information * attached to it. @@ -146,6 +135,11 @@ public: */ Severity severity; + /** + * Message mode. + */ + MessageMode mode; + /** * Actual log message. */ @@ -156,16 +150,52 @@ public: */ SourceLocation loc; + /** + * Default constructor of the Message struct. + */ + Message() : severity(Severity::DEBUG), mode(MessageMode::DEFAULT) {} + /** * Constructor of the Message struct. * * @param severity describes the message severity. + * @param mode is the mode in which the message should be displayed. * @param msg contains the actual message. + * @param loc is the location at which the message should be displayed. */ - Message(Severity severity, std::string msg, const SourceLocation &loc) - : severity(severity), msg(std::move(msg)), loc(loc){}; + Message(Severity severity, MessageMode mode, std::string msg, + const SourceLocation &loc) + : severity(severity), mode(mode), msg(std::move(msg)), loc(loc) + { + } }; + /** + * Calls the getLocation function on the given reference. + * + * @param obj is the object on which the getLocation function should be + * called. + * @return the SourceLocation returned by the getLocation function. + */ + template + static SourceLocation location(const T &obj) + { + return obj.getLocation(); + } + + /** + * Calls the getLocation function on the given pointer. + * + * @param obj is the object on which the getLocation function should be + * called. + * @return the SourceLocation returned by the getLocation function. + */ + template + static SourceLocation location(const T *obj) + { + return obj->getLocation(); + } + protected: /** * Function to be overriden by child classes to actually display or store @@ -188,24 +218,37 @@ protected: virtual bool filterMessage(const Message &msg) { return true; } /** - * Called whenever a new file is pushed onto the stack. + * Called whenever the pushDefaultLocation function is called. * - * @param file is the file structure that should be stored on the stack. + * @param loc is the default location that should be pushed onto the stack. */ - virtual void processPushFile(const File &file) {} + virtual void processPushDefaultLocation(const SourceLocation &loc) {} /** - * Called whenever a scope is popped from the stack. + * Called whenever the popDefaultLocation function is called. + * + * @param loc is the default location that should be popped from the stack. */ - virtual void processPopFile() {} + virtual void processPopDefaultLocation() {} /** * Called whenever the setDefaultLocation function is called. * - * @param loc is the default location that should be set. + * @param loc is the default location that shuold replace the current one on + * the stack. */ virtual void processSetDefaultLocation(const SourceLocation &loc) {} + /** + * Called whenever the setSourceContextCallback function is called. + * + * @param sourceContextCallback is the callback function that should be set. + */ + virtual void processSetSourceContextCallback( + SourceContextCallback sourceContextCallback) + { + } + public: /** * Virtual destructor. @@ -228,28 +271,25 @@ public: * @param severity is the severity of the log message. * @param msg is the actual log message. * @param loc is the location in the source file the message refers to. + * @param mode specifies how the message should be displayed. */ void log(Severity severity, const std::string &msg, - const SourceLocation &loc = SourceLocation{}); + const SourceLocation &loc = SourceLocation{}, + MessageMode mode = MessageMode::DEFAULT); /** * Logs the given loggable exception. * * @param ex is the exception that should be logged. + * @param loc is a location which (if valid overrides the location given in + * the exception. + * @param mode specifies how the message should be displayed. */ - void log(const LoggableException &ex) - { - log(Severity::ERROR, ex.msg, ex.getLocation()); - } - - /** - * Logs the given loggable exception at the given location. - * - * @param ex is the exception that should be logged. - */ - void log(const LoggableException &ex, const SourceLocation &loc) + void log(const LoggableException &ex, + const SourceLocation &loc = SourceLocation{}, + MessageMode mode = MessageMode::DEFAULT) { - log(Severity::ERROR, ex.msg, loc.valid() ? loc : ex.getLocation()); + log(Severity::ERROR, ex.msg, loc.isValid() ? loc : ex.getLocation()); } /** @@ -260,11 +300,13 @@ public: * @param msg is the actual log message. * @param loc is a reference to a variable which provides location * information. + * @param mode specifies how the message should be displayed. */ template - void log(Severity severity, const std::string &msg, LocationType &loc) + void log(Severity severity, const std::string &msg, LocationType loc, + MessageMode mode = MessageMode::DEFAULT) { - log(severity, msg, loc.getLocation()); + log(severity, msg, location(loc), mode); } /** @@ -275,10 +317,11 @@ public: * @param loc is the location in the source file the message refers to. */ void debug(const std::string &msg, - const SourceLocation &loc = SourceLocation{}) + const SourceLocation &loc = SourceLocation{}, + MessageMode mode = MessageMode::DEFAULT) { #ifndef NDEBUG - log(Severity::DEBUG, msg, loc); + log(Severity::DEBUG, msg, loc, mode); #endif } @@ -291,10 +334,11 @@ public: * information. */ template - void debug(const std::string &msg, LocationType &loc) + void debug(const std::string &msg, LocationType loc, + MessageMode mode = MessageMode::DEFAULT) { #ifndef NDEBUG - log(Severity::DEBUG, msg, loc); + log(Severity::DEBUG, msg, loc, mode); #endif } @@ -305,9 +349,10 @@ public: * @param loc is the location in the source file the message refers to. */ void note(const std::string &msg, - const SourceLocation &loc = SourceLocation{}) + const SourceLocation &loc = SourceLocation{}, + MessageMode mode = MessageMode::DEFAULT) { - log(Severity::NOTE, msg, loc); + log(Severity::NOTE, msg, loc, mode); } /** @@ -318,9 +363,10 @@ public: * information. */ template - void note(const std::string &msg, LocationType &loc) + void note(const std::string &msg, LocationType loc, + MessageMode mode = MessageMode::DEFAULT) { - log(Severity::NOTE, msg, loc); + log(Severity::NOTE, msg, loc, mode); } /** @@ -330,9 +376,10 @@ public: * @param loc is a reference to a variable which provides position */ void warning(const std::string &msg, - const SourceLocation &loc = SourceLocation{}) + const SourceLocation &loc = SourceLocation{}, + MessageMode mode = MessageMode::DEFAULT) { - log(Severity::WARNING, msg, loc); + log(Severity::WARNING, msg, loc, mode); } /** @@ -343,9 +390,10 @@ public: * information. */ template - void warning(const std::string &msg, LocationType &loc) + void warning(const std::string &msg, LocationType loc, + MessageMode mode = MessageMode::DEFAULT) { - log(Severity::WARNING, msg, loc); + log(Severity::WARNING, msg, location(loc), mode); } /** @@ -355,9 +403,10 @@ public: * @param loc is a reference to a variable which provides position */ void error(const std::string &msg, - const SourceLocation &loc = SourceLocation{}) + const SourceLocation &loc = SourceLocation{}, + MessageMode mode = MessageMode::DEFAULT) { - log(Severity::ERROR, msg, std::move(loc)); + log(Severity::ERROR, msg, loc, mode); } /** @@ -368,9 +417,10 @@ public: * information. */ template - void error(const std::string &msg, LocationType &loc) + void error(const std::string &msg, LocationType loc, + MessageMode mode = MessageMode::DEFAULT) { - log(Severity::ERROR, msg, loc); + log(Severity::ERROR, msg, location(loc), mode); } /** @@ -380,9 +430,10 @@ public: * @param loc is a reference to a variable which provides position */ void fatalError(const std::string &msg, - const SourceLocation &loc = SourceLocation{}) + const SourceLocation &loc = SourceLocation{}, + MessageMode mode = MessageMode::DEFAULT) { - log(Severity::FATAL_ERROR, msg, loc); + log(Severity::FATAL_ERROR, msg, loc, mode); } /** @@ -393,41 +444,44 @@ public: * information. */ template - void fatalError(const std::string &msg, LocationType &loc) + void fatalError(const std::string &msg, LocationType loc, + MessageMode mode = MessageMode::DEFAULT) { - log(Severity::FATAL_ERROR, msg, loc); + log(Severity::FATAL_ERROR, msg, location(loc), mode); } /** - * Pushes a new file name onto the internal filename stack. + * Sets the source context callback to be used to resolve SourceLocation + * instances to SourceContext instances. The sourceContextCallback should be + * set as early as possible when using the logger. * - * @param name is the name of the file to be added to the stack. - * @param loc is the position from which the new file is included. - * @param ctxCallback is the callback function that should be called if a - * SourceLocation needs to be resolved to a SourceContext. - * @param ctxCallbackData is the data that should be passed to the callback. + * @param sourceContextCallback is the new sourceContextCallback to be used. */ - void pushFile(std::string name, SourceLocation loc = SourceLocation{}, - SourceContextCallback ctxCallback = nullptr, - void *ctxCallbackData = nullptr) + void setSourceContextCallback(SourceContextCallback sourceContextCallback) { - processPushFile( - File(std::move(name), loc, ctxCallback, ctxCallbackData)); + processSetSourceContextCallback(sourceContextCallback); } /** - * Pops the filename from the internal filename stack. Resets any location - * set by the setDefaultLocation() method. + * Pushes a new default location onto the default location stack. + * + * @param loc is the location that should be used if no (valid) location is + * specified in the Logger. */ - void popFile() + void pushDefaultLocation(const SourceLocation &loc) { - processPopFile(); - resetDefaultLocation(); + processPushDefaultLocation(loc); } /** - * Sets the default location. The default location is automatically reset - * once the popFile() method is called. + * Pops the last default location from the default location stack. + */ + void popDefaultLocation() { processPopDefaultLocation(); } + + /** + * Replaces the topmost default location on the location stack with the + * given location. Creates a new entry in the location stack if the stack + * was empty. * * @param loc is the location that should be used if no (valid) location is * specified in the Logger. @@ -437,12 +491,6 @@ public: processSetDefaultLocation(loc); } - /** - * Resets the default location, a previously set default location will be - * no longer used. - */ - void resetDefaultLocation() { processSetDefaultLocation(SourceLocation{}); } - /** * Returns a forked logger instance which can be used to collect log * messages for which it is not sure whether they will be used. @@ -469,7 +517,13 @@ private: /** * Intanally used to store the incomming function calls. */ - enum class CallType { MESSAGE, PUSH_FILE, POP_FILE, SET_DEFAULT_LOCATION }; + enum class CallType { + MESSAGE, + PUSH_LOCATION, + POP_LOCATION, + SET_LOCATION, + SET_CONTEXT_CALLBACK + }; /** * Datastructure used to represent a logger function call. @@ -506,14 +560,14 @@ private: std::vector messages; /** - * Vector storing all incomming pushed Scope instances. + * Vector storing all incomming location instances. */ - std::vector files; + std::vector locations; /** - * Vector storing all incomming location instances. + * Vector storing all incomming source context callbacks. */ - std::vector locations; + std::vector callbacks; /** * Parent logger instance. @@ -529,9 +583,11 @@ private: protected: void processMessage(const Message &msg) override; - void processPushFile(const File &file) override; - void processPopFile() override; + void processPushDefaultLocation(const SourceLocation &loc) override; + void processPopDefaultLocation() override; void processSetDefaultLocation(const SourceLocation &loc) override; + void processSetSourceContextCallback( + SourceContextCallback sourceContextCallback) override; public: // Default move constructor @@ -578,93 +634,54 @@ protected: * * @param msg is the message to be relayed to the parent logger. */ - void processMessage(const Message &msg) override - { - parent.processMessage(msg); - } + void processMessage(const Message &msg) override; /** * Relays the filterMessage call to the parent logger. * * @param msg is the message to be relayed to the parent logger. */ - bool filterMessage(const Message &msg) override - { - return parent.filterMessage(msg); - } + bool filterMessage(const Message &msg) override; /** - * Relays the processPushFile call to the parent logger and increments the - * stack depth counter. - * - * @param file is the File instance to be relayed to the parent logger. + * Relays the processPushDefaultLocation call to the parent logger and + * increments the stack depth counter. */ - void processPushFile(const File &file) - { - parent.processPushFile(file); - depth++; - } + void processPushDefaultLocation(const SourceLocation &loc) override; /** - * Relays the processPopFile call to the parent logger and decrements the - * stack depth counter. + * Relays the processPopDefaultLocation call to the parent logger and + * decrements the stack depth counter. */ - void processPopFile() - { - depth--; - parent.processPopFile(); - } + void processPopDefaultLocation() override; /** * Relays the processSetDefaultLocation call to the parent logger. - * - * @param loc is the location to be passed to the parent logger. */ - void processSetDefaultLocation(const SourceLocation &loc) - { - parent.processSetDefaultLocation(loc); - } + void processSetDefaultLocation(const SourceLocation &loc) override; -public: /** - * Constructor of the ScopedLogger class. - * - * @param parent is the parent logger instance to which all calls should - * be relayed. + * Relays the processSetSourceContextCallback call to the parent logger. */ - ScopedLogger(Logger &parent) : Logger(), parent(parent) {} + void processSetSourceContextCallback( + SourceContextCallback sourceContextCallback) override; +public: /** * Constructor of the ScopedLogger class, pushes a first file instance onto * the file stack. * * @param parent is the parent logger instance to which all calls should * be relayed. - * @param name is the name of the file to be added to the stack. - * @param loc is the position from which the new file is included. - * @param ctxCallback is the callback function that should be called if a - * SourceLocation needs to be resolved to a SourceContext. - * @param ctxCallbackData is the data that should be passed to the callback. - */ - ScopedLogger(Logger &parent, std::string name, - SourceLocation loc = SourceLocation{}, - SourceContextCallback ctxCallback = nullptr, - void *ctxCallbackData = nullptr) - : Logger(), parent(parent), depth(0) - { - pushFile(name, loc, ctxCallback, ctxCallbackData); - } + * @param loc specifies the first source location. + */ + ScopedLogger(Logger &parent, SourceLocation loc = SourceLocation{}); /** * Destructor of the ScopedLogger class, automatically unwinds the file * stack. */ - ~ScopedLogger() - { - while (depth > 0) { - processPopFile(); - } - } + ~ScopedLogger(); }; /** @@ -681,7 +698,7 @@ protected: { if (msg.severity == Severity::ERROR || msg.severity == Severity::FATAL_ERROR) { - throw LoggableException(msg.msg); + throw LoggableException(msg.msg, msg.loc); } } }; @@ -701,24 +718,29 @@ constexpr Severity DEFAULT_MIN_SEVERITY = Severity::DEBUG; class ConcreteLogger : public Logger { private: /** - * Stack containing the current file instance. + * Current source context callback. */ - std::vector files; + SourceContextCallback sourceContextCallback; /** * Vector used to store the counts of each message type. */ std::vector messageCounts; + /** + * Vector used to store the current default locations. + */ + std::vector locations; + /** * Minimum severity to be used for filtering messages. */ Severity minSeverity; /** - * Current default location. + * Current source context callback. */ - SourceLocation defaultLocation; + SourceContextCallback callback; protected: /** @@ -730,25 +752,11 @@ protected: */ bool filterMessage(const Message &msg) override; - /** - * Pushes the given file descriptor onto the internal file stack. - * - * @param file is the File descriptor to be pushed onto the internal file - * stack. - */ - void processPushFile(const File &file) override; - - /** - * Pops the given file descriptor from the internal file stack. - */ - void processPopFile() override; - - /** - * Sets the default location. - * - * @param loc is the new default location. - */ + void processPushDefaultLocation(const SourceLocation &loc) override; + void processPopDefaultLocation() override; void processSetDefaultLocation(const SourceLocation &loc) override; + void processSetSourceContextCallback( + SourceContextCallback sourceContextCallback) override; public: /** @@ -757,24 +765,7 @@ public: * @param minSeverity is the severity below which message should be * discarded. */ - ConcreteLogger(Severity minSeverity = DEFAULT_MIN_SEVERITY) - : minSeverity(minSeverity) - { - } - - /** - * Returns the name of the current file or an empty instance of the File - * instance if no current file is available. - * - * @return the name of the current file. - */ - const File ¤tFile() const; - - /** - * Returns the current filename or an empty string if no surch file is - * available. - */ - const std::string ¤tFilename() const; + ConcreteLogger(Severity minSeverity = Severity::DEFAULT_MIN_SEVERITY); /** * Returns the current cursor location. @@ -800,7 +791,8 @@ public: /** * Returns the number of messages for the given severity. * - * @param severity is the log severity for which the message count should + * @param severity is the log severity for which the message count + *should * be returned. * @return the number of messages for this severity. Returns zero for * invalid arguments. @@ -808,22 +800,32 @@ public: size_t getSeverityCount(Severity severity); /** - * Resets the statistics gathered by the ConcreteLogger instance (the number + * Resets the statistics gathered by the ConcreteLogger instance (the + * number * of messages per log severity) and the internal file stack. */ void reset(); /** - * Returns true if at least one message with either a fatal error or error - * severity was logged. + * Returns true if at least one message with either a fatal error or + * error severity was logged. * * @return true if an error or fatal error was logged. */ bool hasError(); + + /** + * Returns true if at least one message with either a fatal error was + * logged. + * + * @return true if a fatal error was logged. + */ + bool hasFatalError(); }; /** - * Class extending the Logger class and printing the log messages to the given + * Class extending the Logger class and printing the log messages to the + * given * stream. */ class TerminalLogger : public ConcreteLogger { @@ -850,7 +852,8 @@ public: * Should be set to std::cerr in most cases. * @param useColor if true, the TerminalLogger class will do its best to * use ANSI/VT100 control sequences for colored log messages. - * @param minSeverity is the minimum severity below which log messages are + * @param minSeverity is the minimum severity below which log messages + *are * discarded. */ TerminalLogger(std::ostream &os, bool useColor = false, -- cgit v1.2.3 From d4457c98def55d694abc51e008d3fe5663768aab Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 15:26:40 +0100 Subject: Improved and fixed CharReader --- src/core/common/CharReader.cpp | 33 ++++++++++++++++++++++----------- src/core/common/CharReader.hpp | 35 ++++++++++++++++++++++++++++++----- 2 files changed, 52 insertions(+), 16 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/CharReader.cpp b/src/core/common/CharReader.cpp index b0bbade..6fd3d45 100644 --- a/src/core/common/CharReader.cpp +++ b/src/core/common/CharReader.cpp @@ -405,10 +405,10 @@ CharReader::~CharReader() buffer->deleteCursor(peekCursor); } -bool CharReader::readAtCursor(Cursor &cursor, char &c) +bool CharReader::readAtCursor(Buffer::CursorId &cursor, char &c) { // Return false if we're at the end of the stream - if (!buffer->read(cursor.cursor, c)) { + if (!buffer->read(cursor, c)) { return false; } @@ -420,9 +420,9 @@ bool CharReader::readAtCursor(Cursor &cursor, char &c) // Check whether the next character is a continuation of the // current character char c2; - if (buffer->read(cursor.cursor, c2)) { + if (buffer->read(cursor, c2)) { if ((c2 != '\n' && c2 != '\r') || c2 == c) { - buffer->moveCursor(cursor.cursor, -1); + buffer->moveCursor(cursor, -1); } } } @@ -486,8 +486,8 @@ bool CharReader::consumeWhitespace() CharReaderFork CharReader::fork() { - return CharReaderFork(buffer, readCursor, peekCursor, sourceId, offs, - coherent); + return CharReaderFork{buffer, readCursor, peekCursor, + sourceId, offs, coherent}; } size_t CharReader::readRaw(char *buf, size_t size) @@ -502,11 +502,16 @@ size_t CharReader::readRaw(char *buf, size_t size) return res; } -bool CharReader::atEnd() const { return buffer->atEnd(readCursor.cursor); } +bool CharReader::atEnd() const { return buffer->atEnd(readCursor); } -size_t CharReader::getOffset() const +SourceOffset CharReader::getOffset() const { - return buffer->offset(readCursor.cursor) + offs; + return buffer->offset(readCursor) + offs; +} + +SourcePosition CharReader::getPosition() const +{ + return getOffset(); } SourceLocation CharReader::getLocation() const @@ -514,13 +519,19 @@ SourceLocation CharReader::getLocation() const return SourceLocation{sourceId, getOffset()}; } +SourceLocation CharReader::getLocation(SourcePosition start) const +{ + return SourceLocation{sourceId, start, getOffset()}; +} + +SourceId CharReader::getSourceId() const { return sourceId; } + /* Class CharReaderFork */ CharReaderFork::CharReaderFork(std::shared_ptr buffer, Buffer::CursorId parentReadCursor, Buffer::CursorId parentPeekCursor, - SourceContextCallback sourceId, size_t offs, - bool coherent) + SourceId sourceId, size_t offs, bool coherent) : CharReader(buffer, sourceId, offs), parentReadCursor(parentReadCursor), parentPeekCursor(parentPeekCursor) diff --git a/src/core/common/CharReader.hpp b/src/core/common/CharReader.hpp index 0957e97..5a4d906 100644 --- a/src/core/common/CharReader.hpp +++ b/src/core/common/CharReader.hpp @@ -367,7 +367,7 @@ private: * @param c a reference to the character that should be written. * @return true if another character needs to be read. */ - bool substituteLinebreaks(Cursor &cursor, char &c); + bool substituteLinebreaks(Buffer::CursorId &cursor, char &c); /** * Reads a single character from the given cursor. @@ -534,7 +534,14 @@ public: * * @return the offset of the read cursor in bytes. */ - size_t getOffset() const; + SourceOffset getOffset() const; + + /** + * Returns the offset of the read cursor in bytes. + * + * @return the offset of the read cursor in bytes. + */ + SourcePosition getPosition() const; /** * Returns a SourceLocation object describing the exact position (including @@ -544,6 +551,24 @@ public: * cursor. */ SourceLocation getLocation() const; + + /** + * Returns a SourceLocation object starting at the given start position and + * ending at the exact position (including the source file) of the read + * cursor. + * + * @return a SourceLocation object at the position of the current read + * cursor. + */ + SourceLocation getLocation(SourcePosition start) const; + + /** + * Returns the current SourceId which describes the Resource on which the + * CharReader is currently working. + * + * @return the current SourceId. + */ + SourceId getSourceId() const; }; /** @@ -577,9 +602,9 @@ private: * coherently. */ CharReaderFork(std::shared_ptr buffer, - Buffer::CursorId &parentReadCursor, - Buffer::CursorId &parentPeekCursor, - SourceContextCallback sourceId, size_t offs, bool coherent); + Buffer::CursorId parentReadCursor, + Buffer::CursorId parentPeekCursor, SourceId sourceId, + size_t offs, bool coherent); public: /** -- cgit v1.2.3 From 9e084e8e7f657112436c3e07f12a2319373b1909 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 15:26:47 +0100 Subject: typo --- src/core/common/Location.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/core/common') diff --git a/src/core/common/Location.cpp b/src/core/common/Location.cpp index 7a75347..7fe5ea5 100644 --- a/src/core/common/Location.cpp +++ b/src/core/common/Location.cpp @@ -24,9 +24,10 @@ namespace ousia { const SourceLocation NullSourceLocation; -void SourceContext NullSourceContextCallback(const SourceLocation &location) +SourceContext NullSourceContextCallback(const SourceLocation &location) { return SourceContext{}; } + } -- cgit v1.2.3 From 1131b68bdf2949f56422a2c53617a5f7d2d9be47 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 15:28:22 +0100 Subject: Fixed typos, autoformat and setIsOneOf method --- src/core/common/Rtti.cpp | 32 +++++++++++++++++++++++--------- src/core/common/Rtti.hpp | 10 ++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/Rtti.cpp b/src/core/common/Rtti.cpp index 668e418..a913d76 100644 --- a/src/core/common/Rtti.cpp +++ b/src/core/common/Rtti.cpp @@ -47,8 +47,8 @@ const Rtti &RttiStore::lookup(const std::type_info &native) /* Class RttiBuilderBase */ -RttiBuilderBase &RttiBuilderBase::genericMethod(const std::string &name, - std::shared_ptr function) +RttiBuilderBase &RttiBuilderBase::genericMethod( + const std::string &name, std::shared_ptr function) { if (!methods.emplace(name, function).second) { throw OusiaException(std::string("Method with name \"") + name + @@ -80,10 +80,11 @@ void Rtti::initialize() const // Register the parent properties and methods { - for (const Rtti *parent: parents) { + for (const Rtti *parent : parents) { parent->initialize(); methods.insert(parent->methods.begin(), parent->methods.end()); - properties.insert(parent->properties.begin(), parent->properties.end()); + properties.insert(parent->properties.begin(), + parent->properties.end()); } } @@ -125,10 +126,10 @@ bool Rtti::isa(const Rtti &other) const return parents.count(&other) > 0; } -bool Rtii::isOneOf(const RttiSet &others) const +bool Rtti::isOneOf(const RttiSet &others) const { initialize(); - for (const Rtti *other: others) { + for (const Rtti *other : others) { if (parents.count(other) > 0) { return true; } @@ -136,18 +137,30 @@ bool Rtii::isOneOf(const RttiSet &others) const return false; } +bool Rtti::setIsOneOf(const RttiSet &s1, const RttiSet &s2) +{ + for (const Rtti *t1 : s1) { + if (t1->isOneOf(s2)) { + return true; + } + } + return false; +} + bool Rtti::composedOf(const Rtti &other) const { initialize(); return compositeTypes.count(&other) > 0; } -const RttiMethodMap &Rtti::getMethods() const { +const RttiMethodMap &Rtti::getMethods() const +{ initialize(); return methods; } -const RttiPropertyMap &Rtti::getProperties() const { +const RttiPropertyMap &Rtti::getProperties() const +{ initialize(); return properties; } @@ -162,7 +175,8 @@ std::shared_ptr Rtti::getMethod(const std::string &name) const return it->second; } -std::shared_ptr Rtti::getProperty(const std::string &name) const +std::shared_ptr Rtti::getProperty( + const std::string &name) const { initialize(); auto it = properties.find(name); diff --git a/src/core/common/Rtti.hpp b/src/core/common/Rtti.hpp index 53043e2..e2f1fa2 100644 --- a/src/core/common/Rtti.hpp +++ b/src/core/common/Rtti.hpp @@ -392,6 +392,16 @@ public: */ bool isOneOf(const RttiSet &others) const; + /** + * Checks whether any type in the first set is one type in the second set. + * + * @param s1 is the first set. For each type in this set we check whether + * it is one of the types in s2. + * @param s2 is the second set. + * @return true if the above condition is fulfilled, false otherwise. + */ + static bool setIsOneOf(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 -- cgit v1.2.3 From 4aee189703a9305206094858165c67043c2e1953 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 15:30:37 +0100 Subject: Logger compiles now --- src/core/common/Logger.cpp | 94 ++++++++++++++++++++++++++-------------------- src/core/common/Logger.hpp | 11 ++---- 2 files changed, 57 insertions(+), 48 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/Logger.cpp b/src/core/common/Logger.cpp index 9f070f9..034953d 100644 --- a/src/core/common/Logger.cpp +++ b/src/core/common/Logger.cpp @@ -27,11 +27,10 @@ namespace ousia { /* Class Logger */ void Logger::log(Severity severity, const std::string &msg, - const SourceLocation &loc, - MessageMode mode = MessageMode::DEFAULT) + const SourceLocation &loc, MessageMode mode) { // Assemble the message and pass it through the filter, then process it - Message message{severity, std::move(msg), loc, mode}; + Message message{severity, mode, std::move(msg), loc}; if (filterMessage(message)) { processMessage(message); } @@ -60,8 +59,14 @@ void LoggerFork::processPopDefaultLocation() void LoggerFork::processSetDefaultLocation(const SourceLocation &loc) { - calls.emplace_back(CallType : SET_LOCATION, locations.size()); - locations.push_back(loc); + // Check whether setDefaultLocation was called immediately before, if yes, + // simply override the data + if (!calls.empty() && calls.back().type == CallType::SET_LOCATION) { + locations.back() = loc; + } else { + calls.emplace_back(CallType::SET_LOCATION, locations.size()); + locations.emplace_back(loc); + } } void LoggerFork::processSetSourceContextCallback( @@ -70,7 +75,7 @@ void LoggerFork::processSetSourceContextCallback( // Check whether setSourceContextCallback was called immediately before, // if yes, simply override the data if (!calls.empty() && calls.back().type == CallType::SET_CONTEXT_CALLBACK) { - callbacks.back() = loc; + callbacks.back() = sourceContextCallback; } else { calls.emplace_back(CallType::SET_CONTEXT_CALLBACK, callbacks.size()); callbacks.emplace_back(sourceContextCallback); @@ -114,8 +119,8 @@ void LoggerFork::commit() /* Class ScopedLogger */ -ScopedLogger::ScopedLogger(Logger &parent, SourceLocation loc = SourceLocation{}) - : Logger(), parent(parent), depth(0) +ScopedLogger::ScopedLogger(Logger &parent, SourceLocation loc) + : parent(parent), depth(0) { pushDefaultLocation(loc); } @@ -157,12 +162,12 @@ void ScopedLogger::processSetDefaultLocation(const SourceLocation &loc) void ScopedLogger::processSetSourceContextCallback( SourceContextCallback sourceContextCallback) { - parent.processSetContextCallback(sourceContextCallback); + parent.processSetSourceContextCallback(sourceContextCallback); } /* Class ConcreteLogger */ -ConcreteLogger(Severity minSeverity = Severity::DEFAULT_MIN_SEVERITY) +ConcreteLogger::ConcreteLogger(Severity minSeverity) : minSeverity(minSeverity), sourceContextCallback(NullSourceContextCallback) { } @@ -180,11 +185,13 @@ bool ConcreteLogger::filterMessage(const Message &msg) return sev >= static_cast(minSeverity); } -void ConcreteLogger::processPushDefaultLocation(const SourceLocation &loc) { +void ConcreteLogger::processPushDefaultLocation(const SourceLocation &loc) +{ locations.emplace_back(loc); } -void ConcreteLogger::processPopDefaultLocation() { +void ConcreteLogger::processPopDefaultLocation() +{ if (!locations.empty()) { locations.pop_back(); } @@ -199,11 +206,17 @@ void ConcreteLogger::processSetDefaultLocation(const SourceLocation &loc) } } +void ConcreteLogger::processSetSourceContextCallback( + SourceContextCallback sourceContextCallback) +{ + this->sourceContextCallback = sourceContextCallback; +} + const SourceLocation &ConcreteLogger::messageLocation(const Message &msg) const { - if (msg.loc.valid()) { + if (msg.loc.isValid()) { return msg.loc; - } else if (!locatios.empty()) { + } else if (!locations.empty()) { return locations.back(); } return NullSourceLocation; @@ -235,8 +248,9 @@ size_t ConcreteLogger::getSeverityCount(Severity severity) void ConcreteLogger::reset() { - files.clear(); + locations.clear(); messageCounts.clear(); + sourceContextCallback = NullSourceContextCallback; } bool ConcreteLogger::hasError() @@ -266,7 +280,7 @@ void TerminalLogger::processMessage(const Message &msg) // Print line and column number if (ctx.hasLine()) { - if (hasFile) { + if (ctx.hasFile()) { os << ':'; } os << t.bright() << ctx.startLine << t.reset(); @@ -303,30 +317,30 @@ void TerminalLogger::processMessage(const Message &msg) os << msg.msg << std::endl; // Print the error message context if available -/* if (ctx.valid()) { - size_t relPos = ctx.relPos; - if (ctx.truncatedStart) { - os << "[...] "; - } - os << ctx.text; - if (ctx.truncatedEnd) { - os << " [...]"; - } - os << std::endl; - - if (ctx.truncatedStart) { - os << " "; - } - - for (size_t i = 0; i < relPos; i++) { - if (i < ctx.text.size() && ctx.text[i] == '\t') { - os << '\t'; - } else { - os << ' '; - } - } - os << t.color(Terminal::GREEN) << '^' << t.reset() << std::endl; - }*/ + /* if (ctx.valid()) { + size_t relPos = ctx.relPos; + if (ctx.truncatedStart) { + os << "[...] "; + } + os << ctx.text; + if (ctx.truncatedEnd) { + os << " [...]"; + } + os << std::endl; + + if (ctx.truncatedStart) { + os << " "; + } + + for (size_t i = 0; i < relPos; i++) { + if (i < ctx.text.size() && ctx.text[i] == '\t') { + os << '\t'; + } else { + os << ' '; + } + } + os << t.color(Terminal::GREEN) << '^' << t.reset() << std::endl; + }*/ } } diff --git a/src/core/common/Logger.hpp b/src/core/common/Logger.hpp index 092bd3a..85b1bb1 100644 --- a/src/core/common/Logger.hpp +++ b/src/core/common/Logger.hpp @@ -594,8 +594,8 @@ public: LoggerFork(LoggerFork &&l) : calls(std::move(l.calls)), messages(std::move(l.messages)), - files(std::move(l.files)), locations(std::move(l.locations)), + callbacks(std::move(l.callbacks)), parent(std::move(l.parent)){}; /** @@ -717,11 +717,6 @@ constexpr Severity DEFAULT_MIN_SEVERITY = Severity::DEBUG; */ class ConcreteLogger : public Logger { private: - /** - * Current source context callback. - */ - SourceContextCallback sourceContextCallback; - /** * Vector used to store the counts of each message type. */ @@ -740,7 +735,7 @@ private: /** * Current source context callback. */ - SourceContextCallback callback; + SourceContextCallback sourceContextCallback; protected: /** @@ -765,7 +760,7 @@ public: * @param minSeverity is the severity below which message should be * discarded. */ - ConcreteLogger(Severity minSeverity = Severity::DEFAULT_MIN_SEVERITY); + ConcreteLogger(Severity minSeverity = DEFAULT_MIN_SEVERITY); /** * Returns the current cursor location. -- cgit v1.2.3 From d242f74de618e92bb7baaca59aa224685783c5a8 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Fri, 23 Jan 2015 15:31:43 +0100 Subject: Made more stuff const --- src/core/common/Location.hpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src/core/common') diff --git a/src/core/common/Location.hpp b/src/core/common/Location.hpp index 57892cc..808abbd 100644 --- a/src/core/common/Location.hpp +++ b/src/core/common/Location.hpp @@ -115,7 +115,7 @@ public: * * @return true if the SourcePosition instance is value, false otherwise. */ - bool isValid() { return pos != InvalidSourceOffset; } + bool isValid() const { return pos != InvalidSourceOffset; } }; /** @@ -252,7 +252,7 @@ public: * * @return true if the Range is valid. */ - bool isValid() + bool isValid() const { return start.isValid() && end.isValid() && start.getPosition() <= end.getPosition(); @@ -333,7 +333,7 @@ public: * * @return the id of the source file this instance is bound to. */ - SourceId getSourceId() { return sourceId; } + SourceId getSourceId() const { return sourceId; } /** * Returns true if this location is actually valid. This is the case if @@ -341,7 +341,7 @@ public: * * @return true if the Range is valid. */ - bool isValid() + bool isValid() const { return SourceRange::isValid() && sourceId != InvalidSourceId; } @@ -469,7 +469,7 @@ struct SourceContext { * @return the corresponding SourceContext. */ using SourceContextCallback = - std::function; + std::function; /** * Function to be used as default value for the SourceContextCallback. Returns @@ -478,7 +478,7 @@ using SourceContextCallback = * @param location is the location for which the context should be looked up. * @return an empty, invalid SourceContext. */ -void SourceContext NullSourceContextCallback(const SourceLocation &location); +SourceContext NullSourceContextCallback(const SourceLocation &location); } -- cgit v1.2.3