Documentation for classes.

--HG--
branch : feature
This commit is contained in:
dismine 2013-10-07 18:34:14 +03:00
parent 8a7ace463c
commit 2b1da2ac32
4 changed files with 270 additions and 265 deletions

View file

@ -40,12 +40,12 @@ qreal Calculator::eval(QString prog, QString *errorMsg){
this->errorMsg->clear();
debugFormula.clear();
this->prog = prog;
//qDebug()<<"Формула: "<<prog;
//qDebug()<<"Formula: "<<prog;
index = 0;
qreal result = get_exp();
QString str = QString(" = %1").arg(result, 0, 'f', 3);
debugFormula.append(str);
//qDebug()<<"Результат:"<<debugFormula;
//qDebug()<<"Result:"<<debugFormula;
return result;
}
@ -57,12 +57,10 @@ qreal Calculator::get_exp(){
return 0;
}
level2(&result);
putback(); /* возвращает последнюю считаную
лексему обратно во входной поток */
putback();
return result;
}
/* Сложение или вычитание двух термов */
void Calculator::level2(qreal *result){
QChar op;
qreal hold;
@ -75,7 +73,6 @@ void Calculator::level2(qreal *result){
}
}
/* Вычисление произведения или частного двух фвкторов */
void Calculator::level3(qreal *result){
QChar op;
qreal hold;
@ -89,7 +86,6 @@ void Calculator::level3(qreal *result){
}
}
/* Обработка степени числа (целочисленной) */
void Calculator::level4(qreal *result){
qreal hold;
@ -101,7 +97,6 @@ void Calculator::level4(qreal *result){
}
}
/* Унарный + или - */
void Calculator::level5(qreal *result){
QChar op;
@ -115,7 +110,6 @@ void Calculator::level5(qreal *result){
unary(op, result);
}
/* Обработка выражения в круглых скобках */
void Calculator::level6(qreal *result){
if((token[0] == '(') && (token_type == DELIMITER)) {
get_token();
@ -127,7 +121,6 @@ void Calculator::level6(qreal *result){
primitive(result);
}
/* Определение значения переменной по ее имени */
void Calculator::primitive(qreal *result){
QString str;
switch(token_type) {
@ -148,9 +141,8 @@ void Calculator::primitive(qreal *result){
}
}
/* Выполнение специфицированной арифметики */
void Calculator::arith(QChar o, qreal *r, qreal *h){
qreal t;//, ex;
qreal t;
switch(o.toLatin1()) {
case '-':
@ -171,78 +163,54 @@ void Calculator::arith(QChar o, qreal *r, qreal *h){
break;
case '^':
*r = pow(*r, *h);
// ex =*r;
// if(*h==0) {
// *r = 1;
// break;
// }
// for(t=*h-1; t>0; --t)
// *r = (*r) * ex;
break;
}
}
/* Изменение знака */
void Calculator::unary(QChar o, qreal *r){
if(o=='-')
*r = -(*r);
}
/* Поиск значения переменной */
qreal Calculator::find_var(QString s){
bool ok = false;
qreal value = data->FindVar(s, &ok);
if(!ok){
qDebug()<<s;
serror(4); /* не переменная */
serror(4); /* don't variable */
return 0;
}
return value;
}
/* выдать сообщение об ошибке */
void Calculator::serror(qint32 error){
QString e[]= {
"Синтаксическая ошибка",
"Непарные круглые скобки",
"Это не выражение",
"Предполагается символ равенства",
"Не переменная"
tr("Syntax error"),
tr("Parentheses do not match"),
tr("This is not an expression"),
tr("It is assumed the equality symbol"),
tr("Do not variable")
};
errorMsg->clear();
*errorMsg = e[error];
qDebug()<<e[error];
}
/* Поиск соответствия внутреннего формата для
текущей лексемы в таблице лексем.
*/
char Calculator::look_up(QString s){
QString p;
/* преобразование к нижнему регистру */
p = s;
p = p.toLower();
/* просматривается, если лексема обнаружена в
таблице */
/*
*у нас більше немає команд що потрібно опрацьовувати
*/
// if(commands.contains(p)){
// return commands[p];
// }
return 0; /* нераспознанная команда */
return 0;
}
/* Возвращает "истину", если "c" разделитель */
bool Calculator::isdelim(QChar c){
if(StrChr(" ;,+-<>/*%^=()",c) || c=='\n' || c=='\r' || c=='\0')
return true;
return false;
}
/* Возвращает 1, если "с" пробел или табуляция */
bool Calculator::iswhite(QChar c){
if(c==' ' || c=='\t')
return true;
@ -257,14 +225,14 @@ void Calculator::get_token(){
token.clear();
temp=&token;
if(prog[index]=='\0') { /* Конец файла */
if(prog[index]=='\0') { /* end of file */
token="\0";
tok=FINISHED;
token_type=DELIMITER;
return;
}
while(iswhite(prog[index])) ++index; /* пропуск пробелов */
while(iswhite(prog[index])) ++index; /* skip spaces */
if(prog[index]=='\r') { /* crtl */
++index; ++index;
@ -274,15 +242,15 @@ void Calculator::get_token(){
return;
}
if(StrChr("+-*^/%=;(),><", prog[index])) { /* разделитель */
if(StrChr("+-*^/%=;(),><", prog[index])) { /* delimiter */
*temp=prog[index];
index++; /* переход на следующую позицию */
index++; /* jump to the next position */
temp->append("\0");
token_type=DELIMITER;
debugFormula.append(token);
return;
}
if(prog[index]=='"') { /* строка в кавычках */
if(prog[index]=='"') { /* quoted string */
index++;
while(prog[index] != '"' && prog[index] != '\r'){
temp->append(prog[index]);
@ -294,7 +262,7 @@ void Calculator::get_token(){
token_type=QUOTE;
return;
}
if(prog[index].isDigit()) { /* число */
if(prog[index].isDigit()) { /* number */
while(!isdelim(prog[index])){
temp->append(prog[index]);
index++;
@ -304,7 +272,7 @@ void Calculator::get_token(){
return;
}
if(prog[index].isPrint()) { /* переменная или команда */
if(prog[index].isPrint()) { /* variable or command */
while(!isdelim(prog[index])){
temp->append(prog[index]);
index++;
@ -313,13 +281,12 @@ void Calculator::get_token(){
}
temp->append("\0");
/* Просматривается, если строка есть команда или переменная */
/* Seen if there is a command line or a variable */
if(token_type==STRING) {
tok=look_up(token); /* преобразование во внутренний
формат */
tok=look_up(token);
if(!tok)
token_type = VARIABLE;
else token_type = COMMAND; /* это команда */
else token_type = COMMAND; /* It is command */
}
return;
}
@ -328,7 +295,6 @@ bool Calculator::StrChr(QString string, QChar c){
return string.contains(c, Qt::CaseInsensitive);
}
/* Возвращает лексему обратно во входной поток */
void Calculator::putback(){
QString t;
t = token;

View file

@ -26,140 +26,146 @@
#include "vcontainer.h"
/**
* @brief The Calculator клас калькулятора формул лекал. Виконує розрахунок формул з підставлянням
* значеннь зміних.
* @brief The Calculator class calculate formulas of pattern. Support operation +,-,/,* and braces.
* Can replace name of variables her value.
*/
class Calculator
{
class Calculator{
public:
/**
* @brief Calculator конструктор класу. Використовується при розрахунку лекала.
* @param data покажчик на контейнер змінних
* @brief Calculator class constructor.
* @param data pointer to a variable container.
*/
explicit Calculator(const VContainer *data);
/**
* @brief eval виконує розрахунок формули.
* @param prog рядко в якому зберігається формула.
* @return значення формули.
* @brief eval calculate formula.
* @param prog string of formula.
* @return value of formula.
*/
qreal eval(QString prog, QString *errorMsg);
private:
Q_DISABLE_COPY(Calculator)
/**
* @brief errorMsg keeps error message of calculation.
*/
QString *errorMsg;
/**
* @brief token теперішня лексема.
* @brief token current token.
*/
QString token;
/**
* @brief tok внутрішне представлення лексеми.
* @brief tok internal representation of token.
*/
qint32 tok;
/**
* @brief token_type тип лексеми.
* @brief token_type type of token.
*/
qint32 token_type;
/**
* @brief prog рядок в якому зберігається формула.
* @brief prog string where keeps formula.
*/
QString prog; /* Содержит анализируемое выражение */
QString prog;
/**
* @brief index номер символу в рядку формули.
* @brief index number character in string of formula.
*/
qint32 index; /* Индекс символа в строке*/
qint32 index;
/**
* @brief data контейнер усіх змінних.
* @brief data container of all variables.
*/
const VContainer *data;
/**
* @brief debugFormula рядок розшифрованої формули.
* @brief debugFormula decoded string of formula.
*/
QString debugFormula;
/**
* @brief get_exp виконує розрахунок формули.
* @return значення формули.
* @brief get_exp calculate formula.
* @return value of formula.
*/
qreal get_exp();
/**
* @brief get_token повертає наступну лексему.
* @brief get_token return next token.
*/
void get_token();/* Получить лексему */
void get_token();
/**
* @brief StrChr перевіряє чи символ належить рядку.
* @param string рядок
* @param c символ.
* @return true - належить рядку, false - не належить рядку.
* @brief StrChr checks whether the character belongs to the line.
* @param string string with formula
* @param c character.
* @return true - belongs to the line, false - don't belongs to the line.
*/
static bool StrChr(QString string, QChar c);
/**
* @brief putback повертає зчитану лексему назад у потік.
* @brief putback returns the readout token back into the flow.
*/
void putback();
/**
* @brief level2 метод додавання і віднімання двух термів.
* @param result результат операції.
* @brief level2 method of addition and subtraction of two terms.
* @param result result of operation.
*/
void level2(qreal *result);
/**
* @brief level3 метод множення, ділення, знаходження процентів.
* @param result результат операції.
* @brief level3 method of multiplication, division, finding percent.
* @param result result of operation.
*/
void level3(qreal *result);
/**
* @brief level4 метод знаходження степені двох чисел.
* @param result результат операції.
* @brief level4 method of degree two numbers.
* @param result result of operation.
*/
void level4(qreal *result);
/**
* @brief level5 метод знаходження унарного плюса чи мінуса.
* @param result результат операції.
* @brief level5 method for finding unary plus or minus.
* @param result result of operation.
*/
void level5(qreal *result);
/**
* @brief level6 метод обробки виразу в круглих лапках.
* @param result результат операції.
* @brief level6 processing method of the expression in brackets.
* @param result result of operation.
*/
void level6(qreal *result);
/**
* @brief primitive метод визначення значення зміної по її імені.
* @param result результат операції.
* @brief primitive method of determining the value of a variable by its name.
* @param result result of operation.
*/
void primitive(qreal *result);
/**
* @brief arith виконання специфікованої арифметики. Результат записується в перший елемент.
* @param o знак операції.
* @param r перший елемент.
* @param h другий елемент.
* @brief arith perform the specified arithmetic. The result is written to the first element.
* @param o sign operation.
* @param r first element.
* @param h second element.
*/
static void arith(QChar o, qreal *r, qreal *h);
/**
* @brief unary метод зміни знаку.
* @param o символ знаку.
* @param r елемент.
* @brief unary method changes the sign.
* @param o sign of symbol.
* @param r element.
*/
static void unary(QChar o, qreal *r);
/**
* @brief find_var метод знаходить змінну за іменем.
* @param s ім'я змінної.
* @return значення зміної.
* @brief find_var method is finding variable by name.
* @param s name of variable.
* @return value of variable.
*/
qreal find_var(QString s);
/**
* @brief serror report an error
* @param error error code
*/
void serror(qint32 error);
/**
* @brief look_up пошук відповідного внутрішнього формату для теперішньої лексеми в таблиці лексем. текущей лексемы в таблице лексем
* @param s ім'я лексеми.
* @return внутрішній номер лексеми.
* @brief look_up Finding the internal format for the current token in the token table.
* @param s name of token.
* @return internal number of token.
*/
static char look_up(QString s);
/**
* @brief isdelim повертає "істино", якщо с розділювач.
* @param c символ.
* @return розділювач, або ні.
* @brief isdelim return true if c delimiter.
* @param c character.
* @return true - delimiter, false - do not delimiter.
*/
static bool isdelim(QChar c);
/**
* @brief iswhite перевіряє чи с пробіл чи табуляція.
* @param c символ.
* @return так або ні.
* @brief iswhite checks whether c space or tab.
* @param c character.
* @return true - space or tab, false - don't space and don't tab.
*/
static bool iswhite(QChar c);
};

View file

@ -32,26 +32,48 @@
#include <QCoreApplication>
/**
* @brief The VContainer class
* @brief The VContainer class container of all variables.
*/
class VContainer
{
class VContainer{
Q_DECLARE_TR_FUNCTIONS(VContainer)
public:
/**
* @brief VContainer
* @brief VContainer create empty container
*/
VContainer();
/**
* @brief operator = copy constructor
* @param data container
* @return copy container
*/
VContainer &operator=(const VContainer &data);
/**
* @brief VContainer create container from another container
* @param data container
*/
VContainer(const VContainer &data);
/**
* @brief setData copy data from container
* @param data container
*/
void setData(const VContainer &data);
/**
* @brief GetPoint
* @param id
* @return
* @brief GetPoint returns a point by id
* @param id id of point
* @return point
*/
VPointF GetPoint(qint64 id) const;
/**
* @brief GetModelingPoint return a modeling point by id
* @param id id of modeling point
* @return modeling point
*/
VPointF GetModelingPoint(qint64 id) const;
/**
* @brief GetStandartTableCell
* @param name
* @return
*/
VStandartTableCell GetStandartTableCell(const QString& name) const;
VIncrementTableRow GetIncrementTableRow(const QString& name) const;
qreal GetLine(const QString &name) const;
@ -67,10 +89,13 @@ public:
qint64 AddPoint(const VPointF& point);
qint64 AddModelingPoint(const VPointF& point);
qint64 AddDetail(const VDetail& detail);
void AddStandartTableCell(const QString& name, const VStandartTableCell& cell);
void AddIncrementTableRow(const QString& name, const VIncrementTableRow &cell);
void AddStandartTableCell(const QString& name,
const VStandartTableCell& cell);
void AddIncrementTableRow(const QString& name,
const VIncrementTableRow &cell);
void AddLengthLine(const QString &name, const qreal &value);
void AddLengthSpline(const qint64 &firstPointId, const qint64 &secondPointId,
void AddLengthSpline(const qint64 &firstPointId,
const qint64 &secondPointId,
Draw::Draws mode = Draw::Calculation);
void AddLengthSpline(const QString &name, const qreal &value);
void AddLengthArc(const qint64 &center, const qint64 &id);
@ -86,7 +111,8 @@ public:
qint64 AddModelingArc(const VArc& arc);
QString GetNameLine(const qint64 &firstPoint, const qint64 &secondPoint,
Draw::Draws mode = Draw::Calculation) const;
QString GetNameLineAngle(const qint64 &firstPoint, const qint64 &secondPoint,
QString GetNameLineAngle(const qint64 &firstPoint,
const qint64 &secondPoint,
Draw::Draws mode = Draw::Calculation) const;
QString GetNameSpline(const qint64 &firstPoint, const qint64 &secondPoint,
Draw::Draws mode = Draw::Calculation) const;
@ -103,8 +129,10 @@ public:
void UpdateModelingSplinePath(qint64 id, const VSplinePath& splPath);
void UpdateArc(qint64 id, const VArc& arc);
void UpdateModelingArc(qint64 id, const VArc& arc);
void UpdateStandartTableCell(const QString& name, const VStandartTableCell& cell);
void UpdateIncrementTableRow(const QString& name, const VIncrementTableRow& cell);
void UpdateStandartTableCell(const QString& name,
const VStandartTableCell& cell);
void UpdateIncrementTableRow(const QString& name,
const VIncrementTableRow& cell);
qreal GetValueStandartTableCell(const QString& name) const;
qreal GetValueIncrementTableRow(const QString& name) const;
void Clear();
@ -140,11 +168,14 @@ public:
const QHash<qint64, VDetail> *DataDetails() const;
static void UpdateId(qint64 newId);
QPainterPath ContourPath(qint64 idDetail) const;
QPainterPath Equidistant(QVector<QPointF> points, const Detail::Equidistant &eqv,
QPainterPath Equidistant(QVector<QPointF> points,
const Detail::Equidistant &eqv,
const qreal &width)const;
static QLineF ParallelLine(const QLineF &line, qreal width );
static QPointF SingleParallelPoint(const QLineF &line, const qreal &angle, const qreal &width);
QVector<QPointF> EkvPoint(const QLineF &line1, const QLineF &line2, const qreal &width)const;
static QPointF SingleParallelPoint(const QLineF &line, const qreal &angle,
const qreal &width);
QVector<QPointF> EkvPoint(const QLineF &line1, const QLineF &line2,
const qreal &width)const;
QVector<QPointF> CheckLoops(const QVector<QPointF> &points) const;
void PrepareDetails(QVector<VItem*> & list)const;
private:
@ -168,10 +199,12 @@ private:
template <typename key, typename val> static val GetObject(const QHash<key,val> &obj, key id);
template <typename val> static void UpdateObject(QHash<qint64, val> &obj, const qint64 &id,
const val& point);
template <typename key, typename val> static qint64 AddObject(QHash<key, val> &obj, const val& value);
template <typename key, typename val> static qint64 AddObject(QHash<key, val> &obj,
const val& value);
void CreateManTableIGroup ();
QVector<QPointF> GetReversePoint(const QVector<QPointF> &points)const;
qreal GetLengthContour(const QVector<QPointF> &contour, const QVector<QPointF> &newPoints)const;
qreal GetLengthContour(const QVector<QPointF> &contour,
const QVector<QPointF> &newPoints)const;
};
#endif // VCONTAINER_H

View file

@ -74,7 +74,7 @@ CREATE_SUBDIRS = NO
# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak,
# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
OUTPUT_LANGUAGE = Ukrainian
OUTPUT_LANGUAGE = English
# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
# include brief member descriptions after the members that are listed in
@ -369,7 +369,7 @@ EXTRACT_PACKAGE = NO
# If the EXTRACT_STATIC tag is set to YES all static members of a file
# will be included in the documentation.
EXTRACT_STATIC = NO
EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
# defined locally in source files will be included in the documentation.