file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
kimsooyoung/rb_issac_tutorial/docs/README.md
|
# Usage
To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name}
- Clone This repo into your prefer location.
- Navigate to `Window`` -> `Extensions` in the toolbar to open the Extensions Manager.
- Click the hamburger icon in the Extensions Manager, and then `Settings` in the sub-menu to add the path to the folder you created for your user extensions.
- Find your extension in the Extensions Manager under `Third Party Extensions` and enable it. It will now appear in the toolbar.
> please refer this link : https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html#isaac-sim-extension-workflow
<p align="center">
<img src="./img/demo_img.png" height="200">
</p>
| 781 |
Markdown
| 54.857139 | 159 | 0.759283 |
daniel-kun/omni/README.md
|
**INFO** _My efforts around Omni have been on hold for a long time and will be for the foreseeable future - mostly because my kids keep me busy :-) In the meantime, a few other projects spawned and have made progress, that I would like to mention:_
* [isomorƒ](https://isomorf.io/)
* [Unison](http://unisonweb.org/)
* [Expressions of Change](http://www.expressionsofchange.org/)
* [Codeflow](http://codeflow.co/)
* [Luna](http://www.luna-lang.org/)
# The Omni Programming Language Manifest
This manifest declares goals that The Omni Programming Language is designed to reach.
Omni is meant to provide a new way of coding. A way of coding where less time is spent on text editing and more time spent on engineering, designing, defining and changing logic and architecture, assuring quality and documenting.
In short, Omni frees the programmer of unnecessary tasks that the classic way of writing programs in text files imposes on them to let you get things done.
# Goals
## Productivity
Higher productivity and quality for programmers
* Let programmers focus on coding
* Let programmers create higher quality and more robust code, with less effort
* Integrated backlogs and work tasks
## Agility
* Make wide-scale code changes *safe*, fast and easy
* Make code easier to refactor
* Make code easier to be statically analysed
* Make code easier to be automatically manipulated
## Quality
* Integrated unit tests
* Integrated test director
* Integrated documentation system
## Technology
* Code is not stored in text files, but in a database
* This enables Omni to present code pieces independent of their physical storage
* Declarative and imperative code model in the same language
* Deterministic Garbage Collector via Automatic Reference Counting
* API to access the code model (for coded refactoring, analysis, metrics, reports, etc.)
* Built-in, compile-time-safe multithreading
# Further readings
- [Motivation](Motivation.md "Motivation")
- Technology (Coming soon)
- Vision (Coming soon)
# Status quo
Update: 15.05.2017
After 2 years of hibernation, I returned to working on this project. I took the time to follow current development trends, see all the hilarious rise and fall of JavaScript-languages / Web Frontend Frameworks and contemplating about whether I should build Omni as an on-premise desktop software or an online SaaS.
I finally concluded that a web based approach is more suitable to the current direction of the Developer Ecosystem and Communities. I re-started work on Omni using [Elm](http://elm-lang.org/) as a Front End language/framework and was somewhat surprised. [The Elm Architeture](https://guide.elm-lang.org/architecture/) actually will make implement Omni *much easier* than my last approach using WPF, and even more robust! I am very pleased with what I have seen and learned so far and am currently investigating Backend solutions. (I tried [ASP.NET Core](https://www.asp.net/), with which I already have experience, and am installing Scala, sbt and [Play](https://www.playframework.com/) right now. I'd like to have a "mainstream" functional language in the backend, to make contributions more accessible.)
I'll post an update as soon as I have a similar prototype ready to what you can see in WPF below.
Update: 23.06.2015
More work on the input system Prototype, looks good so far. Well, not exactly pretty, but the mechanics are sound.
Look at this awesome stuff:

Update: 10.06.2015
The progress on the Prototype is coming along nicely. I chose to implement the prototype in C#, because a) I am much faster in GUI coding in C# + WPF than in C++ with Qt (but can't use it for the final product because it is not cross-platform) and b) I will not be able to copy+paste quick&dirty-code from the prototype to the production code. Here's a small teaser:

Just for kicks, I hooked up two views that display the same code model with different templates. This way you can synchronously edit the same code in C-style and in Lisp-style. Feels awesome!
Update: 02.06.2015
I have made progress on a prototype for the input architecture. This is not trivial, but I might be able to show a small sneak preview soon.
Update: 13.05.2015
I haven't been working much on th code base lately, because my primary goal was to get portability before driving features. I have ported the build system to CMake and Omni now builds on Win32 and Linux on x86, x86_64 and ARM v7 (using a Raspberry Pi as a development platform).
There is even a little bi GUI up and running (on all platforms). I have built a few input fields for literal expressions and variable definitions. I am not very happy with the result, though - both the code architecture and the look&feel.
So I decided to do some backend work, which currently consists mainly of reseach, hence little code changes. I am trying to integrate either static code analysis or automatic unit test generation to Omni, so I am currently looking around to see what has already been done. My plan is to update the Wikipedia article to include a comprehensive feature comparison of C++ Static Code Analysis tools.
Omni is going slow-paced, because I don't find much time to work on it. But this gives me the time to build up the ideas and the big picture in my mind before hacking away. :-)
Update: 04.11.2014
Currently, the code model exists for basic structures such as functions, variables, if/for/while/etc. and can be compiled to binaries on Win32 and Linux.
A flexible meta-information system that allows you to attach any kind of information to entity types (expressions and statements) is finished and used to combine the code model and the UI.
There are some little prototypes for the UI to edit and view elements such as literals and variable declarations. The next step will be a "free-form" input field that automatically detects the type of entity that is being written and auto-transforms in that entity's special ui. E.g. when I write "va", it auto-expands to the UI for variable declarations, looking like "var [variable-name] = [init-expression]".
In parallel, I am writing the docs "Motivation" and "Technology". "Vision" is to follow.
| 6,246 |
Markdown
| 62.744897 | 805 | 0.779379 |
daniel-kun/omni/resources/syntax.xml
|
<syntax>
<abstract name="statement">
<concrete name="block">
<fixed text="{"/>
<indentright/>
<repeater prefix="\n">
<variable name="statement"/>
</repeater>
<indentleft/>
<fixed text="}"/>
</concrete>
<concrete name="if">
<fixed text="if("/>
<syntax name="condition" type="expression"/>
<fixed text=") {"/>
<indentright/>
<syntax name="body" type="block"/>
<indentleft/>
<fixed text="}"/>
</concrete>
<concrete name="return">
<fixed text="return "/>
<syntax name="value" type="expression"/>
</concrete>
<concrete name="while">
<fixed text="while("/>
<syntax name="condition" type="expression"/>
<fixed text=") {"/>
<indentright/>
<syntax name="body" type="block"/>
<indentleft/>
<fixed text="}"/>
</concrete>
<concrete name="do_while">
<fixed text="do {"/>
<indentright/>
<syntax name="body" type="block"/>
<indentleft/>
<fixed text="} while("/>
<syntax name="condition" type="expression"/>
<fixed text=")"/>
</concrete>
<abstract name="expression">
<abstract name="pure_expression">
<concrete name="binary_operator">
<syntax name="lhs" type="expression"/>
<fixed text=" "/>
<variable name="operator"/>
<fixed text=" "/>
<syntax name="rhs" type="expression"/>
</concrete>
<abstract name="cast_expression">
<concrete name="cast_expression">
<fixed text="bitcast<"/>
<syntax name="target" type="type"/>
<fixed text=">("/>
<syntax name="source" type="expression"/>
<fixed text=")"/>
</concrete>
</abstract>
<concrete name="literal_expression">
<variable name="literal"/>
</concrete>
<concrete name="variable_declaration_expression">
<fixed text="var "/>
<variable name="name"/>
<fixed text=" = ("/>
<syntax name="init_value" type="expression"/>
<fixed text=")"/>
</concrete>
<concrete name="variable_expression">
<variable name="variable"/>
</concrete>
</abstract>
<abstract name="modifying_expression">
<concrete name="function_call_expression">
<variable name="function"/>
<fixed text="("/>
<repeater prefix=",">
<syntax name="parameter" type="expression"/>
</repeater>
<fixed text=")"/>
</concrete>
<concrete name="variable_assignment_expression">
<variable name="variable"/>
<fixed text=" = "/>
<syntax name="rhs" type="expression"/>
</concrete>
</abstract>
</abstract>
</abstract>
</syntax>
| 3,532 |
XML
| 33.980198 | 68 | 0.421574 |
daniel-kun/omni/source/omni/runtime/memory.cpp
|
#include <omni/runtime/memory.hpp>
#include <cstdlib>
/**
Allocates new memory and returns a pointer to it. The returned memory's reference counter is set to 1.
@param sizeInBytes Specifies the size of the memory to allocate.
@return Returns a pointer to a newly allocated memory structure of the given size.
**/
void * omni_runtime_memory_allocate (std::size_t sizeInBytes)
{
// Allocate space for the reference counter and the requested number of bytes:
reference_count_t * result = reinterpret_cast <reference_count_t *> (std::malloc (sizeof (reference_count_t) + sizeInBytes));
if (result == nullptr) {
return nullptr;
}
*result = 1u;
return ++ result;
}
/**
Increments the reference counter for the specified memory block.
@param memory The memory on which the referene counter should be incremented.
@result Always returns memory.
**/
void * omni_runtime_memory_add_reference (void * memory)
{
reference_count_t * result = reinterpret_cast <reference_count_t *> (memory);
++ (*(result - 1));
return result;
}
/**
Decrements the reference counter for the specified memory block. If the reference counter reaches 0, the memory block
is deallocated.
@param memory The memory on which the reference counter should be decremented.
@result Returns memory as long as the reference counter is greater than zero. If it reached zero, a nullpointer is returned.
**/
void * omni_runtime_memory_remove_reference (void * memory)
{
reference_count_t * result = reinterpret_cast <reference_count_t *> (memory);
// Decrement the memory pointer to access the reference counter.
-- result;
if (* result == 1u) {
// If the reference counter would decrement to 0, free the memory buffer and return a null pointer.
std::free (result);
return nullptr;
}
-- (*result); // Decrement the reference count.
return ++ result; // Return the original memory pointer.
}
| 1,944 |
C++
| 36.403845 | 129 | 0.710905 |
daniel-kun/omni/source/omni/forge/main_window.hpp
|
#ifndef OMNI_FORGE_MAIN_WINDOW_HPP
#define OMNI_FORGE_MAIN_WINDOW_HPP
#include "sandbox_selector.hpp"
#include "sandbox_widget.hpp"
#include <omni/core/context.hpp>
#include <omni/core/model/module.hpp>
#include <QLabel>
#include <QPushButton>
#include <QGridLayout>
#include <QGroupBox>
#include <QShortcut>
namespace omni {
namespace forge {
/**
@brief Main window for the interactive sandbox demos.
Displays a tree of available sandbox demos on the left side and the selected demo in action on the right side.
**/
class main_window : public QWidget {
Q_OBJECT
public:
main_window ();
private slots:
void showEvent (QShowEvent * event) override;
void activateDemo (sandbox_widget & demo);
void compileAndRunActiveDemo ();
private:
omni::core::context _c;
omni::core::model::module _m;
QHBoxLayout _layout;
QVBoxLayout _rightLayout;
QGroupBox _groupDemoList;
QVBoxLayout _groupDemoListLayout;
sandbox_selector _selector;
sandbox_widget _demoLabel;
QLabel _demoChildLabel;
sandbox_widget * _activeDemo;
QPushButton _compileAndRunButton;
QShortcut _searchShortcut;
};
} // namespace forge
} // namespace omni
#endif // include guard
| 1,211 |
C++
| 21.444444 | 110 | 0.724195 |
daniel-kun/omni/source/omni/forge/sandbox_widget.cpp
|
#include "sandbox_widget.hpp"
omni::forge::sandbox_widget::sandbox_widget (QWidget & parent, omni::forge::sandbox_widget::CompileAndRunFun compileAndRunFunction) :
QWidget (& parent),
_compileAndRunFun (compileAndRunFunction)
{
}
void omni::forge::sandbox_widget::compileAndRun (omni::core::context & context, omni::core::model::module & module)
{
if (_compileAndRunFun) {
_compileAndRunFun (context, module);
}
}
| 441 |
C++
| 26.624998 | 133 | 0.709751 |
daniel-kun/omni/source/omni/forge/sandbox_selector.cpp
|
#include "sandbox_selector.hpp"
#include <QHeaderView>
omni::forge::sandbox_selector::sandbox_selector (omni::core::context & context, omni::core::model::module & module, QWidget * parent) :
QWidget (parent),
_layout (this),
_searchField (this),
_selector (this),
_model (context, module),
_filterModel ()
{
_searchField.setPlaceholderText ("Search demos...");
_filterModel.setSourceModel (& _model);
_layout.addWidget (& _searchField);
_layout.addWidget (& _selector);
_selector.setModel (& _filterModel);
_selector.expandAll ();
_selector.header ()->hide ();
connect (& _searchField, SIGNAL(textChanged(QString)), SLOT(setFilter(QString)));
connect (_selector.selectionModel (), SIGNAL(currentChanged(QModelIndex, QModelIndex)), SLOT (emitDemoSelected(QModelIndex)));
}
/**
@brief Updates the current filter.
Sets the filter criteria to `filterText', showing only demos in the tree view that match the filter (or their children match the filter).
@param filterText The filter-text. case-sensitive, partial matching.
**/
void omni::forge::sandbox_selector::setFilter (QString filterText)
{
_filterModel.setFilterFixedString (filterText);
if (! filterText.isEmpty ()) {
QModelIndex firstMatchingDemo = _filterModel.firstMatchingIndex ();
if (firstMatchingDemo.isValid ()) {
_selector.selectionModel ()->clearSelection ();
_selector.selectionModel ()->select (firstMatchingDemo, QItemSelectionModel::SelectCurrent);
_selector.setCurrentIndex (firstMatchingDemo);
}
} else {
_selector.clearSelection ();
_selector.setCurrentIndex (QModelIndex ());
}
}
void omni::forge::sandbox_selector::focusSearchField ()
{
_searchField.setFocus (Qt::TabFocusReason);
}
void omni::forge::sandbox_selector::emitDemoSelected (const QModelIndex & current)
{
if (current != QModelIndex ()) {
sandbox_widget * demoWidget = _model.createDemoFromModelIndex (* parentWidget (), _filterModel.mapToSource (current));
if (demoWidget != nullptr) {
emit demoSelected (*demoWidget);
}
}
}
| 2,165 |
C++
| 35.099999 | 137 | 0.68037 |
daniel-kun/omni/source/omni/forge/sandbox_selector_model.cpp
|
#include "sandbox_selector_model.hpp"
#include "sandbox_widget.hpp"
#include <omni/ui/literal_expression_view.hpp>
#include <omni/ui/entity_toggle_widget.hpp>
#include <omni/ui/entity_widget_provider.hpp>
#include <omni/ui/variable_declaration_expression_view.hpp>
#include <omni/ui/entity_placeholder_widget.hpp>
#include <omni/core/invalid_argument_error.hpp>
#include <omni/core/context.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/function.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/model/return_statement.hpp>
#include <omni/core/model/variable_expression.hpp>
#include <QLibrary>
#include <QMessageBox>
#include <boost/filesystem.hpp>
#include <sstream>
#include <functional>
using creator_function = std::function <std::unique_ptr <omni::forge::sandbox_widget> (omni::core::context & context, omni::core::model::module & module, QWidget & parent)>;
class omni::forge::sandbox_selector_model::sandbox_selector_data_base {
public:
sandbox_selector_data_base (
sandbox_selector_data_base * parent,
QString title,
QString description,
creator_function creator,
std::vector <std::shared_ptr <sandbox_selector_data_base>> children = std::vector <std::shared_ptr <sandbox_selector_data_base>> ());
sandbox_selector_data_base * parent;
QString title;
QString description;
std::unique_ptr <sandbox_widget> widget;
creator_function creator;
std::vector <std::shared_ptr <sandbox_selector_data_base>> children;
};
omni::forge::sandbox_selector_model::sandbox_selector_data_base::sandbox_selector_data_base (
sandbox_selector_data_base * parent,
QString title,
QString description,
creator_function creator,
std::vector <std::shared_ptr <sandbox_selector_data_base>> children) :
parent (parent),
title (title),
description (description),
widget (),
creator (creator),
children (children)
{
}
namespace {
template <typename Widget>
std::unique_ptr <Widget> createWidget (QWidget &parent)
{
return std::unique_ptr <Widget> (new Widget (& parent));
}
template <typename Widget>
class sandbox_selector_data : public omni::forge::sandbox_selector_model::sandbox_selector_data_base {
public:
sandbox_selector_data (
QString title,
QString description,
creator_function creator,
std::vector <std::shared_ptr <sandbox_selector_data_base>> children = std::vector <std::shared_ptr <sandbox_selector_data_base>> ()) :
sandbox_selector_data_base (
nullptr,
title,
description,
creator,
children)
{
}
};
template <>
class sandbox_selector_data <void>: public omni::forge::sandbox_selector_model::sandbox_selector_data_base {
public:
sandbox_selector_data (
QString title,
QString description,
std::vector <std::shared_ptr <sandbox_selector_data_base>> children = std::vector <std::shared_ptr <sandbox_selector_data_base>> ()) :
sandbox_selector_data_base (
nullptr,
title,
description,
[] (omni::core::context &, omni::core::model::module &, QWidget &) -> std::unique_ptr <omni::forge::sandbox_widget> {
return std::unique_ptr <omni::forge::sandbox_widget> ();
},
children)
{
}
};
void setParents (omni::forge::sandbox_selector_model::sandbox_selector_data_base & item)
{
for (auto & i : item.children) {
i->parent = & item;
setParents (*i);
}
}
/*
Creates an entity_toggle_widget with an entity_widget_provider named "literal_expression" in a sandbox_widget container to be shown in the main_window.
*/
std::unique_ptr <omni::forge::sandbox_widget> createLiteralView (omni::core::context & context, omni::core::model::module &, QWidget & parent)
{
auto literal = std::make_shared <omni::core::model::builtin_literal_expression <int>> (context, 42);
QWidget & localParent (parent);
// For editor and layout, we rely on Qt's object ownership mechanism to free them:
auto * editor = new omni::ui::entity_toggle_widget (context, omni::ui::entity_widget_provider::getProvider ("literal_expression"), & parent);
auto result = std::unique_ptr <omni::forge::sandbox_widget> (
new omni::forge::sandbox_widget (
parent,
[editor, & localParent] (omni::core::context &, omni::core::model::module & module) -> void {
auto literalExpression = std::dynamic_pointer_cast <omni::core::model::literal_expression> (editor->getEntity ());
auto body = std::make_shared <omni::core::model::block> ();
body->appendStatement (std::make_shared <omni::core::model::return_statement> (literalExpression));
auto fun = module.createFunction (
"test",
literalExpression->getType (),
body);
fun->setExported (true);
std::string libraryFileName =
(boost::filesystem::temp_directory_path() /
boost::filesystem::unique_path ("omni-sandbox-%%%%%%%%%%%.dll")).string ();
module.emitSharedLibraryFile (libraryFileName);
module.removeFunction (fun);
QLibrary lib (QString::fromStdString (libraryFileName));
auto realFunc = reinterpret_cast <int (*) ()> (lib.resolve ("test"));
std::stringstream str;
str << (*realFunc) ();
QMessageBox::information (& localParent, "Test", QString::fromStdString (str.str ()));
}));
auto * layout = new QVBoxLayout (result.get ());
layout->addWidget (editor);
editor->setEntity (literal);
return std::move (result);
}
/*
Creates a variable_declaration_expression_view in a sandbox_widget container to be shown in the main_window.
*/
std::unique_ptr <omni::forge::sandbox_widget> createVariableDeclarationView (omni::core::context & context, omni::core::model::module & module, QWidget & parent)
{
auto variableDecl = std::make_shared <omni::core::model::variable_declaration_expression> ();
variableDecl->setName ("foobar");
// For editor and layout, we rely on Qt's object ownership mechanism to free them:
auto * editor = new omni::ui::variable_declaration_expression_view (context, module, & parent);
editor->setEntity (variableDecl);
QWidget & localParent (parent);
auto result = std::unique_ptr <omni::forge::sandbox_widget> (
new omni::forge::sandbox_widget (
parent,
[editor, & localParent] (omni::core::context &, omni::core::model::module & module) -> void {
auto variableExpression = std::dynamic_pointer_cast <omni::core::model::variable_declaration_expression> (editor->getEntity ());
auto body = std::make_shared <omni::core::model::block> ();
body->appendStatement (variableExpression);
body->appendStatement (std::make_shared <omni::core::model::return_statement> (
std::make_shared <omni::core::model::variable_expression> (variableExpression)));
auto fun = module.createFunction (
"test",
variableExpression->getType (),
body);
fun->setExported (true);
std::string libraryFileName =
(boost::filesystem::temp_directory_path() /
boost::filesystem::unique_path ("omni-sandbox-%%%%%%%%%%%.dll")).string ();
module.emitSharedLibraryFile (libraryFileName);
module.removeFunction (fun);
QLibrary lib (QString::fromStdString (libraryFileName));
auto realFunc = reinterpret_cast <int (*) ()> (lib.resolve ("test"));
std::stringstream str;
str << (*realFunc) ();
QMessageBox::information (& localParent, "Test", QString::fromStdString (str.str ()));
}));
auto * layout = new QVBoxLayout (result.get ());
layout->addWidget (editor);
return std::move (result);
}
/*
Creates an entity_placeholder_widget for the root type omni::core::model::entity, wrapped in a sandbox_widget.
*/
std::unique_ptr <omni::forge::sandbox_widget> createEntityPlaceholderWidget (omni::core::context & context, omni::core::model::module & module, QWidget & parent)
{
auto result = std::unique_ptr <omni::forge::sandbox_widget> (
new omni::forge::sandbox_widget (
parent,
[] (omni::core::context &, omni::core::model::module &) -> void {
}));
// Relies on Qt's object ownership mechanism to free it:
auto * placeholderWidget = new omni::ui::entity_placeholder_widget (context, module, & parent, omni::core::model::entity::getStaticMetaInfo ());
auto * layout = new QVBoxLayout (result.get ());
layout->addWidget (placeholderWidget);
return std::move (result);
}
/*
Initializes the sandbox tree structure:
*/
std::unique_ptr <omni::forge::sandbox_selector_model::sandbox_selector_data_base> initSandboxData ()
{
using data_list = std::vector <std::shared_ptr <omni::forge::sandbox_selector_model::sandbox_selector_data_base>>;
auto result = std::unique_ptr <sandbox_selector_data <void>> (
new sandbox_selector_data <void> (
"root",
"root",
data_list {
std::make_shared <sandbox_selector_data <void>> (
"core",
"core",
data_list {
std::make_shared <sandbox_selector_data <omni::ui::literal_expression_view>> (
"literal_expression",
"literal_expression",
& createLiteralView),
std::make_shared <sandbox_selector_data <omni::ui::variable_declaration_expression_view>> (
"variable_declaration_expression",
"variable_declaration_expression",
& createVariableDeclarationView)
}),
std::make_shared <sandbox_selector_data <void>> (
"ui",
"ui",
data_list {
std::make_shared <sandbox_selector_data <omni::ui::literal_expression_view>> (
"entity_placeholder_widget",
"entity_placeholder_widget",
& createEntityPlaceholderWidget)
})
}));
setParents (* result);
return std::move (result);
}
}
omni::forge::sandbox_selector_model::sandbox_selector_model (omni::core::context & context, omni::core::model::module & module) :
_context (context),
_module (module),
_root (initSandboxData ())
{
}
omni::forge::sandbox_selector_model::~ sandbox_selector_model ()
{
}
omni::forge::sandbox_widget * omni::forge::sandbox_selector_model::createDemoFromModelIndex (QWidget & parent, const QModelIndex & index)
{
auto item = reinterpret_cast <sandbox_selector_data_base *> (index.internalPointer ());
if (item->widget == nullptr) {
item->widget = item->creator (_context, _module, parent);
}
return item->widget.get ();
}
QModelIndex omni::forge::sandbox_selector_model::index (int row, int column, const QModelIndex & parent) const
{
sandbox_selector_data_base * base;
if (parent == QModelIndex ()) {
base = _root.get ();
} else {
base = reinterpret_cast <sandbox_selector_data_base *> (parent.internalPointer ());
}
switch (static_cast <columns> (column)) {
case columns::title:
return createIndex (row, column, base->children [row].get ());
default:
throw omni::core::invalid_argument_error (__FILE__, __FUNCTION__, __LINE__, "column", "Invalid column");
}
return QModelIndex ();
}
QModelIndex omni::forge::sandbox_selector_model::parent (const QModelIndex & index) const
{
sandbox_selector_data_base & parent = * reinterpret_cast <sandbox_selector_data_base *> (index.internalPointer ())->parent;
sandbox_selector_data_base * grandParent = parent.parent;
if (grandParent == nullptr) {
return QModelIndex ();
} else {
return createIndex (
std::find_if (
grandParent->children.begin (),
grandParent->children.end (),
[&parent] (std::shared_ptr <sandbox_selector_data_base> & item) -> bool {
return item.get () == & parent;
}) - grandParent->children.begin (),
index.column (),
& parent);
}
}
int omni::forge::sandbox_selector_model::rowCount (const QModelIndex & parent) const
{
if (parent == QModelIndex ()) {
return _root->children.size ();
} else {
return reinterpret_cast <sandbox_selector_data_base *> (parent.internalPointer ())->children.size ();
}
}
int omni::forge::sandbox_selector_model::columnCount (const QModelIndex &) const
{
return 1;
}
QVariant omni::forge::sandbox_selector_model::headerData (int section, Qt::Orientation orientation, int role) const
{
switch (orientation) {
case Qt::Horizontal:
switch (role) {
case Qt::DisplayRole:
switch (section) {
case 0:
return "Available demos";
}
break;
}
break;
}
return QVariant ();
}
QVariant omni::forge::sandbox_selector_model::data (const QModelIndex & index, int role) const
{
sandbox_selector_data_base * base;
if (index == QModelIndex ()) {
base = _root.get ();
} else {
base = reinterpret_cast <sandbox_selector_data_base *> (index.internalPointer ());
}
sandbox_selector_data_base & item = * base;//->children [index.row ()];
switch (role) {
case Qt::DisplayRole:
switch (static_cast <columns> (index.column ())) {
case columns::title:
return item.title;
default:
throw omni::core::invalid_argument_error (__FILE__, __FUNCTION__, __LINE__, "column", "Invalid column");
}
default:
return QVariant ();
//throw omni::core::invalid_argument_error (__FILE__, __FUNCTION__, __LINE__, "role", "Unsupported role");
}
}
| 14,584 |
C++
| 38.958904 | 173 | 0.607584 |
daniel-kun/omni/source/omni/forge/sandbox_widget.hpp
|
#ifndef OMNI_FORGE_SANDBOX_WIDGET_HPP
#define OMNI_FORGE_SANDBOX_WIDGET_HPP
#include <QWidget>
#include <functional>
namespace omni {
namespace core {
class context;
namespace model {
class module;
}
}
}
namespace omni {
namespace forge {
/**
@brief A base class for sandbox demo widgets that are displayed in the main_window.
Sandbox demo widgets contain a "live", interactive demo of some view that is used in Omni Forge.
A demo can be compiled and run so that the piece of code-generation for the corresponding view can be tested.
**/
class sandbox_widget : public QWidget {
Q_OBJECT
public:
using CompileAndRunFun = std::function <void (omni::core::context & context, omni::core::model::module & module)>;
sandbox_widget (QWidget & parent, CompileAndRunFun compileAndRunFunction = CompileAndRunFun ());
virtual void compileAndRun (omni::core::context & context, omni::core::model::module & module);
private:
CompileAndRunFun _compileAndRunFun;
};
}
}
#endif // include guard
| 1,011 |
C++
| 22 | 118 | 0.738872 |
daniel-kun/omni/source/omni/forge/sandbox_selector_model.hpp
|
#ifndef OMNI_UI_SANDBOX_SELECTOR_MODEL_HPP
#define OMNI_UI_SANDBOX_SELECTOR_MODEL_HPP
#include <QAbstractItemModel>
#include <memory>
namespace omni {
namespace core {
class context;
namespace model {
class module;
}
}
}
namespace omni {
namespace forge {
class sandbox_widget;
/**
@brief The hierarchical data model that contains all available sandbox demos. Suitable for QTreeView.
The available sandbox demos are "hardcoded" in this model.
The model has currently one column: title, which displays a title of the corresponding sandbox demo.
**/
class sandbox_selector_model : public QAbstractItemModel {
public:
class sandbox_selector_data_base;
enum class columns {
title
};
sandbox_selector_model (omni::core::context & context, omni::core::model::module & module);
~ sandbox_selector_model ();
sandbox_widget * createDemoFromModelIndex (QWidget & parent, const QModelIndex & index);
QModelIndex index (int row, int column, const QModelIndex & parent) const override;
QModelIndex parent (const QModelIndex & index) const override;
int rowCount (const QModelIndex & parent) const override;
int columnCount (const QModelIndex & parent) const override;
QVariant headerData (int section, Qt::Orientation orientation, int role) const override;
QVariant data (const QModelIndex & index, int role) const override;
private:
omni::core::context & _context;
omni::core::model::module & _module;
std::unique_ptr <sandbox_selector_data_base> _root;
};
}
}
#endif
| 1,539 |
C++
| 25.101694 | 101 | 0.732294 |
daniel-kun/omni/source/omni/forge/main.cpp
|
#include <omni/ui/init.hpp>
#include "main_window.hpp"
#include <QApplication>
/*
statement
- block
- if_statement
- return_statement
- while_statemnt
+ expression
+ modifying_expression
- function_call_expression
- variable_assignment_expression
+ pure_expression
- binary_operator_expression
+ cast_expression
- bitcast_expression
- literal_expression
- variable_declaration_expression
- variable_expression
*/
int main (int argc, char * argv[])
{
omni::ui::init ();
QApplication app (argc, argv);
omni::forge::main_window mainWindow;
mainWindow.show ();
return app.exec ();
}
| 742 |
C++
| 19.081081 | 45 | 0.586253 |
daniel-kun/omni/source/omni/forge/sandbox_selector.hpp
|
#ifndef OMNI_FORGE_SANDBOX_SELECTOR_HPP
#define OMNI_FORGE_SANDBOX_SELECTOR_HPP
#include "sandbox_selector_model.hpp"
#include <omni/ui/tree_sort_filter_proxy_model.hpp>
#include <QWidget>
#include <QHBoxLayout>
#include <QTreeView>
#include <QLineEdit>
namespace omni {
namespace forge {
class sandbox_widget;
/**
@brief A widget that lets you select sandbox demos.
sandbox_selector uses the sandbox_selector_model, which itself contains a standard set of available sandbox demos.
If a demo is selected by the user, demoSelected(sandbox_widget) will be emitted.
**/
class sandbox_selector : public QWidget {
Q_OBJECT
public:
sandbox_selector (omni::core::context & context, omni::core::model::module & module, QWidget * parent);
signals:
void demoSelected (sandbox_widget & demoWidget);
public slots:
void focusSearchField ();
void setFilter (QString filterText);
private slots:
void emitDemoSelected (const QModelIndex & current);
private:
QVBoxLayout _layout;
QLineEdit _searchField;
QTreeView _selector;
sandbox_selector_model _model;
omni::ui::tree_sort_filter_proxy_model _filterModel;
};
}
}
#endif
| 1,162 |
C++
| 22.26 | 114 | 0.740964 |
daniel-kun/omni/source/omni/forge/main_window.cpp
|
#include "main_window.hpp"
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/ui/entity_widget_provider.hpp>
omni::forge::main_window::main_window () :
QWidget (),
_c (),
_m (_c, "forge-sandbox"),
_layout (this),
_rightLayout (),
_groupDemoList (this),
_groupDemoListLayout (& _groupDemoList),
_selector (_c, _m, & _groupDemoList),
_demoLabel (* this),
_demoChildLabel (& _demoLabel),
_activeDemo (& _demoLabel),
_compileAndRunButton (this),
_searchShortcut (QKeySequence ("Ctrl+F"), this)
{
setAutoFillBackground (true);
QPalette pal = palette ();
pal.setBrush (QPalette::Background, QColor::fromRgb (0x30, 0x3D, 0x35));
pal.setBrush (QPalette::Foreground, Qt::white);
setPalette (pal);
setWindowState (Qt::WindowMaximized);
_layout.addWidget (& _groupDemoList);
_groupDemoListLayout.addWidget (& _selector);
_groupDemoList.setTitle ("Available demos");
_groupDemoList.setMaximumWidth (300u);
_layout.addLayout (& _rightLayout);
_rightLayout.addWidget (& _demoLabel, 1);
_rightLayout.addWidget (& _compileAndRunButton, 0, Qt::AlignBottom);
_compileAndRunButton.setText ("Compile &and run");
_demoChildLabel.setText ("Select a demo in the tree on the left side.");
_selector.connect (& _searchShortcut, SIGNAL(activated()), SLOT (focusSearchField ()));
connect (& _selector, SIGNAL (demoSelected(sandbox_widget&)), SLOT (activateDemo(sandbox_widget&)));
connect (& _compileAndRunButton, SIGNAL(clicked()), SLOT(compileAndRunActiveDemo()));
}
void omni::forge::main_window::activateDemo (sandbox_widget & demo)
{
if (_activeDemo != nullptr) {
_rightLayout.removeWidget (_activeDemo);
_activeDemo->hide ();
}
_activeDemo = & demo;
if (_activeDemo != nullptr) {
_rightLayout.insertWidget (0, _activeDemo, 1, Qt::AlignVCenter);
_activeDemo->show ();
}
}
void omni::forge::main_window::showEvent (QShowEvent *)
{
_selector.focusSearchField ();
}
void omni::forge::main_window::compileAndRunActiveDemo ()
{
if (_activeDemo != nullptr) {
_activeDemo->compileAndRun (_c, _m);
}
}
| 2,198 |
C++
| 31.338235 | 104 | 0.657416 |
daniel-kun/omni/source/omni/ui/suggestion_list_model.cpp
|
#include <omni/ui/suggestion_list_model.hpp>
void omni::ui::suggestion_list_model::addSuggestion (omni::core::input::syntax_suggestion suggestion)
{
beginInsertRows (QModelIndex (), _suggestions.size (), _suggestions.size () + 1);
_suggestions.push_back (suggestion);
endInsertRows ();
}
omni::core::input::syntax_suggestion omni::ui::suggestion_list_model::getSuggestion (int row) const
{
return _suggestions [row];
}
omni::core::input::syntax_suggestion omni::ui::suggestion_list_model::getSuggestion (QString suggestionText) const
{
std::string text = suggestionText.toStdString ();
for (auto const & suggestion : _suggestions) {
if (suggestion.text == text) {
return suggestion;
}
}
throw std::out_of_range ("No such suggestion: " + text);
}
void omni::ui::suggestion_list_model::clear ()
{
if (_suggestions.size () > 0) {
beginRemoveRows (QModelIndex (), 0, _suggestions.size () - 1);
_suggestions.clear ();
endRemoveRows ();
}
}
int omni::ui::suggestion_list_model::rowCount (QModelIndex const &) const
{
return _suggestions.size ();
}
QVariant omni::ui::suggestion_list_model::data (QModelIndex const & index, int role) const
{
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
return QString::fromStdString (_suggestions [index.row ()].text);
default:
return QVariant ();
}
}
| 1,428 |
C++
| 28.163265 | 114 | 0.654062 |
daniel-kun/omni/source/omni/ui/variable_declaration_expression_view.cpp
|
#include <omni/ui/variable_declaration_expression_view.hpp>
#include <omni/ui/generic_entity_editor.hpp>
#include <omni/core/invalid_argument_error.hpp>
namespace {
class variable_name_view_widget : public omni::ui::entity_base_widget {
public:
variable_name_view_widget (QWidget * parent) :
entity_base_widget (parent),
_layout (this),
_label (this),
_variableDecl ()
{
_layout.addWidget (& _label);
}
std::shared_ptr <omni::core::model::entity> getEntity ()
{
return _variableDecl;
}
void setEntity (std::shared_ptr <omni::core::model::entity> entity)
{
_variableDecl = std::dynamic_pointer_cast <omni::core::model::variable_declaration_expression> (entity);
if (!_variableDecl) {
throw omni::core::invalid_argument_error (__FILE__, __FUNCTION__, __LINE__, "entity", "Not of type variable_declaration_expression or null");
}
_label.setText (QString::fromStdString (_variableDecl->getName ()));
}
private:
QHBoxLayout _layout;
QLabel _label;
std::shared_ptr <omni::core::model::variable_declaration_expression> _variableDecl;
};
class variable_name_edit_provider : public omni::ui::entity_widget_provider_base {
public:
std::unique_ptr <omni::ui::entity_base_widget> createViewWidget (QWidget * parent, omni::core::context &, omni::ui::entity_base_widget * editWidget) override
{
auto result = std::unique_ptr <variable_name_view_widget> (new variable_name_view_widget (parent));
if (editWidget != nullptr) {
result->setEntity (editWidget->getEntity ());
}
return std::move (result);
}
std::unique_ptr <omni::ui::entity_base_widget> createEditWidget (QWidget * parent, omni::core::context &, omni::ui::entity_base_widget & viewWidget) override
{
auto result = std::unique_ptr <omni::ui::generic_entity_editor> (new omni::ui::generic_entity_editor (parent));
result->setEntityToTextConverter (
[] (std::shared_ptr <omni::core::model::entity> originatingEntity) -> std::string {
return originatingEntity->getName ();
});
result->setTextToEntityConverter (
[] (std::string text, std::shared_ptr <omni::core::model::entity> originatingEntity) -> std::shared_ptr <omni::core::model::entity> {
auto variableDecl = std::dynamic_pointer_cast <omni::core::model::variable_declaration_expression> (originatingEntity);
if (! variableDecl) {
throw omni::core::invalid_argument_error (__FILE__, __FUNCTION__, __LINE__, "entity", "Can't convert text to entity. Not of type variable_declaration_expression or null");
}
variableDecl->setName (text);
return variableDecl;
});
result->setEntity (viewWidget.getEntity ());
return std::move (result);
}
bool keyPressEvent (QKeyEvent * ) override
{
return false;
}
};
}
omni::ui::variable_declaration_expression_view::variable_declaration_expression_view (omni::core::context & context, omni::core::model::module & module, QWidget * parent) :
entity_base_widget (parent),
_layout (this),
_varFixedText (this),
_nameWidgetProvider (std::unique_ptr <variable_name_edit_provider> (new variable_name_edit_provider ())),
_nameWidget (context, * _nameWidgetProvider, this),
_assignmentOperator (this),
_initializationExpression (context, module, this, omni::core::model::expression::getStaticMetaInfo ()),
_variableDeclExpression (),
_initExpressionExpandedConnection (_initializationExpression.onEntityExpanded.connect ([this] (std::shared_ptr <omni::core::model::entity> entity) -> void { updateInitializationExpression (entity); }))
{
_layout.addWidget (& _varFixedText, 0, Qt::AlignLeft);
_layout.addWidget (& _nameWidget, 0, Qt::AlignLeft);
_layout.addWidget (& _assignmentOperator, 0, Qt::AlignLeft);
_layout.addWidget (& _initializationExpression, 1, Qt::AlignLeft);
_varFixedText.setText ("var ");
_assignmentOperator.setText (" = ");
setAutoFillBackground (true);
auto pal = palette ();
pal.setBrush (QPalette::Background, QBrush (QColor (128, 73, 255)));
setPalette (pal);
}
std::shared_ptr <omni::core::model::entity> omni::ui::variable_declaration_expression_view::getEntity ()
{
return _variableDeclExpression;
}
void omni::ui::variable_declaration_expression_view::setEntity (std::shared_ptr <omni::core::model::entity> entity)
{
_variableDeclExpression = std::dynamic_pointer_cast <omni::core::model::variable_declaration_expression> (entity);
if (!_variableDeclExpression) {
throw omni::core::invalid_argument_error (__FILE__, __FUNCTION__, __LINE__, "entity", "Not of type variable_declaration_expression or null");
}
_nameWidget.setEntity (entity);
}
void omni::ui::variable_declaration_expression_view::startEdit ()
{
if (_nameWidget.currentViewMode () != omni::ui::entity_toggle_widget::Mode::m_edit) {
_nameWidget.toggleViewMode ();
_nameWidget.setFocus (Qt::TabFocusReason);
}
}
void omni::ui::variable_declaration_expression_view::updateInitializationExpression (std::shared_ptr <omni::core::model::entity> initializationExpression)
{
auto initExpr = std::dynamic_pointer_cast <omni::core::model::expression> (initializationExpression);
if (!initExpr) {
throw omni::core::invalid_argument_error (__FILE__, __FUNCTION__, __LINE__, "initializationExpression", "Not of type expression or null");
}
_variableDeclExpression->setInitializationExpression (initExpr);
}
| 5,718 |
C++
| 43.333333 | 205 | 0.66142 |
daniel-kun/omni/source/omni/ui/entity_base_widget.cpp
|
#include <omni/ui/entity_base_widget.hpp>
omni::ui::entity_base_widget::entity_base_widget (QWidget * parent) :
QWidget (parent)
{
}
std::shared_ptr <omni::core::model::entity> omni::ui::entity_base_widget::getEntity ()
{
return std::shared_ptr <omni::core::model::entity> ();
}
void omni::ui::entity_base_widget::setEntity (std::shared_ptr <omni::core::model::entity> entity)
{
// nop
}
/**
@brief Called after entity_placeholder_widget has been completed to this entity_base_widget and this widget needs to be put into editing mode to continue typing.
**/
void omni::ui::entity_base_widget::startEdit ()
{
}
| 628 |
C++
| 23.192307 | 161 | 0.697452 |
daniel-kun/omni/source/omni/ui/literal_expression_view.cpp
|
#include <omni/ui/literal_expression_view.hpp>
#include <omni/core/model/literal_expression.hpp>
#include <omni/core/model/type.hpp>
omni::ui::literal_expression_view::literal_expression_view (QWidget * parent) :
entity_base_widget (parent),
_layout (this),
_valueLabel (this),
_typeLabel (this),
_literalExpression ()
{
setAutoFillBackground (true);
_layout.addWidget (& _valueLabel, 0, Qt::AlignRight);
_layout.addWidget (& _typeLabel);
}
std::shared_ptr <omni::core::model::entity> omni::ui::literal_expression_view::getEntity ()
{
return getLiteral ();
}
void omni::ui::literal_expression_view::setEntity (std::shared_ptr <omni::core::model::entity> entity)
{
setLiteral (std::dynamic_pointer_cast <omni::core::model::literal_expression> (entity));
}
void omni::ui::literal_expression_view::setLiteral (std::shared_ptr <omni::core::model::literal_expression> literalExpression)
{
_literalExpression = literalExpression;
if (_literalExpression) {
_literalValueChangedConnection = _literalExpression->connectValueChanged ([this] (omni::core::model::literal_expression &, boost::any oldValue, boost::any newValue) -> void {
updateContent ();
});
}
updateContent ();
}
std::shared_ptr <omni::core::model::literal_expression> omni::ui::literal_expression_view::getLiteral ()
{
return _literalExpression;
}
void omni::ui::literal_expression_view::updateContent ()
{
if (_literalExpression) {
_valueLabel.setText (QString::fromStdString (_literalExpression->toString (false)));
_typeLabel.setText (QString::fromStdString (_literalExpression->getType ()->toString (false)));
} else {
_valueLabel.setText (QString ());
_typeLabel.setText (QString ());
}
}
| 1,790 |
C++
| 32.792452 | 182 | 0.684358 |
daniel-kun/omni/source/omni/ui/entity_placeholder_widget.cpp
|
#include <omni/ui/entity_placeholder_widget.hpp>
#include <omni/core/parser.hpp>
#include <omni/core/model/module.hpp>
#include <omni/ui/ui_meta_extension.hpp>
#include <omni/ui/entity_base_widget.hpp>
#include <omni/core/model/entity.hpp>
#include <QContextMenuEvent>
#include <QMessageBox>
#include <QStringBuilder>
namespace {
/**
@brief Enriches an QAction object with a reference to a meta_info.
**/
class meta_action : public QAction {
public:
meta_action (const omni::core::model::meta_info & metaInfo, const QString & text, QObject * parent);
const omni::core::model::meta_info & getMetaInfo ();
private:
const omni::core::model::meta_info & _metaInfo;
};
meta_action::meta_action (const omni::core::model::meta_info & metaInfo, const QString & text, QObject * parent) :
QAction (text, parent),
_metaInfo (metaInfo)
{
}
const omni::core::model::meta_info & meta_action::getMetaInfo ()
{
return _metaInfo;
}
}
omni::ui::entity_placeholder_widget::entity_placeholder_widget (
omni::core::context & context,
omni::core::model::module & module,
QWidget * parent,
omni::core::model::meta_info const & entityMeta) :
QWidget (parent),
_context (context),
_module (module),
_entityMeta (entityMeta),
_selectorPopup (this),
_layout (this),
_editor (this),
_entityWidget ()
{
_layout.addWidget (& _editor);
connect (& _editor, & QLineEdit::textChanged, this, & entity_placeholder_widget::editorTextChanged);
setMinimumSize (100, 100);
setAutoFillBackground (true);
QPalette pal = palette ();
pal.setBrush (QPalette::Background, Qt::gray);
setPalette (pal);
}
void omni::ui::entity_placeholder_widget::contextMenuEvent (QContextMenuEvent * event)
{
_selectorPopup.clear ();
populateMenu (_entityMeta, _selectorPopup);
_selectorPopup.popup (QPoint (event->globalX (), event->globalY ()));
}
void omni::ui::entity_placeholder_widget::switchToEntityType ()
{
auto * action = dynamic_cast <meta_action *> (sender ());
createEditorViewFromMetaInfo (action->getMetaInfo (), std::unique_ptr <omni::core::model::entity> ());
}
void omni::ui::entity_placeholder_widget::populateMenu (omni::core::model::meta_info const & meta, QMenu & menu)
{
if (! meta.isAbstract ()) {
auto * action = new meta_action (meta, QString::fromStdString (meta.getName ()), & menu);
connect (action, SIGNAL(triggered()), SLOT(switchToEntityType()));
menu.addAction (action);
}
for (std::size_t i = 0u; i < meta.getChildCount (); ++ i) {
auto & child = meta.getChildAt (i);
populateMenu (child, menu);
}
}
void omni::ui::entity_placeholder_widget::editorTextChanged (const QString & text)
{
omni::core::parser::StatementList statements = omni::core::parser::parseStatement (_module, text.toStdString ());
if (statements.size () == 1u) {
std::shared_ptr <omni::core::model::statement> statement = statements [0].entity;
createEditorViewFromMetaInfo (statement->getMetaInfo (), statement);
}
}
void omni::ui::entity_placeholder_widget::createEditorViewFromMetaInfo (const omni::core::model::meta_info & metaInfo,
std::shared_ptr <omni::core::model::entity> entity)
{
const auto & uiExtension = * dynamic_cast <const ui_meta_extension *> (metaInfo.getExtension ("omni.ui"));
_entityWidget = uiExtension.createViewWidget (_context, _module, this, entity);
_editor.hide ();
_layout.addWidget (_entityWidget.get ());
_entityWidget->startEdit ();
onEntityExpanded (_entityWidget->getEntity ());
}
| 3,678 |
C++
| 31.557522 | 123 | 0.662588 |
daniel-kun/omni/source/omni/ui/generic_entity_editor.cpp
|
#include <omni/ui/generic_entity_editor.hpp>
#include <omni/core/model/literal_expression.hpp>
omni::ui::generic_entity_editor::generic_entity_editor (QWidget * parent, std::shared_ptr <omni::core::model::entity> entity) :
entity_base_widget (parent),
_entityToTextConverter (),
_textToEntityConverter (),
_entity (entity),
_layout (this),
_edit (this)
{
_layout.addWidget (& _edit);
setFocusProxy (& _edit);
}
std::function <std::string (std::shared_ptr <omni::core::model::entity>)> omni::ui::generic_entity_editor::getEntityToTextConverter () const
{
return _entityToTextConverter;
}
void omni::ui::generic_entity_editor::setEntityToTextConverter (std::function <std::string (std::shared_ptr <omni::core::model::entity>)> converter)
{
_entityToTextConverter = converter;
}
std::function <std::shared_ptr <omni::core::model::entity> (std::string text, std::shared_ptr <omni::core::model::entity> originatingEntity)> omni::ui::generic_entity_editor::getTextToEntityConverter () const
{
return _textToEntityConverter;
}
void omni::ui::generic_entity_editor::setTextToEntityConverter (std::function <std::shared_ptr <omni::core::model::entity> (std::string text, std::shared_ptr <omni::core::model::entity> originatingEntity)> converter)
{
_textToEntityConverter = converter;
}
std::shared_ptr <omni::core::model::entity> omni::ui::generic_entity_editor::getEntity ()
{
if (_textToEntityConverter) {
return _textToEntityConverter (_edit.text ().toStdString (), _entity);
} else {
return _entity;
}
}
void omni::ui::generic_entity_editor::setEntity (std::shared_ptr <omni::core::model::entity> entity)
{
_entity = entity;
if (_entityToTextConverter) {
_edit.setText (QString::fromStdString (_entityToTextConverter (entity)));
} else {
// TODO: This is only for tests, toString needs to be added to omni::core::model::entity:
auto literal = std::dynamic_pointer_cast <omni::core::model::literal_expression> (entity);
_edit.setText (QString::fromStdString (literal->toString (false)));
}
}
| 2,117 |
C++
| 36.821428 | 216 | 0.692017 |
daniel-kun/omni/source/omni/ui/ui.cpp
|
#include <omni/ui/ui.hpp>
| 26 |
C++
| 12.499994 | 25 | 0.692308 |
daniel-kun/omni/source/omni/ui/blueprint.cpp
|
#include <omni/ui/blueprint.hpp>
#include <QPainter>
omni::ui::blueprint::blueprint (QWidget * parent) :
QWidget (parent)
{
setAutoFillBackground (true);
QPalette pal;
pal.setColor (QPalette::Background, QColor::fromRgb (0xFF, 0xFF, 0xFF));
// pal.setColor (QPalette::Background, QColor::fromRgb (0x64, 0xA7, 0xC1));
setPalette (pal);
}
void omni::ui::blueprint::paintEvent (QPaintEvent *)
{
return;
QPainter painter (this);
painter.setPen (QColor::fromRgb (0xE3, 0xE3, 0xE5));
int w = width ();
int h = height ();
const int hstep = 20;
const int vstep = 20;
for (int x = 0; x <= w; x += hstep) {
for (int y = 0; y <= h; y += vstep) {
painter.drawLine (0, y, w, y);
painter.drawLine (x, 0 ,x, h);
}
}
}
| 805 |
C++
| 24.999999 | 78 | 0.582609 |
daniel-kun/omni/source/omni/ui/syntax_input.cpp
|
#include <omni/ui/syntax_input.hpp>
#include <omni/ui/suggestion_text_edit.hpp>
#include <omni/core/input/syntax_element.hpp>
#include <omni/core/input/syntax_template_element.hpp>
#include <omni/core/input/regex_template_element.hpp>
#include <omni/core/input/variable_template_element.hpp>
#include <omni/core/input/fixed_template_element.hpp>
#include <omni/core/input/repeater_template_element.hpp>
#include <omni/core/input/template_visitor.hpp>
#include <QLabel>
omni::ui::syntax_input::syntax_input (QWidget * parent, omni::core::input::syntax_element & syntaxElement) :
QWidget (parent),
_syntaxElement (syntaxElement),
_layout (this, 0, 0, 0),
_widgets ()
{
//setContentsMargins (QMargins (5, 5, 5, 5));
_layout.setMargin (0);
//QPalette pal;
//pal.setBrush (QPalette::Background, Qt::red);
// fromRgb (0xE3, 0xE3, 0xE5)
//setPalette (pal);
//setAutoFillBackground (true);
addRootTextEdit ();
}
void omni::ui::syntax_input::addRootTextEdit ()
{
auto textEdit = std::make_shared <suggestion_text_edit> (this);
connect (
textEdit.get (),
SIGNAL (suggestionsRequested(QString const &, std::vector <omni::core::input::syntax_suggestion> &)),
this,
SLOT (provideSuggestions(QString const &, std::vector <omni::core::input::syntax_suggestion> &)));
connect (
textEdit.get (),
SIGNAL (suggestionAccepted (omni::core::input::syntax_suggestion)),
this,
SLOT (acceptSuggestion (omni::core::input::syntax_suggestion)));
_layout.addWidget (textEdit.get ());
_widgets.push_back (textEdit);
}
void omni::ui::syntax_input::provideSuggestions (QString const & text, std::vector <omni::core::input::syntax_suggestion> & suggestions)
{
std::vector <omni::core::input::syntax_suggestion> newSuggestions = _syntaxElement.suggest (text.toStdString ());
suggestions.insert (suggestions.end (), newSuggestions.begin (), newSuggestions.end ());
}
void omni::ui::syntax_input::clearWidgets ()
{
for (auto widget : _widgets) {
_layout.removeWidget (widget.get ());
widget->setParent (nullptr);
}
_widgets.clear ();
}
void omni::ui::syntax_input::acceptSuggestion (omni::core::input::syntax_suggestion suggestion)
{
clearWidgets ();
using namespace omni::core::input;
class template_create_widget_visitor : public template_visitor {
public:
template_create_widget_visitor (
QWidget & parent,
QLayout & layout,
std::list <std::shared_ptr <QWidget>> & widgets) :
_parent (parent),
_layout (layout),
_widgets (widgets)
{
}
void visitSyntaxTemplateElement (syntax_template_element & syntaxTemplateElement) override
{
auto textEdit = std::make_shared <syntax_input> (& _parent, * syntaxTemplateElement.getSyntaxElement ());
_layout.addWidget (textEdit.get ());
_widgets.push_back (textEdit);
}
void visitVariableTemplateElement (variable_template_element &) override
{
auto textEdit = std::make_shared <QLineEdit> (& _parent);
textEdit->setPlaceholderText ("(variable)");
_layout.addWidget (textEdit.get ());
_widgets.push_back (textEdit);
}
void visitRegexTemplateElement (regex_template_element &) override
{
auto textEdit = std::make_shared <QLineEdit> (& _parent);
textEdit->setPlaceholderText ("(regex)");
_layout.addWidget (textEdit.get ());
_widgets.push_back (textEdit);
}
void visitFixedTemplateElement (fixed_template_element & element) override
{
auto label = std::make_shared <QLabel> (& _parent);
label->setText (QString::fromStdString (element.getText ()));
_layout.addWidget (label.get ());
_widgets.push_back (label);
}
void visitRepeaterTemplateElement (repeater_template_element &) override
{
auto textEdit = std::make_shared <QLineEdit> (& _parent);
textEdit->setPlaceholderText ("(repeater)");
_layout.addWidget (textEdit.get ());
_widgets.push_back (textEdit);
}
private:
QWidget & _parent;
QLayout & _layout;
std::list <std::shared_ptr <QWidget>> & _widgets;
} visitor (* this, _layout, _widgets);
syntax_element & e = * suggestion.syntaxElement;
for (std::size_t i = 0; i < e.templateElementCount (); ++i) {
template_element & t = * e.templateElementAt (i);
t.visit (visitor);
}
}
| 4,704 |
C++
| 34.643939 | 136 | 0.621386 |
daniel-kun/omni/source/omni/ui/tree_sort_filter_proxy_model.cpp
|
#include <omni/ui/tree_sort_filter_proxy_model.hpp>
/**
@return Returns the QModelIndex of the first row that matches the current filter criteria exactly.
**/
QModelIndex omni::ui::tree_sort_filter_proxy_model::firstMatchingIndex () const
{
return firstMatchingIndexImpl (QModelIndex ());
}
/**
@brief Recursive implementation detail to firstMatchingIndex ().
**/
QModelIndex omni::ui::tree_sort_filter_proxy_model::firstMatchingIndexImpl (const QModelIndex & parent) const
{
for (int r = 0; r < rowCount (parent); ++ r) {
if (filterAcceptsRowExactly (r, mapToSource (parent))) {
return index (r, 0, parent);
}
QModelIndex result = firstMatchingIndexImpl (index (r, 0, parent));
if (result.isValid ()) {
return result;
}
}
return QModelIndex ();
}
/**
@brief Provides the original functionality of QSortFilterProxyModel's filterAcceptRow() function.
@return True, if the given row itself matches the current filter criteria. Children are not checked.
**/
bool omni::ui::tree_sort_filter_proxy_model::filterAcceptsRowExactly (int sourceRow, const QModelIndex & sourceParent) const
{
return QSortFilterProxyModel::filterAcceptsRow (sourceRow, sourceParent);
}
bool omni::ui::tree_sort_filter_proxy_model::filterAcceptsRow (int sourceRow, const QModelIndex & sourceParent) const
{
// If this row matches, return true:
if (filterAcceptsRowExactly (sourceRow, sourceParent)) {
return true;
}
// Now check whether any of this row's child rows matches:
QModelIndex row = sourceModel ()->index (sourceRow, filterKeyColumn (), sourceParent);
for (int i = 0; i < sourceModel ()->rowCount (row); ++ i) {
if (filterAcceptsRow (i, row)) {
return true;
}
}
// Neither this row, nor any children, match.
return false;
}
| 1,868 |
C++
| 33.61111 | 124 | 0.683619 |
daniel-kun/omni/source/omni/ui/suggestion_text_edit.cpp
|
#include <omni/ui/suggestion_text_edit.hpp>
omni::ui::suggestion_text_edit::suggestion_text_edit (QWidget * parent) :
suggestion_text_edit (QString (), parent)
{
}
omni::ui::suggestion_text_edit::suggestion_text_edit (QString const & text, QWidget * parent) :
QLineEdit (text, parent),
_model (),
_completer (& _model)
{
connect (this, SIGNAL(textChanged(QString const &)), this, SLOT (showSuggestionsWhenTextChanged(QString const &)));
_completer.setCompletionMode (QCompleter::UnfilteredPopupCompletion);
_completer.setWidget (this);
connect (& _completer, SIGNAL(activated(QString const &)), this, SLOT (acceptCompletion(QString const &)));
}
void omni::ui::suggestion_text_edit::showSuggestionsWhenTextChanged (QString const & text)
{
std::vector <omni::core::input::syntax_suggestion> suggestions;
emit suggestionsRequested (text, suggestions);
_model.clear ();
for (auto suggestion : suggestions) {
_model.addSuggestion (suggestion);
}
_completer.complete ();
}
void omni::ui::suggestion_text_edit::acceptCompletion (QString const & text)
{
disconnect (this, SIGNAL(textChanged(QString const &)), this, SLOT (showSuggestionsWhenTextChanged(QString const &)));
setText (text);
connect (this, SIGNAL(textChanged(QString const &)), this, SLOT (showSuggestionsWhenTextChanged(QString const &)));
emit suggestionAccepted (_model.getSuggestion (text));
}
| 1,440 |
C++
| 36.921052 | 122 | 0.711111 |
daniel-kun/omni/source/omni/ui/entity_toggle_widget.cpp
|
#include <omni/ui/entity_toggle_widget.hpp>
#include <omni/ui/entity_widget_provider_base.hpp>
omni::ui::entity_toggle_widget::entity_toggle_widget (omni::core::context & context, entity_widget_provider_base & provider, QWidget * parent) :
entity_base_widget (parent),
_c (context),
_provider (provider),
_toggleAction ("Test", this),
_layout (this),
_entity (),
_viewWidget (),
_editWidget ()
{
_toggleAction.setShortcut (QKeySequence (Qt::Key_Return));
_toggleAction.setShortcutContext (Qt::WidgetWithChildrenShortcut);
addAction (& _toggleAction);
connect (& _toggleAction, SIGNAL(triggered()), SLOT (toggleViewMode()));
toggleViewMode ();
setAutoFillBackground (true);
setFocusPolicy (Qt::StrongFocus);
}
std::shared_ptr <omni::core::model::entity> omni::ui::entity_toggle_widget::getEntity ()
{
if (_viewWidget) {
return _viewWidget->getEntity ();
} else if (_editWidget) {
return _editWidget->getEntity ();
} else {
return std::shared_ptr <omni::core::model::entity> ();
}
}
void omni::ui::entity_toggle_widget::setEntity (std::shared_ptr <omni::core::model::entity> entity)
{
if (_viewWidget) {
_viewWidget->setEntity (entity);
} else if (_editWidget) {
_editWidget->setEntity (entity);
}
}
void omni::ui::entity_toggle_widget::focusInEvent (QFocusEvent * event)
{
QWidget::focusInEvent (event);
QPalette pal;
pal.setBrush (QPalette::Background, Qt::red);
setPalette (pal);
}
void omni::ui::entity_toggle_widget::focusOutEvent (QFocusEvent * event)
{
QWidget::focusOutEvent (event);
QPalette pal;
setPalette (pal);
}
omni::ui::entity_toggle_widget::Mode omni::ui::entity_toggle_widget::currentViewMode ()
{
if (_viewWidget) {
return Mode::m_view;
} else {
return Mode::m_edit;
}
}
omni::ui::entity_toggle_widget::Mode omni::ui::entity_toggle_widget::toggleViewMode ()
{
if (_viewWidget) {
// Go into edit mode:
bool hadFocus = hasFocus () || _viewWidget->hasFocus ();
_editWidget = _provider.createEditWidget (this, _c, *_viewWidget);
_layout.addWidget (_editWidget.get ());
_viewWidget.reset ();
if (hadFocus) {
_editWidget->setFocus (Qt::TabFocusReason);
}
setFocusProxy (_editWidget.get ());
return Mode::m_edit;
} else {
// Accept input, go into view mode:
bool hadFocus;
if (_editWidget) {
hadFocus = hasFocus () || _editWidget->hasFocus ();
} else {
hadFocus = hasFocus ();
}
_viewWidget = _provider.createViewWidget (this, _c, _editWidget.get ());
_editWidget.reset ();
_layout.addWidget (_viewWidget.get ());
setFocusProxy (nullptr);
if (hadFocus) {
setFocus (Qt::TabFocusReason);
}
return Mode::m_view;
}
}
void omni::ui::entity_toggle_widget::keyPressEvent (QKeyEvent * /*event*/)
{
/*
if (! _editProvider.keyPressEvent (event)) {
QWidget::keyPressEvent (event);
}
*/
}
/*
bool omni::forge::literal_edit_provider::keyPressEvent (QKeyEvent * event)
{
if (std::isalnum (event->key (), std::locale (""))) {
return true;
} else {
return false;
}
}
*/
| 3,330 |
C++
| 26.991596 | 144 | 0.607508 |
daniel-kun/omni/source/omni/ui/init.cpp
|
#include <omni/ui/init.hpp>
#include <omni/ui/ui_meta_extension.hpp>
#include <omni/ui/literal_expression_view.hpp>
#include <omni/ui/variable_declaration_expression_view.hpp>
#include <omni/ui/entity_widget_provider.hpp>
#include <omni/core/model/entity.hpp>
#include <omni/core/model/meta_info.hpp>
#include <omni/core/model/external_function.hpp>
#include <omni/core/model/function.hpp>
#include <omni/core/model/parameter.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/model/function_call_expression.hpp>
#include <omni/core/model/variable_assignment_expression.hpp>
#include <omni/core/model/binary_operator_expression.hpp>
#include <omni/core/model/bitcast_expression.hpp>
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/model/variable_declaration_expression.hpp>
#include <omni/core/model/variable_expression.hpp>
#include <omni/core/model/if_statement.hpp>
#include <omni/core/model/return_statement.hpp>
#include <omni/core/model/while_statement.hpp>
#include <omni/core/model/do_while_statement.hpp>
#include <memory>
namespace {
// Creator functions:
std::unique_ptr <omni::ui::entity_base_widget> createBuiltinLiteralExpressionView (omni::core::context & context,
omni::core::model::module &,
QWidget * parent,
std::shared_ptr <omni::core::model::entity> entity)
{
auto result = std::unique_ptr <omni::ui::entity_toggle_widget> (new omni::ui::entity_toggle_widget (context, omni::ui::entity_widget_provider::getProvider ("literal_expression"), parent));
result->setEntity (entity);
return std::move (result);
}
std::unique_ptr <omni::ui::entity_base_widget> createVariableDeclarationExpression (omni::core::context & context,
omni::core::model::module & module,
QWidget * parent,
std::shared_ptr <omni::core::model::entity> entity)
{
auto result = std::unique_ptr <omni::ui::variable_declaration_expression_view> (new omni::ui::variable_declaration_expression_view (context, module, parent));
result->setEntity (entity);
return std::move (result);
}
// Helper functions:
template <typename T>
void setUiMeta (omni::ui::ui_meta_extension::CreateViewWidgetFunction viewWidgetCreator)
{
auto & meta = T::getStaticMetaInfo ();
meta.setExtension ("omni.ui", std::make_shared <omni::ui::ui_meta_extension> (viewWidgetCreator));
}
}
/*
type
module
[ ] external_function
[ ] function
[ ] parameter
[ ] block
[ ] function_call_expression
[ ] variable_assignment_expression
[ ] binary_operator_expression
[ ] bitcast_expression
[ ] builtin_literal_expression
[ ] variable_declaration_expression
[ ] variable_expression
[ ] if_statement
[ ] return_statement
[ ] while_statement
[ ] do_while_statement
*/
/**
@class init init.hpp omni/ui/init.hpp
@brief Initializes the Omni UI Subsystem. Call this function before using any Omni UI class.
**/
void omni::ui::init ()
{
using namespace omni::core::model;
setUiMeta <builtin_literal_expression <unsigned int>> (createBuiltinLiteralExpressionView);
setUiMeta <variable_declaration_expression> (createVariableDeclarationExpression);
}
| 3,688 |
C++
| 39.097826 | 192 | 0.625542 |
daniel-kun/omni/source/omni/ui/flowlayout.cpp
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include <QWidget>
#include <omni/ui/flowlayout.hpp>
FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing)
: QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing)
{
setContentsMargins(margin, margin, margin, margin);
}
FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing)
: m_hSpace(hSpacing), m_vSpace(vSpacing)
{
setContentsMargins(margin, margin, margin, margin);
}
FlowLayout::~FlowLayout()
{
QLayoutItem *item;
while ((item = takeAt(0)))
delete item;
}
void FlowLayout::addItem(QLayoutItem *item)
{
itemList.append(item);
}
int FlowLayout::horizontalSpacing() const
{
if (m_hSpace >= 0) {
return m_hSpace;
} else {
return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
}
}
int FlowLayout::verticalSpacing() const
{
if (m_vSpace >= 0) {
return m_vSpace;
} else {
return smartSpacing(QStyle::PM_LayoutVerticalSpacing);
}
}
int FlowLayout::count() const
{
return itemList.size();
}
QLayoutItem *FlowLayout::itemAt(int index) const
{
return itemList.value(index);
}
QLayoutItem *FlowLayout::takeAt(int index)
{
if (index >= 0 && index < itemList.size())
return itemList.takeAt(index);
else
return 0;
}
Qt::Orientations FlowLayout::expandingDirections() const
{
return 0;
}
bool FlowLayout::hasHeightForWidth() const
{
return true;
}
int FlowLayout::heightForWidth(int width) const
{
int height = doLayout(QRect(0, 0, width, 0), true);
return height;
}
void FlowLayout::setGeometry(const QRect &rect)
{
QLayout::setGeometry(rect);
doLayout(rect, false);
}
QSize FlowLayout::sizeHint() const
{
return minimumSize();
}
QSize FlowLayout::minimumSize() const
{
QSize size;
QLayoutItem *item;
foreach (item, itemList)
size = size.expandedTo(item->minimumSize());
size += QSize(2*margin(), 2*margin());
return size;
}
int FlowLayout::doLayout(const QRect &rect, bool testOnly) const
{
int left, top, right, bottom;
getContentsMargins(&left, &top, &right, &bottom);
QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);
int x = effectiveRect.x();
int y = effectiveRect.y();
int lineHeight = 0;
QLayoutItem *item;
foreach (item, itemList) {
QWidget *wid = item->widget();
int spaceX = horizontalSpacing();
if (spaceX == -1)
spaceX = wid->style()->layoutSpacing(
QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal);
int spaceY = verticalSpacing();
if (spaceY == -1)
spaceY = wid->style()->layoutSpacing(
QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical);
int nextX = x + item->sizeHint().width() + spaceX;
if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) {
x = effectiveRect.x();
y = y + lineHeight + spaceY;
nextX = x + item->sizeHint().width() + spaceX;
lineHeight = 0;
}
if (!testOnly)
item->setGeometry(QRect(QPoint(x, y), item->sizeHint()));
x = nextX;
lineHeight = qMax(lineHeight, item->sizeHint().height());
}
return y + lineHeight - rect.y() + bottom;
}
int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const
{
QObject *parent = this->parent();
if (!parent) {
return -1;
} else if (parent->isWidgetType()) {
QWidget *pw = static_cast<QWidget *>(parent);
return pw->style()->pixelMetric(pm, 0, pw);
} else {
return static_cast<QLayout *>(parent)->spacing();
}
}
| 5,836 |
C++
| 29.401042 | 83 | 0.626285 |
daniel-kun/omni/source/omni/ui/entity_widget_provider.cpp
|
#include <omni/ui/entity_widget_provider.hpp>
#include <omni/ui/entity_base_widget.hpp>
#include <omni/ui/literal_expression_view.hpp>
#include <omni/ui/generic_entity_editor.hpp>
#include <omni/core/invalid_argument_error.hpp>
#include <omni/core/model/literal_expression.hpp>
std::map <std::string, omni::ui::entity_widget_provider> s_widgetProviderRegistry = {
{ "literal_expression", omni::ui::entity_widget_provider (
[] (QWidget * parent, omni::core::context &, omni::ui::entity_base_widget * editWidget) -> std::unique_ptr <omni::ui::entity_base_widget> {
std::shared_ptr <omni::core::model::literal_expression> literal;
if (editWidget != nullptr) {
literal = std::dynamic_pointer_cast <omni::core::model::literal_expression> (editWidget->getEntity ());
}
auto viewWidget = std::unique_ptr <omni::ui::literal_expression_view> (new omni::ui::literal_expression_view (parent));
viewWidget->setLiteral (literal);
return std::move (viewWidget);
},
[] (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget & viewWidget) -> std::unique_ptr <omni::ui::entity_base_widget> {
auto result = std::unique_ptr <omni::ui::generic_entity_editor> (new omni::ui::generic_entity_editor (parent, viewWidget.getEntity ()));
result->setTextToEntityConverter ([&context] (std::string text, std::shared_ptr <omni::core::model::entity> originatingEntity) -> std::shared_ptr <omni::core::model::entity> {
auto literal = std::dynamic_pointer_cast <omni::core::model::literal_expression> (originatingEntity);
return omni::core::model::literal_expression::fromString (context, text, literal.get ());
});
result->setEntity (viewWidget.getEntity ());
return std::move (result);
},
std::function <bool (QKeyEvent * event)> ())
}
};
omni::ui::entity_widget_provider & omni::ui::entity_widget_provider::getProvider (std::string entityType)
{
auto iterator = s_widgetProviderRegistry.find (entityType);
if (iterator != s_widgetProviderRegistry.end ()) {
return iterator->second;
} else {
throw omni::core::invalid_argument_error (__FILE__, __FUNCTION__, __LINE__, "entityType", "An entity \"" + entityType + "\" was not found.");
}
}
omni::ui::entity_widget_provider::entity_widget_provider (
std::function <std::unique_ptr <omni::ui::entity_base_widget> (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget * editWidget)> viewCreator,
std::function <std::unique_ptr <omni::ui::entity_base_widget> (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget & viewWidget)> editCreator,
std::function <bool (QKeyEvent * event)> keyHandler) :
_viewCreator (viewCreator),
_editCreator (editCreator),
_keyHandler (keyHandler)
{
}
std::unique_ptr <omni::ui::entity_base_widget> omni::ui::entity_widget_provider::createViewWidget (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget * editWidget)
{
return _viewCreator (parent, context, editWidget);
}
std::unique_ptr <omni::ui::entity_base_widget> omni::ui::entity_widget_provider::createEditWidget (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget & viewWidget)
{
return _editCreator (parent, context, viewWidget);
}
bool omni::ui::entity_widget_provider::keyPressEvent (QKeyEvent * event)
{
return _keyHandler (event);
}
| 3,719 |
C++
| 52.913043 | 191 | 0.639688 |
daniel-kun/omni/source/omni/ui/ui_meta_extension.cpp
|
#include <omni/ui/ui_meta_extension.hpp>
/**
@brief Initializes this ui_meta_extension with the given parameters.
@param viewWidgetCreator This function will be used in createViewWidget() to return a new widget for an entity of the type corresponding to the meta_info that this
extension is attached to.
**/
omni::ui::ui_meta_extension::ui_meta_extension (CreateViewWidgetFunction viewWidgetCreator) :
_viewWidgetCreator (viewWidgetCreator)
{
}
/**
@brief Returns a new widget for an entity of the type corresponding to the meta_info that this extension is attached to.
@return A new widget for an entity of the type corresponding to the meta_info that this extension is attached to.
**/
std::unique_ptr <omni::ui::entity_base_widget> omni::ui::ui_meta_extension::createViewWidget (omni::core::context & context,
omni::core::model::module & module,
QWidget * parent,
std::shared_ptr <omni::core::model::entity> entity) const
{
return _viewWidgetCreator (context, module, parent, entity);
}
| 1,354 |
C++
| 55.458331 | 163 | 0.563516 |
daniel-kun/omni/source/omni/core/no_context_error.cpp
|
#include <omni/core/no_context_error.hpp>
#include <sstream>
namespace {
std::string buildNoContextErrorMessage (omni::core::domain domain, std::string const & identifier)
{
std::stringstream result;
switch (domain) {
case omni::core::domain::function:
result << "The function \"" << identifier << "\" was not added to a context.";
break;
default:
result << "The entity \"" << identifier << "\" was not added to a context.";
break;
}
return result.str ();
}
}
omni::core::no_context_error::no_context_error (omni::core::domain domain, std::string const & identifier) :
std::runtime_error (buildNoContextErrorMessage (domain, identifier).c_str ())
{
}
| 713 |
C++
| 28.749999 | 108 | 0.645161 |
daniel-kun/omni/source/omni/core/statement_emit_result.cpp
|
#include <omni/core/statement_emit_result.hpp>
/**
Initializes this result with the given continueBlock and the given value
@param continueBlock The block that should be used to emit following statements. Some statements branch a new block and use the continueBlock
to return this new block to the llvm emitting code. If the statement does not branch, continueBlock should be set to the same as the llvmBasicBlock
provided to omni::core::statement::llvmEmit. @see getContinueBlock().
@param value nullptr for statements that are not expressions. Expressions return their result value with this field. @see getValue() @see hasValue().
**/
omni::core::statement_emit_result::statement_emit_result (llvm::BasicBlock * continueBlock, llvm::Value * value) :
_continueBlock (continueBlock),
_value (value)
{
}
/**
Returns the block that should be used for further emitting code after this statement has been emitted. This is used for branching statements.
**/
llvm::BasicBlock * omni::core::statement_emit_result::getContinueBlock () const
{
return _continueBlock;
}
/**
If the statement is an expression, getValue returns the expression's value. Is always nullptr for all statements that are not expressions.
**/
llvm::Value * omni::core::statement_emit_result::getValue () const
{
return _value;
}
/**
Returns true, when this statement has a value (i.e. is an expression).
**/
bool omni::core::statement_emit_result::hasValue () const
{
return _value != nullptr;
}
| 1,485 |
C++
| 37.102563 | 149 | 0.754209 |
daniel-kun/omni/source/omni/core/runtime.cpp
|
#include <omni/core/runtime.hpp>
#include <omni/core/context.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/type_class.hpp>
#include <omni/core/model/parameter.hpp>
#include <omni/core/model/external_function.hpp>
namespace {
#ifdef WIN32
std::string omniRuntimeLib = "omni-runtime.lib";
#else
std::string omniRuntimeLib = "omni-runtime";
#endif
}
/**
Initializes this runtime for the given module.
**/
omni::core::runtime::runtime (omni::core::model::module & module) :
_module (module),
_memoryAllocate (),
_memoryAddReference (),
_memoryRemoveReference ()
{
}
/**
Returns an external_function describing the Omni Runtime function void * omni_runtime_memory_allocate(std::size_t sizeInBytes).
**/
std::shared_ptr <omni::core::model::external_function> omni::core::runtime::getMemoryAllocate ()
{
if (_memoryAllocate == nullptr) {
context & c (* _module.getContext ());
_memoryAllocate.reset (
new model::external_function (
omniRuntimeLib,
"omni_runtime_memory_allocate",
c.sharedBasicType (model::type_class::t_unsignedByte, 1)));
_memoryAllocate->setParameters (
std::vector <std::shared_ptr <model::parameter>> {
static_cast <std::shared_ptr <model::parameter>> (new model::parameter (c.sharedBasicType (model::type_class::t_unsignedInt), "sizeInBytes"))
});
_module.addFunction (_memoryAllocate);
}
return _memoryAllocate;
}
/**
Returns an external_function describing the Omni Runtime function void * omni_runtime_add_allocate(void * memory).
**/
std::shared_ptr <omni::core::model::external_function> omni::core::runtime::getMemoryAddReference ()
{
if (_memoryAddReference == nullptr) {
context & c (* _module.getContext ());
_memoryAddReference.reset (
new model::external_function (
omniRuntimeLib,
"omni_runtime_memory_add_reference",
c.sharedBasicType (model::type_class::t_unsignedByte, 1)));
_memoryAddReference->setParameters (
std::vector <std::shared_ptr <model::parameter>> {
static_cast <std::shared_ptr <model::parameter>> (new model::parameter (c.sharedBasicType (model::type_class::t_unsignedByte, 1), "memory"))
});
_module.addFunction (_memoryAddReference);
}
return _memoryAddReference;
}
/**
Returns an external_function describing the Omni Runtime function void * omni_runtime_add_allocate(void * memory).
**/
std::shared_ptr <omni::core::model::external_function> omni::core::runtime::getMemoryRemoveReference ()
{
if (_memoryRemoveReference == nullptr) {
context & c (* _module.getContext ());
_memoryRemoveReference.reset (
new model::external_function (
omniRuntimeLib,
"omni_runtime_memory_remove_reference",
c.sharedBasicType (model::type_class::t_unsignedByte, 1)));
_memoryRemoveReference->setParameters (
std::vector <std::shared_ptr <model::parameter>> {
static_cast <std::shared_ptr <model::parameter>> (new model::parameter (c.sharedBasicType (model::type_class::t_unsignedByte, 1), "memory"))
});
_module.addFunction (_memoryRemoveReference);
}
return _memoryRemoveReference;
}
| 3,429 |
C++
| 37.111111 | 157 | 0.646253 |
daniel-kun/omni/source/omni/core/domain.cpp
|
#include <omni/core/domain.hpp>
#include <boost/format.hpp>
std::ostream & omni::core::operator << (std::ostream & lhs, omni::core::domain rhs)
{
switch (rhs) {
case omni::core::domain::invalid:
lhs << "invalid";
break;
case omni::core::domain::binary_operator_expression:
lhs << "binary_operator_expression";
break;
case omni::core::domain::bitcast_expression:
lhs << "bitcast_expression";
break;
case omni::core::domain::block:
lhs << "block";
break;
case omni::core::domain::do_while_statement:
lhs << "do_while_statement";
break;
case omni::core::domain::expression:
lhs << "expression";
break;
case omni::core::domain::external_function:
lhs << "external_function";
break;
case omni::core::domain::function:
lhs << "function";
break;
case omni::core::domain::function_call_expression:
lhs << "function_call_expression";
break;
case omni::core::domain::if_statement:
lhs << "if_statement";
break;
case omni::core::domain::builtin_literal_expression:
lhs << "builtin_literal_expression";
break;
case omni::core::domain::module:
lhs << "module";
break;
case omni::core::domain::parameter:
lhs << "parameter";
break;
case omni::core::domain::return_statement:
lhs << "return_statement";
break;
case omni::core::domain::statement:
lhs << "statement";
break;
case omni::core::domain::type:
lhs << "type";
break;
case omni::core::domain::variable_assignment_expression:
lhs << "variable_assignment_expression";
break;
case omni::core::domain::variable_declaration_expression:
lhs << "variable_declaration_expression";
break;
case omni::core::domain::variable_expression:
lhs << "variable_expression";
break;
case omni::core::domain::while_statement:
lhs << "while_statement";
break;
default:
throw std::runtime_error ((boost::format ("Can not stream unknown domain %1% to std::ostream") % static_cast <std::size_t> (rhs)).str ());
}
return lhs;
}
| 2,271 |
C++
| 30.123287 | 146 | 0.582563 |
daniel-kun/omni/source/omni/core/logic_error.cpp
|
#include <omni/core/logic_error.hpp>
#include <sstream>
namespace {
std::string buildErrorMessage (std::string const & fileName, std::string const & functionName, int lineNumber, std::string const & errorMessage)
{
std::stringstream result;
result << "Error at " << functionName << " in " << fileName << ":" << lineNumber << ": " << errorMessage;
return result.str ();
}
}
omni::core::logic_error::logic_error (std::string const & fileName, std::string const & functionName, int lineNumber, std::string const & errorMessage) :
std::logic_error (buildErrorMessage (fileName, functionName, lineNumber, errorMessage).c_str ())
{
}
| 648 |
C++
| 33.157893 | 153 | 0.691358 |
daniel-kun/omni/source/omni/core/already_exists_error.cpp
|
#include <omni/core/already_exists_error.hpp>
#include <sstream>
namespace {
std::string buildAlreadyExistsErrorMessage (omni::core::domain domain, std::string const & identifier)
{
std::stringstream result;
switch (domain) {
case omni::core::domain::function:
result << "The function \"" << identifier << "\" already exists.";
break;
default:
result << "The identifier \"" << identifier << "\" already exists.";
break;
}
return result.str ();
}
}
omni::core::already_exists_error::already_exists_error (omni::core::domain domain, std::string const & identifier) :
std::runtime_error (buildAlreadyExistsErrorMessage (domain, identifier).c_str ())
{
}
| 713 |
C++
| 28.749999 | 116 | 0.656381 |
daniel-kun/omni/source/omni/core/not_implemented_error.cpp
|
#include <omni/core/not_implemented_error.hpp>
omni::core::not_implemented_error::not_implemented_error (std::string const & fileName, std::string const & functionName, int lineNumber) :
omni::core::logic_error (functionName, fileName, lineNumber, "Function is not (fully) implemented")
{
}
| 296 |
C++
| 41.428566 | 139 | 0.746622 |
daniel-kun/omni/source/omni/core/id.cpp
|
#include <omni/core/id.hpp>
std::ostream & omni::core::operator << (std::ostream & lhs, omni::core::id const & rhs)
{
lhs << rhs.getDomain () << ":" << rhs.getId ();
return lhs;
}
/**
Initializes this id with an invalid domain and an empty string id.
**/
omni::core::id::id () :
_domain (domain::invalid),
_id ()
{
}
/**
Initializes this id for the domain `domain' and the string id `id'.
@param domain The domain for this id.
@param id The string id for this id.
**/
omni::core::id::id (omni::core::domain domain, std::string id) :
_domain (domain),
_id (id)
{
}
bool omni::core::id::operator<(id const & rhs) const
{
if (! isValid () && ! rhs.isValid ()) {
return false;
}
if (getDomain () == rhs.getDomain ()) {
return getId () < rhs.getId ();
} else {
return getDomain () < rhs.getDomain ();
}
}
bool omni::core::id::operator==(omni::core::id const & rhs) const
{
return getDomain () == rhs.getDomain () && getId () == rhs.getId ();
}
/**
Returns false if this id does not have valid domain and a valid string id.
An invalid id is created by the default constructor.
**/
bool omni::core::id::isValid () const
{
return _domain != domain::invalid;
}
/**
Returns the domain that this id is valid for.
**/
omni::core::domain omni::core::id::getDomain () const
{
return _domain;
}
/**
Returns the string id for this id.
**/
std::string omni::core::id::getId () const
{
return _id;
}
| 1,475 |
C++
| 19.788732 | 87 | 0.60339 |
daniel-kun/omni/source/omni/core/verification_failed_error.cpp
|
#include <omni/core/verification_failed_error.hpp>
#include <boost/format.hpp>
namespace {
std::string buildVerificationFailedErrorMessage (std::string moduleName, std::string verificationErrorInfo)
{
return (boost::format ("Verification of module %1% failed:\n%2%") % moduleName % verificationErrorInfo).str ();
}
}
/**
Initializes this verification_failed_error with an error message stating the verification of module with the given moduleName failed for the reasons
specified in the verificationErrorInfo.
**/
omni::core::verification_failed_error::verification_failed_error (std::string moduleName, std::string verificationErrorInfo) :
std::runtime_error (buildVerificationFailedErrorMessage (moduleName, verificationErrorInfo).c_str ())
{
}
| 773 |
C++
| 39.73684 | 148 | 0.768435 |
daniel-kun/omni/source/omni/core/parser.cpp
|
#include <omni/core/parser.hpp>
#include <omni/core/not_implemented_error.hpp>
#include <omni/core/tools/string.hpp>
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/model/variable_declaration_expression.hpp>
#include <cctype>
#include <sstream>
namespace {
const std::string startIf = "if(";
const std::string startVar = "var ";
}
/**
@brief Parses text and tries to interpret it as a statement. Since names can be ambiguous, a list of possible statements is returned.
These are the statement types that can be returned:
- if_statement
- return_statement
- while_statement
- do_while_statement
Plus all expression types. @see parseExpression()
@param scope The scope that is used to look up entity names.
@param text The text that is to parse into a statement, expression or candidates.
@result A list of possible statements that `text' could be interpreted as.
**/
omni::core::parser::StatementList omni::core::parser::parseStatement (omni::core::model::scope & scope, std::string const & text)
{
if (tools::starts_with (text, startIf)) {
return parseIfStatement (scope, text.substr (startIf.size ()));
}
auto expressions = parseExpression (scope, text);
StatementList result;
for (auto parserExpression : expressions) {
result.push_back (parser_result <omni::core::model::statement> { parserExpression.entity, parserExpression.exact });
}
return result;
}
/**
@brief Parses text as an if-statement, while text is guaranteed to start with "if(".
@param scope The scope that is used to look up entity names.
@param text The text that is to parse into an if-statement or candidates.
@return Either an empty list or a list with exactly one element that is an omni::core::model::if_statement.
**/
omni::core::parser::StatementList omni::core::parser::parseIfStatement (omni::core::model::scope & scope, std::string const & text)
{
throw not_implemented_error (__FILE__, __FUNCTION__, __LINE__);
}
/*
[ ] external_function
[ ] function
[ ] parameter
[ ] block
[ ] function_call_expression
[ ] variable_assignment_expression
[ ] binary_operator_expression
[ ] bitcast_expression
[ ] builtin_literal_expression
[ ] variable_declaration_expression
[ ] variable_expression
[ ] if_statement
[ ] return_statement
[ ] while_statement
[ ] do_while_statement
*/
omni::core::parser::ExpressionList omni::core::parser::parseExpression (omni::core::model::scope & scope, std::string const & text)
{
if (text.size () == 0u) {
return omni::core::parser::ExpressionList ();
}
if (omni::core::tools::is_numeric (text)) {
return parseBuiltinLiteral (scope, text);
}
if (tools::starts_with (text, startVar)) {
auto result = parseVariableDeclaration (scope, text);
if (result.size () > 0) {
return result;
} // else: Try to parse it as something else...
}
return omni::core::parser::ExpressionList ();
}
/**
@brief Parses text as an variable declaration expression, while text is guaranteed to start with "var ".
**/
omni::core::parser::ExpressionList omni::core::parser::parseVariableDeclaration(omni::core::model::scope & scope, std::string const & text)
{
std::string rest = text.substr (startVar.size ());
std::size_t separator = rest.find ('=');
ExpressionList initExpression;
std::string varName = rest.substr (0, separator);
if (separator != std::string::npos) {
std::string initExpressionText = rest.substr (separator + 1);
initExpression = parseExpression (scope, initExpressionText);
}
std::shared_ptr <omni::core::model::variable_declaration_expression> varDecl;
if (initExpression.size () == 1) {
varDecl = std::make_shared <omni::core::model::variable_declaration_expression> (initExpression [0].entity->getType ());
} else {
varDecl = std::make_shared <omni::core::model::variable_declaration_expression> ();
}
varDecl->setName (varName);
return ExpressionList { parser_result <omni::core::model::expression> { varDecl, false } };
}
omni::core::parser::ExpressionList omni::core::parser::parseBuiltinLiteral (omni::core::model::scope & scope, std::string const & text)
{
std::stringstream str (text);
unsigned int value; // TODO: Determine and use the type encoded in the text.
if (str >> value) {
return ExpressionList { parser_result <omni::core::model::expression> { std::make_shared <omni::core::model::builtin_literal_expression <unsigned int>> (* scope.getContext (), value), false } };
} else {
return ExpressionList ();
}
}
| 4,607 |
C++
| 37.082644 | 202 | 0.692425 |
daniel-kun/omni/source/omni/core/module_emit_options.cpp
|
#include <omni/core/module_emit_options.hpp>
omni::core::module_emit_options::module_emit_options () :
_librarySearchPaths (),
_libraries ()
{
}
omni::core::module_emit_options::~ module_emit_options ()
{
}
/**
Adds a path to the library search path that is passed on to the linker.
@see getLibrarySearchPaths()
**/
void omni::core::module_emit_options::addLibrarySearchPath (boost::filesystem::path searchPath)
{
_librarySearchPaths.push_back (searchPath);
}
/**
Returns a list of library search paths that have been previously added by calling addLibrarySearchPath().
@see addLibrarySearchPath()
**/
std::vector <boost::filesystem::path> omni::core::module_emit_options::getLibrarySearchPaths () const
{
return _librarySearchPaths;
}
/**
Adds a library that will be linked into the executable or shared object file by passing it to the linker.
@see getLibraries()
**/
void omni::core::module_emit_options::addLibrary (std::string library)
{
if (_libraries.find (library) == _libraries.end ()) {
_libraries.insert (library);
}
}
/**
Returns a set of libraries that have been previously added by calling addLibrary().
@see addLibrary().
**/
std::set <std::string> omni::core::module_emit_options::getLibraries () const
{
return _libraries;
}
| 1,284 |
C++
| 24.7 | 105 | 0.714953 |
daniel-kun/omni/source/omni/core/invalid_argument_error.cpp
|
#include <omni/core/invalid_argument_error.hpp>
#include <sstream>
namespace {
std::string buildErrorMessage (std::string const & fileName, std::string const & functionName, int lineNumber, std::string argumentName, std::string const & errorMessage)
{
std::stringstream result;
result << "Error at " << functionName << " in " << fileName << ":" << lineNumber << ": The argument \"" << argumentName << "\" has an invalid value (" << errorMessage << ")";
return result.str ();
}
}
omni::core::invalid_argument_error::invalid_argument_error (
std::string const & fileName,
std::string const & functionName,
int lineNumber,
std::string argumentName,
std::string const & errorMessage) :
std::invalid_argument (buildErrorMessage (fileName, functionName, lineNumber, argumentName, errorMessage).c_str ())
{
}
| 843 |
C++
| 32.759999 | 178 | 0.68446 |
daniel-kun/omni/source/omni/core/context.cpp
|
#include <omni/core/context.hpp>
#include <omni/core/model/type.hpp>
#include <llvm/IR/LLVMContext.h>
omni::core::context::context () :
_llvmContext (new llvm::LLVMContext ()),
_sharedBasicTypes (),
_modules ()
{
}
/**
A destructor must be explicitly defined, because llvm::LLVMContext is an incomplete type to users of omni/core/context.hpp. Without an explicit
dtor, the compiler will try to generate a dtor in whichever place omni::core::context is used. In those places, most likely llvm::LLVMContext is an
incomplete type (because it is only forward-declared) and hence it leads to a compiler error.
So even if this dtor is non-virtual an empty, don't remove it.
**/
omni::core::context::~ context()
{
}
/**
Returns a shared_ptr for a instance of type for the desired context and type_class.
Short-hand for creating a type with new type (*this, typeClass, indirectionLevel); with the additional benefit that types are cached in this context.
@param typeClass The type class of the desired type. @see type_class
@param indirectionLevel The level of pointer-indirection. This is only for internal usage and for representing types imported from external C code.
The Omni Language itself does not use types with an indiretionLevel > 0. Instead, "optionals" and "references" are used.
@return A shared instance of type with the specified typeClass and indirectionLevel.
@see type::sharedBasicType(context&, type_class);
**/
std::shared_ptr <omni::core::model::type> omni::core::context::sharedBasicType (model::type_class typeClass, int indirectionLevel) const
{
auto typePair = std::make_pair (typeClass, indirectionLevel);
std::map <std::pair <model::type_class, int>, std::shared_ptr <model::type>>::const_iterator result = _sharedBasicTypes.find (typePair);
if (result == _sharedBasicTypes.cend ()) {
auto * unconst = const_cast <context *> (this);
std::shared_ptr <model::type> resultType (new model::type (* unconst, typeClass, indirectionLevel));
unconst->_sharedBasicTypes [typePair] = resultType;
return resultType;
}
return result->second;
}
const llvm::LLVMContext & omni::core::context::llvmContext () const
{
return * _llvmContext;
}
llvm::LLVMContext & omni::core::context::llvmContext ()
{
return * _llvmContext;
}
| 2,310 |
C++
| 41.018181 | 149 | 0.728571 |
daniel-kun/omni/source/omni/core/model/entity.cpp
|
#include <omni/core/model/entity.hpp>
#include <omni/core/model/scope.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/context.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info entityMetaInfo;
}
/**
@brief Initializes this entity with an empty name and an invalid id.
The id will be set as soon as this entity is added to a context.
**/
omni::core::model::entity::entity () :
_parent (),
_name (),
_id (),
_components (),
_changedSignal ()
{
}
/**
@brief Initializes this entity with the given name.
The id will be set as soon as this entity is added to a context.
@param name The name for this entity.
@see getName
**/
omni::core::model::entity::entity (std::string const & name) :
_parent (),
_name (name),
_id (),
_components (),
_changedSignal ()
{
}
/**
@brief Initializes this entity within the given parent and with the given id and name.
@see getName
@see getId
**/
omni::core::model::entity::entity (omni::core::id entityId, std::string const & name) :
_parent (),
_name (name),
_id (entityId),
_components (),
_changedSignal ()
{
}
omni::core::model::entity::~entity ()
{
clearComponents ();
}
/**
@brief Returns the base meta-information for entity objects.
The meta-information of the root `entity' class that is the base for all entities in the omni code model can be used to get information
that is valid for all entities, or to represent "any" kind of entity.
@return Base meta-information for entity objects.
**/
omni::core::model::meta_info & omni::core::model::entity::getStaticMetaInfo ()
{
return omniMetaImpl::entityMetaInfo;
}
/**
@brief Returns the meta-information for the actual kind of entity that this object has.
@return The meta-information for the actual kind of entity that this object has.
**/
omni::core::model::meta_info & omni::core::model::entity::getMetaInfo () const
{
return getStaticMetaInfo ();
}
/**
@brief Sets a new id for this entity.
This function should usually never be called directly. A new id is automatically assigned as soon as this entity becomes part of a module (see getModule()).
Relations throughout this context are not affected by changing an id.
However, changing the id will affect external resources that are relating to this entity.
For example, if another Omni project is calling a function from this context, the call can no longer be resolved when the function's id is changed.
For all public entities, the id should never be changed in it's whole lifetime.
The id's main purpose is to maintain relations while serializing or deserializing the model.
@param newId The new id that will be assigned to this entity.
@see getId
**/
void omni::core::model::entity::setId (omni::core::id newId)
{
_id = newId;
}
/**
@brief Returns the unique id of this entity.
@return The current id of this entity.
@see setId
**/
omni::core::id omni::core::model::entity::getId () const
{
return _id;
}
/**
@brief Returns the domain of this entity.
The domain is fixed for every class and does not change at runtime.
<b>Important:</b> This function is reimplemented by every non-abstract class that directly or indirectly derives from entity.
This means that every class that derives from entity that can be instantiated returns a different value for getDomain that corresponds to that specific class.
@return The domain of this entity.
**/
omni::core::domain omni::core::model::entity::getDomain () const
{
return domain::invalid;
}
/**
@brief Changes the name of this entity.
@see getName
**/
void omni::core::model::entity::setName (const std::string & name)
{
_name = name;
}
/**
@brief Returns the name of this entity.
The name does not need to be unique in a given scope - however, it should be, to be able to distinguish two different entities with the same name.
@return The current name of this entity.
@see setName
@see getId
**/
std::string omni::core::model::entity::getName () const
{
return _name;
}
/**
@brief Changes the parent of this entity to the given parent.
When this entity does not have an id, yet, and the new parent is already added to a module, this entity and all components
that do not already have an id will be assigned a newly created id each.
setParent() should never be called explicitly - the parent is automatically changed as soon as this entity
becomes a component of another entity.
@see getParent
**/
void omni::core::model::entity::setParent (entity * parent)
{
_parent = parent;
module * mod = getModule ();
if (mod != nullptr) {
updateIds ();
}
}
/**
@brief Returns the parent of this entity.
If this entity is part of a scope, that scope is returned. If this entity was not added to another entity, yet, nullptr is returned.
The return value of getParent can change when setParent is called. This usually happens when this entity is added as a component of another entity.
The returned parent can be modified.
@return The current parent of this entity. Can be nullptr.
@see setParent
**/
omni::core::model::entity * omni::core::model::entity::getParent ()
{
return _parent;
}
/**
@brief Returns the parent of this entity.
If this entity is part of a scope, that scope is returned. If this entity was not added to another entity, yet, nullptr is returned.
The return value of getParent can change when setParent is called. This usually happens when this entity is added as a component of another entity.
The returned parent is const and can not be modified.
@return The current parent of this entity. Can be nullptr.
@see setParent
**/
const omni::core::model::entity * omni::core::model::entity::getParent () const
{
return _parent;
}
/**
@brief Returns the module that this entity resides in.
This entiy's module is equivalent the parent's module. If this entity is not part of a parent-hierarchy that in turn has been added to
a module, this entity itself is not part of a module and nullptr is returned.
The return value of getModule can change when setParent is called. This usually happens when this entity is added as a component of another entity.
The returned module can be modified.
@return The module that this entity resides in. Can be nullptr.
**/
omni::core::model::module * omni::core::model::entity::getModule ()
{
if (getParent () != nullptr) {
return getParent ()->getModule ();
} else {
return nullptr;
}
}
/**
@brief Returns the module that this entity resides in.
This entiy's module is equivalent the parent's module. If this entity is not part of a parent-hierarchy that in turn has been added to
a module, this entity itself is not part of a module and nullptr is returned.
The return value of getModule can change when setParent is called. This usually happens when this entity is added as a component of another entity.
The returned module is const and can not be modified.
@return The module that this entity resides in. Can be nullptr.
**/
const omni::core::model::module * omni::core::model::entity::getModule () const
{
if (getParent () != nullptr) {
return getParent ()->getModule ();
} else {
return nullptr;
}
}
/**
@brief Returns the context that this entity resides in.
This entiy's context is equivalent the module's context. If this entity is not part of a module, it is not part of a context, either.
The return value of getContext can change when setParent is called. This usually happens when this entity is added as a component of another entity.
The returned context can be modified.
@return The context that this entity resides in. Can be nullptr.
**/
omni::core::context * omni::core::model::entity::getContext ()
{
module * mod = getModule ();
if (mod != nullptr) {
return mod->getContext ();
} else {
return nullptr;
}
}
/**
@brief Returns the context that this entity resides in.
This entiy's context is equivalent the module's context. If this entity is not part of a module, it is not part of a context, either.
The return value of getContext can change when setParent is called. This usually happens when this entity is added as a component of another entity.
The returned context can be modified.
@return The context that this entity resides in. Can be nullptr.
**/
const omni::core::context * omni::core::model::entity::getContext () const
{
module const * mod = getModule ();
if (mod != nullptr) {
return mod->getContext ();
} else {
return nullptr;
}
}
/**
@brief Adds or overwrites a component for the given domain and the given name.
For an explanation of what a component is, @see getComponents()
Adds `entity' as a component for the given domain and with the given name. When adding an entity as a component, that entity's parent is set to this entity.
If such a component already exists, it is overwritten and it's parent is set to nullptr.
If entity is nullptr, instead of adding a new component, the given component is removed, if it exists.
In other termns, calling setComponent (someDomain, someName, nullptr) has the same meaning as removeComponent (someDomain, someName).
Note that a component's name has nothing to do with an entity's name that can be retrieved by getName().
@param domain The domain that the component should be stored in.
@param name The name that the component should be stored as.
@param entity The entity that should be stored as a component of this entity.
**/
void omni::core::model::entity::setComponent (omni::core::domain domain, std::string name, std::shared_ptr <entity> entity)
{
if (! entity) {
removeComponent (domain, name);
} else {
auto it = _components [domain].find (name);
// If a component with this name exists, the new entity will overwrite it. Hence the old entity is not a component of this entity anymore,
// which in turn means that this entity is not it's parent anymore:
if (it != _components [domain].end ()) {
it->second->setParent (nullptr);
}
_components [domain] [name] = entity;
entity->setParent (this);
}
}
/**
@brief Returns a list of all components of this entity.
A component is a part of an entity, and all components together are used to build up an entity.
There are some entities that have components and others that don't. For example, the variable_expression does not have a component, while the variable_declaration_expression
has the initialization expression as a component. While variable_expression *references* a variable_declaration_expression, the variable_declaration_expression is not part of
the variable_expression and therefore is not a component of it.
This entity is the parent of all of it's components. It's a direct parent-child-relationship.
The returned list of components is const, so that the list and the contained components can not be modified.
@return A list of all components of this entity.
**/
const omni::core::model::entity::domain_to_name_to_entities_map & omni::core::model::entity::getComponents () const
{
return _components;
}
/**
@brief Returns a list of all components of this entity.
A component is a part of an entity, and all components together are used to build up an entity.
There are some entities that have components and others that don't. For example, the variable_expression does not have a component, while the variable_declaration_expression
has the initialization expression as a component. While variable_expression *references* a variable_declaration_expression, the variable_declaration_expression is not part of
the variable_expression and therefore is not a component of it.
This entity is the parent of all of it's components. It's a direct parent-child-relationship.
The returned list of components is a copy of the component list, so that the component list of this entity can not be modified, but the contained components can be modified.
@return A list of all components of this entity.
**/
omni::core::model::entity::domain_to_name_to_entities_map omni::core::model::entity::getComponents ()
{
return _components;
}
/**
@brief Returns a list of components for the given domain.
For an explanation of what a component is, @see getComponents()
Which domains are used to store the components depends on the actual entity, see the respective documentation of the actual entity's class.
The returned list is const, so that the list and the contained components can not be modified.
@param domain The domain that the components are stored in.
@return A list of components for the given domain.
@see getDomain()
**/
const omni::core::model::entity::name_to_entities_map omni::core::model::entity::getComponents (omni::core::domain domain) const
{
auto it = _components.find (domain);
if (it != _components.end ()) {
return it->second;
} else {
return omni::core::model::entity::name_to_entities_map ();
}
}
/**
@brief Returns a list of components for the given domain.
For an explanation of what a component is, @see getComponents()
Which domains are used to store the components depends on the actual entity, see the respective documentation of the actual entity's class.
The returned list is a copy and can be modified, and the contained components can be modified, too.
@param domain The domain that the components are stored in.
@return A list of components for the given domain.
@see getDomain()
**/
omni::core::model::entity::name_to_entities_map omni::core::model::entity::getComponents (omni::core::domain domain)
{
return _components [domain];
}
/**
@brief Returns the component that is stored for the given domain with the given name.
For an explanation of what a component is, @see getComponents()
Which domains and names are used to store the components depends on the actual entity, see the respective documentation of the actual entity's class.
Note that a component's name has nothing to do with an entity's name that can be retrieved by getName().
@param domain The domain that the component is stored in.
@param name The name that the component is stored as.
@return The component that is stored for the given domain with the given name. Returns nullptr if the component does not exist.
**/
std::shared_ptr <omni::core::model::entity> omni::core::model::entity::getComponent (omni::core::domain domain, std::string name) const
{
auto c = _components.find (domain);
if (c != _components.end ()) {
auto it = c->second.find (name);
if (it != c->second.end ()) {
return it->second;
}
}
return std::shared_ptr <entity> ();
}
/**
@brief Returns a list of components for the given domain whose names start with the given prefix.
For an explanation of what a component is, @see getComponents()
This function can be used when an entity contains a list of components with the same meaning, such as a function contains a list of parameters.
All parameters start with the same name, so a list of parameters can be retrieved by calling getComponentsStartingWith(omni::core::domain::parameter, "parameter").
@param domain The domain that the components are stored in.
@param prefix The prefix that the names of the components start with.
@return A list that maps the component's name to the stored entity.
**/
std::map <std::string, std::shared_ptr <omni::core::model::entity>> omni::core::model::entity::getComponentsStartingWith (omni::core::domain domain, std::string prefix) const
{
std::map <std::string, std::shared_ptr <omni::core::model::entity>> result;
auto c = _components.find (domain);
if (c != _components.end ()) {
for (auto i : c->second) {
if (i.first.find (prefix) == 0) {
result [i.first] = i.second;
}
}
}
return result;
}
/**
@brief Returns the entity with the given id, if it was found in this entity's list of components, or nullptr, if not.
The entity is looked up in each domain, since entities can be stored in component-lists for domains that do not match the entity's domain.
@param id The id of the entity that should be returned. This should not be an invalid id.
@return The entity with the id, if such has been added to the context. A null-shared_ptr is returned, if no such entity exists in this scope.
**/
std::shared_ptr <omni::core::model::entity> omni::core::model::entity::lookupComponentById (omni::core::id id)
{
for (auto c : _components) {
name_to_entities_map & m = c.second;
auto found = std::find_if (m.begin (), m.end (), [id] (std::pair <std::string, std::shared_ptr <entity>> f) -> bool {
return f.second->getId () == id;
});
if (found != m.end ()) {
return found->second;
}
}
return std::shared_ptr <entity> ();
}
/**
@brief Removes the given component.
For an explanation of what a component is, @see getComponents()
Removes an entity from the list of components of the given domain, if it exists.
If the entity does not exist, this call has no effect and returns false.
Note that removing components can make an entity being invalid, because one or more components might be mandatory.
@param domain The domain that the entity that should be removed is stored in.
@param component The entity that should be removed from the list of components for the given domain.
@return Returns true if such a component existed and was removed. Returns false if no such component exists.
**/
bool omni::core::model::entity::removeComponent (omni::core::domain domain, std::shared_ptr <entity> component)
{
auto & domainComponents = _components [domain];
auto it = std::find_if (
domainComponents.begin (),
domainComponents.end (),
[component] (std::pair <std::string, std::shared_ptr <entity>> item) -> bool {
return item.second == component;
});
if (it != domainComponents.end ()) {
it->second->setParent (nullptr);
domainComponents.erase (it);
return true;
} else {
return false;
}
}
/**
@brief Removes the given component.
For an explanation of what a component is, @see getComponents()
Removes an entity from the list of components of the given domain with the given name.
If the entity does not exist, this call has no effect and returns false.
Note that removing components can make an entity being invalid, because one or more components might be mandatory.
@param domain The domain that the entity that should be removed is stored in.
@param name The full name of the component that should be removed.
@return Returns true if such a component existed and was removed. Returns false if no such component exists.
**/
bool omni::core::model::entity::removeComponent (omni::core::domain domain, std::string name)
{
auto & domainComponents = _components [domain];
auto it = domainComponents.find (name);
if (it != domainComponents.end ()) {
it->second->setParent (nullptr);
domainComponents.erase (it);
return true;
} else {
return false;
}
}
/**
@brief Removes all components stored in the given domain from this entity.
For an explanation of what a component is, @see getComponents()
Clears the list of components for the given domain, so that getComponent(domain) will return an empty list.
Note that removing components can make an entity being invalid, because one or more components might be mandatory.
@param domain All components stored for this domain in this entity will be removed.
**/
void omni::core::model::entity::clearComponents (omni::core::domain domain)
{
for (auto i : _components [domain]) {
i.second->setParent (nullptr);
}
_components [domain].clear ();
}
/**
@brief Removes all components from this entity.
For an explanation of what a component is, @see getComponents()
Clears the list of components for this entity for all domains.
Note that removing components can make an entity being invalid, because one or more components might be mandatory.
**/
void omni::core::model::entity::clearComponents ()
{
for (auto i : _components) {
for (auto j : i.second) {
j.second->setParent (nullptr);
}
}
_components.clear ();
}
/**
Can be overridden by specific entities.
Overrides can add entries to 'libraries'. These entries will be added to the linker when @see context::emitSharedLibraryFile is used to create
a shared library file.
@param libraries A list of libraries that will be included when linking the module of this entity. If the same library is added by multiple entities,
the library will only be linked once.
**/
void omni::core::model::entity::fillLibraries (std::set <std::string> & libraries)
{
}
/**
@brief Connects a handler to the Changed signal that is emitted after a change has been made to this entity.
Each kind of entity has other "changes" that can happen. Refer to the specific class for a list of possible changes that emit the Changed signal.
@param handler The handler that will be called after something within this entity changed.
@return A signal connection that can be used disconnect this handler.
**/
boost::signals2::connection omni::core::model::entity::connectChanged (ChangedSignal::slot_type handler)
{
return _changedSignal.connect (handler);
}
/**
@brief Emits the signal Changed.
When overriding this function, make sure to call the base class implementation. Otherwise, all other functionality that depends on the Changed signal will break.
**/
void omni::core::model::entity::changed ()
{
_changedSignal (* this);
}
/**
Recursively sets the ids of all components their components that do not have an id, yet.
Only call this function when getModule () does not return nullptr!
**/
void omni::core::model::entity::updateIds ()
{
// Set ids for components that do not already have an id:
module * mod = getModule ();
if (! getId ().isValid ()) {
setId (mod->createId (getDomain ()));
}
for (auto d : getComponents ()) {
for (auto c : d.second) {
if (! c.second->getId ().isValid ()) {
c.second->updateIds ();
}
}
}
}
| 22,263 |
C++
| 35.498361 | 174 | 0.717154 |
daniel-kun/omni/source/omni/core/model/pure_expression.cpp
|
#include <omni/core/model/pure_expression.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info pure_expressionMetaInfo;
}
omni::core::model::pure_expression::pure_expression () :
expression ()
{
}
omni::core::model::meta_info & omni::core::model::pure_expression::getStaticMetaInfo ()
{
return omniMetaImpl::pure_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::pure_expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
| 526 |
C++
| 22.954544 | 87 | 0.724335 |
daniel-kun/omni/source/omni/core/model/type.cpp
|
#include <omni/core/model/type.hpp>
#include <omni/core/context.hpp>
#include <omni/core/not_implemented_error.hpp>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/LLVMContext.h>
#include <sstream>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info typeMetaInfo;
}
namespace {
/*
Returns the type that points to baseType with the given indirectionLevel. For example, if baseType is int32 and indirectionLevel is 1,
the result is int32*. If indirection is 2, the result is int32** and if indirection is 0, the result is int32.
*/
llvm::Type * addIndirection (llvm::Type * baseType, unsigned int indirectionLevel)
{
llvm::Type * result = baseType;
for (unsigned i = 0; i < indirectionLevel; ++ i) {
result = result->getPointerTo ();
}
return result;
}
} // anonymous namespace
/**
@brief Initializes this type with the given type_class and indirectionLevel.
Neither the typeClass, nor the indirectionLevel can be changed later. If you need a type with a different typeClass or indirectionLevel,
use another call to sharedBasicType for built-in types.
<b>Important:</b> You should always use sharedBasicType instead of instantiating your own type object.
@param context The context that this type is used in.
@param typeClass The type class of the desired type. @see type_class
@param indirectionLevel The level of pointer-indirection. This is only for internal usage and for representing types imported from external C code.
The Omni Language itself does not use types with an indiretionLevel > 0. Instead, "optionals" and "references" are used. (Not yet implemented.)
**/
omni::core::model::type::type (omni::core::context & context, omni::core::model::type_class typeClass, unsigned int indirectionLevel) :
entity (),
_context (context),
_typeClass (typeClass),
_indirectionLevel (indirectionLevel)
{
std::stringstream typeName;
typeName << typeClass;
setName (typeName.str ());
}
omni::core::model::type::~ type ()
{
}
omni::core::model::meta_info & omni::core::model::type::getStaticMetaInfo ()
{
return omniMetaImpl::typeMetaInfo;
}
omni::core::model::meta_info & omni::core::model::type::getMetaInfo () const
{
return getStaticMetaInfo ();
}
/**
Returns a human-readable text that represents this type.
@param fullyQualified Specifies, whether the type should be returned fully qualified, or in canonical form. The exact meaning of this depends on the actualy type.
@return A human-readable text that represents this type.
**/
std::string omni::core::model::type::toString (bool fullyQualified)
{
return toString (_typeClass, fullyQualified);
}
/**
Returns a human-readable text that represents `typeClass'. Only suitable for built-in types (no classes, no enums).
@param typeClass The type-class that will be converted to text.
@param fullyQualified Specifies, whether the type should be returned fully qualified, or in canonical form. The exact meaning of this depends on the actualy type.
@return A human-readable text that represents `typeClass'.
**/
std::string omni::core::model::type::toString (type_class typeClass, bool fullyQualified)
{
switch (typeClass) {
case type_class::t_void:
return "void";
case type_class::t_boolean:
return "boolean";
case type_class::t_unsignedByte:
return "unsigned byte";
case type_class::t_signedByte:
return "signed byte";
case type_class::t_unsignedShort:
return "unsigned short";
case type_class::t_signedShort:
return "signed short";
case type_class::t_unsignedInt:
return "unsigned int";
case type_class::t_signedInt:
return "signed int";
case type_class::t_unsignedLong:
return "unsigned long";
case type_class::t_signedLong:
return "signed long";
case type_class::t_unsignedLongLong:
return "unsigned long long";
case type_class::t_signedLongLong:
return "signed long long";
case type_class::t_char:
return "character";
default:
throw not_implemented_error (__FILE__, __FUNCTION__, __LINE__);
}
}
omni::core::domain omni::core::model::type::getDomain () const
{
return domain::type;
}
omni::core::context * omni::core::model::type::getContext ()
{
return & _context;
}
const omni::core::context * omni::core::model::type::getContext () const
{
return & _context;
}
omni::core::model::module * omni::core::model::type::getModule ()
{
return nullptr;
}
const omni::core::model::module * omni::core::model::type::getModule () const
{
return nullptr;
}
void omni::core::model::type::setComponent (omni::core::domain domain, std::string name, std::shared_ptr <omni::core::model::entity> entity)
{
// At this time, a type does not contain components.
}
/**
@rief Returns the type_class of this type.
@return The type_class of this type.
@see type_class
**/
omni::core::model::type_class omni::core::model::type::getTypeClass () const
{
return _typeClass;
}
/**
@brief Returns the pointer indirection-level of this type.
E.g. when the type_class is t_signedInt and the indirectionLevel is 2, the underlying C-type would be "int**".
@return The pointer indirection-level of this type.
**/
unsigned int omni::core::model::type::getIndirectionLevel () const
{
return _indirectionLevel;
}
/**
@brief Returns a shared_ptr for a instance of type for the desired context and type_class.
Short-hand for creating a type with new type(context, typeClass, indirectionLevel); with the additional benefit that types are cached in the context.
You should always use sharedBasicType instead of instantiating your own type object.
@param context The context that this type is used in.
@param typeClass The type class of the desired type. @see type_class
@param indirectionLevel The level of pointer-indirection. This is only for internal usage and for representing types imported from external C code.
The Omni Language itself does not use types with an indiretionLevel > 0. Instead, "optionals" and "references" are used. (Not yet implemented.)
@see context::sharedBasicType(type_class);
**/
std::shared_ptr <omni::core::model::type> omni::core::model::type::sharedBasicType (context & context, type_class typeClass, unsigned int indirectionLevel)
{
return context.sharedBasicType (typeClass, indirectionLevel);
}
/*
Returns an llvm::Type that corresponds to this Omni type. For built-in types, these directly map to i1, i8, i16, i32, and so on.
A pointer-asterisk is added per indirectionLevel. (E.g. type_class t_signedInt with indirectionLevel 2 becomes an i32** on x86).
*/
llvm::Type * omni::core::model::type::llvmType ()
{
switch (_typeClass) {
case type_class::t_void:
return addIndirection (llvm::Type::getVoidTy (getContext ()->llvmContext ()), getIndirectionLevel ());
break;
case type_class::t_boolean:
return addIndirection (llvm::Type::getInt1Ty (getContext ()->llvmContext ()), getIndirectionLevel ());
break;
case type_class::t_char:
case type_class::t_unsignedByte:
case type_class::t_signedByte:
return addIndirection (llvm::Type::getInt8Ty (getContext ()->llvmContext ()), getIndirectionLevel ());
break;
case type_class::t_unsignedShort:
case type_class::t_signedShort:
return addIndirection (llvm::Type::getInt16Ty (getContext ()->llvmContext ()), getIndirectionLevel ());
break;
case type_class::t_unsignedLong:
case type_class::t_signedLong:
#ifdef ENVIRONMENT64
return addIndirection (llvm::Type::getInt64Ty (getContext ()->llvmContext ()), getIndirectionLevel ());
#endif
case type_class::t_unsignedInt:
case type_class::t_signedInt:
return addIndirection (llvm::Type::getInt32Ty (getContext ()->llvmContext ()), getIndirectionLevel ());
break;
case type_class::t_unsignedLongLong:
case type_class::t_signedLongLong:
return addIndirection (llvm::Type::getInt64Ty (getContext ()->llvmContext ()), getIndirectionLevel ());
break;
default:
throw not_implemented_error (__FILE__, __FUNCTION__, __LINE__);
}
}
| 8,192 |
C++
| 35.413333 | 162 | 0.709717 |
daniel-kun/omni/source/omni/core/model/meta_info.cpp
|
#include <omni/core/model/meta_info.hpp>
/**
@brief Initializes this meta_info as a root entity type with the given `name'.
@param name The name of the entity type that this meta-info belong to.
**/
omni::core::model::meta_info::meta_info (const std::string & name) :
_parent (nullptr),
_name (name),
_children (),
_extensions ()
{
}
/**
@brief Initializes this meta_info as a child entity type of `parent' with the given `name'.
@param parent The parent entity type which the entity type this meta-info belongs to implements or extends.
@param name The name of the entity type that this meta-info belong to.
**/
omni::core::model::meta_info::meta_info (const meta_info & parent, const std::string & name) :
_parent (const_cast <meta_info *> (& parent)),
_name (name),
_children (),
_extensions ()
{
_parent->_children.push_back (this);
}
/**
@brief Returns true when the entity type of this meta_info is abstract and is solely a base class for other entity types.
This is identical to checking whether getChildCount() returns > 0u.
@return True, when the entity type of this meta_info is abstract and is solely a base class for other entity types.
**/
bool omni::core::model::meta_info::isAbstract () const
{
return getChildCount () > 0u;
}
/**
@brief Returns the name of the entity-type that this meta-info belongs to.
@return The name of the entity-type that this meta-info belongs to.
**/
const std::string & omni::core::model::meta_info::getName () const
{
return _name;
}
/**
@brief Returns the parent of this entity-type, if any. (e.g. "expression" is the parent of "modifying_expression".)
@return The parent of the entity-type.
**/
const omni::core::model::meta_info * omni::core::model::meta_info::getParent () const
{
return _parent;
}
/**
@brief Returns the child at index `index'.
@param index The index of the child that is to be retrieved. Needs to be less than getChildCount ().
@return The child at index `index'.
@exceptions Throws std::out_of_range if index is >= getChildCount().
**/
const omni::core::model::meta_info & omni::core::model::meta_info::getChildAt (std::size_t index) const
{
return * _children.at (index);
}
/**
@brief Returns the number of children of this meta-info.
Children are added to this meta_info by making new meta_info objects and pass this object as it's "parent" parameter to the ctor.
@return The number of children of this meta-info.
**/
std::size_t omni::core::model::meta_info::getChildCount () const
{
return _children.size ();
}
/**
@brief Returns the extension property with the name extensionName.
@param extensionName The name of the extension property that should be retrieved.
@return The extension property with the name extensionName, if such an extension has been added before. Returns nullptr, if no such extension is registered via setExtension.
**/
const omni::core::model::meta_info_extension * omni::core::model::meta_info::getExtension (const std::string & extensionName) const
{
auto it = _extensions.find (extensionName);
if (it == _extensions.end ()) {
return nullptr;
} else {
return it->second.get ();
}
}
/**
@brief Sets a new extension property or overwrites an existing with the given extensionName.
@param extensionName The name of the extension property that should be added or overwritten.
@param extension The extension object that should be registered by the given name.
**/
void omni::core::model::meta_info::setExtension (const std::string & extensionName, std::shared_ptr <meta_info_extension> extension)
{
_extensions [extensionName] = extension;
}
// Initialization of all meta_info objects:
// (This has to be done in a central translation unit, because initialization order is undefined across translation units.)
namespace omniMetaImpl {
omni::core::model::meta_info entityMetaInfo ("entity");
omni::core::model::meta_info typeMetaInfo (entityMetaInfo, "type");
omni::core::model::meta_info scopeMetaInfo (entityMetaInfo, "scope");
omni::core::model::meta_info function_prototypeMetaInfo (scopeMetaInfo, "function_prototype");
omni::core::model::meta_info external_functionMetaInfo (function_prototypeMetaInfo, "external_function");
omni::core::model::meta_info functionMetaInfo (function_prototypeMetaInfo, "function");
omni::core::model::meta_info moduleMetaInfo (scopeMetaInfo, "module");
omni::core::model::meta_info parameterMetaInfo (scopeMetaInfo, "parameter");
omni::core::model::meta_info statementMetaInfo (scopeMetaInfo, "statement");
omni::core::model::meta_info blockMetaInfo (statementMetaInfo, "block");
omni::core::model::meta_info expressionMetaInfo (statementMetaInfo, "expression");
omni::core::model::meta_info modifying_expressionMetaInfo (expressionMetaInfo, "modifying_expression");
omni::core::model::meta_info function_call_expressionMetaInfo (modifying_expressionMetaInfo, "function_call_expression");
omni::core::model::meta_info variable_assignment_expressionMetaInfo (modifying_expressionMetaInfo, "variable_assignment_expression");
omni::core::model::meta_info pure_expressionMetaInfo (expressionMetaInfo, "pure_expression");
omni::core::model::meta_info binary_operator_expressionMetaInfo (pure_expressionMetaInfo, "binary_operator_expression");
omni::core::model::meta_info cast_expressionMetaInfo (pure_expressionMetaInfo, "cast_expression");
omni::core::model::meta_info bitcast_expressionMetaInfo (cast_expressionMetaInfo, "bitcast_expression");
omni::core::model::meta_info literal_expressionMetaInfo (pure_expressionMetaInfo, "literal_expression");
omni::core::model::meta_info builtin_literal_expressionMetaInfo (literal_expressionMetaInfo, "builtin_literal_expression");
omni::core::model::meta_info variable_declaration_expressionMetaInfo (pure_expressionMetaInfo, "variable_declaration_expression");
omni::core::model::meta_info variable_expressionMetaInfo (pure_expressionMetaInfo, "variable_expression");
omni::core::model::meta_info if_statementMetaInfo (statementMetaInfo, "if_statement");
omni::core::model::meta_info return_statementMetaInfo (statementMetaInfo, "return_statement");
omni::core::model::meta_info while_statementMetaInfo (statementMetaInfo, "while_statement");
omni::core::model::meta_info do_while_statementMetaInfo (statementMetaInfo, "do_while_statement");
}
| 6,673 |
C++
| 48.80597 | 173 | 0.709576 |
daniel-kun/omni/source/omni/core/model/binary_operator_expression.cpp
|
#include <omni/core/model/binary_operator_expression.hpp>
#include <omni/core/context.hpp>
#include <omni/core/not_implemented_error.hpp>
#include <omni/core/model/type_mismatch_error.hpp>
#include <omni/core/model/type.hpp>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/NoFolder.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info binary_operator_expressionMetaInfo;
}
/**
Initializes this binary_operator_expression with the binary_operation op and the leftOperand and rightOperand.
@param op The operation that is to be performed with leftOperand and rightOperand. E.g. in "5 - 7", this is "-" or binary_operation::binary_minus_operation.
@param leftOperand The left operand of this operation. E.g. in "5 + 7", this is "5".
@param rightOperand The right operand of this operation. E.g. in "5 / 7", this is "7".
**/
omni::core::model::binary_operator_expression::binary_operator_expression (
omni::core::context & context,
binary_operation op,
std::shared_ptr <expression> leftOperand,
std::shared_ptr <expression> rightOperand) :
pure_expression (),
_type (),
_operator (op)
{
setLeftOperand (leftOperand);
setRightOperand (rightOperand);
if (leftOperand->getType () != rightOperand->getType ()) {
throw type_mismatch_error (* leftOperand->getType (), * rightOperand->getType ());
}
switch (_operator) {
case binary_operation::binary_lessthan_operation:
_type = context.sharedBasicType (type_class::t_boolean);
break;
case binary_operation::binary_minus_operation:
case binary_operation::binary_plus_operation:
_type = leftOperand->getType ();
break;
default:
throw not_implemented_error (__FILE__, __FUNCTION__, __LINE__);
}
}
omni::core::model::meta_info & omni::core::model::binary_operator_expression::getStaticMetaInfo ()
{
return omniMetaImpl::binary_operator_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::binary_operator_expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::binary_operator_expression::getDomain () const
{
return domain::binary_operator_expression;
}
void omni::core::model::binary_operator_expression::setLeftOperand (std::shared_ptr <omni::core::model::expression> leftOperand)
{
setComponent (domain::expression, "leftOperand", leftOperand);
}
std::shared_ptr <omni::core::model::expression> omni::core::model::binary_operator_expression::getLeftOperand () const
{
return getComponentAs <expression> (domain::expression, "leftOperand");
}
void omni::core::model::binary_operator_expression::setRightOperand (std::shared_ptr <omni::core::model::expression> rightOperand)
{
setComponent (domain::expression, "rightOperand", rightOperand);
}
std::shared_ptr <omni::core::model::expression> omni::core::model::binary_operator_expression::getRightOperand () const
{
return getComponentAs <expression> (domain::expression, "rightOperand");
}
/**
Returns the type of this binary_operator_expression. The type is deduced from the left and right operands.
**/
std::shared_ptr <omni::core::model::type> omni::core::model::binary_operator_expression::getType () const
{
return _type;
}
/**
@internal
**/
omni::core::statement_emit_result omni::core::model::binary_operator_expression::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
std::shared_ptr <expression> leftOperand = getLeftOperand ();
llvm::Value * lhs = leftOperand->llvmEmit (llvmBasicBlock).getValue ();
llvm::Value * rhs = getRightOperand ()->llvmEmit (llvmBasicBlock).getValue ();
switch (_operator) {
case binary_operation::binary_lessthan_operation:
switch (leftOperand->getType ()->getTypeClass ()) {
case type_class::t_signedInt:
return statement_emit_result (llvmBasicBlock, builder.CreateICmp (llvm::CmpInst::ICMP_SLT, lhs, rhs));
default:
throw not_implemented_error (__FILE__, __FUNCTION__, __LINE__);
}
case binary_operation::binary_plus_operation:
return statement_emit_result (llvmBasicBlock, builder.CreateBinOp (llvm::Instruction::BinaryOps::Add, lhs, rhs));
case binary_operation::binary_minus_operation:
return statement_emit_result (llvmBasicBlock, builder.CreateBinOp (llvm::Instruction::BinaryOps::Sub, lhs, rhs));
default:
throw not_implemented_error (__FILE__, __FUNCTION__, __LINE__);
}
}
| 4,574 |
C++
| 37.771186 | 156 | 0.705072 |
daniel-kun/omni/source/omni/core/model/use_before_declaration_error.cpp
|
#include <omni/core/model/use_before_declaration_error.hpp>
#include <sstream>
namespace {
std::string buildUseBeforeDeclarationErrorMessage (omni::core::domain domain, std::string const & identifier)
{
std::stringstream result;
switch (domain) {
case omni::core::domain::variable_expression:
result << "Variable " << identifier << " was used, before it was declared.";
break;
default:
result << "Entity" << identifier << " was used, before it was declared.";
}
return result.str ();
}
}
omni::core::model::use_before_declaration_error::use_before_declaration_error (domain domain, std::string const & identifier) :
std::runtime_error (buildUseBeforeDeclarationErrorMessage (domain, identifier))
{
}
| 756 |
C++
| 29.279999 | 127 | 0.690476 |
daniel-kun/omni/source/omni/core/model/type_class.cpp
|
#include <omni/core/model/type_class.hpp>
#include <omni/core/not_implemented_error.hpp>
std::ostream & omni::core::model::operator << (std::ostream & lhs, const omni::core::model::type_class rhs)
{
using namespace omni::core::model;
switch (rhs) {
case type_class::t_void:
lhs << "t_void";
break;
case type_class::t_boolean:
lhs << "t_boolean";
break;
case type_class::t_unsignedByte:
lhs << "t_unsignedByte";
break;
case type_class::t_signedByte:
lhs << "t_signedByte";
break;
case type_class::t_unsignedShort:
lhs << "t_unsignedShort";
break;
case type_class::t_signedShort:
lhs << "t_signedShort";
break;
case type_class::t_unsignedInt:
lhs << "t_unsignedInt";
break;
case type_class::t_signedInt:
lhs << "t_signedInt";
break;
case type_class::t_unsignedLong:
lhs << "t_unsignedLong";
break;
case type_class::t_signedLong:
lhs << "t_signedLong";
break;
case type_class::t_unsignedLongLong:
lhs << "t_unsignedLongLong";
break;
case type_class::t_signedLongLong:
lhs << "t_signedLongLong";
break;
case type_class::t_char:
lhs << "t_char";
break;
case type_class::t_string:
lhs << "t_string";
break;
case type_class::t_class:
lhs << "t_class";
break;
case type_class::t_enum:
lhs << "t_enum";
break;
default:
throw omni::core::not_implemented_error (__FILE__, __FUNCTION__, __LINE__);
}
return lhs;
}
| 1,652 |
C++
| 25.66129 | 107 | 0.549031 |
daniel-kun/omni/source/omni/core/model/variable_assignment_expression.cpp
|
#include <omni/core/model/variable_assignment_expression.hpp>
#include <omni/core/model/variable_declaration_expression.hpp>
#include <omni/core/model/type_mismatch_error.hpp>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Value.h>
#include <llvm/IR/NoFolder.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info variable_assignment_expressionMetaInfo;
}
/**
Initializes this variabe_assignment_expresion to assign `value' to `variable'.
variable and value need to be of exactly the same type.
**/
omni::core::model::variable_assignment_expression::variable_assignment_expression (std::shared_ptr <variable_declaration_expression> variable, std::shared_ptr <expression> value) :
modifying_expression (),
_variable (variable),
_llvmValue (nullptr)
{
setValue (value);
if (_variable->getType () != value->getType ()) {
throw type_mismatch_error (* _variable->getType (), * value->getType ());
}
}
omni::core::model::meta_info & omni::core::model::variable_assignment_expression::getStaticMetaInfo ()
{
return omniMetaImpl::variable_assignment_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::variable_assignment_expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::variable_assignment_expression::getDomain () const
{
return domain::variable_assignment_expression;
}
void omni::core::model::variable_assignment_expression::setVariable (std::shared_ptr <omni::core::model::variable_declaration_expression> variable)
{
_variable = variable;
}
/**
Returns the variable that is being assigned to by this expression.
**/
std::shared_ptr <omni::core::model::variable_declaration_expression> omni::core::model::variable_assignment_expression::getVariable () const
{
return _variable;
}
void omni::core::model::variable_assignment_expression::setValue (std::shared_ptr <omni::core::model::expression> value)
{
setComponent (domain::expression, "value", value);
}
/**
Returns the value that is being assigned to a variable by this expression.
**/
std::shared_ptr <omni::core::model::expression> omni::core::model::variable_assignment_expression::getValue () const
{
return getComponentAs <expression> (domain::expression, "value");
}
std::shared_ptr <omni::core::model::type> omni::core::model::variable_assignment_expression::getType () const
{
return _variable->getType ();
}
/**
Internal
**/
omni::core::statement_emit_result omni::core::model::variable_assignment_expression::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
return variable_assignment_expression::llvmEmitImpl (llvmBasicBlock, * _variable, * getValue ());
}
/**
Internal
**/
omni::core::statement_emit_result omni::core::model::variable_assignment_expression::llvmEmitImpl (llvm::BasicBlock * llvmBasicBlock, variable_declaration_expression & variable, expression & value)
{
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
statement_emit_result result = value.llvmEmit (llvmBasicBlock);
builder.CreateStore (result.getValue (), variable.llvmPointerValue ());
return result;
}
| 3,177 |
C++
| 32.452631 | 197 | 0.73497 |
daniel-kun/omni/source/omni/core/model/variable_expression.cpp
|
#include <omni/core/model/variable_expression.hpp>
#include <omni/core/model/variable_declaration_expression.hpp>
#include <omni/core/model/use_before_declaration_error.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/domain.hpp>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/NoFolder.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info variable_expressionMetaInfo;
}
/**
Initializes this expression to return variable's at the time this expression is executed.
**/
omni::core::model::variable_expression::variable_expression (std::shared_ptr <variable_declaration_expression> variable) :
pure_expression ()
{
setVariable (variable);
}
omni::core::model::meta_info & omni::core::model::variable_expression::getStaticMetaInfo ()
{
return omniMetaImpl::variable_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::variable_expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::variable_expression::getDomain () const
{
return domain::variable_expression;
}
std::shared_ptr <omni::core::model::type> omni::core::model::variable_expression::getType () const
{
return _variable->getType ();
}
/**
Sets the variable which value this expression returns.
**/
void omni::core::model::variable_expression::setVariable (std::shared_ptr <variable_declaration_expression> variable)
{
_variable = variable;
}
/**
Returns the variable which value this expression returns.
**/
const std::shared_ptr <omni::core::model::variable_declaration_expression> omni::core::model::variable_expression::getVariable () const
{
return _variable;
}
omni::core::statement_emit_result omni::core::model::variable_expression::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
llvm::Value * pointerValue = _variable->llvmPointerValue ();
if (pointerValue == nullptr) {
throw use_before_declaration_error (omni::core::domain::variable_expression, _variable->getName ());
}
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
return statement_emit_result (llvmBasicBlock, builder.CreateLoad (pointerValue));
}
| 2,192 |
C++
| 30.782608 | 135 | 0.73677 |
daniel-kun/omni/source/omni/core/model/module.cpp
|
#include <omni/core/model/module.hpp>
#include <omni/core/context.hpp>
#include <omni/core/model/function.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/logic_error.hpp>
#include <omni/core/already_exists_error.hpp>
#include <omni/core/verification_failed_error.hpp>
#include <llvm/IR/Module.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/IR/PassManager.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/IRPrintingPasses.h>
#include <llvm/IR/Verifier.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetOptions.h>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <sstream>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info moduleMetaInfo;
}
namespace {
/**
Adds a function with the prototype "dllexport x86_stdcallcc i8 @DllMain(i32*, i32, i32*)" if such a function does not already exist.
TODO: Implement this in omni instead of llvm.
**/
void addDllMainIfMissing (omni::core::context & c, llvm::Module & module)
{
#ifdef _MSC_VER
llvm::Type * i32ptr = llvm::Type::getInt32PtrTy (c.llvmContext ());
llvm::Type * i32 = llvm::Type::getInt32Ty (c.llvmContext ());
llvm::Type * i8 = llvm::Type::getInt8Ty (c.llvmContext ());
std::vector <llvm::Type *> params = { i32ptr, i32, i32ptr };
llvm::FunctionType * ft = llvm::FunctionType::get (i8, params, false);
llvm::Function * func = llvm::Function::Create (ft, llvm::Function::ExternalLinkage, "DllMain", & module);
func->setDLLStorageClass (llvm::GlobalValue::DLLExportStorageClass);
func->setCallingConv(llvm::CallingConv::X86_StdCall);
llvm::BasicBlock * body = llvm::BasicBlock::Create (c.llvmContext (), "__entry__", func);
llvm::IRBuilder <> builder (body);
builder.CreateRet (llvm::ConstantInt::get (i8, 1));
#endif
}
}
/**
Initializes this module in the context `context' with the name `name'. A new, random id will be assigned to this module.
**/
omni::core::model::module::module (omni::core::context & context, std::string name) :
scope (name),
_llvmModule (),
_context (context),
_entryPoint ()
{
}
/**
Initializes this existing module in the given context and the given name and moduleId.
**/
omni::core::model::module::module (context & context, id moduleId, std::string name) :
scope (moduleId, name),
_llvmModule (),
_context (context),
_entryPoint ()
{
}
omni::core::model::meta_info & omni::core::model::module::getStaticMetaInfo ()
{
return omniMetaImpl::moduleMetaInfo;
}
omni::core::model::meta_info & omni::core::model::module::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::module::getDomain () const
{
return domain::module;
}
/**
Returns the context that this module is defined in.
**/
omni::core::context * omni::core::model::module::getContext ()
{
return & _context;
}
/**
Returns the context that this module is defined in.
**/
const omni::core::context * omni::core::model::module::getContext () const
{
return & _context;
}
omni::core::model::module * omni::core::model::module::getModule ()
{
return this;
}
const omni::core::model::module * omni::core::model::module::getModule () const
{
return this;
}
/**
Create a new, unique id for the domain `domain'.
@param domain The domain that the id should be valid for.
@return A new, unique id that can be used to identify newly created entities for this context.
**/
omni::core::id omni::core::model::module::createId (omni::core::domain domain)
{
static unsigned int counter = 0;
//static boost::uuids::random_generator generator;
std::string strId;
do {
//boost::uuids::uuid uuid = generator ();
std::stringstream str;
str << ++ counter;
//strId = boost::lexical_cast <std::string> (uuid);
strId = str.str ();
} while (lookupComponentById (id (domain, strId)).get () != nullptr);
return id (domain, strId);
}
/**
Sets the entry point for this module.
Not implemented yet.
**/
void omni::core::model::module::setEntryPoint (std::shared_ptr <model::function> function)
{
_entryPoint = function;
}
/**
Emits llvm IR language code to the file at path fileName.
@param fileName Path to the file where the code should be written to.
// TODO error reporting
**/
void omni::core::model::module::emitAssemblyFile (std::string const & fileName, const module_emit_options & options)
{
std::error_code errorInfo;
llvm::raw_fd_ostream fileStream (static_cast <llvm::StringRef> (fileName), errorInfo, llvm::sys::fs::F_None);
emitAssemblyFile (fileStream, options);
}
/**
Emits llvm IR language code to the stream `stream'.
This function is not very fast since it first writes the whole code to a temporary buffer and then
writes the whole buffer to `stream'. If you need a more efficient way, use emitAssemblyFile(llvm::raw_ostream).
@param stream The ostream where the code should be written to.
**/
void omni::core::model::module::emitAssemblyFile (std::ostream & stream, const module_emit_options & options)
{
std::string tmp;
llvm::raw_string_ostream rawStream (tmp);
emitAssemblyFile (rawStream, options);
stream << tmp;
}
/**
Emits llvm IR language code to the llvm stream `stream'.
@param stream The llvm stream wher the code should be written to.
**/
void omni::core::model::module::emitAssemblyFile (llvm::raw_ostream & stream, const module_emit_options & options)
{
llvm::Module & m (llvmModule ());
for (auto f : getComponents (domain::function)) {
model::function_prototype & func = * std::dynamic_pointer_cast <model::function_prototype> (f.second);
func.llvmFunction ();
}
llvm::verifyModule(m, & llvm::outs ());
llvm::legacy::PassManager pm;
pm.add (llvm::createPrintModulePass (stream));
pm.run (m);
}
/**
Emits a native object file (e.g. .obj on win32) to stream.
This function is not very fast since it first writes the whole object file to a temporary buffer and then
writes the whole buffer to `stream'. If you need a more efficient way, use emitObjectFile (llvm::raw_ostream).
@param stream Any ostream that should receive the content of the objectFile.
**/
void omni::core::model::module::emitObjectFile (std::ostream & stream, const module_emit_options & options)
{
std::string tmp;
llvm::raw_string_ostream rawStream (tmp);
emitObjectFile (rawStream, options);
stream << tmp;
}
/**
Emits a native object file (e.g. .obj on win32) to stream.
@param stream Any llvm::raw_ostream that should receive the content of the objectFile.
**/
void omni::core::model::module::emitObjectFile (llvm::raw_ostream & stream, const module_emit_options & options)
{
llvm::Module & m (llvmModule ());
addDllMainIfMissing (_context, m);
for (auto f : getComponents (domain::function)) {
model::function_prototype & func = * std::dynamic_pointer_cast <model::function_prototype> (f.second);
func.llvmFunction ();
}
std::string errorInfo;
llvm::raw_string_ostream errorStream (errorInfo);
if (llvm::verifyModule(m, & errorStream)) {
errorStream.flush ();
throw verification_failed_error (getName (), errorInfo);
}
std::string errors;
#ifdef WIN32
std::string targetTriple = "i686-pc-win32";
#else
# ifdef OMNI_ARM
std::string targetTriple = "armv6-unknown-linux-gnueabi";
# else
std::string targetTriple = "x86_64-pc-linux";
# endif
#endif
llvm::Triple triple = llvm::Triple (targetTriple);
llvm::InitializeNativeTarget ();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
const llvm::Target * target = llvm::TargetRegistry::lookupTarget ("", triple, errors);
llvm::TargetOptions targetOptions;
#ifdef OMNI_ARM
// Required to output Hard-Float object code. Otherwise linking will fail with error message "*.so uses VFP register arguments, *.o does not".
targetOptions.FloatABIType = llvm::FloatABI::Hard;
#endif
llvm::TargetMachine * targetMachine = target->createTargetMachine (targetTriple, std::string (), std::string (), targetOptions, llvm::Reloc::PIC_);
llvm::legacy::PassManager pm;
llvm::formatted_raw_ostream formattedStream (stream);
targetMachine->addPassesToEmitFile (pm, formattedStream, llvm::TargetMachine::CGFT_ObjectFile);
pm.run (m);
formattedStream.flush ();
}
/**
Emits a native object file (e.g. .obj on win32) to the file `fileName'.
@param fileName The path of the file where the object file should be written to.
**/
void omni::core::model::module::emitObjectFile (std::string const & fileName, const module_emit_options & options)
{
std::error_code errorInfo;
llvm::raw_fd_ostream rawStream (static_cast <llvm::StringRef> (fileName), errorInfo, llvm::sys::fs::F_None);
emitObjectFile (rawStream, options);
}
/**
Emits a shared object file (.so on Linux/Unix, .dll on Windows or .dylib on Mac OS) to the file at the path `fileName'.
Remember to set functions to "external" with function::setExternal(true) when you want to export them from your shared object.
For every shared object file, an object file with the same base name but the extension .obj (on Windows) or .o (on Linux/Unix)
is temporarily created and removed before this function returns.
For example emitSharedLibraryFile /home/foo/shared.so will temporarily create a file /home/foo/shared.o.
**/
void omni::core::model::module::emitSharedLibraryFile (std::string const & fileName, const module_emit_options & options)
{
boost::filesystem::path sharedLibraryPath (fileName);
boost::filesystem::path objectFilePath = sharedLibraryPath;
objectFilePath.replace_extension (".obj");
emitObjectFile (objectFilePath.string (), options);
/*
boost::filesystem::path assemblyFilePath = objectFilePath;
assemblyFilePath.replace_extension (".ll");
emitAssemblyFile (assemblyFilePath.string ());
*/
if (! boost::filesystem::exists (objectFilePath)) {
throw omni::core::logic_error (__FILE__, __FUNCTION__, __LINE__, "Object file \"" + objectFilePath.string () + "\" does not exist");
}
std::set <std::string> additionalLibraries;
for (auto i : getComponents ()) {
for (auto p : i.second) {
p.second->fillLibraries (additionalLibraries);
}
}
#ifdef WIN32
additionalLibraries.insert ("LIBCMT.LIB");
std::string command = "..\\tools\\link_helper.cmd \"" + objectFilePath.string () + "\" \"/OUT:" + sharedLibraryPath.string () + "\"";
// Add library search path:
for (auto librarySearchPath : options.getLibrarySearchPaths ()) {
command += " /LIBPATH:\"" + librarySearchPath.string () + "\"";
}
std::string linkLibraryPrefix = " ";
#else
# ifdef OMNI_ARM
std::string ldFlags = "-mfloat-abi=hard -mfpu=vfpu";
# else
std::string ldFlags;
# endif
std::string command = "gcc -shared \"" + objectFilePath.string () + "\" " + ldFlags + " -o \"" + sharedLibraryPath.string () + "\"";
// Add library search paths:
for (auto librarySearchPath : options.getLibrarySearchPaths ()) {
command += " -L\"" + librarySearchPath.string () + "\"";
}
std::string linkLibraryPrefix = " -l";
#endif
// Add libraries to link:
for (auto library : additionalLibraries) {
if (library.length () > 0) {
command += linkLibraryPrefix + library;
}
}
for (auto library : options.getLibraries ()) {
if (library.length () > 0) {
command += linkLibraryPrefix + library;
}
}
// Now call the linker:
int errorCode = std::system (command.c_str ());
if (errorCode != 0) {
throw std::runtime_error ((boost::format ("Linking the object file %1% failed with command %2%.") % objectFilePath % command).str ().c_str ());
}
boost::system::error_code ignored;
boost::filesystem::remove (objectFilePath, ignored); // ignores failures on purpose
}
/**
Verifies this module.
@param errorInfo When the module contains errors, errorInfo will be filled with the error messages.
@return True, if the module is valid. false, if there are errors.
**/
bool omni::core::model::module::verify (std::string & errorInfo)
{
llvm::Module & m (llvmModule ());
try {
for (auto f : getComponents (domain::function)) {
model::function_prototype & func = *std::dynamic_pointer_cast <model::function_prototype> (f.second);
func.llvmFunction ();
}
}
catch (std::exception const & e) {
errorInfo = e.what ();
return false;
}
return !llvm::verifyModule(m, & llvm::outs ());
}
/**
@internal
**/
llvm::Module & omni::core::model::module::llvmModule ()
{
if (_llvmModule.get () == nullptr) {
_llvmModule.reset (new llvm::Module (getName (), _context.llvmContext ()));
}
return * _llvmModule;
}
| 13,287 |
C++
| 34.153439 | 151 | 0.674945 |
daniel-kun/omni/source/omni/core/model/block.cpp
|
#include <omni/core/model/block.hpp>
#include <omni/core/model/statement.hpp>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/BasicBlock.h>
#include <boost/lexical_cast.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info blockMetaInfo;
}
omni::core::model::block::block () :
statement (),
_statementCount (0u)
{
}
omni::core::model::meta_info & omni::core::model::block::getStaticMetaInfo ()
{
return omniMetaImpl::blockMetaInfo;
}
omni::core::model::meta_info & omni::core::model::block::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::block::getDomain () const
{
return domain::block;
}
/**
@return Returns the list of statements that this block contains.
**/
const std::vector <std::shared_ptr <omni::core::model::statement> > omni::core::model::block::getStatements () const
{
return _statements;
}
/**
Returns an iterator to the given statement that exists in the list of statements that this lock contains.
Can return getStatements ().end () if the statement is not listed in this block.
**/
omni::core::model::block::statement_list::iterator omni::core::model::block::findStatement (std::shared_ptr <statement> statement)
{
return std::find (_statements.begin (), _statements.end (), statement);
}
/**
Returns the end of the statement_list. Can be used to check, whether findStatement retuned a valid result.
**/
omni::core::model::block::statement_list::iterator omni::core::model::block::statementsEnd ()
{
return _statements.end ();
}
/**
Appends the given statement to the list of statements that this block contains.
@return Returns the statement that has been added.
**/
std::shared_ptr <omni::core::model::statement> omni::core::model::block::appendStatement (std::shared_ptr <statement> statement)
{
_statements.push_back (statement);
setComponent (domain::statement, "statement" + boost::lexical_cast <std::string> (++_statementCount), statement);
return statement;
}
/**
Inserts the given statement at the beginning of the list of statements that this block contains.
@return Returns the statement that has been added.
**/
std::shared_ptr <omni::core::model::statement> omni::core::model::block::prependStatement (std::shared_ptr <statement> statement)
{
_statements.insert (_statements.begin (), statement);
setComponent (domain::statement, "statement" + boost::lexical_cast <std::string> (++_statementCount), statement);
return statement;
}
/**
Inserts the given statement after the provided position in the list of statements that this block contains.
Use the vector returned by findStatement to determine the position.
@return Returns the statement that has been added.
**/
std::shared_ptr <omni::core::model::statement> omni::core::model::block::insertStatementAfter (statement_list::iterator position, std::shared_ptr <statement> statement)
{
_statements.insert (++position, statement);
setComponent (domain::statement, "statement" + boost::lexical_cast <std::string> (++_statementCount), statement);
return statement;
}
/**
Inserts the given statement before the provided position in the list of statements that this block contains.
Use the vector returned by findStatement to determine the position.
@return Returns the statement that has been added.
**/
std::shared_ptr <omni::core::model::statement> omni::core::model::block::insertStatementBefore (statement_list::iterator position, std::shared_ptr <statement> statement)
{
_statements.insert (position, statement);
setComponent (domain::statement, "statement" + boost::lexical_cast <std::string> (++_statementCount), statement);
return statement;
}
/**
Removes the statement at the given position from the list of statements that this block contains.
@return Returns the statement that has been removed.
**/
std::shared_ptr <omni::core::model::statement> omni::core::model::block::removeStatement (statement_list::iterator position)
{
std::shared_ptr <statement> result = * position;
_statements.erase (position);
for (auto i : getComponentsStartingWithAs <statement> (domain::statement, "statement")) {
if (i.second == result) {
removeComponent (domain::statement, i.first);
break;
}
}
return result;
}
/**
Removes the given statement from the list of statements that this block contains.
@return Returns the statement that has been removed.
**/
std::shared_ptr <omni::core::model::statement> omni::core::model::block::removeStatement (std::shared_ptr <statement> statement)
{
statement_list::iterator i = std::find (_statements.begin (), _statements.end (), statement);
return removeStatement (i);
}
/**
@internal
**/
llvm::BasicBlock * omni::core::model::block::llvmEmitIntoExistingBlock (llvm::BasicBlock * llvmBasicBlock)
{
llvm::BasicBlock * block = llvmBasicBlock;
for (auto i : _statements) {
block = i->llvmEmit (block).getContinueBlock ();
}
return block;
}
/**
@internal
**/
omni::core::statement_emit_result omni::core::model::block::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
auto result = llvm::BasicBlock::Create (llvmBasicBlock->getContext (), "", llvmBasicBlock->getParent ());
for (auto i : _statements) {
result = i->llvmEmit (result).getContinueBlock ();
}
return statement_emit_result (result, nullptr);
}
| 5,426 |
C++
| 33.788461 | 169 | 0.715076 |
daniel-kun/omni/source/omni/core/model/return_statement.cpp
|
#include <omni/core/model/return_statement.hpp>
#include <omni/core/model/expression.hpp>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/NoFolder.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info return_statementMetaInfo;
}
omni::core::model::return_statement::return_statement () :
statement ()
{
}
omni::core::model::return_statement::return_statement (std::shared_ptr <expression> expression) :
statement ()
{
setExpression (expression);
}
omni::core::model::meta_info & omni::core::model::return_statement::getStaticMetaInfo ()
{
return omniMetaImpl::return_statementMetaInfo;
}
omni::core::model::meta_info & omni::core::model::return_statement::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::return_statement::getDomain () const
{
return domain::return_statement;
}
std::shared_ptr <omni::core::model::expression> omni::core::model::return_statement::getExpression ()
{
return getComponentAs <expression> (domain::expression, "expression");
}
const std::shared_ptr <omni::core::model::expression> omni::core::model::return_statement::getExpression () const
{
return getComponentAs <expression> (domain::expression, "expression");
}
void omni::core::model::return_statement::setExpression (std::shared_ptr <omni::core::model::expression> expression)
{
return setComponent (domain::expression, "expression", expression);
}
omni::core::statement_emit_result omni::core::model::return_statement::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
std::shared_ptr <expression> expression = getExpression ();
if (expression.get () == nullptr) {
builder.CreateRetVoid ();
} else {
builder.CreateRet (expression->llvmEmit (llvmBasicBlock).getValue ());
}
return statement_emit_result (llvmBasicBlock, nullptr);
}
| 1,961 |
C++
| 29.65625 | 116 | 0.717491 |
daniel-kun/omni/source/omni/core/model/expression.cpp
|
#include <omni/core/model/expression.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info expressionMetaInfo;
}
omni::core::model::expression::expression () :
statement ()
{
}
omni::core::model::meta_info & omni::core::model::expression::getStaticMetaInfo ()
{
return omniMetaImpl::expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
| 490 |
C++
| 21.318181 | 82 | 0.718367 |
daniel-kun/omni/source/omni/core/model/do_while_statement.cpp
|
#include <omni/core/model/do_while_statement.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/model/expression.hpp>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/NoFolder.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info do_while_statementMetaInfo;
}
omni::core::model::do_while_statement::do_while_statement () :
while_statement ()
{
}
omni::core::model::do_while_statement::do_while_statement (std::shared_ptr <omni::core::model::expression> condition, std::shared_ptr <omni::core::model::block> body) :
while_statement (condition, body)
{
}
omni::core::model::meta_info & omni::core::model::do_while_statement::getStaticMetaInfo ()
{
return omniMetaImpl::do_while_statementMetaInfo;
}
omni::core::model::meta_info & omni::core::model::do_while_statement::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::do_while_statement::getDomain () const
{
return domain::do_while_statement;
}
omni::core::statement_emit_result omni::core::model::do_while_statement::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
llvm::BasicBlock * whileBlock = getBody ()->llvmEmit (llvmBasicBlock).getContinueBlock ();
llvm::BasicBlock * continueBlock = llvm::BasicBlock::Create (llvmBasicBlock->getContext (), "", llvmBasicBlock->getParent ());
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
builder.CreateBr (whileBlock);
llvm::IRBuilder <true, llvm::NoFolder> whileBuilder (whileBlock);
whileBuilder.CreateCondBr (getCondition ()->llvmEmit (whileBlock).getValue (), whileBlock, continueBlock);
return statement_emit_result (continueBlock, nullptr);
}
| 1,754 |
C++
| 32.749999 | 168 | 0.72691 |
daniel-kun/omni/source/omni/core/model/meta_info_extension.cpp
|
#include <omni/core/model/meta_info_extension.hpp>
omni::core::model::meta_info_extension::~ meta_info_extension ()
{
}
| 121 |
C++
| 19.33333 | 64 | 0.719008 |
daniel-kun/omni/source/omni/core/model/parameter.cpp
|
#include <omni/core/model/parameter.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info parameterMetaInfo;
}
/**
@brief Initializes this parameter with the given type and name.
@param parameterType The type of this parameter. @see getType
@param name The name of this parameter. @see getName
The name can be changed later using entity::setName().
The type can be set or changed later using setType ().
**/
omni::core::model::parameter::parameter (std::shared_ptr <type> parameterType, std::string name) :
scope (name),
_type (parameterType)
{
}
omni::core::model::meta_info & omni::core::model::parameter::getStaticMetaInfo ()
{
return omniMetaImpl::parameterMetaInfo;
}
omni::core::model::meta_info & omni::core::model::parameter::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::parameter::getDomain () const
{
return domain::parameter;
}
/**
@brief Changes the type of this parameter.
Changing the type means that possible function_call_expression s will no longer be valid, because the types might
not match the new type.
@param type The new type that this parameter should have.
@see getType
**/
void omni::core::model::parameter::setType (std::shared_ptr <type> type)
{
}
/**
@brief Returns the type of this parameter.
The type of a parameter specifies which kind of expressions can be passed when calling the function using function_call_expression.
The expressions passed to function_call_expression::appendParameter or function_call_expression::setParameters have to match the
order and exact types of the parameters set in function_prototype::function_prototype, function_prototype::appendParameter or
function_prototype::setParameters.
@return The type of this parameter. The returned type is const and can not be modified.
**/
const std::shared_ptr <omni::core::model::type> omni::core::model::parameter::getType () const
{
return _type;
}
/**
@brief Returns the type of this parameter.
The type of a parameter specifies which kind of expressions can be passed when calling the function using function_call_expression.
The expressions passed to function_call_expression::appendParameter or function_call_expression::setParameters have to match the
order and exact types of the parameters set in function_prototype::function_prototype, function_prototype::appendParameter or
function_prototype::setParameters.
@return The type of this parameter. The returned type can be modified.
**/
std::shared_ptr <omni::core::model::type> omni::core::model::parameter::getType()
{
return _type;
}
| 2,638 |
C++
| 32.405063 | 131 | 0.760804 |
daniel-kun/omni/source/omni/core/model/bitcast_expression.cpp
|
#include <omni/core/model/bitcast_expression.hpp>
#include <omni/core/model/type.hpp>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/NoFolder.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info bitcast_expressionMetaInfo;
}
/**
Initializes this bitcast_expression to convert the result of sourceExpression to the targetType. sourceExpression->getType ()'s bidwidth
must be of the same bit-width as targetType.
**/
omni::core::model::bitcast_expression::bitcast_expression (std::shared_ptr <expression> sourceExpression, std::shared_ptr <type> targetType) :
cast_expression (),
_targetType (targetType)
{
setSourceExpression (sourceExpression);
}
omni::core::model::meta_info & omni::core::model::bitcast_expression::getStaticMetaInfo ()
{
return omniMetaImpl::bitcast_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::bitcast_expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::bitcast_expression::getDomain () const
{
return domain::bitcast_expression;
}
void omni::core::model::bitcast_expression::setSourceExpression (std::shared_ptr <omni::core::model::expression> sourceExpression)
{
setComponent (domain::expression, "sourceExpression", sourceExpression);
}
std::shared_ptr <omni::core::model::expression> omni::core::model::bitcast_expression::getSourceExpression () const
{
return getComponentAs <expression> (domain::expression, "sourceExpression");
}
std::shared_ptr <omni::core::model::type> omni::core::model::bitcast_expression::getType () const
{
return _targetType;
}
omni::core::statement_emit_result omni::core::model::bitcast_expression::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
return statement_emit_result (llvmBasicBlock, builder.CreateBitCast (getSourceExpression ()->llvmEmit (llvmBasicBlock).getValue (), _targetType->llvmType ()));
}
| 2,014 |
C++
| 33.152542 | 163 | 0.747269 |
daniel-kun/omni/source/omni/core/model/scope.cpp
|
#include <omni/core/model/scope.hpp>
#include <omni/core/context.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/function.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/logic_error.hpp>
#include <omni/core/already_exists_error.hpp>
#include <omni/core/verification_failed_error.hpp>
#include <llvm/IR/Module.h>
#include <boost/format.hpp>
#include <sstream>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info scopeMetaInfo;
}
/**
@brief Initializes this scope with an empty name and an invalid id.
The id will be set as soon as this entity is added to a context.
**/
omni::core::model::scope::scope () :
entity ()
{
}
/**
@brief Initializes this scope with the given name and an invalid id.
The id will be set as soon as this entity is added to a context.
@see getName
**/
omni::core::model::scope::scope (std::string name) :
entity (name)
{
}
/**
@brief Initializes this entity within the given parent and with the given id and name.
@see getName
@see getId
**/
omni::core::model::scope::scope (id scopeId, std::string name) :
entity (scopeId, name)
{
}
omni::core::model::scope::~scope ()
{
}
omni::core::model::meta_info & omni::core::model::scope::getStaticMetaInfo ()
{
return omniMetaImpl::scopeMetaInfo;
}
omni::core::model::meta_info & omni::core::model::scope::getMetaInfo () const
{
return getStaticMetaInfo ();
}
/**
@brief Creates a new function with the given characteristics, adds it to this scope and returns it.
The function's parent will be set to this scope and the body's and paremeter's parent will be set to the created function.
Calling createFunction is the same as creating a new omni::core::model::function and then calling addFunction().
@param name The name of the function. There may not be a function with the same name in this scope, otherwise an already_exits_error exception will be thrown.
@param returnType The type of the value that the function returns.
@param body The body of the function.
@param parameters An optional list of parameters that the function receives.
@param isExported Specifies, whether this function is visible from outside the module it is defined in. @see function::isExported().
@exception already_exists_error Is thrown when a function with the given name already exists in this scope.
**/
std::shared_ptr <omni::core::model::function> omni::core::model::scope::createFunction (
std::string const & name,
std::shared_ptr <type> returnType,
std::shared_ptr <block> body,
std::vector <std::shared_ptr <parameter>> parameters,
bool isExported)
{
std::shared_ptr <function> result (new function (name, returnType, body, parameters, isExported));
addFunction (result);
return result;
}
/**
Adds the given function to this scope, if there is not already another function with the same name.
The function's parent will be set to this scope.
@param function The function that should be added to this scope.
@exception already_exists_error Is thrown when a function with the same name as `function's name already exists in this scope.
**/
void omni::core::model::scope::addFunction (std::shared_ptr <function_prototype> function)
{
std::shared_ptr <function_prototype> func = findFunctionByName (function->getName ());
if (func.get () != nullptr) {
throw already_exists_error (domain::function, function->getName ());
}
setComponent (domain::function, function->getName (), function);
}
/**
@brief Returns the function with the given name, if such a function exists in this scope.
Only functions that were created using createFunction or were added via addFunction are part of this scope.
@param name The name of the function that should be returned. Should not be empty.
@return The function with the given name that has previously been added to this context.
**/
std::shared_ptr <omni::core::model::function_prototype> omni::core::model::scope::findFunctionByName (std::string const & name)
{
name_to_entities_map const & functionMap (getComponents (domain::function));
auto found = std::find_if (functionMap.begin (), functionMap.end (), [name] (std::pair <std::string, std::shared_ptr <entity>> f) -> bool {
return f.second->getName () == name;
});
if (found != functionMap.end ()) {
return std::dynamic_pointer_cast <function_prototype> (found->second);
} else {
return std::shared_ptr <function_prototype> ();
}
}
/**
@brief Removes the given from this scope.
This only has an effect if `function' was previously added to this scope by creating it using createFunction or adding it via addFunction.
@param function The function to be removed from this scope.
@return true, if `function' was part of this scope and has been removed. false, if `function' was not found.
**/
bool omni::core::model::scope::removeFunction (std::shared_ptr <model::function_prototype> function)
{
function->llvmFunction ()->eraseFromParent ();
return removeComponent (domain::function, function);
}
| 5,075 |
C++
| 35.257143 | 158 | 0.726108 |
daniel-kun/omni/source/omni/core/model/statement.cpp
|
#include <omni/core/model/statement.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info statementMetaInfo;
}
omni::core::model::statement::statement () :
scope ()
{
}
omni::core::model::statement::~statement ()
{
}
omni::core::model::meta_info & omni::core::model::statement::getStaticMetaInfo ()
{
return omniMetaImpl::statementMetaInfo;
}
omni::core::model::meta_info & omni::core::model::statement::getMetaInfo () const
{
return getStaticMetaInfo ();
}
| 528 |
C++
| 19.346153 | 81 | 0.704545 |
daniel-kun/omni/source/omni/core/model/external_function.cpp
|
#include <omni/core/model/external_function.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/parameter.hpp>
#include <llvm/IR/Function.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info external_functionMetaInfo;
}
/**
@brief Initializes an external_function with the given libraryName, functionName, returnType, parameters and flag whether the function is imported from a dll (isDllImport).
@param libraryName The name of the library that the function is defined in. Can be an empty string, when the library is somehow linked by other means (e.g.
by other functions that use that library or by module_emit_options::addLibrary()). Can be changed later with setLibraryName().
@param functionName The name of the function. If it is a C++ function, this is the mangled name. Can be changed later with entity::setName ().
@param returnType The returnType of the function. Can be changed later with function_prototype::setReturnType ().
@param parameters A list of parameters that this function takes, if any. Can be an empty vector. Can be changed later with setParameters() or appendParameter ().
@param isDllImport True, if this function is imported from a DLL. Only for Windows. Can be changed later with setDllImport().
**/
omni::core::model::external_function::external_function (std::string libraryName,
std::string functionName,
std::shared_ptr <model::type> returnType,
std::vector <std::shared_ptr <parameter>> parameters,
bool isDllImport) :
function_prototype (functionName, returnType, parameters),
_llvmFunction (),
_libraryName (libraryName),
_isDllImport (isDllImport)
{
}
omni::core::model::meta_info & omni::core::model::external_function::getStaticMetaInfo ()
{
return omniMetaImpl::external_functionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::external_function::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::external_function::getDomain () const
{
return domain::external_function;
}
/**
@brief Sets the libraryName that specifies which library this external_function will be imported from.
@param libraryName The name of the library that this external_function will be imoported from. I.e. "foo.so" or "foo.a" on Linux, or "foo.dll" or "foo.lib" on Windows.
If this function is imported from a DLL, you need to setDllImport () to true.
@see getLibraryName
**/
void omni::core::model::external_function::setLibraryName (std::string libraryName)
{
_libraryName = libraryName;
}
/**
@brief Returns the name of the library that this external function is defined in.
The library will automatically be added to the linker when a shared library is emitted (@see module::emitSharedLibraryFile).
@return The name of the libary that this external function is defined in.
@see setLibraryName
**/
std::string omni::core::model::external_function::getLibraryName () const
{
return _libraryName;
}
/**
@brief Changes whether this function is imported from a DLL. Only used on Windows.
@param isDllImport If set to true, this function will be imported from a dll. If set to false, this function will be imported from a static library (.lib).
@see isDllImport
**/
void omni::core::model::external_function::setDllImport (bool isDllImport)
{
_isDllImport = isDllImport;
}
/**
@brief Returns true if this function is imported from a DLL. Only used for Windows.
@return True, if this function is imported from a DLL. False, if this function is imported from a static library (.lib).
@see setDllImport
**/
bool omni::core::model::external_function::isDllImport () const
{
return _isDllImport;
}
void omni::core::model::external_function::fillLibraries (std::set <std::string> & libraries)
{
if (! _libraryName.empty ()) {
if (libraries.find (_libraryName) == libraries.end ())
libraries.insert (_libraryName);
}
}
/*
Internal.
Returns an llvm::Function in the module currently returned by getModule () with the same characteristics as this function
and with llvm::Function::ExternalLinkage. If isDllImport () currently returns true, the DLLStorageClass of the llvm::Function
is set to DLLImportStorageClass.
*/
llvm::Function * omni::core::model::external_function::llvmFunction ()
{
if (_llvmFunction == nullptr) {
_llvmFunction = llvm::Function::Create (
llvmFunctionType (),
llvm::Function::ExternalLinkage,
getName (),
& getModule ()->llvmModule ());
if (_isDllImport) {
_llvmFunction->setDLLStorageClass (llvm::GlobalValue::DLLImportStorageClass);
}
}
return _llvmFunction;
}
| 4,964 |
C++
| 39.365853 | 172 | 0.70004 |
daniel-kun/omni/source/omni/core/model/modifying_expression.cpp
|
#include <omni/core/model/modifying_expression.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info modifying_expressionMetaInfo;
}
omni::core::model::modifying_expression::modifying_expression () :
expression ()
{
}
omni::core::model::meta_info & omni::core::model::modifying_expression::getStaticMetaInfo ()
{
return omniMetaImpl::modifying_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::modifying_expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
| 561 |
C++
| 24.545453 | 92 | 0.741533 |
daniel-kun/omni/source/omni/core/model/native_type_to_type_class.cpp
|
#include <omni/core/model/native_type_to_type_class.hpp>
extern template class omni::core::model::native_type_to_type_class <void>;
extern template class omni::core::model::native_type_to_type_class <bool>;
extern template class omni::core::model::native_type_to_type_class <unsigned char>;
extern template class omni::core::model::native_type_to_type_class <signed char>;
extern template class omni::core::model::native_type_to_type_class <unsigned short>;
extern template class omni::core::model::native_type_to_type_class <signed short>;
extern template class omni::core::model::native_type_to_type_class <unsigned int>;
extern template class omni::core::model::native_type_to_type_class <signed int>;
extern template class omni::core::model::native_type_to_type_class <unsigned long>;
extern template class omni::core::model::native_type_to_type_class <signed long>;
extern template class omni::core::model::native_type_to_type_class <unsigned long long>;
extern template class omni::core::model::native_type_to_type_class <signed long long>;
extern template class omni::core::model::native_type_to_type_class <char>;
extern template class omni::core::model::native_type_to_type_class <std::string>;
| 1,206 |
C++
| 66.055552 | 88 | 0.766998 |
daniel-kun/omni/source/omni/core/model/function.cpp
|
#include <omni/core/model/function.hpp>
#include <omni/core/context.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/model/statement.hpp>
#include <omni/core/model/parameter.hpp>
#include <omni/core/no_context_error.hpp>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/Module.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info functionMetaInfo;
}
/**
@brief Initializes a function implementation with the given name, returnType, body, parameters and visibility.
The body's and the parameter's parent will be set to this function.
@param name The name of this function.
@param returnType The return type of this function. Use a type constucted with the type_class omni::core::type_class::t_void for functions that have no return value.
@param body The body (implementation) of this function.
@param parameters An optional list of parameters that the function receives.
@param isExported Specifies, whether this function is visible from outside the module it is defined in. @see isExported().
**/
omni::core::model::function::function (std::string const & name,
std::shared_ptr <type> returnType,
std::shared_ptr <block> body,
std::vector <std::shared_ptr <parameter>> parameters,
bool isExported) :
function_prototype (name, returnType, parameters),
_llvmFunction (),
_isExported (isExported)
{
setBody (body);
}
omni::core::model::meta_info & omni::core::model::function::getStaticMetaInfo ()
{
return omniMetaImpl::functionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::function::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::function::getDomain () const
{
return domain::function;
}
/**
@brief Changes whether this function is visible from other modules.
@param isExported Should be set to true, if this function should be exported from this module. Should be set to false, if this function should only be visible locally within the module.
@see isExported
**/
void omni::core::model::function::setExported (bool isExported)
{
_isExported = isExported;
}
/**
@brief Return whether this function is visible from other modules.
If a function is exported, it will create a visible symbol in an emitted executable file. Only exported functions can be called across module boundaries.
Non-exported functions can only be called from within the same module that the function is defined in.
@return True, if this function is exported from this module. False, if the function is only visible locally within the module.
**/
bool omni::core::model::function::isExported () const
{
return _isExported;
}
/**
@brief Sets the body of this function.
The body contains the list of statements that are executed when the function is called.
If the function has a non-void return-type, the body must contain a return_statement for every control-flow.
@param body The new body for this function.
**/
void omni::core::model::function::setBody (std::shared_ptr <block> body)
{
setComponent (domain::block, "body", body);
}
/**
@brief Returs the body of this function.
The body contains the list of statements that are executed when the function is called.
If the function has a non-void return-type, the body must contain a return_statement for every control-flow.
The returned body is const and can not be modified.
@result The body of this function.
**/
const std::shared_ptr <omni::core::model::block> omni::core::model::function::getBody () const
{
return getComponentAs <block> (domain::block, "body");
}
/**
@brief Returs the body of this function.
The body contains the list of statements that are executed when the function is called.
If the function has a non-void return-type, the body must contain a return_statement for every control-flow.
The returned body can be modified.
@result The body of this function.
**/
std::shared_ptr <omni::core::model::block> omni::core::model::function::getBody ()
{
return getComponentAs <block> (domain::block, "body");
}
/*
Internal.
Returns an llvm::Function in the module currently returned by getModule () with the same characteristics as this function
and with a BasicBlock as the entry point named __entry__ that contains all statements from the block currently returned by getBody ().
If this function is called subsequently, the llvm::Function will only be created on the first call - all other calls will simply returned
the llvm::Function that was created on the first call.
@return An llvm::Function resembling this omni::core::model::function.
*/
llvm::Function * omni::core::model::function::llvmFunction ()
{
if (getContext () == nullptr) {
throw no_context_error (domain::function, getName ());
}
if (_llvmFunction != nullptr) {
return _llvmFunction;
} else {
llvm::FunctionType * funcType = llvmFunctionType ();
llvm::Function::LinkageTypes linkageType;
if (isExported ()) {
// TODO: Handle static and dynamic libraries differently - if omni will have static libraries, that is.
linkageType = llvm::Function::ExternalLinkage;
} else {
linkageType = llvm::Function::InternalLinkage;
}
_llvmFunction = llvm::Function::Create (funcType, linkageType, getName (), & getModule ()->llvmModule ());
if (isExported ()) {
_llvmFunction->setDLLStorageClass (llvm::GlobalValue::DLLExportStorageClass);
}
auto mainBlock = llvm::BasicBlock::Create (getContext ()->llvmContext (), "__entry__", _llvmFunction);
getBody ()->llvmEmitIntoExistingBlock (mainBlock);
return _llvmFunction;
}
}
| 5,990 |
C++
| 35.754601 | 185 | 0.708013 |
daniel-kun/omni/source/omni/core/model/if_statement.cpp
|
#include <omni/core/model/if_statement.hpp>
#include <omni/core/context.hpp>
#include <omni/core/model/expression.hpp>
#include <omni/core/model/block.hpp>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/NoFolder.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info if_statementMetaInfo;
}
/**
Initializes this if_statement with the given condition and the given true- and elseBlocks.
@param condition The condition depending on which either the trueBlock or the elseBlock will be executed. The condition must be provided.
@param trueBlock The block that will be executed when the condition is true. The trueBlock must be provided.
@param elseBlock The block that will be executed when the condition is false. The elseBlock is optional and can be nullptr.
**/
omni::core::model::if_statement::if_statement (std::shared_ptr <expression> condition,
std::shared_ptr <block> trueBlock,
std::shared_ptr <block> elseBlock) :
statement ()
{
setCondition (condition);
setTrueBlock (trueBlock);
setElseBlock (elseBlock);
}
omni::core::model::meta_info & omni::core::model::if_statement::getStaticMetaInfo ()
{
return omniMetaImpl::if_statementMetaInfo;
}
omni::core::model::meta_info & omni::core::model::if_statement::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::if_statement::getDomain () const
{
return domain::if_statement;
}
void omni::core::model::if_statement::setCondition (std::shared_ptr <omni::core::model::expression> condition)
{
setComponent (domain::expression, "condition", condition);
}
/**
@return Returns the condition depending on which either the trueBlock or the elseBlock will be excuted.
**/
std::shared_ptr <omni::core::model::expression> omni::core::model::if_statement::getCondition ()
{
return getComponentAs <expression> (domain::expression, "condition");
}
/**
@return Returns the condition depending on which either the trueBlock or the elseBlock will be excuted.
**/
const std::shared_ptr <omni::core::model::expression> omni::core::model::if_statement::getCondition () const
{
return getComponentAs <expression> (domain::expression, "condition");
}
void omni::core::model::if_statement::setTrueBlock (std::shared_ptr <omni::core::model::block> trueBlock)
{
setComponent (domain::block, "trueBlock", trueBlock);
}
/**
@return Returns the block that will be execute when the condition is true. Is never nullptr.
**/
std::shared_ptr <omni::core::model::block> omni::core::model::if_statement::getTrueBlock ()
{
return getComponentAs <block> (domain::block, "trueBlock");
}
/**
@return Returns the block that will be execute when the condition is true. Is never nullptr.
**/
const std::shared_ptr <omni::core::model::block> omni::core::model::if_statement::getTrueBlock () const
{
return getComponentAs <block> (domain::block, "trueBlock");
}
void omni::core::model::if_statement::setElseBlock (std::shared_ptr <omni::core::model::block> elseBlock)
{
setComponent (domain::block, "elseBlock", elseBlock);
}
/**
@return Returns the block that will be execute when the condition is false. Can be nullptr.
**/
std::shared_ptr <omni::core::model::block> omni::core::model::if_statement::getElseBlock ()
{
return getComponentAs <block> (domain::block, "elseBlock");
}
/**
@return Returns the block that will be execute when the condition is false. Can be nullptr.
**/
const std::shared_ptr <omni::core::model::block> omni::core::model::if_statement::getElseBlock () const
{
return getComponentAs <block> (domain::block, "elseBlock");
}
/**
@internal
**/
omni::core::statement_emit_result omni::core::model::if_statement::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
llvm::BasicBlock * llvmTrueBlock = getTrueBlock ()->llvmEmit (llvmBasicBlock).getContinueBlock ();
llvm::BasicBlock * llvmFalseBlock = nullptr;
bool terminatorNeeded = false;
std::shared_ptr <block> elseBlock = getElseBlock ();
if (elseBlock != nullptr) {
llvmFalseBlock = elseBlock->llvmEmit (llvmBasicBlock).getContinueBlock ();
if (llvmFalseBlock->getTerminator () == nullptr) {
terminatorNeeded = true;
}
}
if (llvmTrueBlock->getTerminator () == nullptr) {
terminatorNeeded = true;
}
llvm::BasicBlock * result = llvmBasicBlock;
if (terminatorNeeded) {
result = llvm::BasicBlock::Create (llvmBasicBlock->getContext (), "", llvmBasicBlock->getParent ());
if (llvmTrueBlock->getTerminator () == nullptr) {
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmTrueBlock);
builder.CreateBr (result);
}
if (llvmFalseBlock != nullptr && llvmFalseBlock->getTerminator () == nullptr) {
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmFalseBlock);
builder.CreateBr (result);
}
}
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
builder.CreateCondBr (getCondition ()->llvmEmit (llvmBasicBlock).getValue (), llvmTrueBlock, llvmFalseBlock);
return statement_emit_result (result, nullptr);
}
| 5,286 |
C++
| 34.013245 | 137 | 0.693908 |
daniel-kun/omni/source/omni/core/model/while_statement.cpp
|
#include <omni/core/model/while_statement.hpp>
#include <omni/core/model/expression.hpp>
#include <omni/core/model/block.hpp>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/NoFolder.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info while_statementMetaInfo;
}
/**
Initializes this while_statement without a condition and a body.
The condition can be set via setCondition (), and the body via setBody ().
**/
omni::core::model::while_statement::while_statement () :
statement ()
{
}
/**
Initializes this while_statement with the given condition and the given body.
This while_statement will repeatedly execute the given body while the given condition is true.
**/
omni::core::model::while_statement::while_statement (std::shared_ptr <omni::core::model::expression> condition, std::shared_ptr <omni::core::model::block> body) :
statement ()
{
setCondition (condition);
setBody (body);
}
omni::core::model::meta_info & omni::core::model::while_statement::getStaticMetaInfo ()
{
return omniMetaImpl::while_statementMetaInfo;
}
omni::core::model::meta_info & omni::core::model::while_statement::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::while_statement::getDomain () const
{
return domain::while_statement;
}
/**
Returns the condition on which the while_statement keeps repeating it's body.
**/
std::shared_ptr <omni::core::model::expression> omni::core::model::while_statement::getCondition ()
{
return getComponentAs <expression> (domain::expression, "condition");
}
/**
Returns the condition on which the while_statement keeps repeating it's body.
**/
const std::shared_ptr <omni::core::model::expression> omni::core::model::while_statement::getCondition () const
{
return getComponentAs <expression> (domain::expression, "condition");
}
void omni::core::model::while_statement::setCondition (std::shared_ptr <omni::core::model::expression> condition)
{
setComponent (domain::expression, "condition", condition);
}
/**
Returns the body that is being repeated by this whil_statement while the condition is true.
**/
std::shared_ptr <omni::core::model::block> omni::core::model::while_statement::getBody ()
{
return getComponentAs <block> (domain::expression, "body");
}
/**
Returns the body that is being repeated by this whil_statement while the condition is true.
**/
const std::shared_ptr <omni::core::model::block> omni::core::model::while_statement::getBody () const
{
return getComponentAs <block> (domain::expression, "body");
}
void omni::core::model::while_statement::setBody (std::shared_ptr <omni::core::model::block> body)
{
return setComponent (domain::expression, "body", body);
}
omni::core::statement_emit_result omni::core::model::while_statement::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
auto whileBlock = llvm::BasicBlock::Create (llvmBasicBlock->getContext (), "", llvmBasicBlock->getParent ());
auto whileBodyBlock = getBody ()->llvmEmit (llvmBasicBlock);
auto continueBlock = llvm::BasicBlock::Create (llvmBasicBlock->getContext (), "", llvmBasicBlock->getParent ());
// First, jump to the while block
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
builder.CreateBr (whileBlock);
llvm::IRBuilder <true, llvm::NoFolder> whileBuilder (whileBlock);
whileBuilder.CreateCondBr (getCondition ()->llvmEmit (whileBlock).getValue (), whileBodyBlock.getContinueBlock (), continueBlock);
llvm::IRBuilder <true, llvm::NoFolder> whileBodyBuilder (whileBodyBlock.getContinueBlock ());
whileBodyBuilder.CreateBr (whileBlock);
return statement_emit_result (continueBlock, nullptr);
}
| 3,732 |
C++
| 33.247706 | 162 | 0.726688 |
daniel-kun/omni/source/omni/core/model/variable_declaration_expression.cpp
|
#include <omni/core/model/variable_declaration_expression.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/expression.hpp>
#include <omni/core/model/variable_assignment_expression.hpp>
#include <llvm/IR/Value.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/NoFolder.h>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info variable_declaration_expressionMetaInfo;
}
omni::core::model::variable_declaration_expression::variable_declaration_expression () :
pure_expression (),
_type (),
_llvmPointerValue (nullptr)
{
}
/**
@param variableType The type of the variable.
**/
omni::core::model::variable_declaration_expression::variable_declaration_expression (std::shared_ptr <omni::core::model::type> type) :
pure_expression (),
_type (type),
_llvmPointerValue (nullptr)
{
}
/**
**/
omni::core::model::variable_declaration_expression::variable_declaration_expression (std::shared_ptr <omni::core::model::expression> initializer) :
pure_expression (),
_type (),
_llvmPointerValue (nullptr)
{
setInitializationExpression (initializer);
}
omni::core::model::meta_info & omni::core::model::variable_declaration_expression::getStaticMetaInfo ()
{
return omniMetaImpl::variable_declaration_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::variable_declaration_expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::variable_declaration_expression::getDomain () const
{
return domain::variable_declaration_expression;
}
/**
Returns the type of this variable_declaration_expression.
**/
std::shared_ptr <omni::core::model::type> omni::core::model::variable_declaration_expression::getType () const
{
return _type;
}
/**
Changes the type of this variable to `type' and sets the initializer to nullptr.
**/
void omni::core::model::variable_declaration_expression::setType (std::shared_ptr <omni::core::model::type> type)
{
_type = type;
removeComponent (domain::expression, "initializer");
}
/**
Returns the expression that this variable will be initialized with. Can be nullptr.
**/
std::shared_ptr <omni::core::model::expression> omni::core::model::variable_declaration_expression::getInitializationExpression () const
{
return getComponentAs <expression> (domain::expression, "initializer");
}
/**
Sets the initialization-expression of this varibale to `initializer' and changes this variable's type to the type of the expression.
**/
void omni::core::model::variable_declaration_expression::setInitializationExpression (std::shared_ptr <omni::core::model::expression> initializer)
{
setComponent (domain::expression, "initializer", initializer);
_type = initializer->getType ();
}
/**
Internal
**/
llvm::Value * omni::core::model::variable_declaration_expression::llvmPointerValue ()
{
return _llvmPointerValue;
}
omni::core::statement_emit_result omni::core::model::variable_declaration_expression::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
_llvmPointerValue = builder.CreateAlloca (_type->llvmType ());
std::shared_ptr <expression> initializationExpression = getInitializationExpression ();
if (initializationExpression != nullptr) {
return variable_assignment_expression::llvmEmitImpl (llvmBasicBlock, * this, * initializationExpression);
} else {
return statement_emit_result (llvmBasicBlock, builder.CreateLoad (_llvmPointerValue));
}
}
| 3,613 |
C++
| 31.267857 | 147 | 0.734846 |
daniel-kun/omni/source/omni/core/model/function_prototype.cpp
|
#include <omni/core/model/function_prototype.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/parameter.hpp>
#include <llvm/IR/Type.h>
#include <llvm/IR/Function.h>
#include <boost/lexical_cast.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info function_prototypeMetaInfo;
}
/**
@brief Initializes this function prototype with the given function name, return-type and parameters.
@param name The name of the function for this prototype.
@param returnType The return type of the function for this prototype.
@param parameters An optional list of parameters that the function for this prototype receives.
**/
omni::core::model::function_prototype::function_prototype (std::string const & name,
std::shared_ptr <type> returnType,
std::vector <std::shared_ptr <omni::core::model::parameter>> parameters) :
scope (name),
_returnType (returnType),
_paramCount (0u)
{
setParameters (parameters);
}
omni::core::model::function_prototype::~function_prototype ()
{
}
omni::core::model::meta_info & omni::core::model::function_prototype::getStaticMetaInfo ()
{
return omniMetaImpl::function_prototypeMetaInfo;
}
omni::core::model::meta_info & omni::core::model::function_prototype::getMetaInfo () const
{
return getStaticMetaInfo ();
}
/**
@brief Sets the return-type of this function.
Can be nullptr, if the function should have a void return-type (i.e. does not return a value).
It is important to make sure that the body contains return_statements for each control-flow that match the new return-type.
@param returnType The new return-type of this function.
**/
void omni::core::model::function_prototype::setReturnType (std::shared_ptr <type> returnType)
{
_returnType = returnType;
}
/**
@brief Returns the type of the value that this function returns when it is called at runtime.
Returns nullptr, if this function does not return a value (i.e. is a "void function").
If this function's return-type is non-void, the body must contain a return_statement that returns a value of the same type in each control-flow.
The returned type is const and can not be modified.
**/
const std::shared_ptr <omni::core::model::type> omni::core::model::function_prototype::getReturnType () const
{
return _returnType;
}
/**
@brief Returns the type of the value that this function returns when it is called at runtime.
Returns nullptr, if this function does not return a value (i.e. is a "void function").
If this function's return-type is non-void, the body must contain a return_statement that returns a value of the same type in each control-flow.
The returned type can be modified.
**/
std::shared_ptr <omni::core::model::type> omni::core::model::function_prototype::getReturnType ()
{
return _returnType;
}
/**
@brief Adds a parameter at the end of the list of parameters that this function should take.
The parameter's parent will be changed to this funtion_protype.
@param parameter The parameter that should be appended to the list of parameters for this function.
@see function_prototype()
**/
void omni::core::model::function_prototype::appendParameter (std::shared_ptr <parameter> parameter)
{
setComponent (domain::parameter, "parameter" + boost::lexical_cast <std::string> (++_paramCount), parameter);
}
/**
@brief Sets the list of parameters that this function takes to the given parameters;
All parameters that have been set before will be cleared.
The parameter's parents will be changed to this funtion_protype.
@param parameters The list of parameters that this function should take.
**/
void omni::core::model::function_prototype::setParameters (std::vector <std::shared_ptr <parameter>> parameters)
{
_paramCount = 0u;
clearComponents (domain::parameter);
for (auto i : parameters) {
appendParameter (i);
}
}
/**
@brief Returns the list of parameters that this function takes.
The returned list is a copy of the paremeter-list of this function_prototype.
The contained parameters are const and can not be modified.
@return The list of parameters that this function takes.
**/
std::vector <std::shared_ptr <omni::core::model::parameter>> omni::core::model::function_prototype::getParameters ()
{
std::vector <std::shared_ptr <omni::core::model::parameter>> result;
for (auto i : getComponentsStartingWithAs <parameter> (domain::parameter, "parameter")) {
result.push_back (i.second);
}
return result;
}
/*
Internal.
Returns an llvm::FunctionType with the same characteristics as this function_prototype.
*/
llvm::FunctionType * omni::core::model::function_prototype::llvmFunctionType ()
{
std::vector <llvm::Type *> params;
for (auto p : getParameters ()) {
params.push_back (p->getType ()->llvmType ());
}
return llvm::FunctionType::get (getReturnType ()->llvmType (), params, false);
}
| 5,058 |
C++
| 32.726666 | 144 | 0.717477 |
daniel-kun/omni/source/omni/core/model/type_mismatch_error.cpp
|
#include <omni/core/model/type_mismatch_error.hpp>
#include <omni/core/model/type.hpp>
#include <sstream>
namespace {
/**
Builds and returns an error message that leftType is not equal to rightType.
**/
std::string buildTypeMismatchErrorMessage (omni::core::model::type & leftType, omni::core::model::type & rightType)
{
std::stringstream result;
result << "Type mismatch error: Type " << leftType.getName () << " does not equal Type " << rightType.getName ();
return result.str ();
}
}
omni::core::model::type_mismatch_error::type_mismatch_error (type & leftType, type & rightType) :
std::runtime_error (buildTypeMismatchErrorMessage (leftType, rightType).c_str ())
{
}
| 691 |
C++
| 29.086955 | 117 | 0.70767 |
daniel-kun/omni/source/omni/core/model/literal_expression.cpp
|
#include <omni/core/model/literal_expression.hpp>
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/not_implemented_error.hpp>
#include <sstream>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info literal_expressionMetaInfo;
}
/**
@brief Creates a new literal_expression from the human-readable `text'.
The format of a human-readable text that can be converted to a literal follows this form:
<number> <type specifier>
The numer can be typed in the current locale's form, e.g. in English environments, it uses "," as the thousands separator and "." as the decimal separator,
whereas e.g. in German environments, "." as the thousands separator and "," as the decimal separator.
When the same literal will be converted to text on a different locale, it will automatically adapt to the new environment. The internal storage is binary and
therefore independent from the locale.
The resulting object will be a subclass of literal_expression, for example builtin_literal_expression.
@param context The context that the literal should be created in.
@param text The text that represents the literal and should be converted to a literal.
@param originatingLiteral If the text was provided as a modification of an existing literal, pass that literal as the `originatingLiteral'. A missing
type specifier will then be derived from the origin.
@return A new literal_expression, if text can be converted to any kind of literal_expression. nullptr, if text is empty or can not be converted.
**/
std::shared_ptr <omni::core::model::literal_expression> omni::core::model::literal_expression::fromString (
context & context,
std::string const & text,
literal_expression * originatingLiteral)
{
unsigned int value = 0u;
std::stringstream str (text);
str >> value;
auto result = std::make_shared <builtin_literal_expression <int>> (context, value);
return result;
}
omni::core::model::meta_info & omni::core::model::literal_expression::getStaticMetaInfo ()
{
return omniMetaImpl::literal_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::literal_expression::getMetaInfo () const
{
return literal_expression::getStaticMetaInfo ();
}
/**
@brief Connects a handler to the ValueChanged signal that is emitted, after the current value of this builtin_literal has been changed.
@param handler The handler that will be called after the current value changed.
@return A signal connection that can be used disconnect this handler.
**/
boost::signals2::connection omni::core::model::literal_expression::connectValueChanged (ValueChangedSignal::slot_type handler)
{
return _valueChangedSignal.connect (handler);
}
/**
@brief Emits the signals ValueChanged and Changed, int his order.
When overriding this function, make sure to call the base class implementation. Otherwise, all other functionality that depends on the ValueChanged and Changed signals will break.
@param oldValue The value that this builtin_literal had, before it was changed.
@param newValue The new, current value of this builtin_literal.
**/
void omni::core::model::literal_expression::valueChanged (boost::any oldValue, boost::any newValue)
{
_valueChangedSignal (* this, oldValue, newValue);
changed ();
}
| 3,314 |
C++
| 43.199999 | 179 | 0.766445 |
daniel-kun/omni/source/omni/core/model/cast_expression.cpp
|
#include <omni/core/model/cast_expression.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info cast_expressionMetaInfo;
}
omni::core::model::cast_expression::cast_expression () :
pure_expression ()
{
}
omni::core::model::meta_info & omni::core::model::cast_expression::getStaticMetaInfo ()
{
return omniMetaImpl::cast_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::cast_expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
| 531 |
C++
| 23.181817 | 87 | 0.725047 |
daniel-kun/omni/source/omni/core/model/builtin_literal_expression.cpp
|
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/context.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/type_mismatch_error.hpp>
#include <llvm/IR/Constants.h>
#include <sstream>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info builtin_literal_expressionMetaInfo;
}
namespace {
/*
Helper base-class to provide signed values.
See the template specialisations of value_provider below, each picking the correct helper base-class.
*/
class signed_provider {
public:
template <typename T>
static llvm::Value * provideValue (llvm::Type * type, T value)
{
return llvm::ConstantInt::getSigned (type, value);
}
};
/*
Helper base-class to provide unsigned values.
See the template specialisations of value_provider below, each picking the correct helper base-class.
*/
class unsigned_provider {
public:
template <typename T>
static llvm::Value * provideValue (llvm::Type * type, T value)
{
return llvm::ConstantInt::get (type, value);
}
};
template <typename T> class value_provider {};
template <> class value_provider <bool> : public signed_provider { };
template <> class value_provider <char> : public signed_provider { };
template <> class value_provider <signed char> : public signed_provider { };
template <> class value_provider <unsigned char> : public unsigned_provider { };
template <> class value_provider <signed short> : public signed_provider { };
template <> class value_provider <unsigned short> : public unsigned_provider { };
template <> class value_provider <signed int> : public signed_provider { };
template <> class value_provider <unsigned int> : public unsigned_provider { };
template <> class value_provider <signed long> : public signed_provider { };
template <> class value_provider <unsigned long> : public unsigned_provider { };
template <> class value_provider <signed long long> : public signed_provider { };
template <> class value_provider <unsigned long long> : public unsigned_provider { };
}
/**
@brief Initializes this builtin_literal_expression in the given context with the given value.
A builtin_literal_expression can only exist with a context, since the context defines how the given type is stored and how it behaves.
@param context The context that this builtin_literal_expression can be used in.
@param value The value that this builtin_literal_expression will emit.
**/
template <typename T>
omni::core::model::builtin_literal_expression <T>::builtin_literal_expression (context & context, T value) :
_type (type::sharedBasicType (context, native_type_to_type_class <T>::typeClass)),
_value (value)
{
}
template <typename T>
omni::core::model::meta_info & omni::core::model::builtin_literal_expression <T>::getStaticMetaInfo ()
{
return omniMetaImpl::builtin_literal_expressionMetaInfo;
}
template <typename T>
omni::core::model::meta_info & omni::core::model::builtin_literal_expression <T>::getMetaInfo () const
{
return builtin_literal_expression <T>::getStaticMetaInfo ();
}
template <typename T>
std::string omni::core::model::builtin_literal_expression <T>::toString (bool fullyQualified) const
{
std::stringstream str;
str << _value;
if (fullyQualified) {
str << getType ()->toString (false);
}
return str.str ();
}
template <typename T>
omni::core::domain omni::core::model::builtin_literal_expression <T>::getDomain () const
{
return domain::builtin_literal_expression;
}
template <typename T>
std::shared_ptr <omni::core::model::type> omni::core::model::builtin_literal_expression <T>::getType () const
{
return _type;
}
/**
@brief Changes the value of this builtin_literal to `value'.
Emits the signal ValueChanged.
@param value The new value for this builtin_literal
**/
template <typename T>
void omni::core::model::builtin_literal_expression <T>::setValue (T value)
{
T oldValue = _value;
_value = value;
valueChanged (oldValue, _value);
}
/**
@brief Returns the current value for this builtin_literal.
@return Te current value for this builtin_literal.
**/
template <typename T>
T omni::core::model::builtin_literal_expression <T>::getValue () const
{
return _value;
}
template <typename T>
omni::core::statement_emit_result omni::core::model::builtin_literal_expression <T>::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
if (native_type_to_type_class<T>::typeClass != getType ()->getTypeClass ()) {
throw type_mismatch_error (* getType ()->getContext ()->sharedBasicType (native_type_to_type_class<T>::typeClass), * getType ());
}
return statement_emit_result (
llvmBasicBlock,
value_provider <T>::provideValue (getType ()->llvmType (), _value));
}
// We have explicit template instantiations for all supported types.
// That way, we do not need to define everything in the header file.
template class omni::core::model::builtin_literal_expression <bool>;
template class omni::core::model::builtin_literal_expression <char>;
template class omni::core::model::builtin_literal_expression <signed char>;
template class omni::core::model::builtin_literal_expression <unsigned char>;
template class omni::core::model::builtin_literal_expression <signed short>;
template class omni::core::model::builtin_literal_expression <unsigned short>;
template class omni::core::model::builtin_literal_expression <signed int>;
template class omni::core::model::builtin_literal_expression <unsigned int>;
template class omni::core::model::builtin_literal_expression <signed long>;
template class omni::core::model::builtin_literal_expression <unsigned long>;
template class omni::core::model::builtin_literal_expression <signed long long>;
template class omni::core::model::builtin_literal_expression <unsigned long long>;
| 5,846 |
C++
| 35.31677 | 137 | 0.72819 |
daniel-kun/omni/source/omni/core/model/function_call_expression.cpp
|
#include <omni/core/model/function_call_expression.hpp>
#include <omni/core/model/function_prototype.hpp>
#include <llvm/IR/Function.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/NoFolder.h>
#include <boost/lexical_cast.hpp>
// See meta_info.cpp for initialization.
namespace omniMetaImpl {
extern omni::core::model::meta_info function_call_expressionMetaInfo;
}
/**
Initializes this function call expression without any function to call.
**/
omni::core::model::function_call_expression::function_call_expression () :
modifying_expression (),
_function (),
_paramCount (0u)
{
}
/**
Initializes this function call expression to call the function `func'.
**/
omni::core::model::function_call_expression::function_call_expression (std::shared_ptr <function_prototype> func) :
modifying_expression (),
_function (func),
_paramCount (0u)
{
}
omni::core::model::function_call_expression::function_call_expression (std::shared_ptr <function_prototype> func, std::vector <std::shared_ptr <expression>> parameters) :
modifying_expression (),
_function (func),
_paramCount (0u)
{
setParameters (parameters);
}
omni::core::model::meta_info & omni::core::model::function_call_expression::getStaticMetaInfo ()
{
return omniMetaImpl::function_call_expressionMetaInfo;
}
omni::core::model::meta_info & omni::core::model::function_call_expression::getMetaInfo () const
{
return getStaticMetaInfo ();
}
omni::core::domain omni::core::model::function_call_expression::getDomain () const
{
return domain::function_call_expression;
}
std::shared_ptr <omni::core::model::type> omni::core::model::function_call_expression::getType () const
{
return _function->getReturnType ();
}
/**
Sets the function that this expression should call to `func'.
**/
void omni::core::model::function_call_expression::setFunction (std::shared_ptr <function_prototype> func)
{
_function = func;
}
/**
Returns the function that this expression should call. Can be null if no function has been set.
**/
const std::shared_ptr <omni::core::model::function_prototype> omni::core::model::function_call_expression::getFunction () const
{
return _function;
}
/**
Returns the function that this expression should call. Can be null if no function has been set.
**/
std::shared_ptr <omni::core::model::function_prototype> omni::core::model::function_call_expression::getFunction ()
{
return _function;
}
/**
Adds the parameter to the list of parameters that will be fed to the function-call. Note that the number and types of parameters
must match those of the function that has been passed to the ctor or was set using setFunction().
@param parameter The parameter that will be fed to the function that will be called by this expression.
**/
void omni::core::model::function_call_expression::appendParameter (std::shared_ptr <expression> parameter)
{
setComponent (domain::expression, "parameter" + boost::lexical_cast <std::string> (++ _paramCount), parameter);
}
/**
Sets a list of parameter that will be fed to the function-call. Note that the number and types of parameters
must match those of the function that has been passed to the ctor or was set using setFunction().
@param parameters The list of parameters that will be fed to thefunction that will be called by this expression.
**/
void omni::core::model::function_call_expression::setParameters (std::vector <std::shared_ptr <expression>> parameters)
{
clearComponents ();
for (auto i : parameters) {
appendParameter (i);
}
}
std::vector <std::shared_ptr <omni::core::model::expression>> omni::core::model::function_call_expression::getParameters ()
{
std::vector <std::shared_ptr <omni::core::model::expression>> result;
for (auto i : getComponentsStartingWithAs <expression> (domain::expression, "parameter")) {
result.push_back (i.second);
}
return result;
}
/**
@return Returns a llvm::CallInst that has been constructed by a call to llvm::IRBuilder<>::CreateCall.
You can safely dynamic_cast the result to a llvm::CallInst.
**/
omni::core::statement_emit_result omni::core::model::function_call_expression::llvmEmit (llvm::BasicBlock * llvmBasicBlock)
{
llvm::IRBuilder <true, llvm::NoFolder> builder (llvmBasicBlock);
std::vector <llvm::Value*> llvmParameterArguments;
for (auto p : getParameters ()) {
llvm::Value * val = p->llvmEmit (llvmBasicBlock).getValue ();
llvmParameterArguments.push_back (val);
}
return statement_emit_result (llvmBasicBlock, builder.CreateCall (_function->llvmFunction (), llvmParameterArguments));
}
| 4,655 |
C++
| 33.488889 | 170 | 0.723523 |
daniel-kun/omni/source/omni/core/tools/string.cpp
|
#include <omni/core/tools/string.hpp>
#include <cctype>
#include <algorithm>
/**
@brief Returns true, wenn `string' starts with the text `startText'.
Always returns true, wenn startText is an empty string.
@param string The string that is tested whether it starts with `startText'.
@param startText The text that string should start with.
@return True, wenn `string' starts with the text `startText'. False otherwise.
**/
bool omni::core::tools::starts_with (std::string const & string, std::string const & startText)
{
if (string.size () < startText.size ()) {
return false;
}
for (std::size_t i = 0u; i < startText.size (); ++ i) {
if (startText [i] != string [i]) {
return false;
}
}
return true;
}
/**
@brief Returns true, when text can be interpreted as a numeric value.
This includes simple digit-only text like 123, but also text with decimal and thousands separators like 1,234.5678.
@param text The text that is checked for numerical content.
@return True, when text can be interpreted as a numeric value.
**/
bool omni::core::tools::is_numeric (std::string const & text)
{
return std::find_if (text.begin (), text.end (), [] (char p) { return ! std::isdigit (p) && p != '.' && p != ','; }) == text.end ();
}
| 1,283 |
C++
| 32.789473 | 136 | 0.660951 |
daniel-kun/omni/source/omni/core/input/abstract_syntax_element.cpp
|
#include <omni/core/input/abstract_syntax_element.hpp>
omni::core::input::abstract_syntax_element::abstract_syntax_element () :
_possibleSubstitutions ()
{
}
omni::core::input::abstract_syntax_element::abstract_syntax_element (std::vector <std::shared_ptr <omni::core::input::syntax_element>> possibleSubstitutions) :
_possibleSubstitutions (possibleSubstitutions)
{
}
std::vector <omni::core::input::syntax_suggestion> omni::core::input::abstract_syntax_element::suggestImpl (std::string input, std::size_t templatePosition, std::set <syntax_element *> alreadyVisistedElements)
{
if (alreadyVisistedElements.find (this) != alreadyVisistedElements.end ()) {
return std::vector <omni::core::input::syntax_suggestion> ();
}
alreadyVisistedElements.insert (this);
std::vector <omni::core::input::syntax_suggestion> result;
for (auto i : _possibleSubstitutions) {
auto suggestions = i->suggestImpl (input, templatePosition, alreadyVisistedElements);
result.insert (result.end (), suggestions.begin (), suggestions.end ());
}
return result;
}
void omni::core::input::abstract_syntax_element::setPossibleSubstitutions (std::vector <std::shared_ptr <omni::core::input::syntax_element>> possibleSubstitutions)
{
_possibleSubstitutions = possibleSubstitutions;
}
std::vector <std::shared_ptr <omni::core::input::syntax_element>> omni::core::input::abstract_syntax_element::getPossibleSubstitutions () const
{
return _possibleSubstitutions;
}
| 1,507 |
C++
| 40.888888 | 209 | 0.729927 |
daniel-kun/omni/source/omni/core/input/regex_template_element.cpp
|
#include <omni/core/input/regex_template_element.hpp>
#include <omni/core/input/template_visitor.hpp>
void omni::core::input::regex_template_element::visit (template_visitor & visitor)
{
visitor.visitRegexTemplateElement (* this);
}
| 238 |
C++
| 28.874996 | 82 | 0.760504 |
daniel-kun/omni/source/omni/core/input/fixed_template_element.cpp
|
#include <omni/core/input/fixed_template_element.hpp>
#include <omni/core/input/template_visitor.hpp>
omni::core::input::fixed_template_element::fixed_template_element (syntax_element & parent, std::size_t templateIndex, std::string text):
template_element (parent, templateIndex),
_text (text)
{
}
std::string omni::core::input::fixed_template_element::getText () const
{
return _text;
}
std::vector <std::string> omni::core::input::fixed_template_element::suggest (std::string input)
{
if (_text.find (input) == 0u) {
return std::vector <std::string> {
_text
};
} else {
return std::vector <std::string> ();
}
}
void omni::core::input::fixed_template_element::visit (template_visitor & visitor)
{
visitor.visitFixedTemplateElement (* this);
}
| 824 |
C++
| 26.499999 | 137 | 0.652913 |
daniel-kun/omni/source/omni/core/input/syntax_tree_parser_xml.cpp
|
#include <omni/core/input/syntax_tree_parser_xml.hpp>
#include <omni/core/input/syntax_element.hpp>
#include <omni/core/input/abstract_syntax_element.hpp>
#include <omni/core/input/concrete_syntax_element.hpp>
#include <rapidxml/rapidxml.hpp>
#include <memory>
#include <stdexcept>
namespace {
std::shared_ptr <omni::core::input::abstract_syntax_element> parseAbstract (rapidxml::xml_node <char> * node)
{
/*
using namespace rapidxml;
auto result = std::make_shared <omni::core::input::abstract_syntax_element> ();
result->setName (node->first_attribute ("name")->value ());
xml_node <char> * child = node->first_node ();
return result;
*/
return std::make_shared <omni::core::input::abstract_syntax_element> ();
}
}
template <typename T>
class array_deleter : public std::default_delete <char> {
public:
void operator() (T *p)
{
delete [] p;
}
};
std::shared_ptr <omni::core::input::syntax_element> omni::core::input::syntax_tree_parser_xml::parse (std::istream & stream)
{
using namespace rapidxml;
const std::string nodeNameConcrete = "concrete";
const std::string nodeNameAbstract = "abstract";
const std::string nodeNameFixed = "fixed";
const std::string nodeNameVariable = "variable";
const std::string nodeNameSyntax = "syntax";
const std::string nodeNameIndentRight = "indentright";
const std::string nodeNameIndentLeft = "indentleft";
std::string content;
while (stream >> content) {
}
xml_document <> doc;
auto deleter = [] (char *p) -> void { delete [] p;};
std::unique_ptr <char, decltype (deleter)> buffer (new char [content.size ()], deleter);
std::copy (content.begin (), content.end (), buffer.get ());
doc.parse <0> (buffer.get ());
xml_node <char> * root = doc.first_node ();
if (root->name () != std::string ("syntax")) {
throw std::logic_error ("Invalid XML syntax for syntax description file.");
}
xml_node <char> * node = root->first_node ();
while (node != nullptr) {
if (node->name () == nodeNameAbstract) {
auto abstract = parseAbstract (node);
} else if (node->name () == nodeNameConcrete) {
}
}
return nullptr;
}
| 2,246 |
C++
| 31.1 | 124 | 0.639359 |
daniel-kun/omni/source/omni/core/input/input_state.cpp
|
#include <omni/core/input/input_state.hpp>
| 43 |
C++
| 20.99999 | 42 | 0.767442 |
daniel-kun/omni/source/omni/core/input/syntax_suggestion.cpp
|
#include <omni/core/input/syntax_suggestion.hpp>
omni::core::input::syntax_suggestion::syntax_suggestion (syntax_element & syntaxElement, std::size_t templateIndex, std::string text) :
syntaxElement (& syntaxElement),
templateIndex (templateIndex),
text (text)
{
}
| 278 |
C++
| 29.999997 | 135 | 0.733813 |
daniel-kun/omni/source/omni/core/input/syntax_element.cpp
|
#include <omni/core/input/syntax_element.hpp>
void omni::core::input::syntax_element::setName (std::string const & name)
{
_name = name;
}
std::string omni::core::input::syntax_element::getName () const
{
return _name;
}
std::shared_ptr <omni::core::input::template_element> omni::core::input::syntax_element::templateElementAt (std::size_t templatePosition)
{
return nullptr;
}
std::size_t omni::core::input::syntax_element::templateElementCount () const
{
return 0u;
}
std::vector <omni::core::input::syntax_suggestion> omni::core::input::syntax_element::suggest (std::string input, std::size_t templateIndex)
{
std::set <syntax_element *> alreadyVisitedElements;
return suggestImpl (input, templateIndex, alreadyVisitedElements);
}
| 764 |
C++
| 26.321428 | 140 | 0.715969 |
daniel-kun/omni/source/omni/core/input/repeater_template_element.cpp
|
#include <omni/core/input/repeater_template_element.hpp>
#include <omni/core/input/template_visitor.hpp>
void omni::core::input::repeater_template_element::visit (template_visitor & visitor)
{
visitor.visitRepeaterTemplateElement (* this);
}
| 247 |
C++
| 29.999996 | 85 | 0.769231 |
daniel-kun/omni/source/omni/core/input/template_element.cpp
|
#include <omni/core/input/template_element.hpp>
omni::core::input::template_element::template_element (
syntax_element & parent,
std::size_t templateIndex) :
_parent (parent),
_templateIndex (templateIndex)
{
}
/**
If this template_element contains a syntax_element in some form, return that syntax_element.
If this template_element is not a placeholder for a syntax_element, nullptr is returned.
**/
std::shared_ptr <omni::core::input::syntax_element> omni::core::input::template_element::dive ()
{
return nullptr;
}
| 547 |
C++
| 27.842104 | 96 | 0.71298 |
daniel-kun/omni/source/omni/core/input/variable_template_element.cpp
|
#include <omni/core/input/variable_template_element.hpp>
#include <omni/core/input/variable_template_provider.hpp>
#include <omni/core/input/template_visitor.hpp>
omni::core::input::variable_template_element::variable_template_element (
syntax_element & parent,
std::size_t templateIndex,
variable_template_provider & provider) :
template_element (parent, templateIndex),
_provider (provider)
{
}
std::vector <std::string> omni::core::input::variable_template_element::suggest (std::string input)
{
return _provider.provide (input);
}
void omni::core::input::variable_template_element::visit (template_visitor & visitor)
{
visitor.visitVariableTemplateElement (* this);
}
| 710 |
C++
| 29.913042 | 99 | 0.730986 |
daniel-kun/omni/source/omni/core/input/template_visitor.cpp
|
#include <omni/core/input/template_visitor.hpp>
| 48 |
C++
| 23.499988 | 47 | 0.791667 |
daniel-kun/omni/source/omni/core/input/syntax_template_element.cpp
|
#include <omni/core/input/syntax_template_element.hpp>
#include <omni/core/input/syntax_element.hpp>
#include <omni/core/input/syntax_suggestion.hpp>
#include <omni/core/input/template_visitor.hpp>
omni::core::input::syntax_template_element::syntax_template_element (syntax_element & parent, std::size_t templateIndex, std::shared_ptr <syntax_element> target) :
template_element (parent, templateIndex),
_target (target)
{
}
std::vector <std::string> omni::core::input::syntax_template_element::suggest (std::string input)
{
return std::vector <std::string> ();
}
std::shared_ptr <omni::core::input::syntax_element> omni::core::input::syntax_template_element::dive ()
{
return _target;
}
std::shared_ptr <omni::core::input::syntax_element> omni::core::input::syntax_template_element::getSyntaxElement () const
{
return _target;
}
void omni::core::input::syntax_template_element::visit (template_visitor & visitor)
{
visitor.visitSyntaxTemplateElement (* this);
}
| 992 |
C++
| 31.032257 | 163 | 0.726815 |
daniel-kun/omni/source/omni/core/input/concrete_syntax_element.cpp
|
#include <omni/core/input/concrete_syntax_element.hpp>
#include <omni/core/input/template_element.hpp>
omni::core::input::concrete_syntax_element::concrete_syntax_element (int indentationModifier) :
_templates (),
_indentationModifier (indentationModifier)
{
}
std::shared_ptr <omni::core::input::template_element> omni::core::input::concrete_syntax_element::templateElementAt (std::size_t templatePosition)
{
return _templates [templatePosition];
}
std::size_t omni::core::input::concrete_syntax_element::templateElementCount () const
{
return _templates.size ();
}
void omni::core::input::concrete_syntax_element::setTemplates (std::vector <std::shared_ptr <template_element>> templates)
{
_templates = templates;
}
std::vector <omni::core::input::syntax_suggestion> omni::core::input::concrete_syntax_element::suggestImpl (std::string input, std::size_t templatePosition, std::set <syntax_element *> alreadyVisistedElements)
{
if (alreadyVisistedElements.find (this) != alreadyVisistedElements.end ()) {
return std::vector <omni::core::input::syntax_suggestion> ();
}
alreadyVisistedElements.insert (this);
// Find the next template that "goes one level deeper":
std::size_t nextSyntaxTemplate = templatePosition;
for (std::size_t i = nextSyntaxTemplate; i < _templates.size (); ++i) {
if (_templates [i]->dive () != nullptr) {
nextSyntaxTemplate = i;
break;
}
}
// Make my own suggestions first:
std::vector <syntax_suggestion> result;
for (std::string text : _templates [templatePosition]->suggest (input)) {
result.push_back (syntax_suggestion (* this, nextSyntaxTemplate, text));
}
// And then the suggestions of the underlying syntax_element at the given template position:
std::shared_ptr <syntax_element> elem = _templates [templatePosition]->dive ();
if (elem != nullptr) {
std::vector <syntax_suggestion> elemSuggestions = elem->suggestImpl (input, 0u, alreadyVisistedElements);
result.insert (result.end (), elemSuggestions.begin (), elemSuggestions.end ());
}
return result;
}
| 2,154 |
C++
| 39.660377 | 209 | 0.692665 |
daniel-kun/omni/source/omni/tests/test_utils.cpp
|
#include <omni/tests/test_utils.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/model/function.hpp>
#include <omni/core/model/meta_info.hpp>
#include <omni/core/context.hpp>
#include <omni/core/module_emit_options.hpp>
#include <sstream>
/**
Emits a shared library file with the name fileBaseName.dll. The library exports a function "main" that calls the
function `func'. That way, it does not matter whether func is external or not.
Main automatically has the same return type as func. func and main may not take parameters.
@return The path of the created shared library file.
**/
boost::filesystem::path omni::tests::emitSharedLibraryWithFunction (std::shared_ptr <omni::core::model::function> func,
omni::tests::test_file_manager & testFileManager,
std::string const & fileBaseName,
std::string & functionName)
{
static unsigned int counter = 0;
using namespace omni::core;
// First, add a function that calls the wanted function.
std::shared_ptr <model::type> returnType (func->getReturnType ());
std::shared_ptr <model::block> body (new model::block ());
std::shared_ptr <model::expression> callExpression (new model::function_call_expression (func));
std::shared_ptr <model::statement> returnStatement (new model::return_statement (callExpression));
body->appendStatement (returnStatement);
std::stringstream functionNameBuilder;
functionNameBuilder << "main" << (++ counter);
functionName = functionNameBuilder.str ();
model::module & mod (* func->getModule ());
std::shared_ptr <model::function> caller (new model::function (functionName, returnType, body, std::vector <std::shared_ptr <model::parameter>> (), true));
mod.addFunction (caller);
boost::filesystem::path assemblyFileName = testFileManager.getTestFileName (fileBaseName + ".ll");
mod.emitAssemblyFile (assemblyFileName.string ());
module_emit_options options;
#ifdef WIN32
boost::filesystem::path sharedLibraryName = testFileManager.getTestFileName (fileBaseName + ".dll");
options.addLibrarySearchPath ((boost::filesystem::initial_path ().parent_path () /= "build") /= "bin");
#else
boost::filesystem::path sharedLibraryName = testFileManager.getTestFileName (fileBaseName + ".so");
options.addLibrarySearchPath (boost::filesystem::initial_path ());
#endif
mod.emitSharedLibraryFile (sharedLibraryName.string (), options);
// BOOST_CHECK (boost::filesystem::exists(sharedLibraryName));
return sharedLibraryName;
}
/**
@brief Returns true if the children of metaInfo are equal to the provided children.
@return True if the children of metaInfo are equal to the provided children.
**/
bool omni::tests::checkMetaInfoChildren (const omni::core::model::meta_info & metaInfo, std::set <const omni::core::model::meta_info *> children)
{
for (std::size_t i = 0; i < metaInfo.getChildCount (); ++i) {
auto child = children.find (& metaInfo.getChildAt (i));
if (child != children.end ()) {
children.erase (child);
} else {
return false;
}
}
return children.size () == 0u;
}
| 3,398 |
C++
| 48.985293 | 159 | 0.669217 |
daniel-kun/omni/source/omni/tests/test_llvm.cpp
|
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/PassManager.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetOptions.h>
#include <llvm/ADT/Triple.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/NoFolder.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FormattedStream.h>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE (llvmTests)
/*
BOOST_AUTO_TEST_CASE (llvmPlaygroundExternalFunction)
{
llvm::LLVMContext c;
llvm::Module module("test", c);
llvm::Type * int32Type = llvm::Type::getInt32Ty (c);
std::vector <llvm::Type*> putcharArgs (1, int32Type);
llvm::FunctionType * putcharFunctionType = llvm::FunctionType::get (int32Type, putcharArgs, false);
llvm::Function * putcharFunction = llvm::cast <llvm::Function> (llvm::Function::Create (putcharFunctionType, llvm::GlobalValue::ExternalLinkage, "putchar", &module));
llvm::FunctionType * mainFunctionType = llvm::FunctionType::get (int32Type, std::vector <llvm::Type*> (), false);
llvm::Function * llvmFunction = llvm::cast <llvm::Function> (llvm::Function::Create (mainFunctionType, llvm::GlobalValue::ExternalLinkage, "main", & module));
llvmFunction->setCallingConv(llvm::CallingConv::C);
llvm::BasicBlock * body = llvm::BasicBlock::Create(c, "__entry__", llvmFunction);
llvm::IRBuilder <true, llvm::NoFolder> builder(body);
std::vector <llvm::Value*> callArguments;
callArguments.push_back (llvm::ConstantInt::get (int32Type, static_cast <uint64_t> ('O')));
builder.CreateCall (putcharFunction, callArguments);
builder.CreateRet (llvm::ConstantInt::get (int32Type, 0));
llvm::verifyModule(module, llvm::PrintMessageAction);
std::string errorInfo;
llvm::raw_fd_ostream fileStream("playgroundPutchar.ll", errorInfo);
llvm::PassManager pm;
pm.add(llvm::createPrintModulePass(& fileStream));
pm.run(module);
}
BOOST_AUTO_TEST_CASE (llvmPlaygroundExternalVariableDeclaration)
{
llvm::LLVMContext c;
llvm::Module module("test", c);
llvm::Type * int32Type = llvm::Type::getInt32Ty (c);
std::vector <llvm::Type*> putcharArgs (1, int32Type);
llvm::FunctionType * putcharFunctionType = llvm::FunctionType::get (int32Type, putcharArgs, false);
llvm::Function * putcharFunction = llvm::cast <llvm::Function> (llvm::Function::Create (putcharFunctionType, llvm::GlobalValue::ExternalLinkage, "putchar", &module));
llvm::FunctionType * mainFunctionType = llvm::FunctionType::get (int32Type, std::vector <llvm::Type*> (), false);
llvm::Function * llvmFunction = llvm::cast <llvm::Function> (llvm::Function::Create (mainFunctionType, llvm::GlobalValue::ExternalLinkage, "main", & module));
llvmFunction->setCallingConv(llvm::CallingConv::C);
llvm::BasicBlock * body = llvm::BasicBlock::Create(c, "__entry__", llvmFunction);
// Here is the variable declaration and variable usage:
llvm::IRBuilder <true, llvm::NoFolder> builder(body);
// Create a variable on the stack using alloca:
llvm::AllocaInst * pointerAddress = builder.CreateAlloca (int32Type);
// Store a value to the variable:
builder.CreateStore (llvm::ConstantInt::get (int32Type, 'O'), pointerAddress);
// Load the value of the variable again:
llvm::Value * loadedValue = builder.CreateLoad (pointerAddress);
// Call printf with the loaded value:
std::vector <llvm::Value*> callArguments;
callArguments.push_back (loadedValue);
builder.CreateCall (putcharFunction, callArguments);
builder.CreateRet (llvm::ConstantInt::get (int32Type, 0));
llvm::verifyModule(module, llvm::PrintMessageAction);
std::string errorInfo;
llvm::raw_fd_ostream fileStream("playgroundVariableDeclartion.ll", errorInfo);
llvm::PassManager pm;
pm.add(llvm::createPrintModulePass(& fileStream));
pm.run(module);
}
// TODO: This test creates a broken COFF obj file:
// See the test whileStatementTests/doWhileStatement
// See http://llvm.org/bugs/show_bug.cgi?id=18308
BOOST_AUTO_TEST_CASE (llvmPlaygroundDoWhile)
{
using namespace llvm;
LLVMContext c;
Module module("test", c);
Type * int32Type = Type::getInt32Ty (c);
FunctionType * mainFunctionType = FunctionType::get (int32Type, std::vector <Type*> (), false);
Function * llvmFunction = cast <Function> (Function::Create (mainFunctionType, GlobalValue::ExternalLinkage, "doWhileStatementTest", & module));
llvmFunction->setCallingConv(CallingConv::C);
llvmFunction->setLinkage (GlobalValue::InternalLinkage);
BasicBlock * body = BasicBlock::Create(c, "__entry__", llvmFunction);
IRBuilder <true, NoFolder> builder(body);
AllocaInst * variableAddress = builder.CreateAlloca (int32Type);
builder.CreateStore (ConstantInt::get (int32Type, 1), variableAddress);
BasicBlock * whileBlock = BasicBlock::Create (c, "", llvmFunction);
builder.CreateBr (whileBlock);
BasicBlock * continueBlock = BasicBlock::Create (c, "", llvmFunction);
IRBuilder <true, NoFolder> continueBuilder (continueBlock);
continueBuilder.CreateRet (continueBuilder.CreateLoad (variableAddress));
{
IRBuilder <true, NoFolder> whileBuilder (whileBlock);
Value * variableValue = whileBuilder.CreateLoad (variableAddress);
Value * whileCondition = whileBuilder.CreateICmp (CmpInst::ICMP_SLT, variableValue, ConstantInt::get (int32Type, 10));
whileBuilder.CreateCondBr (whileCondition, whileBlock, continueBlock);
}
Function * mainFunction = cast <Function> (Function::Create (mainFunctionType, GlobalValue::ExternalLinkage, "main", & module));
mainFunction->setCallingConv(CallingConv::C);
mainFunction->setLinkage (GlobalValue::DLLExportLinkage);
BasicBlock * mainBody = BasicBlock::Create (c, "__entry__", mainFunction);
IRBuilder <true, NoFolder> mainBuilder (mainBody);
Value * callTestFunction = mainBuilder.CreateCall (llvmFunction);
mainBuilder.CreateRet (callTestFunction);
if (verifyModule(module, PrintMessageAction)) {
throw std::runtime_error ("Verification of module failed");
}
std::string errorInfo;
std::string errors;
std::string targetTriple = "i686-pc-win32";
Triple triple = llvm::Triple (targetTriple);
InitializeAllTargets ();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
const Target * target = TargetRegistry::lookupTarget ("", triple, errors);
TargetOptions targetOptions;
TargetMachine * targetMachine = target->createTargetMachine (targetTriple, std::string (), std::string (), targetOptions);
PassManager pm;
raw_fd_ostream stream ("llvmPlaygroundDoWhile.obj", errorInfo);
formatted_raw_ostream formattedStream (stream);
if (targetMachine->addPassesToEmitFile (pm, formattedStream, TargetMachine::CGFT_ObjectFile)) {
throw std::runtime_error ("Failed to emit object file");
}
pm.run (module);
formattedStream.flush ();
}
*/
BOOST_AUTO_TEST_SUITE_END ()
| 7,402 |
C++
| 42.292397 | 170 | 0.718049 |
daniel-kun/omni/source/omni/tests/test_main.cpp
|
#ifndef _MSC_VER
# define BOOST_TEST_DYN_LINK
#endif
#define BOOST_TEST_MODULE Omni
#include <boost/test/unit_test.hpp>
/*
int main (int argc, char * argv[])
{
init_unit_test_suite (argc, argv);
}
*/
| 209 |
C++
| 12.999999 | 38 | 0.660287 |
daniel-kun/omni/source/omni/tests/test_file_manager.cpp
|
#include <omni/tests/test_file_manager.hpp>
/**
Removes all files that have been returned by getTestFileName.
**/
omni::tests::test_file_manager::~test_file_manager ()
{
for (auto f : _files) {
if (boost::filesystem::exists (f)) {
boost::filesystem::remove (f);
}
}
}
/**
Creates a new path for the file with the name `fileName' in the tests directory.
If such a file exists, it is removed before the path is returned.
Files returned by this function will be removed when this test_file_manager object is destroyed.
**/
boost::filesystem::path omni::tests::test_file_manager::getTestFileName (std::string const & fileName, bool autoDelete)
{
boost::filesystem::path path = boost::filesystem::current_path ().parent_path ();
path /= boost::filesystem::path ("tests") /= fileName;
if (autoDelete) {
_files.push_back (path);
}
return path;
}
| 906 |
C++
| 30.275861 | 119 | 0.668874 |
daniel-kun/omni/source/omni/tests/runtime/test_memory.cpp
|
#include <omni/runtime/memory.hpp>
#include <boost/test/auto_unit_test.hpp>
BOOST_AUTO_TEST_SUITE (runtimeMemoryTests)
BOOST_AUTO_TEST_CASE (referenceCounting)
{
const std::size_t memorySize = 100u;
void * memory = omni_runtime_memory_allocate (memorySize);
char * buffer = reinterpret_cast <char *> (memory);
// Check whether we can write all memory slots that should have been allocated:
for (char * p = buffer; p < buffer + memorySize; ++ p) {
* p = 'A';
}
BOOST_CHECK_EQUAL (std::string (memorySize, 'A'), std::string (buffer, memorySize));
BOOST_CHECK (omni_runtime_memory_add_reference (memory) == memory);
BOOST_CHECK (omni_runtime_memory_remove_reference (memory) == memory);
BOOST_CHECK (omni_runtime_memory_remove_reference (memory) == nullptr);
}
BOOST_AUTO_TEST_SUITE_END ()
| 839 |
C++
| 35.521738 | 88 | 0.682956 |
daniel-kun/omni/source/omni/tests/core/test_parser.cpp
|
#include <omni/core/parser.hpp>
#include <omni/core/context.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/model/variable_declaration_expression.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE (parserTests)
BOOST_AUTO_TEST_CASE (builtinLiteral)
{
omni::core::context c;
omni::core::model::module m (c);
omni::core::parser::ExpressionList expressions = omni::core::parser::parseExpression (m, "1234");
BOOST_CHECK_EQUAL (expressions.size (), 1u);
if (expressions.size () == 1) {
omni::core::parser::parser_result <omni::core::model::expression> parserResult = * expressions.begin ();
BOOST_CHECK (! parserResult.exact); // Meanwhile, exact is always set to false until it gets a meaning.
BOOST_CHECK (parserResult.entity.get () != nullptr);
std::shared_ptr <omni::core::model::expression> expression = parserResult.entity;
using testIntType = unsigned int; // Currently, omni::core::parser only returns unsigned int literals.
BOOST_CHECK_EQUAL (& expression->getMetaInfo (), & omni::core::model::builtin_literal_expression <unsigned int>::getStaticMetaInfo ());
auto builtinLiteral = std::dynamic_pointer_cast <omni::core::model::builtin_literal_expression <unsigned int>> (expression);
BOOST_CHECK (builtinLiteral.get () != nullptr);
BOOST_CHECK_EQUAL (builtinLiteral->getValue (), 1234u);
}
}
BOOST_AUTO_TEST_CASE (variableDeclarationExpression)
{
omni::core::context c;
omni::core::model::module m (c);
omni::core::parser::ExpressionList expressions = omni::core::parser::parseExpression (m, "var ");
BOOST_CHECK_EQUAL (expressions.size (), 1u);
if (expressions.size () == 1) {
omni::core::parser::parser_result <omni::core::model::expression> parserResult = * expressions.begin ();
BOOST_CHECK (! parserResult.exact); // Meanwhile, exact is always set to false until it gets a meaning.
BOOST_CHECK (parserResult.entity.get () != nullptr);
std::shared_ptr <omni::core::model::expression> expression = parserResult.entity;
BOOST_CHECK_EQUAL (& expression->getMetaInfo (), & omni::core::model::variable_declaration_expression::getStaticMetaInfo ());
auto variableDecl = std::dynamic_pointer_cast <omni::core::model::variable_declaration_expression> (expression);
BOOST_CHECK (variableDecl.get () != nullptr);
BOOST_CHECK_EQUAL (variableDecl->getName (), "");
BOOST_CHECK (variableDecl->getInitializationExpression ().get () == nullptr);
}
}
BOOST_AUTO_TEST_SUITE_END ()
| 2,659 |
C++
| 49.188678 | 143 | 0.686348 |
daniel-kun/omni/source/omni/tests/core/test_id.cpp
|
#include <omni/core/id.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE (idTests)
/*
Tests the most common functions omni::core::id:
* the constructors
* isValid ()
* getId ()
* getDomain ()
*/
BOOST_AUTO_TEST_CASE (common)
{
using namespace omni::core;
id i1;
BOOST_CHECK (! i1.isValid ());
BOOST_CHECK_EQUAL (i1.getId (), std::string ());
BOOST_CHECK_EQUAL (i1.getDomain (), domain::invalid);
const std::string idString = "ABCDEFG";
id i2 (domain::function, idString);
BOOST_CHECK (i2.isValid ());
BOOST_CHECK_EQUAL (i2.getId (), idString);
BOOST_CHECK_EQUAL (i2.getDomain (), domain::function);
}
/*
Tests the operator< of omni::core::id with two invalid ids.
*/
BOOST_AUTO_TEST_CASE (operatorLessWithTwoInvalids)
{
using namespace omni::core;
id invalid1;
id invalid2;
BOOST_CHECK (! (invalid1 < invalid2));
}
/*
Tests the operator< of omni::core::id with two ids in the same domain, but with different ids.
*/
BOOST_AUTO_TEST_CASE (operatorLessWithSameDomainAndDifferentIds)
{
using namespace omni::core;
const std::string idString1 = "ABCDEFG";
const std::string idString2 = "HIJKLMN";
id id1 (domain::function, idString1);
id id2 (domain::function, idString2);
BOOST_CHECK_EQUAL (id1 < id2, idString1 < idString2);
BOOST_CHECK_EQUAL (id2 < id1, idString2 < idString1);
}
/*
Tests the operator< of omni::core::id with two ids in different domains, but with the same id.
*/
BOOST_AUTO_TEST_CASE (operatorLessWithDifferentDomainsAndSameId)
{
using namespace omni::core;
const std::string idString = "ABCDEFG";
domain domain1 = domain::function;
domain domain2 = domain::expression;
id id1 (domain1, idString);
id id2 (domain2, idString);
BOOST_CHECK_EQUAL (id1 < id2, domain1 < domain2);
BOOST_CHECK_EQUAL (id2 < id1, domain2 < domain1);
}
/*
Tests the operator< of omni::core::id with two ids in different domains and different ids.
*/
BOOST_AUTO_TEST_CASE (operatorLessWithDifferentDomainsAndDifferentIds)
{
using namespace omni::core;
const std::string idString1 = "ABCDEFG";
const std::string idString2 = "HIJKLMN";
domain domain1 = domain::function;
domain domain2 = domain::expression;
id id1 (domain1, idString1);
id id2 (domain2, idString2);
// When the domain differs, only the domain is relevant for the comparison:
BOOST_CHECK_EQUAL (id1 < id2, domain1 < domain2);
BOOST_CHECK_EQUAL (id2 < id1, domain2 < domain1);
}
BOOST_AUTO_TEST_SUITE_END ()
| 2,540 |
C++
| 28.206896 | 94 | 0.685827 |
daniel-kun/omni/source/omni/tests/core/test_runtime_memory.cpp
|
#include <omni/core/runtime.hpp>
#include <omni/core/context.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/function.hpp>
#include <omni/core/model/parameter.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/model/function_call_expression.hpp>
#include <omni/core/model/external_function.hpp>
#include <omni/core/model/return_statement.hpp>
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/model/variable_declaration_expression.hpp>
#include <omni/core/model/variable_expression.hpp>
#include <omni/core/model/bitcast_expression.hpp>
#include <omni/tests/test_utils.hpp>
#include <memory>
#include <boost/test/auto_unit_test.hpp>
BOOST_AUTO_TEST_SUITE (coreRuntimeMemoryTests)
BOOST_AUTO_TEST_CASE (referenceCounting)
{
using namespace omni::core;
context c;
model::module m (c, "test");
runtime r (m);
auto rawPtr= c.sharedBasicType (model::type_class::t_unsignedByte, 1);
auto ptrInt32 = c.sharedBasicType (model::type_class::t_unsignedInt, 1);
auto typeInt32 = c.sharedBasicType (model::type_class::t_unsignedInt);
auto funcBody = std::make_shared <model::block> ();
auto ptrVariable = std::make_shared <model::variable_declaration_expression> (
std::make_shared <model::bitcast_expression> (
std::make_shared <model::function_call_expression> (
r.getMemoryAllocate (),
std::vector <std::shared_ptr <model::expression>> {
std::make_shared <model::builtin_literal_expression <unsigned int>> (c, 128)
}),
ptrInt32));
// Allocate memory:
funcBody->appendStatement (ptrVariable);
// Increment the reference counter to 2:
funcBody->appendStatement (
std::make_shared <model::function_call_expression> (
r.getMemoryAddReference (),
std::vector <std::shared_ptr <model::expression>> {
std::make_shared <model::bitcast_expression> (
std::make_shared <model::variable_expression> (ptrVariable),
rawPtr)
}));
// Decrement the reference counter to 1:
funcBody->appendStatement (
std::make_shared <model::function_call_expression> (
r.getMemoryRemoveReference (),
std::vector <std::shared_ptr <model::expression>> {
std::make_shared <model::bitcast_expression> (
std::make_shared <model::variable_expression> (ptrVariable),
rawPtr)
}));
// Decrement the reference counter to 0 (memory will be freed):
funcBody->appendStatement (
std::make_shared <model::return_statement> (
std::make_shared <model::bitcast_expression> (
std::make_shared <model::function_call_expression> (
r.getMemoryRemoveReference (),
std::vector <std::shared_ptr <model::expression>> {
std::make_shared <model::bitcast_expression> (
std::make_shared <model::variable_expression> (ptrVariable),
rawPtr)
}),
ptrInt32)));
std::shared_ptr<model::function> func = m.createFunction ("test", ptrInt32, funcBody);
omni::tests::test_file_manager testFileManager;
int * result = omni::tests::runFunction <int*> (func, testFileManager, "runtimeMemoryReferenceCounting");
BOOST_CHECK (result == nullptr);
}
BOOST_AUTO_TEST_SUITE_END ()
| 3,570 |
C++
| 41.511904 | 109 | 0.630532 |
daniel-kun/omni/source/omni/tests/core/test_context.cpp
|
#include <omni/core/context.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/function.hpp>
#include <omni/core/model/entity.hpp>
#include <omni/core/model/return_statement.hpp>
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/model/function_call_expression.hpp>
#include <omni/tests/test_file_manager.hpp>
#include <omni/tests/test_utils.hpp>
#include <set>
#include <memory>
#include <iostream>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(contextTests)
BOOST_AUTO_TEST_CASE(ctor)
{
using namespace omni::core;
context c;
}
/**
Creates 20 ids for each domain and checks whether they are unique.
**/
BOOST_AUTO_TEST_CASE(createId)
{
using namespace omni::core;
context c;
model::module mod (c, "test");
std::set <id> ids;
for (domain d = domain::first; d < domain::last; d = static_cast <domain> (static_cast <int> (d) + 1)) {
for (int i = 0; i < 20; ++ i) {
id id = mod.createId (d);
BOOST_CHECK (ids.find (id) == ids.end ());
ids.insert (id);
BOOST_CHECK (ids.find (id) != ids.end ());
}
}
}
/**
Tests that a function can be created using createFunction and later be found via findFunctionByName and findEntityById.
**/
BOOST_AUTO_TEST_CASE (createAndFindFunction)
{
using namespace omni::core;
context c;
model::module mod (c, "test");
std::shared_ptr <model::block> emptyBody (new model::block ());
const std::string functionName = "test";
std::shared_ptr <model::function> func = mod.createFunction (
functionName,
static_cast <std::shared_ptr <model::type>> (model::type::sharedBasicType (c, model::type_class::t_signedInt)),
emptyBody);
BOOST_CHECK (func->getName () == functionName);
BOOST_CHECK (mod.findFunctionByName (func->getName ()) != nullptr);
BOOST_CHECK (mod.findFunctionByName (func->getName ())->getName () == functionName);
BOOST_CHECK (mod.findFunctionByName (functionName) != nullptr);
BOOST_CHECK (mod.findFunctionByName (functionName)->getName () == functionName);
BOOST_CHECK (mod.lookupComponentById (func->getId ()) != std::shared_ptr <model::entity> ());
BOOST_CHECK (std::dynamic_pointer_cast <model::function> (mod.lookupComponentById (func->getId ()))->getName () == functionName);
}
/**
Tests that a manually created function can be added using addFunction and later be found via findFunctionByName and findEntityById.
**/
BOOST_AUTO_TEST_CASE (addAndFindFunction)
{
using namespace omni::core;
context c;
model::module mod (c, "test");
std::shared_ptr <model::block> emptyBody (new model::block ());
const std::string functionName = "test";
std::shared_ptr <model::function> func (new model::function (
functionName,
model::type::sharedBasicType (c, model::type_class::t_signedInt),
emptyBody));
BOOST_CHECK (func->getContext () == nullptr);
mod.addFunction (func);
BOOST_CHECK (func->getName () == functionName);
BOOST_CHECK (func->getContext () == & c);
BOOST_CHECK (mod.findFunctionByName (func->getName ()) != nullptr);
BOOST_CHECK (mod.findFunctionByName (func->getName ())->getName () == functionName);
BOOST_CHECK (mod.findFunctionByName (functionName) != nullptr);
BOOST_CHECK (mod.findFunctionByName (functionName)->getName () == functionName);
BOOST_CHECK (mod.lookupComponentById (func->getId ()) != std::shared_ptr <model::entity> ());
BOOST_CHECK (std::dynamic_pointer_cast <model::function> (mod.lookupComponentById (func->getId ()))->getName () == functionName);
}
/**
Tests that a previously added function that is verified to exist in a context can be removed using removeFunction.
**/
BOOST_AUTO_TEST_CASE (removeFunction)
{
using namespace omni::core;
context c;
model::module mod (c, "test");
std::shared_ptr <model::block> emptyBody (new model::block ());
const std::string functionName = "test";
std::shared_ptr <model::function> func = mod.createFunction (
functionName,
static_cast <std::shared_ptr <model::type>> (model::type::sharedBasicType (c, model::type_class::t_signedInt)),
emptyBody);
BOOST_CHECK (mod.findFunctionByName (func->getName ()) != nullptr);
BOOST_CHECK (mod.findFunctionByName (func->getName ())->getName () == functionName);
BOOST_CHECK (mod.removeFunction (func));
BOOST_CHECK (func->getContext () == nullptr);
BOOST_CHECK (mod.findFunctionByName (func->getName ()) == nullptr);
BOOST_CHECK (mod.findFunctionByName (functionName) == nullptr);
}
/**
Writes an assembly (.ll) file and checks, whether it exists.
TODO: Check, whether llvm can interpret the resulting ll file.
**/
BOOST_AUTO_TEST_CASE (emitAssemblyFile)
{
using namespace omni::core;
context c;
model::module mod (c, "test");
std::shared_ptr <model::block> body (new model::block ());
std::shared_ptr <model::builtin_literal_expression <signed int>> literal42 (new model::builtin_literal_expression <signed int> (c, 42));
std::shared_ptr <model::statement> return42 (new model::return_statement (literal42));
body->appendStatement (return42);
const std::string functionName = "test";
std::shared_ptr <model::function> func = mod.createFunction (
functionName,
static_cast <std::shared_ptr <model::type>> (model::type::sharedBasicType (c, model::type_class::t_signedInt)),
body);
omni::tests::test_file_manager testFileManager;
std::string assemblyFileName = testFileManager.getTestFileName ("emitAssemblyFile.ll").string ();
mod.emitAssemblyFile (assemblyFileName);
BOOST_CHECK (boost::filesystem::exists(assemblyFileName));
}
/**
Writes an object file (.o on Linux/Unix, .obj on Windows) and checks, whether it exists.
**/
BOOST_AUTO_TEST_CASE (emitObjectFile)
{
using namespace omni::core;
context c;
model::module mod (c, "test");
std::shared_ptr <model::block> body (new model::block ());
std::shared_ptr <model::builtin_literal_expression <signed int>> literal42 (new model::builtin_literal_expression <signed int> (c, 42));
std::shared_ptr <model::statement> return42 (new model::return_statement (literal42));
body->appendStatement (return42);
const std::string functionName = "test";
std::shared_ptr <model::function> func = mod.createFunction (
functionName,
static_cast <std::shared_ptr <model::type>> (model::type::sharedBasicType (c, model::type_class::t_signedInt)),
body);
omni::tests::test_file_manager testFileManager;
boost::filesystem::path objectFilePath = testFileManager.getTestFileName ("emitObjectFile.obj");
std::string objectFileName = objectFilePath.string ();
mod.emitObjectFile (objectFileName);
BOOST_CHECK (boost::filesystem::exists (objectFileName));
}
/**
Writes an shared object file (.so on Linux/Unix, .dll on Windows) and checks, whether it exists, tries to load it and then tries
to call the function exported from it.
**/
BOOST_AUTO_TEST_CASE (emitSharedLibraryFile)
{
using namespace omni::core;
context c;
model::module mod (c, "test");
std::shared_ptr <model::block> body (new model::block ());
std::shared_ptr <model::builtin_literal_expression <signed int>> literal42 (new model::builtin_literal_expression <signed int> (c, 42));
std::shared_ptr <model::statement> return42 (new model::return_statement (literal42));
body->appendStatement (return42);
const std::string functionName = "test";
std::shared_ptr <model::function> func = mod.createFunction (functionName, model::type::sharedBasicType (c, model::type_class::t_signedInt), body);
omni::tests::test_file_manager testFileManager;
int functionCallResult = omni::tests::runFunction <int> (func, testFileManager, "emitSharedLibraryFile");
BOOST_CHECK_EQUAL (functionCallResult, 42);
}
BOOST_AUTO_TEST_SUITE_END()
| 8,073 |
C++
| 39.169154 | 151 | 0.682274 |
daniel-kun/omni/source/omni/tests/core/model/test_builtin_literal_expression.cpp
|
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/model/meta_info.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE (builtinLiteralExpressionTests)
BOOST_AUTO_TEST_CASE (metaInfo)
{
using namespace omni::core::model;
meta_info & meta = builtin_literal_expression <int>::getStaticMetaInfo ();
BOOST_CHECK_EQUAL (meta.getName (), "builtin_literal_expression");
BOOST_CHECK_EQUAL (meta.getParent (), & literal_expression::getStaticMetaInfo ());
BOOST_CHECK_EQUAL (meta.getChildCount (), 0u);
}
BOOST_AUTO_TEST_SUITE_END ();
| 587 |
C++
| 29.947367 | 86 | 0.727428 |
daniel-kun/omni/source/omni/tests/core/model/test_bitcast_expression.cpp
|
#include <omni/core/model/bitcast_expression.hpp>
#include <omni/core/model/meta_info.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE (bitcastExpressionTests)
BOOST_AUTO_TEST_CASE (metaInfo)
{
using namespace omni::core::model;
meta_info & meta = bitcast_expression::getStaticMetaInfo ();
BOOST_CHECK_EQUAL (meta.getName (), "bitcast_expression");
BOOST_CHECK_EQUAL (meta.getParent (), & cast_expression::getStaticMetaInfo ());
BOOST_CHECK_EQUAL (meta.getChildCount (), 0u);
}
BOOST_AUTO_TEST_SUITE_END ();
| 547 |
C++
| 27.842104 | 83 | 0.718464 |
daniel-kun/omni/source/omni/tests/core/model/test_variable.cpp
|
#include <omni/core/context.hpp>
#include <omni/core/model/module.hpp>
#include <omni/core/model/variable_declaration_expression.hpp>
#include <omni/core/model/variable_expression.hpp>
#include <omni/core/model/variable_assignment_expression.hpp>
#include <omni/core/model/binary_operator_expression.hpp>
#include <omni/core/model/function.hpp>
#include <omni/core/model/type.hpp>
#include <omni/core/model/type_class.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/model/builtin_literal_expression.hpp>
#include <omni/core/model/return_statement.hpp>
#include <omni/tests/test_utils.hpp>
#include <boost/test/unit_test.hpp>
#include <numeric>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
namespace {
template <typename T>
void testVariables (T initializationValue, T assignmentValue)
{
BOOST_CHECK_NE (initializationValue, assignmentValue);
using namespace omni::core;
context c;
model::module m (c, "test");
// Declare a variable with the initial value of `initializationValue':
auto variableInitializationLiteral = std::make_shared <model::builtin_literal_expression <T>> (c, initializationValue);
auto variableDeclarationStatement = std::make_shared <model::variable_declaration_expression> (variableInitializationLiteral);
BOOST_CHECK (variableDeclarationStatement->getType ()->getTypeClass () == model::native_type_to_type_class <T>::typeClass);
// Assign `assignmentValue' to the variable:
auto variableValueLiteral = std::make_shared <model::builtin_literal_expression <T>> (c, assignmentValue);
auto variableAssignmentExpression = std::make_shared <model::variable_assignment_expression> (variableDeclarationStatement, variableValueLiteral);
// Add the statements to a function body:
auto body = std::make_shared <model::block> ();
body->appendStatement (variableDeclarationStatement);
body->appendStatement (variableAssignmentExpression);
// Return the variable's value:
body->appendStatement (
std::make_shared <model::return_statement> (
std::make_shared <model::variable_expression> (variableDeclarationStatement)));
auto func = m.createFunction ("test", variableDeclarationStatement->getType (), body);
omni::tests::test_file_manager testFileManager;
T result = omni::tests::runFunction <T> (func, testFileManager, "variableTest");
BOOST_CHECK_EQUAL (result, assignmentValue);
}
template <typename T>
void testVariablesNumericLimits ()
{
testVariables <T> (std::numeric_limits <T>::max (), std::numeric_limits <T>::min ());
testVariables <T> (std::numeric_limits <T>::min (), std::numeric_limits <T>::max ());
}
} // anonymous namespace
/**
Tests the classes variable_declaration_expression, variable_expression and variable_assignment_expression.
**/
BOOST_AUTO_TEST_SUITE (variableTests)
BOOST_AUTO_TEST_CASE (ctor)
{
using namespace omni::core;
context c;
auto variable = std::make_shared <model::variable_declaration_expression> (c.sharedBasicType (model::type_class::t_char));
model::variable_expression variableExpression (variable);
}
/**
Does some fiddling with variable_declaration_expression, variable_expression and variable_assignment_expression.
**/
BOOST_AUTO_TEST_CASE (mixedTests)
{
using namespace omni::core;
context c;
model::module m (c, "test");
auto t = c.sharedBasicType (model::type_class::t_char);
auto body = std::make_shared <model::block> ();
// Declare a variable "A" that holds the letter 'A':
auto variableA = std::make_shared <model::variable_declaration_expression> (
std::make_shared <model::builtin_literal_expression <char>> (c, 'A'));
body->appendStatement (variableA);
// Declare a second variable "B" that holds the value of variableA, incremented by 1. Hence, the value should be 'B'
auto AplusBexpression = std::make_shared <model::binary_operator_expression> (
* m.getContext (),
model::binary_operator_expression::binary_operation::binary_plus_operation,
std::make_shared <model::variable_expression> (variableA),
std::make_shared <model::builtin_literal_expression <char>> (c, static_cast <char> (1)));
auto variableB = std::make_shared <model::variable_declaration_expression> (AplusBexpression);
body->appendStatement (variableB);
// Declare a third variable C that will be initialized with the letter 'A', but then (without usage of the letter 'A') it will be assigned
// the result of variableB plus 1. Hence, the value should be 'C'.
auto variableC = std::make_shared <model::variable_declaration_expression> (std::make_shared <model::builtin_literal_expression <char>> (c, 'A'));
body->appendStatement (variableC);
auto variableCassignment = std::make_shared <model::variable_assignment_expression> (
variableC,
std::make_shared <model::binary_operator_expression> (
* m.getContext (),
model::binary_operator_expression::binary_operation::binary_plus_operation,
std::make_shared <model::variable_expression> (variableB),
std::make_shared <model::builtin_literal_expression <char>> (c, static_cast <char> (1))));
body->appendStatement (variableCassignment);
// Now, return the value of variable "C", which should be 'C':
body->appendStatement (std::make_shared <model::return_statement> (std::make_shared <model::variable_expression> (variableC)));
auto func = std::make_shared <model::function> ("test", c.sharedBasicType (model::type_class::t_char), body);
m.addFunction (func);
omni::tests::test_file_manager testFileManager;
char result = omni::tests::runFunction <char> (func, testFileManager, "variableMixedTests");
BOOST_CHECK_EQUAL (result, 'C');
}
BOOST_AUTO_TEST_CASE (variableBoolean)
{
testVariables <bool> (true, false);
testVariables <bool> (false, true);
testVariablesNumericLimits <bool> ();
}
BOOST_AUTO_TEST_CASE (variableChar)
{
testVariables <char> ('A', 'B');
testVariables <char> ('A', '\0');
testVariablesNumericLimits <char> ();
}
BOOST_AUTO_TEST_CASE (variableUnsignedByte)
{
testVariables <unsigned char> ('A', 'B');
testVariables <unsigned char> ('A', '\0');
testVariablesNumericLimits <unsigned char> ();
}
BOOST_AUTO_TEST_CASE (variableSignedByte)
{
testVariables <signed char> (-1, 0);
testVariables <signed char> (+1, 0);
testVariables <signed char> (0, -1);
testVariables <signed char> (0, +1);
testVariablesNumericLimits <signed char> ();
}
BOOST_AUTO_TEST_CASE (variableUnsignedShort)
{
testVariables <unsigned short> (1, 0);
testVariables <unsigned short> (0, 1);
testVariablesNumericLimits <unsigned short> ();
}
BOOST_AUTO_TEST_CASE (variableSignedShort)
{
testVariables <signed short> (-1, 0);
testVariables <signed short> (+1, 0);
testVariables <signed short> (0, -1);
testVariables <signed short> (0, +1);
testVariablesNumericLimits <signed short> ();
}
BOOST_AUTO_TEST_CASE (variableUnsignedInt)
{
testVariables <unsigned int> (1, 0);
testVariables <unsigned int> (0, 1);
testVariablesNumericLimits <unsigned int> ();
}
BOOST_AUTO_TEST_CASE (variableSignedInt)
{
testVariables <signed int> (-1, 0);
testVariables <signed int> (+1, 0);
testVariables <signed int> (0, -1);
testVariables <signed int> (0, +1);
testVariablesNumericLimits <signed int> ();
}
BOOST_AUTO_TEST_CASE (variableUnsignedLong)
{
testVariables <unsigned long> (1, 0);
testVariables <unsigned long> (0, 1);
testVariablesNumericLimits <unsigned long> ();
}
BOOST_AUTO_TEST_CASE (variableSignedLong)
{
testVariables <signed long> (-1, 0);
testVariables <signed long> (+1, 0);
testVariables <signed long> (0, -1);
testVariables <signed long> (0, +1);
testVariablesNumericLimits <signed long> ();
}
BOOST_AUTO_TEST_CASE (variableUnsignedLongLong)
{
testVariables <unsigned long long> (1, 0);
testVariables <unsigned long long> (0, 1);
testVariablesNumericLimits <unsigned long long> ();
}
BOOST_AUTO_TEST_CASE (variableSignedLongLong)
{
testVariables <signed long long> (-1, 0);
testVariables <signed long long> (+1, 0);
testVariables <signed long long> (0, -1);
testVariables <signed long long> (0, +1);
testVariablesNumericLimits <signed long long> ();
}
BOOST_AUTO_TEST_SUITE_END ();
| 8,442 |
C++
| 36.524444 | 150 | 0.701729 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.