提交 f49b433a 编写于 作者: F f1yegor

translate comments: functions

上级 92712eee
......@@ -5,9 +5,9 @@
namespace DB
{
/** Если прямо сейчас не s, то ошибка.
* Если word_boundary установлен в true, и последний символ строки - словарный (\w),
* то проверяется, что последующий символ строки не словарный.
/** If right now is not `s`, then an error.
* If word_boundary is set to true, and the last character of the string - word (\w),
* then it is checked that the next character in the string is not a word character.
*/
class ParserString : public IParserBase
{
......@@ -27,7 +27,7 @@ protected:
};
/** пробельные символы
/** whitespace characters
*/
class ParserWhiteSpace : public IParserBase
{
......@@ -61,7 +61,7 @@ protected:
};
/** комментарии '--' или c-style
/** comments '--' or c-style
*/
class ParserComment : public IParserBase
{
......
......@@ -15,9 +15,9 @@ protected:
};
/** Если в скобках выражение из одного элемента - возвращает в node этот элемент;
* или если в скобках - подзапрос SELECT - то возвращает в node этот подзапрос;
* иначе возвращает функцию tuple от содержимого скобок.
/** If in parenthesis an expression from one element - returns this element in `node`;
* or if there is a SELECT subquery in parenthesis, then this subquery returned in `node`;
* otherwise returns `tuple` function from the contents of brackets.
*/
class ParserParenthesisExpression : public IParserBase
{
......@@ -27,7 +27,7 @@ protected:
};
/** Подзапрос SELECT в скобках.
/** The SELECT subquery is in parenthesis.
*/
class ParserSubquery : public IParserBase
{
......@@ -37,7 +37,7 @@ protected:
};
/** Идентификатор, например, x_yz123 или `something special`
/** An identifier, for example, x_yz123 or `something special`
*/
class ParserIdentifier : public IParserBase
{
......@@ -47,7 +47,7 @@ protected:
};
/** Идентификатор, возможно, содержащий точку, например, x_yz123 или `something special` или Hits.EventTime
/** An identifier, possibly containing a dot, for example, x_yz123 or `something special` or Hits.EventTime
*/
class ParserCompoundIdentifier : public IParserBase
{
......@@ -76,11 +76,11 @@ protected:
};
/** Функция, например, f(x, y + 1, g(z)).
* Или агрегатная функция: sum(x + f(y)), corr(x, y). По синтаксису - такая же, как обычная функция.
* Или параметрическая агрегатная функция: quantile(0.9)(x + y).
* Синтаксис - две пары круглых скобок вместо одной. Первая - для параметров, вторая - для аргументов.
* Для функций может быть указан модификатор DISTINCT, например count(DISTINCT x, y).
/** A function, for example, f(x, y + 1, g(z)).
* Or an aggregate function: sum(x + f(y)), corr(x, y). The syntax is the same as the usual function.
* Or a parametric aggregate function: quantile(0.9)(x + y).
* Syntax - two pairs of parentheses instead of one. The first is for parameters, the second for arguments.
* For functions, the DISTINCT modifier can be specified, for example, count(DISTINCT x, y).
*/
class ParserFunction : public IParserBase
{
......@@ -139,11 +139,11 @@ protected:
};
/** Массив литералов.
* Массивы могут распарситься и как применение оператора [].
* Но парсинг всего массива как целой константы серьёзно ускоряет анализ выражений в случае очень больших массивов.
* Мы пробуем распарсить массив как массив литералов сначала (fast path),
* а если не получилось (когда массив состоит из сложных выражений) - парсим как применение оператора [] (slow path).
/** An array of literals.
* Arrays can also be parsed as an application of [] operator.
* But parsing the whole array as a whole constant seriously speeds up the analysis of expressions in the case of very large arrays.
* We try to parse the array as an array of literals first (fast path),
* and if it did not work out (when the array consists of complex expressions) - parse as an application of [] operator (slow path).
*/
class ParserArrayOfLiterals : public IParserBase
{
......@@ -153,7 +153,7 @@ protected:
};
/** Литерал - одно из: NULL, UInt64, Int64, Float64, String.
/** The literal is one of: NULL, UInt64, Int64, Float64, String.
*/
class ParserLiteral : public IParserBase
{
......@@ -163,7 +163,7 @@ protected:
};
/** Алиас - идентификатор, перед которым идёт AS. Например: AS x_yz123.
/** The alias is the identifier before which `AS` comes. For example: AS x_yz123.
*/
struct ParserAliasBase
{
......@@ -193,7 +193,7 @@ using ParserAlias = ParserAliasImpl<ParserIdentifier>;
using ParserCastExpressionAlias = ParserAliasImpl<ParserTypeInCastExpression>;
/** Элемент выражения - одно из: выражение в круглых скобках, массив, литерал, функция, идентификатор, звёздочка.
/** The expression element is one of: an expression in parentheses, an array, a literal, a function, an identifier, an asterisk.
*/
class ParserExpressionElement : public IParserBase
{
......@@ -203,7 +203,7 @@ protected:
};
/** Элемент выражения, возможно, с алиасом, если уместно.
/** An expression element, possibly with an alias, if appropriate.
*/
template <typename ParserAlias>
class ParserWithOptionalAliasImpl : public IParserBase
......@@ -237,7 +237,7 @@ protected:
bool parseImpl(Pos & pos, Pos end, ASTPtr & node, Pos & max_parsed_pos, Expected & expected);
};
/** Путь шарда в ZooKeeper вместе с весом.
/** The path of the shard in ZooKeeper along with the weight.
*/
class ParserWeightedZooKeeperPath : public IParserBase
{
......
......@@ -9,13 +9,13 @@
namespace DB
{
/** Идущие подряд пары строк: оператор и соответствующая ему функция. Например, "+" -> "plus".
* Порядок парсинга операторов имеет значение.
/** Consequent pairs of rows: the operator and the corresponding function. For example, "+" -> "plus".
* The parsing order of the operators is significant.
*/
using Operators_t = const char **;
/** Список элементов, разделённых чем-либо. */
/** List of elements separated by something. */
class ParserList : public IParserBase
{
public:
......@@ -33,8 +33,8 @@ private:
};
/** Выражение с инфиксным бинарным лево-ассоциативным оператором.
* Например, a + b - c + d.
/** An expression with an infix binary left-associative operator.
* For example, a + b - c + d.
*/
class ParserLeftAssociativeBinaryOperatorList : public IParserBase
{
......@@ -44,7 +44,7 @@ private:
ParserPtr remaining_elem_parser;
public:
/** operators_ - допустимые операторы и соответствующие им функции
/** `operators_` - allowed operators and their corresponding functions
*/
ParserLeftAssociativeBinaryOperatorList(Operators_t operators_, ParserPtr && first_elem_parser_)
: operators(operators_), first_elem_parser(std::move(first_elem_parser_))
......@@ -65,8 +65,8 @@ protected:
};
/** Выражение с инфиксным оператором произвольной арности.
* Например, a AND b AND c AND d.
/** Expression with an infix operator of arbitrary arity.
* For example, a AND b AND c AND d.
*/
class ParserVariableArityOperatorList : public IParserBase
{
......@@ -88,8 +88,8 @@ protected:
};
/** Выражение с префиксным унарным оператором.
* Например, NOT x.
/** An expression with a prefix unary operator.
* Example, NOT x.
*/
class ParserPrefixUnaryOperatorExpression : public IParserBase
{
......@@ -98,7 +98,7 @@ private:
ParserPtr elem_parser;
public:
/** operators_ - допустимые операторы и соответствующие им функции
/** `operators_` - allowed operators and their corresponding functions
*/
ParserPrefixUnaryOperatorExpression(Operators_t operators_, ParserPtr && elem_parser_)
: operators(operators_), elem_parser(std::move(elem_parser_))
......@@ -336,7 +336,7 @@ protected:
};
/** Список выражений, разделённых запятыми, возможно пустой. */
/** A comma-separated list of expressions, probably empty. */
class ParserExpressionList : public IParserBase
{
public:
......
......@@ -31,7 +31,7 @@ using ASTs = std::vector<ASTPtr>;
class WriteBuffer;
/** Элемент синтаксического дерева (в дальнейшем - направленного ациклического графа с элементами семантики)
/** Element of the syntax tree (hereinafter - directed acyclic graph with elements of semantics)
*/
class IAST
{
......@@ -39,8 +39,8 @@ public:
ASTs children;
StringRange range;
/** Строка с полным запросом.
* Этот указатель не дает ее удалить, пока range в нее ссылается.
/** A string with a full query.
* This pointer does not allow it to be deleted while the range refers to it.
*/
StringPtr query_string;
......@@ -48,25 +48,25 @@ public:
IAST(const StringRange range_) : range(range_) {}
virtual ~IAST() = default;
/** Получить каноническое имя столбца, если элемент является столбцом */
/** Get the canonical name of the column if the element is a column */
virtual String getColumnName() const { throw Exception("Trying to get name of not a column: " + getID(), ErrorCodes::NOT_A_COLUMN); }
/** Получить алиас, если он есть, или каноническое имя столбца, если его нет. */
/** Get the alias, if any, or the canonical name of the column, if it is not. */
virtual String getAliasOrColumnName() const { return getColumnName(); }
/** Получить алиас, если он есть, или пустую строку, если его нет, или если элемент не поддерживает алиасы. */
/** Get the alias, if any, or an empty string if it does not exist, or if the element does not support aliases. */
virtual String tryGetAlias() const { return String(); }
/** Установить алиас. */
/** Set the alias. */
virtual void setAlias(const String & to)
{
throw Exception("Can't set alias of " + getColumnName(), ErrorCodes::UNKNOWN_TYPE_OF_AST_NODE);
}
/** Получить текст, который идентифицирует этот элемент. */
/** Get the text that identifies this element. */
virtual String getID() const = 0;
/** Получить глубокую копию дерева. */
/** Get a deep copy of the tree. */
virtual ASTPtr clone() const = 0;
/** Get text, describing and identifying this element and its subtree.
......@@ -89,20 +89,20 @@ public:
child->dumpTree(ostr, indent + 1);
}
/** Проверить глубину дерева.
* Если задано max_depth и глубина больше - кинуть исключение.
* Возвращает глубину дерева.
/** Check the depth of the tree.
* If max_depth is specified and the depth is greater - throw an exception.
* Returns the depth of the tree.
*/
size_t checkDepth(size_t max_depth) const
{
return checkDepthImpl(max_depth, 0);
}
/** То же самое для общего количества элементов дерева.
/** Same for the total number of tree elements.
*/
size_t checkSize(size_t max_size) const;
/** Получить set из имен индентификаторов
/** Get `set` from the names of the identifiers
*/
virtual void collectIdentifierNames(IdentifierNameSet & set) const
{
......@@ -111,9 +111,9 @@ public:
}
/// Преобразовать в строку.
/// Convert to a string.
/// Настройки формата.
/// Format settings.
struct FormatSettings
{
std::ostream & ostr;
......@@ -129,16 +129,16 @@ public:
}
};
/// Состояние. Например, может запоминаться множество узлов, которых мы уже обошли.
/// State. For example, a set of nodes can be remembered, which we already walk through.
struct FormatState
{
/** Запрос SELECT, в котором найден алиас; идентификатор узла с таким алиасом.
* Нужно, чтобы когда узел встретился повторно, выводить только алиас.
/** The SELECT query in which the alias was found; identifier of a node with such an alias.
* It is necessary that when the node has met again, output only the alias.
*/
std::set<std::pair<const IAST *, std::string>> printed_asts_with_alias;
};
/// Состояние, которое копируется при форматировании каждого узла. Например, уровень вложенности.
/// The state that is copied when each node is formatted. For example, nesting level.
struct FormatStateStacked
{
UInt8 indent = 0;
......@@ -164,7 +164,7 @@ public:
void writeAlias(const String & name, std::ostream & s, bool hilite) const;
protected:
/// Для подсветки синтаксиса.
/// For syntax highlighting.
static const char * hilite_keyword;
static const char * hilite_identifier;
static const char * hilite_function;
......@@ -177,7 +177,7 @@ private:
};
/// Квотировать идентификатор обратными кавычками, если это требуется.
/// Quota the identifier with backquotes, if required.
String backQuoteIfNeed(const String & x);
......
......@@ -14,23 +14,23 @@ namespace DB
using Expected = const char *;
/** Интерфейс для классов-парсеров
/** Interface for parser classes
*/
class IParser
{
public:
using Pos = const char *;
/** Получить текст о том, что парсит этот парсер. */
/** Get the text of this parser parses. */
virtual const char * getName() const = 0;
/** Распарсить кусок текста с позиции pos, но не дальше конца строки (end - позиция после конца строки),
* переместить указатель pos на максимальное место, до которого удалось распарсить,
* вернуть в случае успеха true и результат в node, если он нужен, иначе false,
* в expected записать, что ожидалось в максимальной позиции,
* до которой удалось распарсить, если парсинг был неуспешным,
* или что парсит этот парсер, если парсинг был успешным.
* Строка, в которую входит диапазон [begin, end) может быть не 0-terminated.
/** Parse piece of text from position `pos`, but not beyond end of line (`end` - position after end of line),
* move pointer `pos` to the maximum position to which it was possible to parse,
* in case of success return `true` and the result in `node` if it is needed, otherwise false,
* in `expected` write what was expected in the maximum position,
* to which it was possible to parse if parsing was unsuccessful,
* or what this parser parse if parsing was successful.
* The string to which the [begin, end) range is included may be not 0-terminated.
*/
virtual bool parse(Pos & pos, Pos end, ASTPtr & node, Pos & max_parsed_pos, Expected & expected) = 0;
......@@ -47,7 +47,7 @@ public:
return ignore(pos, end, max_parsed_pos, expected);
}
/** То же самое, но не двигать позицию и не записывать результат в node.
/** The same, but do not move the position and do not write the result to node.
*/
bool check(Pos & pos, Pos end, Pos & max_parsed_pos, Expected & expected)
{
......
......@@ -6,7 +6,7 @@
namespace DB
{
/** Базовый класс для большинства парсеров
/** Base class for most parsers
*/
class IParserBase : public IParser
{
......
......@@ -6,7 +6,7 @@
namespace DB
{
/** Запрос типа такого:
/** Query like this:
* ALTER TABLE [db.]name
* [ADD COLUMN col_name type [AFTER col_after],]
* [DROP COLUMN col_drop, ...]
......
......@@ -4,7 +4,7 @@
namespace DB
{
/** Запрос вида
/** Query of form
* CHECK [TABLE] [database.]table
*/
class ParserCheckQuery : public IParserBase
......
......@@ -14,7 +14,7 @@
namespace DB
{
/** Вложенная таблица. Например, Nested(UInt32 CounterID, FixedString(2) UserAgentMajor)
/** A nested table. For example, Nested(UInt32 CounterID, FixedString(2) UserAgentMajor)
*/
class ParserNestedTable : public IParserBase
{
......@@ -24,12 +24,12 @@ protected:
};
/** Параметрический тип или Storage. Например:
* FixedString(10) или
* Partitioned(Log, ChunkID) или
/** Parametric type or Storage. For example:
* FixedString(10) or
* Partitioned(Log, ChunkID) or
* Nested(UInt32 CounterID, FixedString(2) UserAgentMajor)
* Результат парсинга - ASTFunction с параметрами или без.
*/
* Result of parsing - ASTFunction with or without parameters.
*/
class ParserIdentifierWithParameters : public IParserBase
{
protected:
......@@ -64,9 +64,9 @@ protected:
bool parseImpl(Pos & pos, Pos end, ASTPtr & node, Pos & max_parsed_pos, Expected & expected);
};
/** Имя и тип через пробел. Например, URL String. */
/** The name and type are separated by a space. For example, URL String. */
using ParserNameTypePair = IParserNameTypePair<ParserIdentifier>;
/** Имя и тип через пробел. Имя может содержать точку. Например, Hits.URL String. */
/** Name and type separated by a space. The name can contain a dot. For example, Hits.URL String. */
using ParserCompoundNameTypePair = IParserNameTypePair<ParserCompoundIdentifier>;
template <class NameParser>
......@@ -94,7 +94,7 @@ bool IParserNameTypePair<NameParser>::parseImpl(Pos & pos, Pos end, ASTPtr & nod
return false;
}
/** Список столбцов. */
/** List of columns. */
class ParserNameTypePairList : public IParserBase
{
protected:
......@@ -204,7 +204,7 @@ protected:
};
/** Запрос типа такого:
/** Query like this:
* CREATE|ATTACH TABLE [IF NOT EXISTS] [db.]name
* (
* name1 type1,
......@@ -212,16 +212,16 @@ protected:
* ...
* ) ENGINE = engine
*
* Или:
* Or:
* CREATE|ATTACH TABLE [IF NOT EXISTS] [db.]name AS [db2.]name2 [ENGINE = engine]
*
* Или:
* Or:
* CREATE|ATTACH TABLE [IF NOT EXISTS] [db.]name AS ENGINE = engine SELECT ...
*
* Или:
* Or:
* CREATE|ATTACH DATABASE db [ENGINE = engine]
*
* Или:
* Or:
* CREATE|ATTACH [MATERIALIZED] VIEW [IF NOT EXISTS] [db.]name [ENGINE = engine] [POPULATE] AS SELECT ...
*/
class ParserCreateQuery : public IParserBase
......
......@@ -7,10 +7,10 @@
namespace DB
{
/** Запрос типа такого:
/** Query like this:
* DROP|DETACH TABLE [IF EXISTS] [db.]name
*
* Или:
* Or:
* DROP DATABASE [IF EXISTS] db
*/
class ParserDropQuery : public IParserBase
......
......@@ -7,18 +7,18 @@ namespace DB
{
/** Варианты:
/** Cases:
*
* Обычный вариант:
* Normal case:
* INSERT INTO [db.]table (c1, c2, c3) VALUES (v11, v12, v13), (v21, v22, v23), ...
* INSERT INTO [db.]table VALUES (v11, v12, v13), (v21, v22, v23), ...
*
* Вставка данных в произвольном формате.
* Сами данные идут после перевода строки, если он есть, или после всех пробельных символов, иначе.
* Insert of data in an arbitrary format.
* The data itself comes after LF(line feed), if it exists, or after all the whitespace characters, otherwise.
* INSERT INTO [db.]table (c1, c2, c3) FORMAT format \n ...
* INSERT INTO [db.]table FORMAT format \n ...
*
* Вставка результата выполнения SELECT запроса.
* Insert the result of the SELECT query.
* INSERT INTO [db.]table (c1, c2, c3) SELECT ...
* INSERT INTO [db.]table SELECT ...
*/
......
......@@ -7,7 +7,7 @@
namespace DB
{
/** Запрос OPTIMIZE TABLE [db.]name [PARTITION partition] [FINAL] [DEDUPLICATE]
/** Query OPTIMIZE TABLE [db.]name [PARTITION partition] [FINAL] [DEDUPLICATE]
*/
class ParserOptimizeQuery : public IParserBase
{
......
......@@ -7,9 +7,9 @@
namespace DB
{
/** Запрос типа такого:
/** Query like this:
* RENAME TABLE [db.]name TO [db.]name, [db.]name TO [db.]name, ...
* (Переименовываться может произвольное количество таблиц.)
* (An arbitrary number of tables can be renamed.)
*/
class ParserRenameQuery : public IParserBase
{
......
......@@ -6,8 +6,8 @@
namespace DB
{
/** Коэффициент сэмплирования вида 0.1 или 1/10.
* Парсится как рациональное число без преобразования в IEEE-754.
/** Sampling factor of the form 0.1 or 1/10.
* It is parsed as a rational number without conversion to IEEE-754.
*/
class ParserSampleRatio : public IParserBase
{
......
......@@ -7,7 +7,7 @@
namespace DB
{
/** Запрос типа такого:
/** Query like this:
* SET [GLOBAL] name1 = value1, name2 = value2, ...
*/
class ParserSetQuery : public IParserBase
......@@ -19,7 +19,7 @@ protected:
const char * getName() const { return "SET query"; }
bool parseImpl(Pos & pos, Pos end, ASTPtr & node, Pos & max_parsed_pos, Expected & expected);
/// Парсить список name = value пар, без SET [GLOBAL].
/// Parse the list `name = value` pairs, without SET [GLOBAL].
bool parse_only_internals;
};
......
......@@ -10,7 +10,7 @@
namespace DB
{
/** Запрос SHOW PROCESSLIST
/** Query SHOW PROCESSLIST
*/
class ParserShowProcesslistQuery : public IParserBase
{
......
......@@ -6,9 +6,9 @@
namespace DB
{
/** Запрос типа такого:
/** Query like this:
* SHOW TABLES [FROM db] [[NOT] LIKE 'str']
* или
* or
* SHOW DATABASES.
*/
class ParserShowTablesQuery : public IParserBase
......
......@@ -8,7 +8,7 @@
namespace DB
{
/** Запрос (EXISTS | SHOW CREATE | (DESCRIBE | DESC) ) [TABLE] [db.]name [FORMAT format]
/** Query (EXISTS | SHOW CREATE | (DESCRIBE | DESC)) [TABLE] [db.]name [FORMAT format]
*/
class ParserTablePropertiesQuery : public IParserBase
{
......
......@@ -6,7 +6,7 @@
namespace DB
{
/** Запрос USE db
/** Query USE db
*/
class ParserUseQuery : public IParserBase
{
......
......@@ -9,8 +9,8 @@
namespace DB
{
/** Берёт синтаксическое дерево и превращает его обратно в текст.
* В случае запроса INSERT, данные будут отсутствовать.
/** Takes a syntax tree and turns it back into text.
* In case of INSERT query, the data will be missing.
*/
inline void formatAST(const IAST & ast, std::ostream & s, size_t indent = 0, bool hilite = true, bool one_line = false)
{
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册