repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
kylegmaxwell/training
src/board.h
<gh_stars>0 #pragma once #include <iostream> #include <vector> #include <sstream> #include <unordered_set> #include <unordered_map> #include "unittest.h" /*! * \brief The Board class respresents an N x N chess board * to solve the problem of placing N Queens such that * the Queens do not attack each other. */ class Board { public: //! \brief The TileState enum represents whether a queen has been placed, or can be placed enum class TileState { QUEEN, ATTACKED, EMPTY }; //! Create a chess board of a given size Board(int size); //! \brief Set the state at position row, col //! Also does some checking to prevent over writing of queens void setState(int row, int col, TileState state); //! Get the state of the board at a position TileState getState(int row, int col); //! print a visual record of the board void printFull(std::ostream &stream); //! print just the index of the queens //! Used to check uniqueness of solutions void printQueens(std::ostream &stream); /*! * \brief Find the nth empty tile * \param offset is how many places to skip to find the empty tile * \return true if a place was found */ bool findEmpty(int &row, int &col, int offset = 0); /*! * \brief Place a queen in the specified row and column, * and mark out all the squares which she attacks */ void placeQueen(int row, int col); //! get the number of empty squares in the board int getNumEmpty(); //! Get the length/width of the board in squares int getSize(); private: //! number of squares along one side of the baord int mSize; //! The elements of the board std::vector<TileState> mEntries; //! Number of spaces available in which to place queens int mNumEmpty; //! The index locations of where the queens have been placed std::vector<int> mQueens; };
kylegmaxwell/training
src/powerset.h
#pragma once #include "unittest.h" #include <queue> #include <vector> #include <unordered_set> #include <algorithm> #include <iostream> #include <sstream> class PowerSet : public UnitTest { public: typedef std::vector<std::string> StringList; void makePowerSetRecursive(StringList startSet, std::string element, StringList &powerSet); void makePowerSetIterative(StringList startSet, StringList &powerSet); void printSet(std::ostream &stream, StringList &set); virtual TestResult test() override; };
kylegmaxwell/training
src/listcycle.h
#pragma once #include "unittest.h" #include <iostream> #include <unordered_map> /*! * \brief The ListNode class represents a node in a linked list */ class ListNode { public: ListNode(char iData); ListNode(char iData, ListNode *iNext); // print my data void print(); // recursive print my data and children (later elements on list) void printRecursive(); char mData; ListNode *mNext; }; /*! * \brief The ListCycle class creates linked lists and tests for cycles */ class ListCycle : public UnitTest { public: enum class CycleState { CYCLE, TERMINATES }; //! Check the list for cycles, which cause problems with iteration CycleState findCycle(ListNode *n); virtual TestResult test() override; };
kylegmaxwell/training
src/computeparity.h
#pragma once #include "unittest.h" class ComputeParity : public UnitTest { public: int computeParity(int value); virtual TestResult test() override; };
kylegmaxwell/training
src/unittest.h
<reponame>kylegmaxwell/training #pragma once #include <iostream> #include <string> /*! * Unit test base class. * Tests can implement the test() function to be run as part of a test suite. */ class UnitTest { public: // Allow child classes to override destructor if needed virtual ~UnitTest() = default; //! Tests can pass or fail enum class TestResult { PASS, FAIL }; //! Overridable test function to be implemented by test classes virtual TestResult test(); protected: //! Wheter to print extra logging information bool mVerbose{ false }; /*! * Convenience function to compare strings and return a bool * @returns true when equal */ static auto stringEqual(std::string a, std::string b) { return a.compare(b) == 0; } };
kylegmaxwell/training
src/move.h
#pragma once #include <vector> #include "unittest.h" class Move : public UnitTest { public: Move(); Move(size_t size); ~Move(); Move(const Move & move); Move(Move && move); Move& operator=(const Move& move); Move& operator=(Move && move); std::vector<int> values; virtual UnitTest::TestResult test() override; private: };
kylegmaxwell/training
src/narytree.h
<filename>src/narytree.h #pragma once #include "unittest.h" #include <iostream> #include <vector> #include <queue> #include <stack> #include <sstream> class TreeNode { public: TreeNode(char iData); // recursive print void print(std::iostream &stream); // just print data void printData(std::iostream &stream); char getData(); void addChild(TreeNode *node); std::vector<TreeNode*> mChildren; private: char mData; }; class NaryTree : public UnitTest { public: virtual TestResult test() override; private: TreeNode *mRootNode; void buildTree(); /*! * \brief printBFS Print in Breadth First Search order using a queue * \param stream Output buffer for text */ void printBFS(std::iostream &stream); /*! * \brief printDFS Print in Depth First Search order using a stack * \param stream Output buffer for text */ void printDFS(std::iostream &stream); /*! * \brief printDFSRecursive Print in Depth First Search order using recursion * \param stream Output buffer for text */ void printDFSRecursive(std::iostream &stream); void printDFSHelper(std::iostream &stream, TreeNode *n); //void printBroken(std::iostream &stream); };
kylegmaxwell/training
src/testsuite.h
#pragma once #include <vector> #include <memory> #include "unittest.h" /*! * Container for a list of unit tests. */ class TestSuite { public: /*! * Run all the tests that have been added * @returns status code */ static int test(const std::vector<std::unique_ptr<UnitTest>> &tests); };
kylegmaxwell/training
src/binarysearch.h
<filename>src/binarysearch.h #pragma once #include <vector> #include <algorithm> #include "unittest.h" class BinarySearch : public UnitTest { public: virtual TestResult test() override; /*! * \brief Search for the index of the given value. * \param value The value to look for in the array * \return The index, or -1 if not found. */ template <typename T> static size_t search(std::vector<T> &values, T value); /*! * \brief Search for the leftmost index of the given value. * \param index The index of a known occurence of the searched value * \return The index, or -1 if not found. */ template <typename T> size_t searchLeft(std::vector<T> &values, size_t index); };
kylegmaxwell/training
src/hashletter.h
#pragma once #include <unordered_map> #include <algorithm> #include "unittest.h" class HashLetter : public UnitTest { public: typedef std::unordered_map<char, int> CharIntMap; const static std::string Book; const static std::string Letter; virtual TestResult test() override; /*! * \brief countOccurrences Count the number of occurrences of each character in the given string using the map * \param countMap Mapping from character to number of occurrences * \param s String to search */ void countOccurrences(CharIntMap &countMap, std::string s); void printHistogram(CharIntMap &map); };
kylegmaxwell/training
src/pairsum.h
<gh_stars>0 #pragma once #include "unittest.h" #include <iostream> #include <vector> class PairSum : public UnitTest { public: typedef std::vector<int> IntVec; /*! * \brief hasPairSum Checks to see if there are any two integers that sum to the given value. * Assumes input vector is sorted. * \param vec The vector of numbers which could form pairs. * \param querySum The value of the sum. * \return true If there is such a pair */ bool hasPairSum(IntVec &vec, int querySum); /*! * \brief hasThreeSum Checks to see if there are any three integers in the array that sum to the given value. * Assumes input vector is sorted (O(n log n). * \param vec The vector of numbers which could form triples. * \param querySum The value of the sum. * \return true If there is such a pair */ bool hasThreeSum(IntVec &vec, int querySum); //WARNING: Does not work // This was an attempt to solve the open problem for a n log n 3 sum search using a combination of the pair sum algorithm and binary search bool hasThreeSumFast(IntVec &vec, int querySum); size_t binarySearch(IntVec &values, int searchValue, size_t firstIndex, size_t lastIndex, int &closest, size_t &closestIdx); virtual TestResult test() override; ; };
kylegmaxwell/training
src/sorting.h
#pragma once #include "unittest.h" #include <vector> #include <cstdlib> // rand #include <functional> class Sorting : public UnitTest { public: using IntVec = std::vector<int>; Sorting(); virtual TestResult test() override; private: /*! * \brief testSort Test a sorting algorithm that operates on a vector * \param func The function to call on the vector to sort it * \param numElements The number of elements to add to the vector * \param numValues The range of values in the vector is from zero to this value */ TestResult testSort(std::function<void(Sorting::IntVec&)> func, size_t numElements, size_t numValues); //! print all elements in a vector static void printVec(IntVec &v); //! check if a vector is sorted increasing static TestResult checkVec(const IntVec &v); //! populate a random vector static void randomVec(IntVec &v, size_t size, size_t range); /*! * \brief mergeSort sort using divide and conquer O(n*log(n)) * \param v vector to sort */ static void mergeSort(IntVec &v); /*! * \brief mergeSortHelper helper to sort a specific range * \param v vector to sort * \param L fist valid index * \param R last valid index * \param d recursion depth */ static void mergeSortHelper(IntVec &v, size_t L, size_t R, size_t d); /*! * \brief Selection sort to use for benchmarking O(n^2) * \param v vector to sort */ static void selectionSort(IntVec &v); };
kylegmaxwell/training
src/maxstack.h
<filename>src/maxstack.h #pragma once #include "unittest.h" #include <vector> class MaxStack : public UnitTest { public: using IntVec = std::vector<int>; /*! * \brief push Add a new value to the top of the stack, and compute the max */ void push(int value); /*! * \brief push Remove a value from the top of the stack, and return the max */ int pop(); void getMaxValue(); virtual TestResult test() override; IntVec mStack{}; IntVec mMax{}; };
kylegmaxwell/training
src/dynamicprogramming.h
#pragma once #include <vector> #include "unittest.h" /*! * \brief The Array class stores n x m array of data */ template <class T> class Array2D { public: Array2D(size_t rows, size_t cols); //! Set the value at row, col in the array void setState(size_t row, size_t col, T state); //! Get the value at row, col in the array T getState(size_t row, size_t col) const; //! print a visual record of the board void printFull(std::ostream &stream) const; //! Return the dimensions of the array as a rows, cols pair std::pair<size_t, size_t> getSize() const; //! Return the number of rows auto getRows() const { return mRows; } //! Return the number of columns auto getCols() const { return mCols; } private: //! number of squares along one side of the baord size_t mRows; size_t mCols; //! The elements of the board std::vector<T> mEntries; }; /*! * \brief The Combinations class calculates the combination function in probability theory. * This class caches the results as it goes to speed up redundant lookups */ class Combinations { public: // Define int 64 for big numbers typedef long long int Int; // Define vector of integers type typedef std::vector<Int> IntVec; //! Constructor, does some initialization of the cache Combinations(); //! Destructor cleans up IntVec array ~Combinations(); //! Evaluate the choose function n C k Int choose(Int n, Int k); //! Print out the cache array void print(); private: std::vector<IntVec*> cache; // check how many rows have been cached size_t numRows(); // Adds a row to the cache allowing a value of n one higher to be evaluated // Dynamically allocates an IntVec with memory managed interally to this class void addRow(); }; class DynamicProgramming : public UnitTest { public: //Note: factorial is not implemented with or used for the dynamic programming algorithm at this time // factorial used to compute expected result when no barriers are present Combinations::Int factorial(Combinations::Int n); //Note: this version of calculating combinations uses factiorals, // which can easily go out of bounds for large inputs Combinations::Int chooseFlawed(Combinations::Int n, Combinations::Int k); //Note: this will have trouble with large values of n // use factorial to compute combinations Combinations::Int chooseVeryFlawed(Combinations::Int n, Combinations::Int k); // count the number of paths from (row,col) to (mRows-1, mCols-1) int countPaths(const Array2D<bool> &board, Array2D<int> &cache, size_t row, size_t col); //! Test the factorial function TestResult testFactorial(); //! Test the combinations class TestResult testChoose(Combinations &comb); //! Run the dynamic programming exercise TestResult testPaths(Combinations &comb); virtual TestResult test() override; };
kylegmaxwell/training
src/logger.h
#pragma once #include <iostream> #include <sstream> #ifdef _MSC_VER #include <windows.h> #endif class Logger { public: template <typename T> static void DEBUG_WORD(const T &in) { std::stringstream ss; ss << in; #ifdef _MSC_VER OutputDebugString(ss.str().c_str()); #else std::cout << ss.str(); #endif } template <typename T> static void DEBUG(const T &in) { std::stringstream ss; ss << in << std::endl; DEBUG_WORD(ss.str()); } static void ENDL() { DEBUG(""); } };
kylegmaxwell/training
src/queens.h
<filename>src/queens.h #pragma once #include <iostream> #include <vector> #include <sstream> #include <unordered_set> #include <unordered_map> #include "unittest.h" #include "board.h" /*! * \brief The Queens class uses the queens board to solve the N Queens problem * http://en.wikipedia.org/wiki/Eight_queens_puzzle */ class Queens : public UnitTest { public: /*! * \brief Polymorphic test function inherited from Unit Test. * Runs the queens problem on different board sizes and * checks for the right number of solutions. */ virtual TestResult test() override; /*! * \brief When a solution is found the board state is cached * \param b The board that was successful */ void saveBoard(Board &b, bool debug = false); /*! * \brief placeQueens calculates all possible solutions to the N Queens Problem * This function tries different initial placements and then calls placeQueensHelper, * which then places one queen and recursively calls placeQueens with one fewer queen to place * \param b The board to use * \param nQueens The size of the puzzle * \return true on success */ bool placeQueens(Board &b, int nQueens); //! Parallel helper that places a queen at the nth free space as determined by offset bool placeQueensHelper(Board &b, int nQueens, int offset); private: //! set of working solutions, used to remove exact duplicates std::unordered_set<std::string> mSet{}; //! Total number of completed boards tested, either successful or failed int mCount{ 0 }; };
kylegmaxwell/training
src/binarytree.h
#pragma once #include <iostream> #include <memory> #include "unittest.h" class BinaryNode { public: typedef std::shared_ptr<BinaryNode> Ptr; BinaryNode(int iData); BinaryNode(int iData, BinaryNode *iLeft, BinaryNode *iRight); int mData; Ptr mLeft; Ptr mRight; }; typedef BinaryNode::Ptr BinaryNodePtr; class BinaryTree : public UnitTest { public: BinaryNodePtr buildUnbalancedTree(); BinaryNodePtr buildBalancedTree(); bool isBalanced(BinaryNodePtr node); bool isBalancedHelper(BinaryNodePtr node, int &depth); //! Check if the ordering of the nodes is violated during traversal bool processNode(BinaryNodePtr n, int &prev); //! Check if the tree is a sorted Binary Search Tree. bool isSorted(BinaryNodePtr node); bool isSortedRecursive(BinaryNodePtr node, int &prev); virtual TestResult test() override; };
kylegmaxwell/training
src/convertbase.h
#pragma once #include "unittest.h" #include <iostream> #include <string> class ConvertBase : public UnitTest { public: virtual TestResult test() override; private: /*! * \brief Convert a number from one base to another. * \param baseIn The base that number is represented in * \param number The number to be converted * \param baseOut The new base to change the number into * \return The number after conversion to the new base */ std::string convertBase(int baseIn, std::string number, int baseOut); };
Sdaddy11/openpilotsg
selfdrive/common/version.h
<filename>selfdrive/common/version.h #define COMMA_VERSION "0.8.5-3_clean"
HeylelOS/Heaven
src/hvn-man/main.c
/* SPDX-License-Identifier: BSD-3-Clause */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <libgen.h> #include <limits.h> #include <fcntl.h> #include <err.h> #include <cmark.h> #define SECTION_MAX 8 struct hvn_man_args { char *input, *output; char *pagename; int section; int width; }; struct hvn_man_render_option { const char *name; int value; }; static const struct hvn_man_render_option renderoptions[] = { { "sourcepos", CMARK_OPT_SOURCEPOS }, { "hardbreaks", CMARK_OPT_HARDBREAKS }, { "nobreaks", CMARK_OPT_NOBREAKS }, { "smart", CMARK_OPT_SMART }, { "safe", CMARK_OPT_SAFE }, { "unsafe", CMARK_OPT_UNSAFE }, { "validate-utf8", CMARK_OPT_VALIDATE_UTF8 }, }; static void hvn_man_parse(int fd, cmark_parser *parser) { const int pagesize = getpagesize(); char buffer[pagesize]; ssize_t readval; while(readval = read(fd, buffer, sizeof(buffer)), readval > 0) { cmark_parser_feed(parser, buffer, readval); } if(readval < 0) { perror("read"); } } static void hvn_man_render(FILE *output, cmark_node *document, int options, const struct hvn_man_args *args) { char *result = cmark_render_man(document, options, args->width); fprintf(output, ".TH %s %d\n", args->pagename, args->section); fputs(result, output); free(result); } static void hvn_man_usage(const char *progname) { fprintf(stderr, "usage: %s [-i <input>] [-o <output>] [-p <pagename>] [-s <section>] [-w <width>] [<render options>...]\n", progname); exit(EXIT_FAILURE); } static const struct hvn_man_args hvn_man_parse_args(int argc, char **argv) { struct hvn_man_args args = { .input = NULL, .output = NULL, .pagename = NULL, .section = 0, .width = 0, }; int c; while(c = getopt(argc, argv, ":i:o:p:s:w:"), c != -1) { switch(c) { case 'i': free(args.input); args.input = strdup(optarg); break; case 'o': free(args.output); args.output = strdup(optarg); break; case 'p': free(args.pagename); args.pagename = strdup(optarg); break; case 's': { char *endptr; const unsigned long value = strtoul(optarg, NULL, 10); if(value == 0 || value > SECTION_MAX || *endptr != '\0') { warnx("Invalid section number '%s'", optarg); hvn_man_usage(*argv); } args.section = value; } break; case 'w': { char *endptr; const unsigned long value = strtoul(optarg, NULL, 0); if(value == 0 || value > INT_MAX || *endptr != '\0') { warnx("Invalid wrap width '%s'", optarg); hvn_man_usage(*argv); } args.width = value; } break; case ':': warnx("-%c: Missing argument", optopt); hvn_man_usage(*argv); default: warnx("Unknown argument -%c", optopt); hvn_man_usage(*argv); } } /* Set output name from input's if available */ if(args.input != NULL && args.output == NULL) { const char *filename = basename(args.input); const char *extension = strrchr(filename, '.'); const size_t length = extension != NULL ? extension - filename : strlen(filename); args.output = strndup(filename, length); } /* Set default missing parameters if output is set */ if(args.output != NULL) { const char *filename = basename(args.output); const char *extension = strchr(filename, '.'); const size_t length = extension != NULL ? extension - filename : strlen(filename); /* Create pagename from output name */ if(args.pagename == NULL) { args.pagename = strndup(filename, length); } /* Extract section number from extension if possible */ if(args.section == 0) { const char *section = extension + 1; char *endptr; const unsigned long value = strtoul(section, &endptr, 10); if(value != 0 && value <= SECTION_MAX && *endptr == '\0') { args.section = value; } } } /* Last parameters, if we're in a command pipeline and nothing was specified */ if(args.pagename == NULL) { args.pagename = strdup("?"); } if(args.section == 0) { args.section = 1; } return args; } int main(int argc, char **argv) { const struct hvn_man_args args = hvn_man_parse_args(argc, argv); char **argpos = argv + optind, ** const argend = argv + argc; int options = CMARK_OPT_DEFAULT; /* Parse render options */ while(argpos != argend) { const struct hvn_man_render_option *current = renderoptions, * const end = renderoptions + sizeof(renderoptions) / sizeof(*renderoptions); const char *name = *argpos; while(current != end && strcmp(current->name, name) != 0) { current++; } if(current != end) { options |= current->value; } argpos++; } /* Parse input file */ cmark_parser *parser = cmark_parser_new(options); if(args.input != NULL) { int fd = open(args.input, O_RDONLY); if(fd < 0) { err(EXIT_FAILURE, "open %s", args.input); } hvn_man_parse(fd, parser); close(fd); } else { hvn_man_parse(STDIN_FILENO, parser); } /* Print output file */ cmark_node *document = cmark_parser_finish(parser); cmark_parser_free(parser); if(args.output != NULL) { FILE *output = fopen(args.output, "w"); if(output == NULL) { err(EXIT_FAILURE, "fopen %s", args.output); } hvn_man_render(output, document, options, &args); fclose(output); } else { hvn_man_render(stdout, document, options, &args); } cmark_node_free(document); free(args.pagename); free(args.output); free(args.input); return EXIT_SUCCESS; }
HeylelOS/Heaven
src/hvn-web/main.c
<reponame>HeylelOS/Heaven /* SPDX-License-Identifier: BSD-3-Clause */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <libgen.h> #include <limits.h> #include <fcntl.h> #include <err.h> #include <cmark.h> struct hvn_web_args { char *input, *output; char *head, *tail; }; struct hvn_web_render_option { const char *name; int value; }; static const struct hvn_web_render_option renderoptions[] = { { "sourcepos", CMARK_OPT_SOURCEPOS }, { "hardbreaks", CMARK_OPT_HARDBREAKS }, { "nobreaks", CMARK_OPT_NOBREAKS }, { "smart", CMARK_OPT_SMART }, { "safe", CMARK_OPT_SAFE }, { "unsafe", CMARK_OPT_UNSAFE }, { "validate-utf8", CMARK_OPT_VALIDATE_UTF8 }, }; static void hvn_web_parse(int fd, cmark_parser *parser) { const int pagesize = getpagesize(); char buffer[pagesize]; ssize_t readval; while(readval = read(fd, buffer, sizeof(buffer)), readval > 0) { cmark_parser_feed(parser, buffer, readval); } if(readval < 0) { perror("read"); } } static void hvn_web_dump(const char *filename, FILE *output, const struct hvn_web_args *args) { if(filename != NULL) { int fd = open(filename, O_RDONLY); if(fd >= 0) { const int pagesize = getpagesize(); char buffer[pagesize]; ssize_t readval; while(readval = read(fd, buffer, sizeof(buffer)), readval > 0) { fwrite(buffer, sizeof(*buffer), readval, output); } close(fd); } else { warn("open %s", filename); } } } static void hvn_web_render(FILE *output, cmark_node *document, int options, const struct hvn_web_args *args) { hvn_web_dump(args->head, output, args); char *result = cmark_render_html(document, options); fputs(result, output); free(result); hvn_web_dump(args->tail, output, args); } static void hvn_web_usage(const char *progname) { fprintf(stderr, "usage: %s [-i <input>] [-o <output>] [-H <head>] [-T <tail>] [<render options>...]\n", progname); exit(EXIT_FAILURE); } static const struct hvn_web_args hvn_web_parse_args(int argc, char **argv) { struct hvn_web_args args = { .input = NULL, .output = NULL, .head = NULL, .tail = NULL, }; int c; while(c = getopt(argc, argv, ":i:o:H:T:"), c != -1) { switch(c) { case 'i': free(args.input); args.input = strdup(optarg); break; case 'o': free(args.output); args.output = strdup(optarg); break; case 'H': free(args.head); args.head = strdup(optarg); break; case 'T': free(args.tail); args.tail = strdup(optarg); break; case ':': warnx("-%c: Missing argument", optopt); hvn_web_usage(*argv); default: warnx("Unknown argument -%c", optopt); hvn_web_usage(*argv); } } /* Set output name from input's if available */ if(args.input != NULL && args.output == NULL) { static const char htmlext[] = ".html"; const char *filename = basename(args.input); const char *extension = strrchr(filename, '.'); const size_t length = extension != NULL ? extension - filename : strlen(filename); char buffer[length + sizeof(htmlext)]; strncpy(buffer, filename, length); strncpy(buffer + length, htmlext, sizeof(htmlext)); args.output = strdup(buffer); } return args; } int main(int argc, char **argv) { const struct hvn_web_args args = hvn_web_parse_args(argc, argv); char **argpos = argv + optind, ** const argend = argv + argc; int options = CMARK_OPT_DEFAULT; /* Parse render options */ while(argpos != argend) { const struct hvn_web_render_option *current = renderoptions, * const end = renderoptions + sizeof(renderoptions) / sizeof(*renderoptions); const char *name = *argpos; while(current != end && strcmp(current->name, name) != 0) { current++; } if(current != end) { options |= current->value; } argpos++; } /* Parse input file */ cmark_parser *parser = cmark_parser_new(options); if(args.input != NULL) { int fd = open(args.input, O_RDONLY); if(fd < 0) { err(EXIT_FAILURE, "open %s", args.input); } hvn_web_parse(fd, parser); close(fd); } else { hvn_web_parse(STDIN_FILENO, parser); } /* Print output file */ cmark_node *document = cmark_parser_finish(parser); cmark_parser_free(parser); if(args.output != NULL) { FILE *output = fopen(args.output, "w"); if(output == NULL) { err(EXIT_FAILURE, "fopen %s", args.output); } hvn_web_render(output, document, options, &args); fclose(output); } else { hvn_web_render(stdout, document, options, &args); } cmark_node_free(document); free(args.tail); free(args.head); free(args.output); free(args.input); return EXIT_SUCCESS; }
TamarLabs/redischema
redischema.h
<gh_stars>0 #ifndef REDISCHEMA_H #define REDISCHEMA_H #define MODULE_NAME "redischema" #define SCHEMA_LOAD_ARGS_LIMIT 2 #define SCHEMA_LOAD_ARG_LIST 1 #define REDIS_HIERARCHY_DELIM ":" #define SCHEMA_KEY_SET "module:schema:order" #define SCHEMA_KEY_PREFIX "module:schema:keys:" #define OK_STR "OK" #define ZRANGE_CMD "ZRANGE" #define ZRANGE_FMT "cll" #define ZRANK_CMD "ZRANK" #define ZRANK_FMT "cc" #define ZCOUNT_CMD "ZCOUNT" #define ZCOUNT_FMT "cll" #define KEYS_CMD "keys" #define KEYS_FMT "c" #define ALL_KEYS "*" #define INCR_CMD "INCR" #define INCR_FMT "c" #define GET_CMD "GET" #define GET_FMT "c" #define RM_CreateString(ctx, str) RedisModule_CreateString(ctx,str,strlen(str)) #define MODULE_ERROR -1 #define ERR_MSG_NO_MEM "parse error - insufficient memory" #define ERR_MSG_TOO_MANY_KEYS "the query has too many keys" #define ERR_MSG_SINGLE_VALUE "key is expected to have a single value" #define ERR_MSG_GENERAL_ERROR "a general error has occured" #define ERR_MSG_INVALID_INPUT "json input is invalid" #define ERR_MSG_NOMEM "not enough tokens provided" #define ERR_MSG_MEMBER_NOT_FOUND "key or value not found in schema" #define NO_KEYS_MATCHED "no keys matched the given filter" #define SCHEMA_SET_OK_STR "schema values loaded" typedef enum { PARSER_INIT, PARSER_KEY, PARSER_VAL, PARSER_DONE, PARSER_ERR } PARSER_STAGE; typedef enum { OP_INIT, OP_MID, OP_DONE, OP_ERR } OP_STAGE; typedef enum { false, true } bool; typedef enum { S_OP_SUM, S_OP_AVG, S_OP_MIN, S_OP_MAX, S_OP_CLR, S_OP_INC, S_OP_GET, S_OP_SET } SCHEMA_OP; typedef struct PARSER_STATE PARSER_STATE; //forward declaration typedef int (*parser_handler)(RedisModuleCtx*, PARSER_STATE*); typedef const char *C_CHARS; typedef char* schema_elem_t; typedef struct Query { schema_elem_t **key_set; size_t key_set_size; size_t *val_sizes; } Query; typedef struct PARSER_STATE { const char *input; jsmntok_t *key; int key_ord; jsmntok_t *val; int val_ord; int schema_key_ord; //this field is used in operation parser, remembers the current elem ord in schema bool single_value; //this field is used in parse_next_token, false if vale is in an array Query query; parser_handler handler; PARSER_STAGE stage; const char *err_msg; } PARSER_STATE; typedef struct op_state { OP_STAGE stage; SCHEMA_OP op; size_t match_count; float aggregate; } OP_STATE; #define RMUtil_RegisterReadCmd(ctx, cmd, f) \ if (RedisModule_CreateCommand(ctx, cmd, f, "readonly fast allow-loading allow-stale", \ 1, 1, 1) == REDISMODULE_ERR) return REDISMODULE_ERR; #endif /* REDISCHEMA_H */
TamarLabs/redischema
redischema.c
<reponame>TamarLabs/redischema #include "redismodule.h" #include <string.h> #include <stdlib.h> #include "jsmn.h" #include "redischema.h" int report_error(RedisModuleCtx *ctx, C_CHARS msg, PARSER_STATE *parser) { RedisModule_ReplyWithSimpleString(ctx, msg); return REDISMODULE_ERR; } /* walk a jason array the function allows an array or a single value */ int walk_array(RedisModuleCtx *ctx, jsmntok_t *root, PARSER_STATE *parser) { int steps = 0, resp = 0; int val_count = (root->type != JSMN_ARRAY)? 1 : root->size; parser->single_value = (root->type != JSMN_ARRAY); if(! parser->single_value) steps++; for (int i=0; i < val_count; ++i) { parser->val = root+steps; steps++; parser->stage = PARSER_VAL; resp = parser->handler(ctx, parser); if(resp < 0) return resp; parser->val_ord++; } return steps; } /* walk a json map walk_object */ int walk_object(RedisModuleCtx *ctx, jsmntok_t *root, PARSER_STATE *parser) { int key_count = root->size; //TODO: check are there more than key_count tokens if(root->type != JSMN_OBJECT) { parser->err_msg = ERR_MSG_INVALID_INPUT; return MODULE_ERROR; } int steps = 1; //skip the object opener '{' for (int i=0; i < key_count; ++i) { jsmntok_t *node = root+steps; if (node->type != JSMN_STRING) { parser->err_msg = ERR_MSG_INVALID_INPUT; return MODULE_ERROR; } parser->key = node; parser->val=NULL; parser->stage = PARSER_KEY; int resp = parser->handler(ctx, parser); if(resp < 0) return MODULE_ERROR; parser->val_ord = 0; steps++; node = root + steps; if (node->type != JSMN_ARRAY && node->type != JSMN_PRIMITIVE && node->type != JSMN_STRING) { parser->err_msg = ERR_MSG_INVALID_INPUT; return MODULE_ERROR; } resp = walk_array(ctx, node, parser); if(resp < 0) return MODULE_ERROR; steps += resp; parser->key_ord++; } return steps; } /* walk a json from user input */ int json_walk(RedisModuleCtx *ctx, jsmntok_t *root, PARSER_STATE *parser) { parser->key_ord=0; parser->val_ord= 0; if (root->type != JSMN_OBJECT) { parser->err_msg = ERR_MSG_INVALID_INPUT; return MODULE_ERROR; } return walk_object(ctx, root, parser); } /* delete a key from redis */ int delete_key(RedisModuleCtx *ctx, C_CHARS key) { RedisModuleString *key_str = RM_CreateString(ctx, key); RedisModuleKey *redis_key=RedisModule_OpenKey(ctx,key_str,REDISMODULE_WRITE); int rsp = RedisModule_DeleteKey(redis_key); RedisModule_CloseKey(redis_key); RedisModule_FreeString(ctx, key_str); return rsp; } /* returned pointer must be freed */ char* concat_prefix(C_CHARS prefix, C_CHARS str) { char *ret = malloc((strlen(prefix) + strlen(str) + 1) * sizeof(char)); strcpy(ret, prefix); strcat(ret, str); return ret; } /* returned pointer must be freed */ char *get_string_from_reply(RedisModuleCallReply *reply) { if(reply == NULL) return NULL; size_t len=0; C_CHARS reply_str = RedisModule_CallReplyStringPtr(reply, &len); char *ret = strndup(reply_str, len); return ret; } /* returned pointer must be freed */ char *get_reply_element_at(RedisModuleCallReply *reply, int index) { RedisModuleCallReply *elem = RedisModule_CallReplyArrayElement(reply,index); return get_string_from_reply(elem); } int get_zset_size(RedisModuleCtx *ctx, C_CHARS key) { RedisModuleCallReply *reply = RedisModule_Call(ctx,ZCOUNT_CMD,ZCOUNT_FMT, key,0,REDISMODULE_POSITIVE_INFINITE); int size = RedisModule_CallReplyInteger(reply); RedisModule_FreeCallReply(reply); return size; } /* returned pointer must be freed */ char* zset_get_element_by_index(RedisModuleCtx *ctx, C_CHARS key, int index) { RedisModuleCallReply *reply = RedisModule_Call(ctx,ZRANGE_CMD,ZRANGE_FMT, key,index,index); char *elem = get_reply_element_at(reply,0); RedisModule_FreeCallReply(reply); return elem; } //TODO: test for increment of float and string keys, check for errors int increment_key(RedisModuleCtx *ctx, C_CHARS key) { RedisModuleCallReply *reply = RedisModule_Call(ctx,INCR_CMD,INCR_FMT,key); if(reply == NULL) return MODULE_ERROR; RedisModule_FreeCallReply(reply); return REDISMODULE_OK; } int zset_get_rank(RedisModuleCtx *ctx, C_CHARS key, C_CHARS member) { RedisModuleCallReply *reply = RedisModule_Call(ctx,ZRANK_CMD,ZRANK_FMT, key,member); if(reply == NULL || RedisModule_CallReplyType(reply)==REDISMODULE_REPLY_NULL) return MODULE_ERROR; int rank = RedisModule_CallReplyInteger(reply); RedisModule_FreeCallReply(reply); return rank; } int delete_key_with_prefix(RedisModuleCtx *ctx, C_CHARS prefix, C_CHARS key) { char *full_key = concat_prefix(prefix, key); int rsp = delete_key(ctx, full_key); free(full_key); return rsp; } int cleanup_schema(RedisModuleCtx *ctx, C_CHARS elem_loc, C_CHARS val_prefix) { int i=0; char *elem = zset_get_element_by_index(ctx, elem_loc,i++); while(elem != NULL) { delete_key_with_prefix(ctx, val_prefix, elem); free(elem); elem = zset_get_element_by_index(ctx, elem_loc,i++); } return delete_key(ctx,elem_loc); } int add_elm_to_zset(RedisModuleCtx *ctx, C_CHARS key, C_CHARS key_set,int ord) { RedisModuleString *key_str = RM_CreateString(ctx, key); RedisModuleString *key_set_str = RM_CreateString(ctx, key_set); RedisModuleKey *redis_key_set = RedisModule_OpenKey(ctx,key_set_str, REDISMODULE_WRITE); int flag = REDISMODULE_ZADD_NX; //element must not exist int rsp = RedisModule_ZsetAdd(redis_key_set, ord, key_str, &flag); RedisModule_CloseKey(redis_key_set); RedisModule_FreeString(ctx, key_set_str); RedisModule_FreeString(ctx, key_str); return (flag == REDISMODULE_ZADD_NOP)? flag : rsp; } int add_schema_key(RedisModuleCtx *ctx, C_CHARS key, C_CHARS key_set, int ord) { return add_elm_to_zset(ctx, key, key_set, ord); } int add_schema_val(RedisModuleCtx *ctx, C_CHARS val, C_CHARS key, C_CHARS prefix, int ord) { char *full_key = concat_prefix(prefix, key); int rsp = add_elm_to_zset(ctx, val, full_key, ord); free(full_key); return rsp; } /* returned pointer must be freed */ char* token_to_string(jsmntok_t *token, C_CHARS input) { if(token == NULL) return NULL; return strndup(input + token->start, token->end - token->start); } int SchemaLoad_handler(RedisModuleCtx *ctx, PARSER_STATE *parser) { char *key = token_to_string(parser->key, parser->input); char *val = token_to_string(parser->val, parser->input); int ret = REDISMODULE_ERR; if(parser->stage == PARSER_KEY) ret = add_schema_key(ctx, key, SCHEMA_KEY_SET ,parser->key_ord); else if (parser->stage == PARSER_VAL) ret = add_schema_val(ctx, val, key, SCHEMA_KEY_PREFIX, parser->val_ord); free(val); free(key); return ret; } int check_key_update_parser(RedisModuleCtx *ctx, PARSER_STATE* parser) { char *key = token_to_string(parser->key, parser->input); int rank = zset_get_rank(ctx, SCHEMA_KEY_SET, key), ret = MODULE_ERROR; if(rank == MODULE_ERROR) { parser->err_msg = ERR_MSG_MEMBER_NOT_FOUND; ret = MODULE_ERROR; } else { parser->schema_key_ord = rank; ret = REDISMODULE_OK; } free(key); return ret; } int check_val_update_parser(RedisModuleCtx *ctx, PARSER_STATE* parser) { char *schema_key = token_to_string(parser->key, parser->input); char* full_key = concat_prefix(SCHEMA_KEY_PREFIX, schema_key); char* val = token_to_string(parser->val, parser->input); int rank = zset_get_rank(ctx, full_key, val); if(rank == MODULE_ERROR) parser->err_msg = ERR_MSG_MEMBER_NOT_FOUND; else if (parser->val_ord >= parser->query.val_sizes[parser->schema_key_ord]) parser->err_msg = ERR_MSG_TOO_MANY_KEYS; else parser->query.key_set[parser->schema_key_ord][parser->val_ord] = val; //val is not freed - will be freed when parser is freed free(schema_key); free(full_key); return (parser->err_msg == NULL)? REDISMODULE_OK : MODULE_ERROR; } bool match_key_to_query(C_CHARS key, Query *query) { char *key_dup = strdup(key); int k_ord = 0; char *token = strtok(key_dup,REDIS_HIERARCHY_DELIM); while (token != NULL && k_ord < query->key_set_size) { bool val_match = false; if(query->key_set[k_ord][0] == NULL) { val_match = true; goto advance_while; //No match required for this k_ord } for(int v_ord=0; v_ord < query->val_sizes[k_ord]; v_ord++) { if(query->key_set[k_ord][v_ord] == NULL) break; if(strcmp(query->key_set[k_ord][v_ord], token) == 0) { val_match = true; break; } } advance_while: token = strtok(NULL, REDIS_HIERARCHY_DELIM); k_ord++; if(val_match) continue; free(key_dup); return false; } free(key_dup); return true; } int validate_key(PARSER_STATE *parser) { char *key = token_to_string(parser->key, parser->input); bool match = match_key_to_query(key, &parser->query); free(key); return (match)? REDISMODULE_OK : REDISMODULE_ERR; } int SchemaOperations_handler(RedisModuleCtx *ctx, PARSER_STATE *parser) { switch(parser->stage) { case PARSER_KEY: return check_key_update_parser(ctx, parser); case PARSER_VAL: return check_val_update_parser(ctx, parser); default: parser->err_msg = ERR_MSG_GENERAL_ERROR; return MODULE_ERROR; } } int schema_set_val(RedisModuleCtx *ctx, PARSER_STATE *parser) { char *key = token_to_string(parser->key, parser->input); char *val = token_to_string(parser->val, parser->input); RedisModuleString *key_str = RM_CreateString(ctx, key); RedisModuleString *val_str = RM_CreateString(ctx, val); RedisModuleKey *redis_key= RedisModule_OpenKey(ctx,key_str,REDISMODULE_WRITE); int rsp = RedisModule_StringSet(redis_key, val_str); RedisModule_CloseKey(redis_key); RedisModule_FreeString(ctx, val_str); RedisModule_FreeString(ctx, key_str); free(val); free(key); return rsp; } int SchemaSet_handler(RedisModuleCtx *ctx, PARSER_STATE *parser) { switch(parser->stage) { case PARSER_KEY: return validate_key(parser); case PARSER_VAL: if(! parser->single_value) parser->err_msg = ERR_MSG_SINGLE_VALUE; return (parser->err_msg==NULL)? schema_set_val(ctx, parser): MODULE_ERROR; default: parser->err_msg = ERR_MSG_GENERAL_ERROR; return MODULE_ERROR; } } int parse_input(RedisModuleCtx *ctx, PARSER_STATE *parser) { jsmn_parser p; int r; jsmntok_t *tok; size_t tokcount = strlen(parser->input)/2; jsmn_init(&p); tok = malloc(sizeof(*tok) * tokcount); if (tok == NULL) { parser->err_msg = ERR_MSG_NOMEM; return MODULE_ERROR; } r = jsmn_parse(&p, parser->input, strlen(parser->input), tok, tokcount); if(r<0) { parser->err_msg = (r == JSMN_ERROR_NOMEM)? ERR_MSG_NOMEM: ERR_MSG_INVALID_INPUT; return MODULE_ERROR; } return json_walk(ctx, tok, parser); } //TODO: fix reply int SchemaCleanCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){ int resp = cleanup_schema(ctx, SCHEMA_KEY_SET, SCHEMA_KEY_PREFIX); RedisModule_ReplyWithSimpleString(ctx, OK_STR); return resp; } int SchemaLoadCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){ if(argc != SCHEMA_LOAD_ARGS_LIMIT) { return RedisModule_WrongArity(ctx); } size_t len; int resp; cleanup_schema(ctx, SCHEMA_KEY_SET, SCHEMA_KEY_PREFIX); PARSER_STATE parser; parser.err_msg = NULL; parser.input = RedisModule_StringPtrLen(argv[SCHEMA_LOAD_ARG_LIST], &len); parser.handler = SchemaLoad_handler; resp = parse_input(ctx, &parser); if(resp < 0) return report_error(ctx, parser.err_msg, &parser); // ERR: change message RedisModule_ReplyWithSimpleString(ctx, OK_STR); return REDISMODULE_OK; } float get_numeric_key(RedisModuleCtx *ctx, char const *key, OP_STATE* state) { RedisModuleCallReply *reply = RedisModule_Call(ctx,GET_CMD,GET_FMT,key); if(reply == NULL) { state->stage = OP_ERR; return REDISMODULE_ERR; } //TODO: go over negative infinite and change float ret = atof(get_string_from_reply(reply)); RedisModule_FreeCallReply(reply); return ret; } int schema_op_init(RedisModuleCtx *ctx, char *key, OP_STATE* state) { switch (state->op) { case S_OP_GET: RedisModule_ReplyWithArray(ctx,REDISMODULE_POSTPONED_ARRAY_LEN); break; case S_OP_AVG: case S_OP_SUM: state->aggregate = 0; break; case S_OP_MIN: case S_OP_MAX: state->aggregate = get_numeric_key(ctx, key, state); break; default: break; } state->stage = OP_MID; return REDISMODULE_OK; } int schema_op_mid(RedisModuleCtx *ctx, char *key, OP_STATE* state) { long result=0; switch (state->op) { case S_OP_GET: RedisModule_ReplyWithSimpleString(ctx, key); break; case S_OP_INC: increment_key(ctx, key); break; case S_OP_CLR: delete_key(ctx,key); break; case S_OP_AVG: case S_OP_SUM: result = get_numeric_key(ctx, key, state); state->aggregate += result; break; case S_OP_MIN: result = get_numeric_key(ctx, key, state); if(result < state->aggregate) state->aggregate = result; break; case S_OP_MAX: result = get_numeric_key(ctx, key, state); if(result > state->aggregate) state->aggregate = result; break; default: break; } state->match_count++; return REDISMODULE_OK; } //TODO: error handling + reply for all cases + reply during error int schema_op_done(RedisModuleCtx *ctx, OP_STATE* state) { switch (state->op) { case S_OP_GET: RedisModule_ReplySetArrayLength(ctx,state->match_count); if(state->match_count == 0) RedisModule_ReplyWithSimpleString(ctx, NO_KEYS_MATCHED); break; case S_OP_SUM: case S_OP_MIN: case S_OP_MAX: RedisModule_ReplyWithLongLong(ctx, state->aggregate); break; case S_OP_AVG: RedisModule_ReplyWithLongLong(ctx, state->aggregate/state->match_count); break; default: RedisModule_ReplyWithSimpleString(ctx, OK_STR); break; } return REDISMODULE_OK; } int found_matched_key(RedisModuleCtx *ctx, char *key, OP_STATE* state) { switch (state->stage) { case OP_INIT: schema_op_init(ctx, key, state); case OP_MID: schema_op_mid(ctx, key, state); break; case OP_DONE: schema_op_done(ctx, state); break; default: break; } return REDISMODULE_OK; } int filter_results_and_reply(RedisModuleCtx *ctx, Query *query, SCHEMA_OP op) { RedisModuleCallReply *reply=RedisModule_Call(ctx,KEYS_CMD,KEYS_FMT,ALL_KEYS); size_t keys_length = RedisModule_CallReplyLength(reply); OP_STATE state; state.op = op; state.stage = OP_INIT; state.match_count = 0; for(int i=0; i < keys_length; ++i) { char* key = get_reply_element_at(reply,i); if(match_key_to_query(key, query)) { found_matched_key(ctx, key, &state); } free(key); } RedisModule_FreeCallReply(reply); state.stage = OP_DONE; found_matched_key(ctx, NULL, &state); return REDISMODULE_OK; } void build_query(RedisModuleCtx *ctx, Query *query, bool fill) { query->key_set_size = get_zset_size(ctx, SCHEMA_KEY_SET); query->key_set = malloc(sizeof(schema_elem_t*) * query->key_set_size); query->val_sizes = malloc(sizeof(size_t) * query->key_set_size); for(int i=0; i<query->key_set_size; ++i) { schema_elem_t key = zset_get_element_by_index(ctx, SCHEMA_KEY_SET, i); schema_elem_t full_key = concat_prefix(SCHEMA_KEY_PREFIX, key); query->val_sizes[i] = get_zset_size(ctx, full_key); query->key_set[i] = malloc(sizeof(char*) * query->val_sizes[i]); for (int j=0; j<query->val_sizes[i]; ++j) query->key_set[i][j]=fill?zset_get_element_by_index(ctx,full_key,j):NULL; free(full_key); free(key); } } void free_query(Query *query) { for(int i=0; i< query->key_set_size; ++i) { for(int j=0; j<query->val_sizes[i]; ++j) { if(query->key_set[i][j] != NULL) free(query->key_set[i][j]); } free(query->key_set[i]); } free(query->val_sizes); free(query->key_set); } int schemaOperationsCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc, SCHEMA_OP op) { if(argc != SCHEMA_LOAD_ARGS_LIMIT) { return RedisModule_WrongArity(ctx); } size_t len; int resp = REDISMODULE_OK; PARSER_STATE parser; parser.err_msg = NULL; parser.input = RedisModule_StringPtrLen(argv[SCHEMA_LOAD_ARG_LIST], &len); bool fill = (op == S_OP_SET); parser.handler= (op==S_OP_SET)? SchemaSet_handler : SchemaOperations_handler; build_query(ctx, &parser.query, fill); resp = parse_input(ctx, &parser); if(resp<0) resp = report_error(ctx, parser.err_msg, &parser); // ERR: change message else if(op != S_OP_SET) filter_results_and_reply(ctx, &parser.query, op); else RedisModule_ReplyWithSimpleString(ctx, SCHEMA_SET_OK_STR); free_query(&parser.query); return resp; } int SchemaSetCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { return schemaOperationsCommand(ctx, argv, argc, S_OP_SET); } int SchemaGetCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { return schemaOperationsCommand(ctx, argv, argc, S_OP_GET); } int SchemaSumCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { return schemaOperationsCommand(ctx, argv, argc, S_OP_SUM); } int SchemaAvgCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { return schemaOperationsCommand(ctx, argv, argc, S_OP_AVG); } int SchemaMinCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { return schemaOperationsCommand(ctx, argv, argc, S_OP_MIN); } int SchemaMaxCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { return schemaOperationsCommand(ctx, argv, argc, S_OP_MAX); } int SchemaClrCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { return schemaOperationsCommand(ctx, argv, argc, S_OP_CLR); } int SchemaIncCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { return schemaOperationsCommand(ctx, argv, argc, S_OP_INC); } int RedisModule_OnLoad(RedisModuleCtx *ctx) { // Register the module itself if (RedisModule_Init(ctx, MODULE_NAME, 1, REDISMODULE_APIVER_1) == REDISMODULE_ERR) { return REDISMODULE_ERR; } // register Commands - using the shortened utility registration macro RMUtil_RegisterReadCmd(ctx, "SchemaLoad", SchemaLoadCommand); RMUtil_RegisterReadCmd(ctx, "SchemaClean", SchemaCleanCommand); RMUtil_RegisterReadCmd(ctx, "SchemaGet", SchemaGetCommand); RMUtil_RegisterReadCmd(ctx, "SchemaSet", SchemaSetCommand); //schema operations RMUtil_RegisterReadCmd(ctx, "SchemaSUM", SchemaSumCommand); RMUtil_RegisterReadCmd(ctx, "SchemaAVG", SchemaAvgCommand); RMUtil_RegisterReadCmd(ctx, "SchemaMIN", SchemaMinCommand); RMUtil_RegisterReadCmd(ctx, "SchemaMAX", SchemaMaxCommand); RMUtil_RegisterReadCmd(ctx, "SchemaCLR", SchemaClrCommand); RMUtil_RegisterReadCmd(ctx, "SchemaINC", SchemaIncCommand); return REDISMODULE_OK; }
electrickery/logicTester
arduinoCode/pinMap.h
// pin mapping from IC (adding one) to Arduino, power pins are 0 #define MAX_PINCOUNT 16 #define EXERCISE_PINCOUNT 14 #define QUERY_PINCOUNT 10 byte pins14[] = { 13, 12, 11, 10, 9, 8, 0, 2, 3, 4, 5, 6, 7, 0 }; byte power14 = A5; byte pins16[] = { A0, 13, 12, 11, 10, 9, 8, 0, 2, 3, 4, 5, 6, 7, A1, 0 }; // not implemented //byte power16 = ? byte pins20[] = { A2, A3, A0, 13, 12, 11, 10, 9, 8, 0, 7, 6, 5, 4, 3, 2, A1, A4, A5, 0}; byte *pinMap;
electrickery/logicTester
arduinoMegaCode/pinMap.h
// pin mapping from IC (adding one) to Arduino, power pins are 0 #define MAX_PINCOUNT 16 #define EXERCISE_PINCOUNT 14 #define QUERY_PINCOUNT 10 // Uno config //byte pins14[] = { 13, 12, 11, 10, 9, 8, 0, 2, 3, 4, 5, 6, 7, 0 }; //byte power14 = A5; //byte pins16[] = { A0, 13, 12, 11, 10, 9, 8, 0, 2, 3, 4, 5, 6, 7, A1, 0 }; // not implemented //byte power16 = ? //byte pins20[] = { A2, A3, A0, 13, 12, 11, 10, 9, 8, 0, 7, 6, 5, 4, 3, 2, A1, A4, A5, 0}; // Mega 2560 config byte pins14[] = { 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29 }; byte power14 = 7; byte pins16[] = { 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28 }; byte power16 = 6; byte pins20[] = { 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26 }; byte power20 = 5; byte pins24[] = { 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24 }; byte power24 = 4; byte pins28[] = { 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22 }; byte power28 = 3; byte *pinMap;
Rodrigez01/Meridian_113
blakserv/admincons.c
// Meridian 59, Copyright 1994-2012 <NAME> and <NAME>. // All rights reserved. // // This software is distributed under a license that is described in // the LICENSE file that accompanies it. // // Meridian is a registered trademark. /* * admincons.c * Has a list of constant values for admin mode. */ #include "blakserv.h" #define MAX_CONSTANTS_LINE 200 admin_constant_node *admin_constants; /* local function prototypes */ void AddAdminConstant(char *name,int value); void InitAdminConstants(void) { admin_constants = NULL; } void ResetAdminConstants(void) { admin_constant_node *ac,*temp; ac = admin_constants; while (ac != NULL) { temp = ac->next; FreeMemory(MALLOC_ID_ADMIN_CONSTANTS,ac->name,strlen(ac->name)+1); FreeMemory(MALLOC_ID_ADMIN_CONSTANTS,ac,sizeof(admin_constant_node)); ac = temp; } admin_constants = NULL; } void AddAdminConstant(char *name,int value) { admin_constant_node *ac; ac = (admin_constant_node *)AllocateMemory(MALLOC_ID_ADMIN_CONSTANTS, sizeof(admin_constant_node)); ac->name = (char *)AllocateMemory(MALLOC_ID_ADMIN_CONSTANTS, strlen(name)+1); strcpy(ac->name,name); ac->value = value; ac->next = admin_constants; admin_constants = ac; } void LoadAdminConstants(void) { FILE *constantsfile; char line[MAX_CONSTANTS_LINE]; int lineno; char *name_str,*value_str; int value; if (ConfigBool(CONSTANTS_ENABLED) == False) return; if ((constantsfile = fopen(ConfigStr(CONSTANTS_FILENAME),"rt")) == NULL) { eprintf("LoadAdminConstants can't open %s, no constants\n", ConfigStr(CONSTANTS_FILENAME)); return; } lineno = 0; while (fgets(line,MAX_CONSTANTS_LINE,constantsfile)) { lineno++; name_str = strtok(line,"= \t\n"); if (name_str == NULL) /* ignore blank lines */ continue; if (name_str[0] == '%') /* ignore comments lines */ continue; if (strlen(name_str) > 1 && name_str[0] == '/' && name_str[1] == '/') continue; value_str = strtok(NULL,"= \t\n"); if (name_str == NULL || name_str[0] == '%') { eprintf("LoadAdminConstants error reading value on line %i\n",lineno); continue; } if (sscanf(value_str,"%i",&value) != 1) { eprintf("LoadAdminConstants error parsing integer on line %i\n",lineno); continue; } AddAdminConstant(name_str,value); } fclose(constantsfile); } Bool LookupAdminConstant(const char *name,int *ret_ptr) { admin_constant_node *ac; ac = admin_constants; while (ac != NULL) { if (stricmp(name,ac->name) == 0) { *ret_ptr = ac->value; return True; } ac = ac->next; } return False; }
Rodrigez01/Meridian_113
blakserv/builtin.c
// Meridian 59, Copyright 1994-2012 <NAME> and <NAME>. // All rights reserved. // // This software is distributed under a license that is described in // the LICENSE file that accompanies it. // // Meridian is a registered trademark. /* * builtin.c * This module adds certain hard coded accounts if the accounts cannot be read in from the file. */ #include "blakserv.h" typedef struct { char *name; char *password; int type; char *game_name; } bi_account; bi_account bi_accounts[] = { { "Daenks", "somethingnew", ACCOUNT_ADMIN, "Daenks" }, }; enum { NUM_BUILTIN = sizeof(bi_accounts)/sizeof(bi_account) }; void CreateBuiltInAccounts(void) { int i, account_id, object_id = INVALID_OBJECT; val_type name_val,system_id_val; parm_node p[2]; for (i=0;i<NUM_BUILTIN;i++) { account_node *a; a = GetAccountByName(bi_accounts[i].name); if (a != NULL) account_id = a->account_id; else account_id = CreateAccountSecurePassword(bi_accounts[i].name,bi_accounts[i].password, bi_accounts[i].type); if (bi_accounts[i].game_name != NULL) { /* make a character for this account */ system_id_val.v.tag = TAG_OBJECT; system_id_val.v.data = GetSystemObjectID(); p[0].type = CONSTANT; p[0].value = system_id_val.int_val; p[0].name_id = SYSTEM_PARM; name_val.v.tag = TAG_RESOURCE; name_val.v.data = AddDynamicResource(bi_accounts[i].game_name); p[1].type = CONSTANT; p[1].value = name_val.int_val; p[1].name_id = NAME_PARM; switch (bi_accounts[i].type) { case ACCOUNT_GUEST : object_id = CreateObject(GUEST_CLASS,2,p); break; case ACCOUNT_NORMAL : object_id = CreateObject(USER_CLASS,2,p); break; case ACCOUNT_DM : object_id = CreateObject(DM_CLASS,2,p); break; case ACCOUNT_ADMIN : #if 1 if (i < 2) object_id = CreateObject(CREATOR_CLASS,2,p); else #endif object_id = CreateObject(ADMIN_CLASS,2,p); break; } if (object_id == INVALID_OBJECT || AssociateUser(account_id,object_id) == false) eprintf("CreateBuiltInAccounts had AssociateUser fail, on account %i object %i\n", account_id, object_id); } } }
Rodrigez01/Meridian_113
blakserv/timer.h
<reponame>Rodrigez01/Meridian_113 // Meridian 59, Copyright 1994-2012 <NAME> and <NAME>. // All rights reserved. // // This software is distributed under a license that is described in // the LICENSE file that accompanies it. // // Meridian is a registered trademark. /* * timer.h * */ #ifndef _TIMER_H #define _TIMER_H #define INIT_TIMER_NODES (2000) typedef struct timer_struct { UINT64 time; int timer_id; int object_id; int message_id; int garbage_ref; int heap_index; } timer_node; bool TimerHeapCheck(int i, int level); void InitTimer(void); void ResetTimer(void); void ClearTimer(void); void PauseTimers(void); void UnpauseTimers(void); int CreateTimer(int object_id,int message_id,int milliseconds); Bool LoadTimer(int timer_id,int object_id,char *message_name,int milliseconds); Bool DeleteTimer(int timer_id); void ServiceTimers(void); void QuitTimerLoop(void); timer_node * GetTimerByID(int timer_id); void ForEachTimer(void (*callback_func)(timer_node *t)); void SetNumTimers(int new_next_timer_num); Bool InMainLoop(void); int GetNumActiveTimers(void); #endif
Rodrigez01/Meridian_113
blakserv/sendmsg.c
// Meridian 59, Copyright 1994-2012 <NAME> and <NAME>. // All rights reserved. // // This software is distributed under a license that is described in // the LICENSE file that accompanies it. // // Meridian is a registered trademark. /* * sendmsg.c * This module interprets compiled Blakod. */ #include "blakserv.h" /* global debugging and profiling information */ /* stuff to calculate messages & times */ int message_depth = 0; /* stack has class and bkod ptr for each frame. For current frame, bkod_ptr is as of the beginning of the function call */ kod_stack_type stack[MAX_DEPTH]; kod_statistics kod_stat; /* actual statistics */ char *bkod; int num_interpreted = 0; /* number of instructions in this top level call */ int trace_session_id = INVALID_ID; post_queue_type post_q; // Structs for unary/binary op to read data quicker. Can't include the // info byte as the alignment will be incorrect. Forcing alignment with // the extra byte generates slower code. typedef struct { bkod_type dest; bkod_type source; } unopdata_node; typedef struct { bkod_type dest; bkod_type source1; bkod_type source2; } binopdata_node; /* return values for InterpretAtMessage */ enum { RETURN_NONE = 0, RETURN_PROPAGATE = 1, RETURN_NO_PROPAGATE = 2, }; /* table of pointers to functions to call for ccode functions */ typedef int (*ccall_proc)(int object_id,local_var_type *local_vars, int num_normal_parms,parm_node normal_parm_array[], int num_name_parms,parm_node name_parm_array[]); ccall_proc ccall_table[MAX_C_FUNCTION]; int done; /* local function prototypes */ int InterpretAtMessage(int object_id,class_node* c,message_node* m, int num_sent_parms,parm_node sent_parms[], val_type *ret_val); __inline void StoreValue(int object_id,local_var_type *local_vars,int data_type,int data, val_type new_data); void InterpretUnaryAssign(int object_id,local_var_type *local_vars,opcode_type opcode); void InterpretBinaryAssign(int object_id,local_var_type *local_vars,opcode_type opcode); void InterpretGoto(int object_id, local_var_type *local_vars, opcode_type opcode); void InterpretCall(int object_id,local_var_type *local_vars,opcode_type opcode); void InitProfiling(void) { int i; if (done) return; kod_stat.num_interpreted = 0; kod_stat.num_interpreted_highest = 0; kod_stat.billions_interpreted = 0; kod_stat.num_messages = 0; kod_stat.num_top_level_messages = 0; kod_stat.system_start_time = GetTime(); kod_stat.interpreting_time = 0.0; kod_stat.interpreting_time_highest = 0; kod_stat.interpreting_time_over_second = 0; kod_stat.interpreting_time_message_id = INVALID_ID; kod_stat.interpreting_time_object_id = INVALID_ID; kod_stat.interpreting_time_posts = 0; kod_stat.message_depth_highest = 0; kod_stat.interpreting_class = INVALID_CLASS; for (i = 0; i < MAX_C_FUNCTION; i++) kod_stat.c_count_untimed[i] = 0; for (i = 0; i < MAX_C_FUNCTION; i++) kod_stat.c_count_timed[i] = 0; for (i = 0; i < MAX_C_FUNCTION; i++) kod_stat.ccall_total_time[i] = 0; message_depth = 0; if (ConfigBool(DEBUG_TIME_CALLS)) InitTimeProfiling(); else kod_stat.debugtime = false; done = 1; } void InitTimeProfiling(void) { kod_stat.debugtime = true; } void EndTimeProfiling(void) { kod_stat.debugtime = false; } void InitBkodInterpret(void) { int i; bkod = NULL; post_q.next = 0; post_q.last = 0; for (i=0;i<MAX_C_FUNCTION;i++) ccall_table[i] = C_Invalid; ccall_table[CREATEOBJECT] = C_CreateObject; ccall_table[ISCLASS] = C_IsClass; ccall_table[GETCLASS] = C_GetClass; ccall_table[SENDMESSAGE] = C_SendMessage; ccall_table[POSTMESSAGE] = C_PostMessage; ccall_table[SENDLISTMSG] = C_SendListMessage; ccall_table[SENDLISTMSGBREAK] = C_SendListMessageBreak; ccall_table[SENDLISTMSGBYCLASS] = C_SendListMessageByClass; ccall_table[SENDLISTMSGBYCLASSBREAK] = C_SendListMessageByClassBreak; ccall_table[SAVEGAME] = C_SaveGame; ccall_table[LOADGAME] = C_LoadGame; ccall_table[ADDPACKET] = C_AddPacket; ccall_table[SENDPACKET] = C_SendPacket; ccall_table[SENDCOPYPACKET] = C_SendCopyPacket; ccall_table[CLEARPACKET] = C_ClearPacket; ccall_table[GODLOG] = C_GodLog; ccall_table[DEBUG] = C_Debug; ccall_table[GETINACTIVETIME] = C_GetInactiveTime; ccall_table[DUMPSTACK] = C_DumpStack; ccall_table[STRINGEQUAL] = C_StringEqual; ccall_table[STRINGCONTAIN] = C_StringContain; ccall_table[SETRESOURCE] = C_SetResource; ccall_table[PARSESTRING] = C_ParseString; ccall_table[SETSTRING] = C_SetString; ccall_table[APPENDTEMPSTRING] = C_AppendTempString; ccall_table[CLEARTEMPSTRING] = C_ClearTempString; ccall_table[GETTEMPSTRING] = C_GetTempString; ccall_table[CREATESTRING] = C_CreateString; ccall_table[ISSTRING] = C_IsString; ccall_table[STRINGSUBSTITUTE] = C_StringSubstitute; ccall_table[STRINGLENGTH] = C_StringLength; ccall_table[STRINGCONSISTSOF] = C_StringConsistsOf; ccall_table[CREATETIMER] = C_CreateTimer; ccall_table[DELETETIMER] = C_DeleteTimer; ccall_table[GETTIMEREMAINING] = C_GetTimeRemaining; ccall_table[ISTIMER] = C_IsTimer; ccall_table[CREATEROOMDATA] = C_LoadRoom; ccall_table[FREEROOM] = C_FreeRoom; ccall_table[ROOMDATA] = C_RoomData; ccall_table[LINEOFSIGHTVIEW] = C_LineOfSightView; ccall_table[LINEOFSIGHTBSP] = C_LineOfSightBSP; ccall_table[CANMOVEINROOMBSP] = C_CanMoveInRoomBSP; ccall_table[CHANGETEXTUREBSP] = C_ChangeTextureBSP; ccall_table[MOVESECTORBSP] = C_MoveSectorBSP; ccall_table[GETLOCATIONINFOBSP] = C_GetLocationInfoBSP; ccall_table[BLOCKERADDBSP] = C_BlockerAddBSP; ccall_table[BLOCKERMOVEBSP] = C_BlockerMoveBSP; ccall_table[BLOCKERREMOVEBSP] = C_BlockerRemoveBSP; ccall_table[BLOCKERCLEARBSP] = C_BlockerClearBSP; ccall_table[GETRANDOMPOINTBSP] = C_GetRandomPointBSP; ccall_table[GETSTEPTOWARDSBSP] = C_GetStepTowardsBSP; ccall_table[APPENDLISTELEM] = C_AppendListElem; ccall_table[CONS] = C_Cons; ccall_table[FIRST] = C_First; ccall_table[REST] = C_Rest; ccall_table[LENGTH] = C_Length; ccall_table[LAST] = C_Last; ccall_table[NTH] = C_Nth; ccall_table[MLIST] = C_List; ccall_table[ISLIST] = C_IsList; ccall_table[SETFIRST] = C_SetFirst; ccall_table[SETNTH] = C_SetNth; ccall_table[SWAPLISTELEM] = C_SwapListElem; ccall_table[INSERTLISTELEM] = C_InsertListElem; ccall_table[DELLISTELEM] = C_DelListElem; ccall_table[FINDLISTELEM] = C_FindListElem; ccall_table[ISLISTMATCH] = C_IsListMatch; ccall_table[GETLISTELEMBYCLASS] = C_GetListElemByClass; ccall_table[GETLISTNODE] = C_GetListNode; ccall_table[GETALLLISTNODESBYCLASS] = C_GetAllListNodesByClass; ccall_table[LISTCOPY] = C_ListCopy; ccall_table[GETTIMEZONEOFFSET] = C_GetTimeZoneOffset; ccall_table[GETTIME] = C_GetTime; ccall_table[GETTICKCOUNT] = C_GetTickCount; ccall_table[SETCLASSVAR] = C_SetClassVar; ccall_table[CREATETABLE] = C_CreateTable; ccall_table[ADDTABLEENTRY] = C_AddTableEntry; ccall_table[GETTABLEENTRY] = C_GetTableEntry; ccall_table[DELETETABLEENTRY] = C_DeleteTableEntry; ccall_table[DELETETABLE] = C_DeleteTable; ccall_table[ISTABLE] = C_IsTable; ccall_table[ISOBJECT] = C_IsObject; ccall_table[RECYCLEUSER] = C_RecycleUser; ccall_table[RANDOM] = C_Random; ccall_table[RECORDSTAT] = C_RecordStat; ccall_table[GETSESSIONIP] = C_GetSessionIP; ccall_table[ABS] = C_Abs; ccall_table[BOUND] = C_Bound; ccall_table[SQRT] = C_Sqrt; ccall_table[MINIGAMENUMBERTOSTRING] = C_MinigameNumberToString; ccall_table[MINIGAMESTRINGTONUMBER] = C_MinigameStringToNumber; } kod_statistics * GetKodStats() { return &kod_stat; } /* this pointer only makes sense when interpreting (used by bprintf only) */ char * GetBkodPtr(void) { return bkod; } /* used by object.c to see if creation of object should call SendTopLevelBlakodMessage or SendBlakodMessage */ Bool IsInterpreting(void) { return bkod != NULL; } void TraceInfo(int session_id,char *class_name,int message_id,int num_parms, parm_node parms[]) { int i; val_type val; char trace_buf[BUFFER_SIZE]; char *buf_ptr = trace_buf; int num_chars; int buf_len = 0; if (num_parms == 0) num_chars = sprintf(buf_ptr, "%-15s%-20s\n", class_name, GetNameByID(message_id)); else num_chars = sprintf(buf_ptr, "%-15s%-20s ", class_name, GetNameByID(message_id)); buf_len += num_chars; buf_ptr += num_chars; for (i = 0; i < num_parms; ++i) { val.int_val = parms[i].value; if (i == num_parms - 1) num_chars = sprintf(buf_ptr, "%s = %s %s\n", GetNameByID(parms[i].name_id), GetTagName(val), GetDataName(val)); else num_chars = sprintf(buf_ptr, "%s = %s %s, ", GetNameByID(parms[i].name_id), GetTagName(val), GetDataName(val)); buf_len += num_chars; buf_ptr += num_chars; // Flushing shouldn't be necessary here, but just in case. if (buf_len > BUFFER_SIZE * 0.9) { buf_ptr -= buf_len; SendSessionAdminText(session_id, buf_ptr); buf_len = 0; } } buf_ptr -= buf_len; SendSessionAdminText(session_id, buf_ptr); } void PostBlakodMessage(int object_id,int message_id,int num_parms,parm_node parms[]) { int i, new_next; new_next = (post_q.next + 1) % MAX_POST_QUEUE; if (new_next == post_q.last) { bprintf("PostBlakodMessage can't post MESSAGE %s (%i) to OBJECT %i; queue filled\n", GetNameByID(message_id),message_id,object_id); return; } post_q.data[post_q.next].object_id = object_id; post_q.data[post_q.next].message_id = message_id; post_q.data[post_q.next].num_parms = num_parms; for (i=0;i<num_parms;i++) { post_q.data[post_q.next].parms[i] = parms[i]; } post_q.next = new_next; } /* returns the return value of the blakod */ int SendTopLevelBlakodMessage(int object_id,int message_id,int num_parms,parm_node parms[]) { int ret_val = 0; double start_time = 0; double interp_time = 0; int posts = 0; int accumulated_num_interpreted = 0; if (message_depth != 0) { eprintf("SendTopLevelBlakodMessage called with message_depth %i " "and message id %i\n", message_depth,message_id); } start_time = GetMicroCountDouble(); kod_stat.num_top_level_messages++; trace_session_id = INVALID_ID; num_interpreted = 0; ret_val = SendBlakodMessage(object_id,message_id,num_parms,parms); while (post_q.next != post_q.last) { posts++; accumulated_num_interpreted += num_interpreted; num_interpreted = 0; if (accumulated_num_interpreted > 10 * MAX_BLAKOD_STATEMENTS) { bprintf("SendTopLevelBlakodMessage too many instructions in posted followups\n"); dprintf("SendTopLevelBlakodMessage too many instructions in posted followups\n"); dprintf(" OBJECT %i CLASS %s MESSAGE %s (%i) some followups are being aborted\n", object_id, GetClassByID(GetObjectByID(object_id)->class_id)->class_name, GetNameByID(message_id), message_id); break; } /* posted messages' return value is ignored */ SendBlakodMessage(post_q.data[post_q.last].object_id,post_q.data[post_q.last].message_id, post_q.data[post_q.last].num_parms,post_q.data[post_q.last].parms); post_q.last = (post_q.last + 1) % MAX_POST_QUEUE; } interp_time = GetMicroCountDouble() - start_time; kod_stat.interpreting_time += interp_time; if (interp_time > kod_stat.interpreting_time_highest) { kod_stat.interpreting_time_highest = (int)interp_time; kod_stat.interpreting_time_message_id = message_id; kod_stat.interpreting_time_object_id = object_id; kod_stat.interpreting_time_posts = posts; } if (interp_time > 1000000.0) { kod_stat.interpreting_time_over_second++; kod_stat.interpreting_time_message_id = message_id; kod_stat.interpreting_time_object_id = object_id; kod_stat.interpreting_time_posts = posts; } if (num_interpreted > kod_stat.num_interpreted_highest) kod_stat.num_interpreted_highest = num_interpreted; kod_stat.num_interpreted += num_interpreted; if (kod_stat.num_interpreted > 1000000000L) { kod_stat.num_interpreted -= 1000000000L; kod_stat.billions_interpreted++; } if (message_depth != 0) { eprintf("SendTopLevelBlakodMessage returning with message_depth %i " "and message id %i\n", message_depth, message_id); } return ret_val; } typedef struct { int class_id; int message_id; int num_params; parm_node *parm; } ClassMessage, *PClassMessage; static ClassMessage classMsg; static int numExecuted; void SendClassMessage(object_node *object) { class_node *c = GetClassByID(object->class_id); do { if (c->class_id == classMsg.class_id) { SendBlakodMessage(object->object_id,classMsg.message_id, classMsg.num_params,classMsg.parm); numExecuted++; return; } c = c->super_ptr; } while (c != NULL); } int SendBlakodClassMessage(int class_id,int message_id,int num_params,parm_node parm[]) { numExecuted = 0; classMsg.class_id = class_id; classMsg.message_id = message_id; classMsg.num_params = num_params; classMsg.parm = parm; ForEachObject(SendClassMessage); return numExecuted; } /* returns the return value of the blakod */ int SendBlakodMessage(int object_id,int message_id,int num_parms,parm_node parms[]) { object_node *o; class_node *c,*propagate_class; message_node *m; val_type message_ret; int prev_interpreting_class; char *prev_bkod; int propagate_depth = 0; prev_bkod = bkod; prev_interpreting_class = kod_stat.interpreting_class; o = GetObjectByID(object_id); if (o == NULL) { bprintf("SendBlakodMessage can't find OBJECT %i\n",object_id); return NIL; } c = GetClassByID(o->class_id); if (c == NULL) { eprintf("SendBlakodMessage OBJECT %i can't find CLASS %i\n", object_id,o->class_id); return NIL; } m = GetMessageByID(c->class_id,message_id,&c); if (m == NULL) { bprintf("SendBlakodMessage CLASS %s (%i) OBJECT %i can't find a handler for MESSAGE %s (%i)\n", c->class_name,c->class_id,object_id,GetNameByID(message_id),message_id); return NIL; } kod_stat.num_messages++; stack[message_depth].class_id = c->class_id; stack[message_depth].message_id = m->message_id; stack[message_depth].propagate_depth = 0; stack[message_depth].num_parms = num_parms; memcpy(stack[message_depth].parms,parms,num_parms*sizeof(parm_node)); stack[message_depth].bkod_ptr = bkod; if (message_depth > 0) stack[message_depth-1].bkod_ptr = prev_bkod; message_depth++; if (message_depth > kod_stat.message_depth_highest) kod_stat.message_depth_highest = message_depth; if (message_depth >= MAX_DEPTH) { bprintf("SendBlakodMessage sending to CLASS %s (%i), depth is %i, aborted!\n", c->class_name,c->class_id,message_depth); kod_stat.interpreting_class = prev_interpreting_class; message_depth--; bkod = prev_bkod; return NIL; } if (m->trace_session_id != INVALID_ID) { trace_session_id = m->trace_session_id; m->trace_session_id = INVALID_ID; } if (trace_session_id != INVALID_ID) TraceInfo(trace_session_id,c->class_name,m->message_id,num_parms,parms); kod_stat.interpreting_class = c->class_id; bkod = m->handler; propagate_depth = 1; while (InterpretAtMessage(object_id,c,m,num_parms,parms,&message_ret) == RETURN_PROPAGATE) { propagate_class = m->propagate_class; m = m->propagate_message; if (m == NULL) { bprintf("SendBlakodMessage can't propagate MESSAGE %s (%i) in CLASS %s (%i)\n", GetNameByID(message_id),message_id,c->class_name,c->class_id); message_depth -= propagate_depth; kod_stat.interpreting_class = prev_interpreting_class; bkod = prev_bkod; return NIL; } if (propagate_class == NULL) { bprintf("SendBlakodMessage can't find class to propagate to, from " "MESSAGE %s (%i) in CLASS %s (%i)\n",GetNameByID(message_id), message_id,c->class_name,c->class_id); message_depth -= propagate_depth; kod_stat.interpreting_class = prev_interpreting_class; bkod = prev_bkod; return NIL; } c = propagate_class; if (m->trace_session_id != INVALID_ID) { trace_session_id = m->trace_session_id; m->trace_session_id = INVALID_ID; } if (trace_session_id != INVALID_ID) TraceInfo(trace_session_id,"(propagate)",m->message_id,num_parms,parms); kod_stat.interpreting_class = c->class_id; stack[message_depth-1].bkod_ptr = bkod; stack[message_depth].class_id = c->class_id; stack[message_depth].message_id = m->message_id; stack[message_depth].propagate_depth = propagate_depth; stack[message_depth].num_parms = num_parms; memcpy(stack[message_depth].parms,parms,num_parms*sizeof(parm_node)); stack[message_depth].bkod_ptr = m->handler; message_depth++; propagate_depth++; bkod = m->handler; } message_depth -= propagate_depth; kod_stat.interpreting_class = prev_interpreting_class; bkod = prev_bkod; return message_ret.int_val; } /* interpret code below here */ #define get_byte() (*bkod++) __inline unsigned int get_int() { bkod += 4; return *((unsigned int *)(bkod-4)); } /* before calling this, you MUST set bkod to point to valid bkod. */ /* returns either RETURN_PROPAGATE or RETURN_NO_PROPAGATE. If no propagate, * then the return value in ret_val is good. */ int InterpretAtMessage(int object_id,class_node* c,message_node* m, int num_sent_parms, parm_node sent_parms[],val_type *ret_val) { int parm_id; int i, j; double startTime; val_type parm_init_value; local_var_type local_vars; char num_locals, num_parms; Bool found_parm; // Time messages. if (kod_stat.debugtime) startTime = GetMicroCountDouble(); num_locals = get_byte(); num_parms = get_byte(); local_vars.num_locals = num_locals + num_parms; if (local_vars.num_locals > MAX_LOCALS) { dprintf("InterpretAtMessage found too many locals and parms for OBJECT %i CLASS %s MESSAGE %s (%s) aborting and returning NIL\n", object_id, c? c->class_name : "(unknown)", m? GetNameByID(m->message_id) : "(unknown)", BlakodDebugInfo()); (*ret_val).int_val = NIL; return RETURN_NO_PROPAGATE; } /* both table and call parms are sorted */ j = 0; i = 0; for (;i<num_parms;i++) { parm_id = get_int(); /* match this with parameters */ parm_init_value.int_val = get_int(); /* look if we have a value for this parm */ found_parm = False; j = 0; /* don't assume sorted for now */ while (j < num_sent_parms) { if (sent_parms[j].name_id == parm_id) { /* assuming no RetrieveValue needed here, since InterpretCall does that for us */ local_vars.locals[i].int_val = sent_parms[j].value; found_parm = True; j++; break; } j++; } if (!found_parm) local_vars.locals[i].int_val = parm_init_value.int_val; } // Init all non-parm locals to NIL for (;i < local_vars.num_locals; ++i) local_vars.locals[i].int_val = NIL; for(;;) /* returns when gets a blakod return */ { /* infinite loop check */ if (++num_interpreted > MAX_BLAKOD_STATEMENTS) { bprintf("InterpretAtMessage interpreted too many instructions--infinite loop?\n"); dprintf("Infinite loop at depth %i\n", message_depth); dprintf(" OBJECT %i CLASS %s MESSAGE %s (%s) aborting and returning NIL\n", object_id, c? c->class_name : "(unknown)", m? GetNameByID(m->message_id) : "(unknown)", BlakodDebugInfo()); dprintf(" Local variables:\n"); for (i=0;i<local_vars.num_locals;i++) { dprintf(" %3i : %s %5i\n", i, GetTagName(local_vars.locals[i]), local_vars.locals[i].v.data); } (*ret_val).int_val = NIL; return RETURN_NO_PROPAGATE; } // Get the opcode for this operation opcode_type *opcode = (opcode_type *)bkod++; /* use continues instead of breaks here since there is nothing after the switch, for efficiency */ switch (opcode->command) { case UNARY_ASSIGN : InterpretUnaryAssign(object_id,&local_vars,*opcode); continue; case BINARY_ASSIGN : InterpretBinaryAssign(object_id, &local_vars, *opcode); continue; case GOTO : InterpretGoto(object_id, &local_vars, *opcode); continue; case CALL : InterpretCall(object_id, &local_vars, *opcode); continue; case RETURN : if (kod_stat.debugtime) { m->total_call_time += (GetMicroCountDouble() - startTime); m->timed_call_count++; } else { m->untimed_call_count++; } if (opcode->dest == PROPAGATE) return RETURN_PROPAGATE; else { int data; data = get_int(); *ret_val = RetrieveValue(object_id, &local_vars, opcode->source1, data); return RETURN_NO_PROPAGATE; } /* can't get here */ continue; default : bprintf("InterpretAtMessage found INVALID OPCODE command %i. die.\n", opcode->command); FlushDefaultChannels(); continue; } } } /* RetrieveValue used to be here, but is inline, and used in ccode.c too, so it's in sendmsg.h now */ __inline void StoreValue(int object_id, local_var_type *local_vars, int data_type, int data, val_type new_data) { object_node *o; switch (data_type) { case LOCAL_VAR : if (data < 0 || data >= local_vars->num_locals) { eprintf("[%s] StoreValue can't write to illegal local var %i\n", BlakodDebugInfo(),data); return; } local_vars->locals[data].int_val = new_data.int_val; break; case PROPERTY : o = GetObjectByID(object_id); if (o == NULL) { eprintf("[%s] StoreValue can't find object %i\n", BlakodDebugInfo(),object_id); return; } // num_props includes self, so the max property is stored at [num_props - 1] if (data < 0 || data >= o->num_props) { eprintf("[%s] StoreValue can't write to illegal property %i (max %i)\n", BlakodDebugInfo(), data, o->num_props - 1); return; } o->p[data].val.int_val = new_data.int_val; break; default : eprintf("[%s] StoreValue can't identify type %i\n", BlakodDebugInfo(),data_type); break; } } void InterpretUnaryAssign(int object_id,local_var_type *local_vars,opcode_type opcode) { char info = get_byte(); unopdata_node *opnode = (unopdata_node*)((bkod += sizeof(unopdata_node)) - sizeof(unopdata_node)); val_type source_data = RetrieveValue(object_id, local_vars, opcode.source1, opnode->source); switch (info) { case NOT : if (source_data.v.tag != TAG_INT) { bprintf("InterpretUnaryAssign can't not non-int %i,%i\n", source_data.v.tag,source_data.v.data); break; } source_data.v.data = !source_data.v.data; break; case NEGATE : if (source_data.v.tag != TAG_INT) { bprintf("InterpretUnaryAssign can't negate non-int %i,%i\n", source_data.v.tag,source_data.v.data); break; } source_data.v.data = -source_data.v.data; break; case NONE : break; case BITWISE_NOT : if (source_data.v.tag != TAG_INT) { bprintf("InterpretUnaryAssign can't bitwise not non-int %i,%i\n", source_data.v.tag,source_data.v.data); break; } source_data.v.data = ~source_data.v.data; break; case POST_INCREMENT: if (source_data.v.tag != TAG_INT) { bprintf("InterpretUnaryAssign can't post-increment non-int %i,%i\n", source_data.v.tag,source_data.v.data); break; } if (opnode->source != opnode->dest || opcode.source1 != opcode.dest) StoreValue(object_id, local_vars, opcode.dest, opnode->dest, source_data); ++source_data.v.data; StoreValue(object_id, local_vars, opcode.source1, opnode->source, source_data); return; case PRE_INCREMENT: if (source_data.v.tag != TAG_INT) { bprintf("InterpretUnaryAssign can't pre-increment non-int %i,%i\n", source_data.v.tag, source_data.v.data); break; } ++source_data.v.data; if (opnode->source != opnode->dest || opcode.source1 != opcode.dest) StoreValue(object_id, local_vars, opcode.source1, opnode->source, source_data); break; case POST_DECREMENT : if (source_data.v.tag != TAG_INT) { bprintf("InterpretUnaryAssign can't post-decrement non-int %i,%i\n", source_data.v.tag,source_data.v.data); break; } if (opnode->source != opnode->dest || opcode.source1 != opcode.dest) StoreValue(object_id, local_vars, opcode.dest, opnode->dest, source_data); --source_data.v.data; StoreValue(object_id, local_vars, opcode.source1, opnode->source, source_data); return; case PRE_DECREMENT: if (source_data.v.tag != TAG_INT) { bprintf("InterpretUnaryAssign can't pre-decrement non-int %i,%i\n", source_data.v.tag, source_data.v.data); break; } --source_data.v.data; if (opnode->source != opnode->dest || opcode.source1 != opcode.dest) StoreValue(object_id, local_vars, opcode.source1, opnode->source, source_data); break; default : bprintf("InterpretUnaryAssign can't perform unary op %i\n",info); break; } StoreValue(object_id, local_vars, opcode.dest, opnode->dest, source_data); } void InterpretBinaryAssign(int object_id,local_var_type *local_vars,opcode_type opcode) { val_type source1_data,source2_data; char info = get_byte(); binopdata_node *opnode = (binopdata_node*)((bkod += sizeof(binopdata_node)) - sizeof(binopdata_node)); source1_data = RetrieveValue(object_id,local_vars,opcode.source1, opnode->source1); source2_data = RetrieveValue(object_id, local_vars, opcode.source2, opnode->source2); /* if (source1_data.v.tag != source2_data.v.tag) bprintf("InterpretBinaryAssign is operating on 2 diff types!\n"); */ switch (info) { case ADD : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't add 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data += source2_data.v.data; break; case SUBTRACT : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't sub 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data -= source2_data.v.data; break; case MULTIPLY : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't mult 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data *= source2_data.v.data; break; case DIV : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't div 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } if (source2_data.v.data == 0) { bprintf("InterpretBinaryAssign can't div by 0\n"); break; } source1_data.v.data /= source2_data.v.data; break; case MOD : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't mod 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } if (source2_data.v.data == 0) { bprintf("InterpretBinaryAssign can't mod 0\n"); break; } source1_data.v.data = abs(source1_data.v.data % source2_data.v.data); break; case AND : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't and 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data = source1_data.v.data && source2_data.v.data; break; case OR : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't or 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data = source1_data.v.data || source2_data.v.data; break; case EQUAL : #if 0 // disabled: used to be only TAG_NIL vs TAG_X, or TAG_X vs TAG_X is legal // now: TAG_X vs TAG_Y is legal, and returns FALSE for equal if (source1_data.v.tag != source2_data.v.tag && source1_data.v.tag != TAG_NIL && source2_data.v.tag != TAG_NIL) { bprintf("InterpretBinaryAssign can't = 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } #endif if (source1_data.v.tag != source2_data.v.tag) source1_data.v.data = False; else source1_data.v.data = source1_data.v.data == source2_data.v.data; source1_data.v.tag = TAG_INT; break; case NOT_EQUAL : #if 0 // disabled: used to be only TAG_NIL vs TAG_X, or TAG_X vs TAG_X is legal // now: TAG_X vs TAG_Y is legal, and returns TRUE for not equal if (source1_data.v.tag != source2_data.v.tag && source1_data.v.tag != TAG_NIL && source2_data.v.tag != TAG_NIL) { bprintf("InterpretBinaryAssign can't <> 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } #endif if (source1_data.v.tag != source2_data.v.tag) source1_data.v.data = True; else source1_data.v.data = source1_data.v.data != source2_data.v.data; source1_data.v.tag = TAG_INT; break; case LESS_THAN : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't < 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data = source1_data.v.data < source2_data.v.data; break; case GREATER_THAN : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't > 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data = source1_data.v.data > source2_data.v.data; break; case LESS_EQUAL : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't <= 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data = source1_data.v.data <= source2_data.v.data; break; case GREATER_EQUAL : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't >= 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data = source1_data.v.data >= source2_data.v.data; break; case BITWISE_AND : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't and 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data = source1_data.v.data & source2_data.v.data; break; case BITWISE_OR : if (source1_data.v.tag != TAG_INT || source2_data.v.tag != TAG_INT) { bprintf("InterpretBinaryAssign can't or 2 vars %i,%i and %i,%i\n", source1_data.v.tag,source1_data.v.data, source2_data.v.tag,source2_data.v.data); break; } source1_data.v.data = source1_data.v.data | source2_data.v.data; break; default : bprintf("InterpretBinaryAssign can't perform binary op %i\n", info); break; } StoreValue(object_id, local_vars, opcode.dest, opnode->dest, source1_data); } void InterpretGoto(int object_id, local_var_type *local_vars, opcode_type opcode) { int dest_addr; int var_check; val_type check_data; /* we've read one byte of instruction so far */ char *inst_start = bkod - 1; /* This function is called often, so the switch has been * optimized away to return the value immediately. */ dest_addr = get_int(); /* unconditional gotos have source2 bits set--otherwise, it's a goto only if the source1 bits have a non-zero var */ if (opcode.source2 == GOTO_UNCONDITIONAL) { bkod = inst_start + dest_addr; return; } var_check = get_int(); check_data = RetrieveValue(object_id,local_vars,opcode.source1,var_check); if ((opcode.dest == GOTO_IF_TRUE && check_data.v.data != 0) || (opcode.dest == GOTO_IF_FALSE && check_data.v.data == 0)) bkod = inst_start + dest_addr; } void InterpretCall(int object_id,local_var_type *local_vars,opcode_type opcode) { parm_node normal_parm_array[MAX_C_PARMS], name_parm_array[MAX_NAME_PARMS]; unsigned char info, num_normal_parms, num_name_parms, initial_type; int initial_value; val_type call_return, name_val; int assign_index; int i; info = get_byte(); /* get function id */ switch(opcode.source1) { case CALL_NO_ASSIGN : break; case CALL_ASSIGN_LOCAL_VAR : case CALL_ASSIGN_PROPERTY : assign_index = get_int(); break; } num_normal_parms = get_byte(); if (num_normal_parms > MAX_C_PARMS) { bprintf("InterpretCall found a call w/ more than %i parms, DEATH\n", MAX_C_PARMS); FlushDefaultChannels(); num_normal_parms = MAX_C_PARMS; } for (i=0;i<num_normal_parms;i++) { normal_parm_array[i].type = get_byte(); normal_parm_array[i].value = get_int(); } num_name_parms = get_byte(); if (num_name_parms > MAX_NAME_PARMS) { bprintf("InterpretCall found a call w/ more than %i name parms, DEATH\n", MAX_NAME_PARMS); FlushDefaultChannels(); num_name_parms = MAX_NAME_PARMS; } for (i=0;i<num_name_parms;i++) { name_parm_array[i].name_id = get_int(); initial_type = get_byte(); initial_value = get_int(); /* translate to literal now, because won't have local vars if nested call to sendmessage again */ /* maybe only need to do this in call to sendmessage and postmessage? */ name_val = RetrieveValue(object_id,local_vars,initial_type,initial_value); name_parm_array[i].value = name_val.int_val; } // Time messages. if (kod_stat.debugtime) { double startTime = GetMicroCountDouble(); /* increment timed count of the c function, for profiling info */ kod_stat.c_count_timed[info]++; call_return.int_val = ccall_table[info](object_id, local_vars, num_normal_parms, normal_parm_array, num_name_parms, name_parm_array); kod_stat.ccall_total_time[info] += (GetMicroCountDouble() - startTime); } else { /* increment untimed count of the c function, for profiling info */ kod_stat.c_count_untimed[info]++; call_return.int_val = ccall_table[info](object_id, local_vars, num_normal_parms, normal_parm_array, num_name_parms, name_parm_array); } switch(opcode.source1) { case CALL_NO_ASSIGN : break; case CALL_ASSIGN_LOCAL_VAR : case CALL_ASSIGN_PROPERTY : StoreValue(object_id,local_vars,opcode.source1,assign_index,call_return); break; } } char *BlakodDebugInfo() { static char s[100]; class_node *c; if (kod_stat.interpreting_class == INVALID_CLASS) { sprintf(s,"Server"); } else { c = GetClassByID(kod_stat.interpreting_class); if (c == NULL) sprintf(s,"Invalid class %i",kod_stat.interpreting_class); else sprintf(s,"%s (%i)",c->fname,GetSourceLine(c,bkod)); } return s; } char *BlakodStackInfo() { static char buf[5000]; class_node *c; int i; buf[0] = '\0'; for (i=message_depth-1;i>=0;i--) { char s[1000]; if (stack[i].class_id == INVALID_CLASS) { sprintf(s,"Server"); } else { c = GetClassByID(stack[i].class_id); if (c == NULL) sprintf(s,"Invalid class %i",stack[i].class_id); else { char *bp; char *class_name; char buf2[200]; char parms[800]; int j; /* for current frame, stack[] has pointer at beginning of function; use current pointer instead */ bp = stack[i].bkod_ptr; if (i == message_depth-1) bp = bkod; class_name = "(unknown)"; if (c->class_name) class_name = c->class_name; /* use %.*s with a fixed string of pluses to get exactly one plus per propagate depth */ sprintf(s,"%.*s%s::%s",stack[i].propagate_depth,"++++++++++++++++++++++", class_name,GetNameByID(stack[i].message_id)); strcat(s,"("); parms[0] = '\0'; for (j=0;j<stack[i].num_parms;j++) { val_type val; val.int_val = stack[i].parms[j].value; sprintf(buf2,"#%s=%s %s",GetNameByID(stack[i].parms[j].name_id), GetTagName(val),GetDataName(val)); if (j > 0) strcat(parms,","); strcat(parms,buf2); } strcat(s,parms); strcat(s,")"); sprintf(buf2," %s (%i)",c->fname,GetSourceLine(c,bp)); strcat(s,buf2); } } if (i < message_depth-1) strcat(buf,"\n"); strcat(buf,s); if (strlen(buf) > sizeof(buf) - 1000) { strcat(buf,"\n...and more"); break; } } return buf; }
lovejavaee/apue
std/options.c
#include "apue.h" #include <errno.h> static void pr_sysconf(char *, int); static void pr_pathconf(char *, char *, int); int main(int argc, char *argv[]) { if (argc != 2) err_quit("usage: a.out <dirname>"); #ifdef _POSIX_ADVISORY_INFO printf("_POSIX_ADVISORY_INFO is defined (val is %d)\n", _POSIX_ADVISORY_INFO+0); #else printf("_POSIX_ADVISORY_INFO is undefined\n"); #endif #ifdef _SC_ADVISORY_INFO pr_sysconf("sysconf says _POSIX_ADVISORY_INFO =", _SC_ADVISORY_INFO); #else printf("no symbol for _POSIX_ADVISORY_INFO\n"); #endif printf("\n"); #ifdef _POSIX_ASYNCHRONOUS_IO printf("_POSIX_ASYNCHRONOUS_IO is defined (val is %d)\n", _POSIX_ASYNCHRONOUS_IO+0); #else printf("_POSIX_ASYNCHRONOUS_IO is undefined\n"); #endif #ifdef _SC_ASYNCHRONOUS_IO pr_sysconf("sysconf says _POSIX_ASYNCHRONOUS_IO =", _SC_ASYNCHRONOUS_IO); #else printf("no symbol for _POSIX_ASYNCHRONOUS_IO\n"); #endif printf("\n"); #ifdef _POSIX_BARRIERS printf("_POSIX_BARRIERS is defined (val is %d)\n", _POSIX_BARRIERS+0); #else printf("_POSIX_BARRIERS is undefined\n"); #endif #ifdef _SC_BARRIERS pr_sysconf("sysconf says _POSIX_BARRIERS =", _SC_BARRIERS); #else printf("no symbol for _POSIX_BARRIERS\n"); #endif printf("\n"); #ifdef _POSIX_CPUTIME printf("_POSIX_CPUTIME is defined (val is %d)\n", _POSIX_CPUTIME+0); #else printf("_POSIX_CPUTIME is undefined\n"); #endif #ifdef _SC_CPUTIME pr_sysconf("sysconf says _POSIX_CPUTIME =", _SC_CPUTIME); #else printf("no symbol for _POSIX_CPUTIME\n"); #endif printf("\n"); #ifdef _POSIX_CLOCK_SELECTION printf("_POSIX_CLOCK_SELECTION is defined (val is %d)\n", _POSIX_CLOCK_SELECTION+0); #else printf("_POSIX_CLOCK_SELECTION is undefined\n"); #endif #ifdef _SC_CLOCK_SELECTION pr_sysconf("sysconf says _POSIX_CLOCK_SELECTION =", _SC_CLOCK_SELECTION); #else printf("no symbol for _POSIX_CLOCK_SELECTION\n"); #endif printf("\n"); #ifdef _POSIX_FSYNC printf("_POSIX_FSYNC is defined (val is %d)\n", _POSIX_FSYNC+0); #else printf("_POSIX_FSYNC is undefined\n"); #endif #ifdef _SC_FSYNC pr_sysconf("sysconf says _POSIX_FSYNC =", _SC_FSYNC); #else printf("no symbol for _POSIX_FSYNC\n"); #endif printf("\n"); #ifdef _POSIX_IPV6 printf("_POSIX_IPV6 is defined (val is %d)\n", _POSIX_IPV6+0); #else printf("_POSIX_IPV6 is undefined\n"); #endif #ifdef _SC_IPV6 pr_sysconf("sysconf says _POSIX_IPV6 =", _SC_IPV6); #else printf("no symbol for _POSIX_IPV6\n"); #endif printf("\n"); #ifdef _POSIX_MAPPED_FILES printf("_POSIX_MAPPED_FILES is defined (val is %d)\n", _POSIX_MAPPED_FILES+0); #else printf("_POSIX_MAPPED_FILES is undefined\n"); #endif #ifdef _SC_MAPPED_FILES pr_sysconf("sysconf says _POSIX_MAPPED_FILES =", _SC_MAPPED_FILES); #else printf("no symbol for _POSIX_MAPPED_FILES\n"); #endif printf("\n"); #ifdef _POSIX_MEMLOCK printf("_POSIX_MEMLOCK is defined (val is %d)\n", _POSIX_MEMLOCK+0); #else printf("_POSIX_MEMLOCK is undefined\n"); #endif #ifdef _SC_MEMLOCK pr_sysconf("sysconf says _POSIX_MEMLOCK =", _SC_MEMLOCK); #else printf("no symbol for _POSIX_MEMLOCK\n"); #endif printf("\n"); #ifdef _POSIX_MEMLOCK_RANGE printf("_POSIX_MEMLOCK_RANGE is defined (val is %d)\n", _POSIX_MEMLOCK_RANGE+0); #else printf("_POSIX_MEMLOCK_RANGE is undefined\n"); #endif #ifdef _SC_MEMLOCK_RANGE pr_sysconf("sysconf says _POSIX_MEMLOCK_RANGE =", _SC_MEMLOCK_RANGE); #else printf("no symbol for _POSIX_MEMLOCK_RANGE\n"); #endif printf("\n"); #ifdef _POSIX_MONOTONIC_CLOCK printf("_POSIX_MONOTONIC_CLOCK is defined (val is %d)\n", _POSIX_MONOTONIC_CLOCK+0); #else printf("_POSIX_MONOTONIC_CLOCK is undefined\n"); #endif #ifdef _SC_MONOTONIC_CLOCK pr_sysconf("sysconf says _POSIX_MONOTONIC_CLOCK =", _SC_MONOTONIC_CLOCK); #else printf("no symbol for _POSIX_MONOTONIC_CLOCK\n"); #endif printf("\n"); #ifdef _POSIX_MEMORY_PROTECTION printf("_POSIX_MEMORY_PROTECTION is defined (val is %d)\n", _POSIX_MEMORY_PROTECTION+0); #else printf("_POSIX_MEMORY_PROTECTION is undefined\n"); #endif #ifdef _SC_MEMORY_PROTECTION pr_sysconf("sysconf says _POSIX_MEMORY_PROTECTION =", _SC_MEMORY_PROTECTION); #else printf("no symbol for _POSIX_MEMORY_PROTECTION\n"); #endif printf("\n"); #ifdef _POSIX_MESSAGE_PASSING printf("_POSIX_MESSAGE_PASSING is defined (val is %d)\n", _POSIX_MESSAGE_PASSING+0); #else printf("_POSIX_MESSAGE_PASSING is undefined\n"); #endif #ifdef _SC_MESSAGE_PASSING pr_sysconf("sysconf says _POSIX_MESSAGE_PASSING =", _SC_MESSAGE_PASSING); #else printf("no symbol for _POSIX_MESSAGE_PASSING\n"); #endif printf("\n"); #ifdef _POSIX_PRIORITIZED_IO printf("_POSIX_PRIORITIZED_IO is defined (val is %d)\n", _POSIX_PRIORITIZED_IO+0); #else printf("_POSIX_PRIORITIZED_IO is undefined\n"); #endif #ifdef _SC_PRIORITIZED_IO pr_sysconf("sysconf says _POSIX_PRIORITIZED_IO =", _SC_PRIORITIZED_IO); #else printf("no symbol for _POSIX_PRIORITIZED_IO\n"); #endif printf("\n"); #ifdef _POSIX_PRIORITIZED_SCHEDULING printf("_POSIX_PRIORITIZED_SCHEDULING is defined (val is %d)\n", _POSIX_PRIORITIZED_SCHEDULING+0); #else printf("_POSIX_PRIORITIZED_SCHEDULING is undefined\n"); #endif #ifdef _SC_PRIORITIZED_SCHEDULING pr_sysconf("sysconf says _POSIX_PRIORITIZED_SCHEDULING =", _SC_PRIORITIZED_SCHEDULING); #else printf("no symbol for _POSIX_PRIORITIZED_SCHEDULING\n"); #endif printf("\n"); #ifdef _POSIX_RAW_SOCKETS printf("_POSIX_RAW_SOCKETS is defined (val is %d)\n", _POSIX_RAW_SOCKETS+0); #else printf("_POSIX_RAW_SOCKETS is undefined\n"); #endif #ifdef _SC_RAW_SOCKETS pr_sysconf("sysconf says _POSIX_RAW_SOCKETS =", _SC_RAW_SOCKETS); #else printf("no symbol for _POSIX_RAW_SOCKETS\n"); #endif printf("\n"); #ifdef _POSIX_REALTIME_SIGNALS printf("_POSIX_REALTIME_SIGNALS is defined (val is %d)\n", _POSIX_REALTIME_SIGNALS+0); #else printf("_POSIX_REALTIME_SIGNALS is undefined\n"); #endif #ifdef _SC_REALTIME_SIGNALS pr_sysconf("sysconf says _POSIX_REALTIME_SIGNALS =", _SC_REALTIME_SIGNALS); #else printf("no symbol for _POSIX_REALTIME_SIGNALS\n"); #endif printf("\n"); #ifdef _POSIX_SEMAPHORES printf("_POSIX_SEMAPHORES is defined (val is %d)\n", _POSIX_SEMAPHORES+0); #else printf("_POSIX_SEMAPHORES is undefined\n"); #endif #ifdef _SC_SEMAPHORES pr_sysconf("sysconf says _POSIX_SEMAPHORES =", _SC_SEMAPHORES); #else printf("no symbol for _POSIX_SEMAPHORES\n"); #endif printf("\n"); #ifdef _POSIX_SHARED_MEMORY_OBJECTS printf("_POSIX_SHARED_MEMORY_OBJECTS is defined (val is %d)\n", _POSIX_SHARED_MEMORY_OBJECTS+0); #else printf("_POSIX_SHARED_MEMORY_OBJECTS is undefined\n"); #endif #ifdef _SC_SHARED_MEMORY_OBJECTS pr_sysconf("sysconf says _POSIX_SHARED_MEMORY_OBJECTS =", _SC_SHARED_MEMORY_OBJECTS); #else printf("no symbol for _POSIX_SHARED_MEMORY_OBJECTS\n"); #endif printf("\n"); #ifdef _POSIX_SYNCHRONIZED_IO printf("_POSIX_SYNCHRONIZED_IO is defined (val is %d)\n", _POSIX_SYNCHRONIZED_IO+0); #else printf("_POSIX_SYNCHRONIZED_IO is undefined\n"); #endif #ifdef _SC_SYNCHRONIZED_IO pr_sysconf("sysconf says _POSIX_SYNCHRONIZED_IO =", _SC_SYNCHRONIZED_IO); #else printf("no symbol for _POSIX_SYNCHRONIZED_IO\n"); #endif printf("\n"); #ifdef _POSIX_SPIN_LOCKS printf("_POSIX_SPIN_LOCKS is defined (val is %d)\n", _POSIX_SPIN_LOCKS+0); #else printf("_POSIX_SPIN_LOCKS is undefined\n"); #endif #ifdef _SC_SPIN_LOCKS pr_sysconf("sysconf says _POSIX_SPIN_LOCKS =", _SC_SPIN_LOCKS); #else printf("no symbol for _POSIX_SPIN_LOCKS\n"); #endif printf("\n"); #ifdef _POSIX_SPAWN printf("_POSIX_SPAWN is defined (val is %d)\n", _POSIX_SPAWN+0); #else printf("_POSIX_SPAWN is undefined\n"); #endif #ifdef _SC_SPAWN pr_sysconf("sysconf says _POSIX_SPAWN =", _SC_SPAWN); #else printf("no symbol for _POSIX_SPAWN\n"); #endif printf("\n"); #ifdef _POSIX_SPORADIC_SERVER printf("_POSIX_SPORADIC_SERVER is defined (val is %d)\n", _POSIX_SPORADIC_SERVER+0); #else printf("_POSIX_SPORADIC_SERVER is undefined\n"); #endif #ifdef _SC_SPORADIC_SERVER pr_sysconf("sysconf says _POSIX_SPORADIC_SERVER =", _SC_SPORADIC_SERVER); #else printf("no symbol for _POSIX_SPORADIC_SERVER\n"); #endif printf("\n"); #ifdef _POSIX_THREAD_CPUTIME printf("_POSIX_THREAD_CPUTIME is defined (val is %d)\n", _POSIX_THREAD_CPUTIME+0); #else printf("_POSIX_THREAD_CPUTIME is undefined\n"); #endif #ifdef _SC_THREAD_CPUTIME pr_sysconf("sysconf says _POSIX_THREAD_CPUTIME =", _SC_THREAD_CPUTIME); #else printf("no symbol for _POSIX_THREAD_CPUTIME\n"); #endif printf("\n"); #ifdef _POSIX_TRACE_EVENT_FILTER printf("_POSIX_TRACE_EVENT_FILTER is defined (val is %d)\n", _POSIX_TRACE_EVENT_FILTER+0); #else printf("_POSIX_TRACE_EVENT_FILTER is undefined\n"); #endif #ifdef _SC_TRACE_EVENT_FILTER pr_sysconf("sysconf says _POSIX_TRACE_EVENT_FILTER =", _SC_TRACE_EVENT_FILTER); #else printf("no symbol for _POSIX_TRACE_EVENT_FILTER\n"); #endif printf("\n"); #ifdef _POSIX_THREADS printf("_POSIX_THREADS is defined (val is %d)\n", _POSIX_THREADS+0); #else printf("_POSIX_THREADS is undefined\n"); #endif #ifdef _SC_THREADS pr_sysconf("sysconf says _POSIX_THREADS =", _SC_THREADS); #else printf("no symbol for _POSIX_THREADS\n"); #endif printf("\n"); #ifdef _POSIX_TIMEOUTS printf("_POSIX_TIMEOUTS is defined (val is %d)\n", _POSIX_TIMEOUTS+0); #else printf("_POSIX_TIMEOUTS is undefined\n"); #endif #ifdef _SC_TIMEOUTS pr_sysconf("sysconf says _POSIX_TIMEOUTS =", _SC_TIMEOUTS); #else printf("no symbol for _POSIX_TIMEOUTS\n"); #endif printf("\n"); #ifdef _POSIX_TIMERS printf("_POSIX_TIMERS is defined (val is %d)\n", _POSIX_TIMERS+0); #else printf("_POSIX_TIMERS is undefined\n"); #endif #ifdef _SC_TIMERS pr_sysconf("sysconf says _POSIX_TIMERS =", _SC_TIMERS); #else printf("no symbol for _POSIX_TIMERS\n"); #endif printf("\n"); #ifdef _POSIX_THREAD_PRIO_INHERIT printf("_POSIX_THREAD_PRIO_INHERIT is defined (val is %d)\n", _POSIX_THREAD_PRIO_INHERIT+0); #else printf("_POSIX_THREAD_PRIO_INHERIT is undefined\n"); #endif #ifdef _SC_THREAD_PRIO_INHERIT pr_sysconf("sysconf says _POSIX_THREAD_PRIO_INHERIT =", _SC_THREAD_PRIO_INHERIT); #else printf("no symbol for _POSIX_THREAD_PRIO_INHERIT\n"); #endif printf("\n"); #ifdef _POSIX_THREAD_PRIO_PROTECT printf("_POSIX_THREAD_PRIO_PROTECT is defined (val is %d)\n", _POSIX_THREAD_PRIO_PROTECT+0); #else printf("_POSIX_THREAD_PRIO_PROTECT is undefined\n"); #endif #ifdef _SC_THREAD_PRIO_PROTECT pr_sysconf("sysconf says _POSIX_THREAD_PRIO_PROTECT =", _SC_THREAD_PRIO_PROTECT); #else printf("no symbol for _POSIX_THREAD_PRIO_PROTECT\n"); #endif printf("\n"); #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING printf("_POSIX_THREAD_PRIORITY_SCHEDULING is defined (val is %d)\n", _POSIX_THREAD_PRIORITY_SCHEDULING+0); #else printf("_POSIX_THREAD_PRIORITY_SCHEDULING is undefined\n"); #endif #ifdef _SC_THREAD_PRIORITY_SCHEDULING pr_sysconf("sysconf says _POSIX_THREAD_PRIORITY_SCHEDULING =", _SC_THREAD_PRIORITY_SCHEDULING); #else printf("no symbol for _POSIX_THREAD_PRIORITY_SCHEDULING\n"); #endif printf("\n"); #ifdef _POSIX_TRACE printf("_POSIX_TRACE is defined (val is %d)\n", _POSIX_TRACE+0); #else printf("_POSIX_TRACE is undefined\n"); #endif #ifdef _SC_TRACE pr_sysconf("sysconf says _POSIX_TRACE =", _SC_TRACE); #else printf("no symbol for _POSIX_TRACE\n"); #endif printf("\n"); #ifdef _POSIX_TRACE_INHERIT printf("_POSIX_TRACE_INHERIT is defined (val is %d)\n", _POSIX_TRACE_INHERIT+0); #else printf("_POSIX_TRACE_INHERIT is undefined\n"); #endif #ifdef _SC_TRACE_INHERIT pr_sysconf("sysconf says _POSIX_TRACE_INHERIT =", _SC_TRACE_INHERIT); #else printf("no symbol for _POSIX_TRACE_INHERIT\n"); #endif printf("\n"); #ifdef _POSIX_TRACE_LOG printf("_POSIX_TRACE_LOG is defined (val is %d)\n", _POSIX_TRACE_LOG+0); #else printf("_POSIX_TRACE_LOG is undefined\n"); #endif #ifdef _SC_TRACE_LOG pr_sysconf("sysconf says _POSIX_TRACE_LOG =", _SC_TRACE_LOG); #else printf("no symbol for _POSIX_TRACE_LOG\n"); #endif printf("\n"); #ifdef _POSIX_THREAD_ATTR_STACKADDR printf("_POSIX_THREAD_ATTR_STACKADDR is defined (val is %d)\n", _POSIX_THREAD_ATTR_STACKADDR+0); #else printf("_POSIX_THREAD_ATTR_STACKADDR is undefined\n"); #endif #ifdef _SC_THREAD_ATTR_STACKADDR pr_sysconf("sysconf says _POSIX_THREAD_ATTR_STACKADDR =", _SC_THREAD_ATTR_STACKADDR); #else printf("no symbol for _POSIX_THREAD_ATTR_STACKADDR\n"); #endif printf("\n"); #ifdef _POSIX_THREAD_SAFE_FUNCTIONS printf("_POSIX_THREAD_SAFE_FUNCTIONS is defined (val is %d)\n", _POSIX_THREAD_SAFE_FUNCTIONS+0); #else printf("_POSIX_THREAD_SAFE_FUNCTIONS is undefined\n"); #endif #ifdef _SC_THREAD_SAFE_FUNCTIONS pr_sysconf("sysconf says _POSIX_THREAD_SAFE_FUNCTIONS =", _SC_THREAD_SAFE_FUNCTIONS); #else printf("no symbol for _POSIX_THREAD_SAFE_FUNCTIONS\n"); #endif printf("\n"); #ifdef _POSIX_THREAD_PROCESS_SHARED printf("_POSIX_THREAD_PROCESS_SHARED is defined (val is %d)\n", _POSIX_THREAD_PROCESS_SHARED+0); #else printf("_POSIX_THREAD_PROCESS_SHARED is undefined\n"); #endif #ifdef _SC_THREAD_PROCESS_SHARED pr_sysconf("sysconf says _POSIX_THREAD_PROCESS_SHARED =", _SC_THREAD_PROCESS_SHARED); #else printf("no symbol for _POSIX_THREAD_PROCESS_SHARED\n"); #endif printf("\n"); #ifdef _POSIX_THREAD_SPORADIC_SERVER printf("_POSIX_THREAD_SPORADIC_SERVER is defined (val is %d)\n", _POSIX_THREAD_SPORADIC_SERVER+0); #else printf("_POSIX_THREAD_SPORADIC_SERVER is undefined\n"); #endif #ifdef _SC_THREAD_SPORADIC_SERVER pr_sysconf("sysconf says _POSIX_THREAD_SPORADIC_SERVER =", _SC_THREAD_SPORADIC_SERVER); #else printf("no symbol for _POSIX_THREAD_SPORADIC_SERVER\n"); #endif printf("\n"); #ifdef _POSIX_THREAD_ATTR_STACKSIZE printf("_POSIX_THREAD_ATTR_STACKSIZE is defined (val is %d)\n", _POSIX_THREAD_ATTR_STACKSIZE+0); #else printf("_POSIX_THREAD_ATTR_STACKSIZE is undefined\n"); #endif #ifdef _SC_THREAD_ATTR_STACKSIZE pr_sysconf("sysconf says _POSIX_THREAD_ATTR_STACKSIZE =", _SC_THREAD_ATTR_STACKSIZE); #else printf("no symbol for _POSIX_THREAD_ATTR_STACKSIZE\n"); #endif printf("\n"); #ifdef _POSIX_TYPED_MEMORY_OBJECTS printf("_POSIX_TYPED_MEMORY_OBJECTS is defined (val is %d)\n", _POSIX_TYPED_MEMORY_OBJECTS+0); #else printf("_POSIX_TYPED_MEMORY_OBJECTS is undefined\n"); #endif #ifdef _SC_TYPED_MEMORY_OBJECTS pr_sysconf("sysconf says _POSIX_TYPED_MEMORY_OBJECTS =", _SC_TYPED_MEMORY_OBJECTS); #else printf("no symbol for _POSIX_TYPED_MEMORY_OBJECTS\n"); #endif printf("\n"); #ifdef _XOPEN_UNIX printf("_XOPEN_UNIX is defined (val is %d)\n", _XOPEN_UNIX+0); #else printf("_XOPEN_UNIX is undefined\n"); #endif #ifdef _SC_XOPEN_UNIX pr_sysconf("sysconf says _XOPEN_UNIX =", _SC_XOPEN_UNIX); #else printf("no symbol for _XOPEN_UNIX\n"); #endif printf("\n"); #ifdef _XOPEN_STREAMS printf("_XOPEN_STREAMS is defined (val is %d)\n", _XOPEN_STREAMS+0); #else printf("_XOPEN_STREAMS is undefined\n"); #endif #ifdef _SC_XOPEN_STREAMS pr_sysconf("sysconf says _XOPEN_STREAMS =", _SC_XOPEN_STREAMS); #else printf("no symbol for _XOPEN_STREAMS\n"); #endif printf("\n"); #ifdef _XOPEN_CRYPT printf("_XOPEN_CRYPT is defined (val is %d)\n", _XOPEN_CRYPT+0); #else printf("_XOPEN_CRYPT is undefined\n"); #endif #ifdef _SC_XOPEN_CRYPT pr_sysconf("sysconf says _XOPEN_CRYPT =", _SC_XOPEN_CRYPT); #else printf("no symbol for _XOPEN_CRYPT\n"); #endif printf("\n"); #ifdef _XOPEN_LEGACY printf("_XOPEN_LEGACY is defined (val is %d)\n", _XOPEN_LEGACY+0); #else printf("_XOPEN_LEGACY is undefined\n"); #endif #ifdef _SC_XOPEN_LEGACY pr_sysconf("sysconf says _XOPEN_LEGACY =", _SC_XOPEN_LEGACY); #else printf("no symbol for _XOPEN_LEGACY\n"); #endif printf("\n"); #ifdef _XOPEN_REALTIME printf("_XOPEN_REALTIME is defined (val is %d)\n", _XOPEN_REALTIME+0); #else printf("_XOPEN_REALTIME is undefined\n"); #endif #ifdef _SC_XOPEN_REALTIME pr_sysconf("sysconf says _XOPEN_REALTIME =", _SC_XOPEN_REALTIME); #else printf("no symbol for _XOPEN_REALTIME\n"); #endif printf("\n"); #ifdef _XOPEN_REALTIME_THREADS printf("_XOPEN_REALTIME_THREADS is defined (val is %d)\n", _XOPEN_REALTIME_THREADS+0); #else printf("_XOPEN_REALTIME_THREADS is undefined\n"); #endif #ifdef _SC_XOPEN_REALTIME_THREADS pr_sysconf("sysconf says _XOPEN_REALTIME_THREADS =", _SC_XOPEN_REALTIME_THREADS); #else printf("no symbol for _XOPEN_REALTIME_THREADS\n"); #endif printf("\n"); #ifdef _POSIX_JOB_CONTROL printf("_POSIX_JOB_CONTROL is defined (val is %d)\n", _POSIX_JOB_CONTROL+0); #else printf("_POSIX_JOB_CONTROL is undefined\n"); #endif #ifdef _SC_JOB_CONTROL pr_sysconf("sysconf says _POSIX_JOB_CONTROL =", _SC_JOB_CONTROL); #else printf("no symbol for _POSIX_JOB_CONTROL\n"); #endif printf("\n"); #ifdef _POSIX_READER_WRITER_LOCKS printf("_POSIX_READER_WRITER_LOCKS is defined (val is %d)\n", _POSIX_READER_WRITER_LOCKS+0); #else printf("_POSIX_READER_WRITER_LOCKS is undefined\n"); #endif #ifdef _SC_READER_WRITER_LOCKS pr_sysconf("sysconf says _POSIX_READER_WRITER_LOCKS =", _SC_READER_WRITER_LOCKS); #else printf("no symbol for _POSIX_READER_WRITER_LOCKS\n"); #endif printf("\n"); #ifdef _POSIX_REGEXP printf("_POSIX_REGEXP is defined (val is %d)\n", _POSIX_REGEXP+0); #else printf("_POSIX_REGEXP is undefined\n"); #endif #ifdef _SC_REGEXP pr_sysconf("sysconf says _POSIX_REGEXP =", _SC_REGEXP); #else printf("no symbol for _POSIX_REGEXP\n"); #endif printf("\n"); #ifdef _POSIX_SAVED_IDS printf("_POSIX_SAVED_IDS is defined (val is %d)\n", _POSIX_SAVED_IDS+0); #else printf("_POSIX_SAVED_IDS is undefined\n"); #endif #ifdef _SC_SAVED_IDS pr_sysconf("sysconf says _POSIX_SAVED_IDS =", _SC_SAVED_IDS); #else printf("no symbol for _POSIX_SAVED_IDS\n"); #endif printf("\n"); #ifdef _POSIX_SHELL printf("_POSIX_SHELL is defined (val is %d)\n", _POSIX_SHELL+0); #else printf("_POSIX_SHELL is undefined\n"); #endif #ifdef _SC_SHELL pr_sysconf("sysconf says _POSIX_SHELL =", _SC_SHELL); #else printf("no symbol for _POSIX_SHELL\n"); #endif printf("\n"); #ifdef _XOPEN_ENH_I18N printf("_XOPEN_ENH_I18N is defined (val is %d)\n", _XOPEN_ENH_I18N+0); #else printf("_XOPEN_ENH_I18N is undefined\n"); #endif #ifdef _SC_XOPEN_ENH_I18N pr_sysconf("sysconf says _XOPEN_ENH_I18N =", _SC_XOPEN_ENH_I18N); #else printf("no symbol for _XOPEN_ENH_I18N\n"); #endif printf("\n"); #ifdef _XOPEN_SHM printf("_XOPEN_SHM is defined (val is %d)\n", _XOPEN_SHM+0); #else printf("_XOPEN_SHM is undefined\n"); #endif #ifdef _SC_XOPEN_SHM pr_sysconf("sysconf says _XOPEN_SHM =", _SC_XOPEN_SHM); #else printf("no symbol for _XOPEN_SHM\n"); #endif printf("\n"); #ifdef _POSIX_VERSION printf("_POSIX_VERSION is defined (val is %d)\n", _POSIX_VERSION+0); #else printf("_POSIX_VERSION is undefined\n"); #endif #ifdef _SC_VERSION pr_sysconf("sysconf says _POSIX_VERSION =", _SC_VERSION); #else printf("no symbol for _POSIX_VERSION\n"); #endif printf("\n"); #ifdef _XOPEN_VERSION printf("_XOPEN_VERSION is defined (val is %d)\n", _XOPEN_VERSION+0); #else printf("_XOPEN_VERSION is undefined\n"); #endif #ifdef _SC_XOPEN_VERSION pr_sysconf("sysconf says _XOPEN_VERSION =", _SC_XOPEN_VERSION); #else printf("no symbol for _XOPEN_VERSION\n"); #endif printf("\n"); #ifdef _POSIX_CHOWN_RESTRICTED printf("_POSIX_CHOWN_RESTRICTED is defined (val is %d)\n", _POSIX_CHOWN_RESTRICTED+0); #else printf("_POSIX_CHOWN_RESTRICTED is undefined\n"); #endif #ifdef _PC_CHOWN_RESTRICTED pr_pathconf("pathconf says _POSIX_CHOWN_RESTRICTED =", argv[1], _PC_CHOWN_RESTRICTED); #else printf("no symbol for _POSIX_CHOWN_RESTRICTED\n"); #endif printf("\n"); #ifdef _POSIX_NO_TRUNC printf("_POSIX_NO_TRUNC is defined (val is %d)\n", _POSIX_NO_TRUNC+0); #else printf("_POSIX_NO_TRUNC is undefined\n"); #endif #ifdef _PC_NO_TRUNC pr_pathconf("pathconf says _POSIX_NO_TRUNC =", argv[1], _PC_NO_TRUNC); #else printf("no symbol for _POSIX_NO_TRUNC\n"); #endif printf("\n"); #ifdef _POSIX_VDISABLE printf("_POSIX_VDISABLE is defined (val is %d)\n", _POSIX_VDISABLE+0); #else printf("_POSIX_VDISABLE is undefined\n"); #endif #ifdef _PC_VDISABLE pr_pathconf("pathconf says _POSIX_VDISABLE =", argv[1], _PC_VDISABLE); #else printf("no symbol for _POSIX_VDISABLE\n"); #endif printf("\n"); #ifdef POSIX_ASYNC_IO printf("POSIX_ASYNC_IO is defined (val is %d)\n", POSIX_ASYNC_IO+0); #else printf("POSIX_ASYNC_IO is undefined\n"); #endif #ifdef _PC_ASYNC_IO pr_pathconf("pathconf says POSIX_ASYNC_IO =", argv[1], _PC_ASYNC_IO); #else printf("no symbol for POSIX_ASYNC_IO\n"); #endif printf("\n"); #ifdef POSIX_PRIO_IO printf("POSIX_PRIO_IO is defined (val is %d)\n", POSIX_PRIO_IO+0); #else printf("POSIX_PRIO_IO is undefined\n"); #endif #ifdef _PC_PRIO_IO pr_pathconf("pathconf says POSIX_PRIO_IO =", argv[1], _PC_PRIO_IO); #else printf("no symbol for POSIX_PRIO_IO\n"); #endif printf("\n"); #ifdef POSIX_SYNC_IO printf("POSIX_SYNC_IO is defined (val is %d)\n", POSIX_SYNC_IO+0); #else printf("POSIX_SYNC_IO is undefined\n"); #endif #ifdef _PC_SYNC_IO pr_pathconf("pathconf says POSIX_SYNC_IO =", argv[1], _PC_SYNC_IO); #else printf("no symbol for POSIX_SYNC_IO\n"); #endif printf("\n"); exit(0); } static void pr_sysconf(char *mesg, int name) { long val; fputs(mesg, stdout); errno = 0; if ((val = sysconf(name)) < 0) { if (errno != 0) { if (errno == EINVAL) fputs(" (not supported)\n", stdout); else err_sys("sysconf error"); } else { fputs(" (no limit)\n", stdout); } } else { printf(" %ld\n", val); } } static void pr_pathconf(char *mesg, char *path, int name) { long val; fputs(mesg, stdout); errno = 0; if ((val = pathconf(path, name)) < 0) { if (errno != 0) { if (errno == EINVAL) fputs(" (not supported)\n", stdout); else err_sys("pathconf error, path = %s", path); } else { fputs(" (no limit)\n", stdout); } } else { printf(" %ld\n", val); } }
hepburnalex/HBLineCharts
LineCharts/LineChartYAxisView.h
// // LineChartYAxisView.h // TestChart // // Created by Hepburn on 2020/3/9. // Copyright © 2020 Hepburn. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface LineChartYAxisView : UIView @property (nonatomic, strong) UIFont *axisFont; //坐标轴字体 @property (nonatomic, strong) UIColor *axisColor; //坐标轴颜色 /// 画纵轴标尺 /// @param maxValue 纵轴最大值 /// @param margin 纵轴标尺与折线图的间距 /// @param labelCount 纵轴数量 - (void)drawChartAxis:(CGFloat)maxValue margin:(CGFloat)margin count:(NSInteger)labelCount; @end NS_ASSUME_NONNULL_END
hepburnalex/HBLineCharts
LineCharts/LineChartView.h
<gh_stars>0 // // LineChartView.h // TestChart // // Created by Hepburn on 2020/3/9. // Copyright © 2020 Hepburn. All rights reserved. // #import <UIKit/UIKit.h> #import "LineChartHeader.h" #import "LineChartScrollView.h" #import "LineChartMarkBaseView.h" @interface LineChartView : UIView @property (nonatomic, assign) NSInteger currentIndex; //当前选中目标点 @property (nonatomic, assign) NSInteger yLabelCount; //纵轴标尺数量 @property (nonatomic, assign) CGFloat xSpace; //横轴两点间距 @property (nonatomic, assign) CGFloat xMargin; //横轴与标尺间隙 @property (nonatomic, assign) CGFloat yMargin; //纵轴与标尺间隙 @property (nonatomic, assign) UIEdgeInsets contentInsets; //折线图与四边距离 @property (nonatomic, strong) void(^OnLineChartSelect)(NSInteger index); @property (nonatomic, strong) void(^OnLineChartScroll)(NSInteger index); @property (nonatomic, strong) UIFont *axisFont; //坐标轴字体 @property (nonatomic, strong) UIColor *axisColor; //坐标轴颜色 @property (nonatomic, strong) UIColor *lineColor; //折线颜色 @property (nonatomic, strong) UIColor *selectLineColor; //选中竖线颜色 @property (nonatomic, strong) UIColor *fillColor; //折线填充颜色 @property (nonatomic, strong) LineChartMarkBaseView *markView; /** * 画折线图 * @param names x轴值的所有值名称 * @param targetValues 所有目标值 * @param lineType 直线类型 */ -(void)drawLineChartView:(NSArray *)names xValues:(NSArray *)xValues targetValues:(NSArray *)targetValues lineType:(LineType)lineType; - (void)addLineLayer:(NSInteger)index color:(UIColor *)color; - (void)addLineLayer:(NSInteger)index color:(UIColor *)color offset:(CGFloat)offset; - (void)cleanLineLayers; - (void)registerMarkView:(NSString *)markname size:(CGSize)size; - (void)fillLines:(NSInteger)startIndex startOffset:(CGFloat)startOffset endIndex:(NSInteger)endIndex startOffset:(CGFloat)endOffset fillColor:(UIColor *)fillColor; @end
hepburnalex/HBLineCharts
LineCharts/LineChartXAxisView.h
<gh_stars>0 // // LineChartXAxisView.h // TestChart // // Created by Hepburn on 2020/3/9. // Copyright © 2020 Hepburn. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface LineChartXAxisView : UIScrollView @property (nonatomic, strong) UIFont *axisFont; //坐标轴字体 @property (nonatomic, strong) UIColor *axisColor; //坐标轴颜色 /// 画横轴标尺 /// @param names 标尺名 /// @param margin 标尺与折线图间距 /// @param xSpace 横轴目标点间距 - (void)drawChartAxis:(NSArray *)names margin:(CGFloat)margin xspace:(CGFloat)xSpace; @end NS_ASSUME_NONNULL_END
hepburnalex/HBLineCharts
LineCharts/LineChartHeader.h
<filename>LineCharts/LineChartHeader.h // // LineChartHeader.h // UVLOOK // // Created by Hepburn on 2020/3/10. // Copyright © 2020 Hepburn. All rights reserved. // #ifndef LineChartHeader_h #define LineChartHeader_h // 线条类型 typedef NS_ENUM(NSInteger, LineType) { LineType_Straight, // 折线 LineType_Curve // 曲线 }; typedef enum { LineChartMarkAlign_TopLeft, LineChartMarkAlign_TopRight, LineChartMarkAlign_BottomLeft, LineChartMarkAlign_BottomRight } LineChartMarkAlign; #endif /* LineChartHeader_h */
hepburnalex/HBLineCharts
LineCharts/LineChartScrollView.h
<gh_stars>0 // // LineChartScrollView.h // TestChart // // Created by Hepburn on 2020/3/9. // Copyright © 2020 Hepburn. All rights reserved. // #import <UIKit/UIKit.h> #import "LineChartDrawView.h" NS_ASSUME_NONNULL_BEGIN @interface LineChartScrollView : UIScrollView @property (nonatomic, assign) NSInteger currentIndex; //选中坐标点索引 @property (nonatomic, strong) LineChartDrawView *drawView; /// 绘制折线 /// @param targetValues 目标点 /// @param lineType 折线类型 /// @param xspace 横轴间距 - (void)drawLines:(NSArray *)targetValues lineType:(LineType)lineType xspace:(CGFloat)xspace; @end NS_ASSUME_NONNULL_END
hepburnalex/HBLineCharts
LineCharts/LineChartDrawView.h
<reponame>hepburnalex/HBLineCharts<gh_stars>0 // // LineChartDrawView.h // TestChart // // Created by Hepburn on 2020/3/9. // Copyright © 2020 Hepburn. All rights reserved. // #import <UIKit/UIKit.h> #import "LineChartHeader.h" NS_ASSUME_NONNULL_BEGIN @interface LineChartDrawView : UIView @property (nonatomic, strong) UIColor *lineColor; //折线颜色 @property (nonatomic, strong) UIColor *selectLineColor; //选中竖线颜色 @property (nonatomic, strong) UIColor *fillColor; //折线填充颜色 @property (nonatomic, assign) CGFloat xSpace; //横轴坐标间距 @property (nonatomic, assign) NSInteger currentIndex; @property (nonatomic, strong) void(^OnLineChartSelect)(NSInteger index, CGPoint point, LineChartMarkAlign markAlign); /// 绘制折线图 /// @param targetValues 纵轴目标点 /// @param lineType 折线类型 /// @param xspace 横轴间距 - (void)drawLines:(NSArray *)targetValues lineType:(LineType)lineType xspace:(CGFloat)xspace; /// 绘制竖线 - (void)addLineLayer:(NSInteger)index color:(UIColor *)color; /// 绘制竖线 - (void)addLineLayer:(NSInteger)index color:(UIColor *)color offset:(CGFloat)offset; - (void)fillLines:(NSInteger)startIndex startOffset:(CGFloat)startOffset endIndex:(NSInteger)endIndex startOffset:(CGFloat)endOffset fillColor:(UIColor *)fillColor; - (void)cleanLineLayers; @end NS_ASSUME_NONNULL_END
hepburnalex/HBLineCharts
LineCharts/LineChartMarkBaseView.h
<gh_stars>0 // // LineChartMarkBaseView.h // UVLOOK // // Created by Hepburn on 2020/3/24. // Copyright © 2020 Hepburn. All rights reserved. // #import <UIKit/UIKit.h> #import "LineChartHeader.h" NS_ASSUME_NONNULL_BEGIN @interface LineChartMarkBaseView : UIImageView - (void)refreshMark:(LineChartMarkAlign)markAlign xValue:(NSString *)xValue yValue:(CGFloat)yValue point:(CGPoint)point; @end NS_ASSUME_NONNULL_END
MatthewDupraz/Graphics-Engine
inc/matrix.h
<reponame>MatthewDupraz/Graphics-Engine #pragma once #include "math.h" #include <ostream> #include <array> #include "vect.h" template <unsigned int N, unsigned int M> class matrix { public: matrix():data_{{0}} {} matrix(float (&&data)[N][M]): matrix(data) {} matrix(float (&data)[N][M]) { for (unsigned int i(0); i < N; ++i) { for (unsigned int j(0); j < N; ++j) { data_[i][j] = data[i][j]; } } } static matrix<N, N> scalar(float d) { static_assert(N == M); matrix<N, N> m; for (unsigned int i(0); i < N; ++i) { m.data_[i][i] = d; } return m; } static matrix<N, N> identity() { static_assert(N == M); return scalar(1.0); } static matrix<4, 4> perspective( float near, float far, float fov, float aspect) { static_assert(N == M && N == 4); float t = 1.0 / tan(fov / 2.0); matrix<4, 4> m; m[0][0] = aspect * t; m[1][1] = t; m[2][2] = far / (far - near); m[2][3] = -near * far / (far - near); m[3][2] = 1; m[3][3] = 0; return m; } static matrix<4, 4> translation( float x, float y, float z) { static_assert(N == M && N == 4); matrix<4, 4> m = identity(); m[0][3] = x; m[1][3] = y; m[2][3] = z; return m; } static matrix<4, 4> rotation_x(float a) { static_assert(N == M && N == 4); matrix<4, 4> m = identity(); m[1][1] = cos(a); m[1][2] = -sin(a); m[2][1] = sin(a); m[2][2] = cos(a); return m; } static matrix<4, 4> rotation_y(float a) { static_assert(N == M && N == 4); matrix<4, 4> m = identity(); m[0][0] = cos(a); m[0][2] = sin(a); m[2][0] = -sin(a); m[2][2] = cos(a); return m; } static matrix<4, 4> rotation_z(float a) { static_assert(N == M && N == 4); matrix<4, 4> m = identity(); m[0][0] = cos(a); m[0][1] = -sin(a); m[1][0] = sin(a); m[1][1] = cos(a); return m; } std::array<float, M> const& operator[](unsigned int i) const { return data_[i]; } std::array<float, M>& operator[](unsigned int i) { return data_[i]; } template<unsigned int L> matrix<N, L> operator*(matrix<M, L> const& other) const { matrix<N, L> result; for (unsigned int i(0); i < N; ++i) { for (unsigned int j(0); j < L; ++j) { for (unsigned int k(0); k < M; ++k) { result[i][j] += data_[i][k] * other.data_[k][j]; } } } return result; } private: std::array<std::array<float, M>, N> data_; }; typedef matrix<2, 2> matrix2f; typedef matrix<3, 3> matrix3f; typedef matrix<4, 4> matrix4f; template<unsigned int N, unsigned int M> vec<N> operator*(matrix<N, M> const& m, vec<M> const& v) { vec<N> result {0}; for (unsigned int i(0); i < N; ++i) { for (unsigned int j(0); j < M; ++j) { result[i] += v[j] * m[i][j]; } } return result; } template<unsigned int N, unsigned int M> std::ostream &operator<<(std::ostream& os, matrix<N, M> const& mat) { for (unsigned int i(0); i < N; ++i) { for (unsigned int j(0); j < M; ++j) { os << mat[i][j]; if (j < M - 1) { os << " "; } } os << "\n"; } return os; }
MatthewDupraz/Graphics-Engine
inc/sfml_raster.h
<reponame>MatthewDupraz/Graphics-Engine #pragma once #include <SFML/Graphics.hpp> #include "raster.h" class SFMLRaster : public Raster { public: SFMLRaster(unsigned int w, unsigned int h); ~SFMLRaster() override; void draw_pixel(unsigned int x, unsigned int y, uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) override; void update_texture(); const sf::Sprite& get_sprite() const; void resize(unsigned int w, unsigned int h) override; unsigned int get_width() const override { return width; } unsigned int get_height() const override { return height; } void clear() override; private: unsigned int width; unsigned int height; sf::Uint8* pixels; sf::Texture texture; sf::Sprite sprite; };
MatthewDupraz/Graphics-Engine
inc/raster.h
<gh_stars>0 #pragma once class Raster { public: virtual ~Raster() {} virtual void draw_pixel(unsigned int x, unsigned int y, uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) = 0; virtual unsigned int get_width() const = 0; virtual unsigned int get_height() const = 0; virtual void resize(unsigned int w, unsigned int h) = 0; virtual void clear() = 0; };
MatthewDupraz/Graphics-Engine
inc/sfml_app.h
<filename>inc/sfml_app.h #pragma once #include <SFML/Graphics.hpp> #include "sfml_raster.h" #include "renderer.h" class SFMLApp { public: SFMLApp(unsigned int width, unsigned int height, sf::String const& title); int start(); void draw(); private: sf::RenderWindow window; sf::Sprite sprite; SFMLRaster raster; Renderer renderer; };
MatthewDupraz/Graphics-Engine
inc/renderer.h
<filename>inc/renderer.h #pragma once #include "matrix.h" #include "vect.h" #include "raster.h" #include "math.h" #include <vector> struct attribute { vec3f pos; vec3f color; vec3f normal; }; struct varying { vec3f pos; vec3f color; vec3f normal; }; class Renderer { public: Renderer(Raster* raster) :raster(raster) {} void render(std::vector<vec3f> const& vertices, std::vector<vec3f> const& colors, std::vector<vec3f> const& normals); void render_triangle(vec3f const* vertices, vec3f const* colors, vec3f const* normals); void vertex_shader(attribute const& in, vec4f& gl_Position, varying& out); void fragment_shader(varying const& in, vec4f& gl_FragColor); void set_model_matrix(matrix4f const& m) { model = m; } void set_view_matrix (matrix4f const& m) { view = m; } void set_near_plane(float val) { near_plane = val; } void set_far_plane(float val) { aspect_ratio = val; } void set_fov(float val) { aspect_ratio = val; } void set_aspect_ratio(float val) { aspect_ratio = val; } void update_perspective() { perspective = matrix4f::perspective( near_plane, far_plane, fov, aspect_ratio); } private: Raster* raster; float near_plane = 0.1f; float far_plane = 1000.0f; float fov = M_PI/2.0f; float aspect_ratio = 1.0f; // Uniforms matrix4f model = matrix4f::identity(); matrix4f perspective = matrix4f::identity(); matrix4f view = matrix4f::translation(0.0, 0.0, 4.0f); vec3f light_pos {2.0f, 2.0, -5.0f}; vec3f light_color {1.0f, 1.0f, 1.0f}; float ambient_strength = 0.2; };
MatthewDupraz/Graphics-Engine
inc/vect.h
#pragma once #include <ostream> #include "math.h" template <unsigned int N> struct vec { float coords[N]; float norm2() const { float sum(0); for (float d: coords) { sum += pow(d, 2); } return sum; } float norm() const { return sqrt(norm2()); } float operator[](unsigned int i) const { return coords[i]; } float& operator[](unsigned int i) { return coords[i]; } vec<N> operator+=(vec<N> const& other) { for (unsigned int i(0); i < N; ++i) { coords[i] += other.coords[i]; } return *this; } vec<N> operator-=(vec<N> const& other) { for (unsigned int i(0); i < N; ++i) { coords[i] -= other.coords[i]; } return *this; } vec<N> operator*=(float val) { for (unsigned int i(0); i < N; ++i) { coords[i] *= val; } return *this; } float x() const { static_assert(N >= 1); return coords[0]; } float y() const { static_assert(N >= 2); return coords[1]; } float z() const { static_assert(N >= 3); return coords[2]; } float w() const { static_assert(N >= 4); return coords[3]; } void set_x(float val) { static_assert(N >= 1); coords[0] = val; } void set_y(float val) { static_assert(N >= 2); coords[1] = val; } void set_z(float val) { static_assert(N >= 3); coords[2] = val; } void set_w(float val) { static_assert(N >= 4); coords[3] = val; } vec<3> operator^(vec<3> const& other) { static_assert(N == 3); return vec<3>({ y()*other.z() - z()*other.y(), z()*other.x() - x()*other.z(), x()*other.y() - y()*other.x()}); } vec<4> to_4D(float val = 1.0) const { static_assert(N == 3); return vec<4> { x(), y(), z(), val }; } vec<3> to_3D() const { static_assert(N == 4); return vec<3> { x(), y(), z() }; } }; typedef vec<2> vec2f; typedef vec<3> vec3f; typedef vec<4> vec4f; template<unsigned int N> vec<N> operator+(vec<N> v1, vec<N> const& v2) { return (v1 += v2); } template<unsigned int N> vec<N> operator-(vec<N> v1, vec<N> const& v2) { return (v1 -= v2); } template<unsigned int N> vec<N> operator*(float d, vec<N> v) { return (v *= d); } template<unsigned int N> vec<N> operator*(vec<N> v, float d) { return (v *= d); } template<unsigned int N> vec<N> operator~(vec<N> v) { return (v *= (1.0 / v.norm())); } template<unsigned int N> float operator*(vec<N> v1, vec<N> v2) { float result(0); for (unsigned int i(0); i < N; ++i) { result += v1[i] * v2[i]; } return result; } template<unsigned int N> std::ostream &operator<<(std::ostream& os, vec<N> const& vec) { for (unsigned int i(0); i < N; ++i) { os << vec[i]; if (i < N - 1) { os << " "; } } return os; }
lrx0014/SeeJson
src/SeeJSON.h
<gh_stars>1-10 /* SeeJSON.h */ /* SeeJSON @Ryann */ /* Under Development */ /* 2018/3/16 Updated */ #ifndef SEEJSON_H_INCLUDED #define SEEJSON_H_INCLUDED #include <stddef.h> /* size_t */ #ifdef __cplusplus #ifdef _WIN32 #define EXPORT extern "C" __declspec (dllexport) #else #define EXPORT extern "C" #endif // _WIN32 #else #ifdef _WIN32 #define EXPORT __declspec (dllexport) #else #define EXPORT #endif // _WIN32 #endif int isGetErr = 0; /* JSON DataType */ typedef enum{ JSON_NULL, JSON_FALSE, JSON_TRUE, JSON_NUMBER, JSON_STRING, JSON_ARRAY, JSON_OBJECT }json_type; typedef struct json_node json_node; typedef struct json_member json_member; typedef struct json_visitor json_visitor; /* JSON Data Structure */ struct json_node{ /* Value of JSON Node */ union{ /* Object */ struct{ json_member* member; size_t size; }object; /* Array */ struct{ json_node* element; size_t size; }array; /* String */ struct{ char* value; size_t length; }string; /* Number */ double number; }value; /* Type of JSON Node */ json_type type; /* Visit JSON Structure */ const json_node* (*getValue)(const json_node* this,const char* k); }; struct json_member{ char* key; size_t key_len; json_node node; }; struct json_visitor{ /* */ }; /* Error Code */ enum{ /* 0*/JSON_PARSE_SUCCESS = 0, /* 1*/JSON_PARSE_EXPECT_VALUE, /* 2*/JSON_PARSE_INVALID_VALUE, /* 3*/JSON_PARSE_ROOT_ERROR, /* 4*/JSON_PARSE_NUMBER_OVERFLOW, /* 5*/JSON_PARSE_NO_QUOTATION_ERROR, /* 6*/JSON_PARSE_INVALID_STRING_ESCAPE, /* 7*/JSON_PARSE_INVALID_STRING, /* 8*/JSON_PARSE_INVALID_UNICODE, /* 9*/JSON_PARSE_INVALID_UNICODE_SURROGATE, /*10*/JSON_PARSE_UNCOMPLETE_ARRAY_FORMAT, /*11*/JSON_PARSE_KEY_NOTFOUND, /*12*/JSON_PARSE_MISS_COLON, /*13*/JSON_PARSE_UNCOMPLETE_OBJECT_FORMAT, /*14*/JSON_GET_STRING_ERROR, /*15*/JSON_GET_NUMBER_ERROR, /*16*/JSON_GET_BOOLEAN_ERROR, /*17*/JSON_GET_NULL_ERROR, /*18*/JSON_GET_ARRAY_ERROR, /*19*/JSON_GET_OBJECT_ERROR }json_errcode; /* char* err_code[] = { "JSON_PARSE_SUCCESS", "JSON_PARSE_EXPECT_VALUE", "JSON_PARSE_INVALID_VALUE", "JSON_PARSE_ROOT_ERROR", "JSON_PARSE_NUMBER_OVERFLOW", "JSON_PARSE_NO_QUOTATION_ERROR", "JSON_PARSE_INVALID_STRING_ESCAPE", "JSON_PARSE_INVALID_STRING", "JSON_PARSE_INVALID_UNICODE", "JSON_PARSE_INVALID_UNICODE_SURROGATE", "JSON_PARSE_UNCOMPLETE_ARRAY_FORMAT", "JSON_PARSE_KEY_NOTFOUND", "JSON_PARSE_MISS_COLON", "JSON_PARSE_UNCOMPLETE_OBJECT_FORMAT", "JSON_GET_STRING_ERROR", "JSON_GET_NUMBER_ERROR", "JSON_GET_BOOLEAN_ERROR", "JSON_GET_NULL_ERROR", "JSON_GET_ARRAY_ERROR", "JSON_GET_OBJECT_ERROR" }; */ /****************************************************************** Public APIs ******************************************************************/ EXPORT void SeeJSON_Version (void); EXPORT void json_init (json_node* node); EXPORT void json_free (json_node* node); EXPORT void json_set_null (json_node* node); EXPORT int json_get_bool (const json_node* node); EXPORT void json_set_bool (json_node* node,int val); EXPORT double json_get_number (const json_node* node); EXPORT void json_set_number (json_node* node,double val); EXPORT const char* json_get_string (const json_node* node); EXPORT size_t json_get_string_length (const json_node* node); EXPORT void json_set_string (json_node* node,const char* str,size_t len); EXPORT size_t json_get_array_size (const json_node* node); EXPORT json_node* json_get_array_element_by_index (const json_node* node,size_t index); EXPORT size_t json_get_object_size (const json_node* node); EXPORT const char* json_get_object_key_by_index (const json_node* node,size_t index); EXPORT size_t json_get_object_key_len_by_index(const json_node* node,size_t index); EXPORT json_node* json_get_object_value_by_index (const json_node* node,size_t index); EXPORT int json_parse (json_node* json_node,const char* json_str); EXPORT int json_decode (json_node* node,const char* json_str); EXPORT char* json_encode (const json_node* node,size_t* length); EXPORT json_type json_get_type (const json_node* json_node); EXPORT const char* read_string_from_file (char* path); EXPORT json_node read_json_from_file (char* path); /****************************************************************** Visit Methods ******************************************************************/ EXPORT const char* getString (const json_node* node,const char* key); EXPORT const double getNumber (const json_node* node,const char* key); EXPORT const int getBoolean (const json_node* node,const char* key); EXPORT const json_node* getArray (const json_node* node,const char* key); EXPORT const json_node getObject (const json_node* node,const char* key); EXPORT const char* getNull (const json_node* node,const char* key); /****************************************************************** TODOs ******************************************************************/ EXPORT json_visitor see_json (const json_node* node,const char* key); #endif
lrx0014/SeeJson
src/Test_SeeJSON.c
<gh_stars>1-10 /* Test_SeeJSON.c */ /* SeeJSON @Ryann */ /* Under Development */ /* 2018/3/16 Updated */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "SeeJSON.h" #include "SeeJSON.c" static int cases_total = 0; /* Sum of Test Cases */ static int cases_passed = 0; /* Sum of Cases passed the test */ static int status = 0; /* Return value of Main */ #define TEST_CORE(func,expect,fact,format) \ do{ \ cases_total++; \ if(func) \ cases_passed++; \ else{ \ fprintf(stderr,"%s:%d\nExpect for: " format " \nBut actually get: " format "\n\n",__FILE__,__LINE__,expect,fact); \ status = 1; \ } \ }while(0) #define TEST_INT(expect,fact)\ TEST_CORE((expect)==(fact),expect,fact,"%d") #define TEST_DOUBLE(expect,fact)\ TEST_CORE((expect)==(fact),expect,fact,"%.17g") #define TEST_STRING_IS_RIGHT(expect,fact,length)\ TEST_CORE(((sizeof(expect)-1)==length && memcmp(expect,fact,length+1)==0),expect,fact,"%s") #define TEST_TRUE(fact) \ TEST_CORE((fact)!=0,"true","false","%s") #define TEST_FALSE(fact) \ TEST_CORE((fact)==0,"false","true","%s") #define TEST_NUMBER(expect,json) \ do{ \ json_node node; \ json_init(&node); \ TEST_INT(JSON_PARSE_SUCCESS,json_parse(&node,json));\ TEST_INT(JSON_NUMBER,json_get_type(&node));\ TEST_DOUBLE(expect,json_get_number(&node));\ json_free(&node); \ }while(0) #define TEST_STRING(expect,json) \ do{ \ json_node node; \ json_init(&node); \ TEST_INT(JSON_PARSE_SUCCESS,json_parse(&node,json)); \ TEST_INT(JSON_STRING,json_get_type(&node)); \ TEST_STRING_IS_RIGHT(expect,json_get_string(&node),json_get_string_length(&node)); \ json_free(&node); \ }while(0) #if defined(_MSC_VER) #define TEST_SIZE_T(expect,fact) TEST_CORE((expect) == (fact), (size_t)expect, (size_t)fact, "%Iu") #else #define TEST_SIZE_T(expect,fact) TEST_CORE((expect) == (fact), (size_t)expect, (size_t)fact, "%zu") #endif /* Encapsulate the Test method */ #define TESTER(error,json)\ do{\ json_node node;\ json_init(&node); \ node.type = JSON_FALSE;\ TEST_INT(error,json_parse(&node,json));\ TEST_INT(JSON_NULL,json_get_type(&node));\ json_free(&node); \ }while(0) #define RT_TESTER(json) \ do{ \ json_node node; \ char* json_test; \ size_t len; \ json_init(&node); \ TEST_INT(JSON_PARSE_SUCCESS,json_parse(&node,json)); \ json_test = json_encode(&node,&len); \ TEST_STRING_IS_RIGHT(json,json_test,len); \ json_free(&node); \ free(json_test); \ }while(0) /********************************************** TestCases *********************************************/ static void test_for_parse_null() { json_node node; json_init(&node); json_set_bool(&node,0); TEST_INT(JSON_PARSE_SUCCESS,json_parse(&node,"null")); TEST_INT(JSON_NULL,json_get_type(&node)); json_free(&node); } static void test_for_parse_true() { json_node node; json_init(&node); json_set_bool(&node,0); TEST_INT(JSON_PARSE_SUCCESS,json_parse(&node,"true")); TEST_INT(JSON_TRUE,json_get_type(&node)); json_free(&node); } static void test_for_parse_false() { json_node node; json_init(&node); json_set_bool(&node,0); TEST_INT(JSON_PARSE_SUCCESS,json_parse(&node,"false")); TEST_INT(JSON_FALSE,json_get_type(&node)); json_free(&node); } static void test_for_error() { /* Test for PARSE_EXPECT_VALUE */ TESTER(JSON_PARSE_EXPECT_VALUE,""); TESTER(JSON_PARSE_EXPECT_VALUE," "); /* Test for INVALID NUMBER Type */ TESTER(JSON_PARSE_INVALID_VALUE,"nux"); TESTER(JSON_PARSE_INVALID_VALUE,"?"); TESTER(JSON_PARSE_INVALID_VALUE, "+0"); TESTER(JSON_PARSE_INVALID_VALUE, "+1"); TESTER(JSON_PARSE_INVALID_VALUE, ".123"); TESTER(JSON_PARSE_INVALID_VALUE, "1."); TESTER(JSON_PARSE_INVALID_VALUE, "INF"); TESTER(JSON_PARSE_INVALID_VALUE, "inf"); TESTER(JSON_PARSE_INVALID_VALUE, "NAN"); TESTER(JSON_PARSE_INVALID_VALUE, "nan"); /* Test for PARSE_ROOT_ERROR */ TESTER(JSON_PARSE_ROOT_ERROR,"null x"); TESTER(JSON_PARSE_ROOT_ERROR, "0123"); /* after zero should be '.' or nothing */ TESTER(JSON_PARSE_ROOT_ERROR, "0x0"); TESTER(JSON_PARSE_ROOT_ERROR, "0x123"); /* Test for PARSE_NUMBER_OVERFLOW */ TESTER(JSON_PARSE_NUMBER_OVERFLOW,"1e309"); TESTER(JSON_PARSE_NUMBER_OVERFLOW,"-1e309"); /* Test for PARSE_NO_QUATATION_ERROR */ TESTER(JSON_PARSE_NO_QUOTATION_ERROR,"\""); TESTER(JSON_PARSE_NO_QUOTATION_ERROR,"\"abc"); /* Test for PARSE_INVALID_STRING_ESCAPE */ TESTER(JSON_PARSE_INVALID_STRING_ESCAPE,"\"\\v\""); TESTER(JSON_PARSE_INVALID_STRING_ESCAPE,"\"\\'\""); TESTER(JSON_PARSE_INVALID_STRING_ESCAPE,"\"\\0\""); TESTER(JSON_PARSE_INVALID_STRING_ESCAPE,"\"\\x12\""); /* Test for PARSE_INVALID_STRING */ TESTER(JSON_PARSE_INVALID_STRING,"\"\x01\""); TESTER(JSON_PARSE_INVALID_STRING,"\"\x1F\""); /* Test for PARSE_INVALID_UNICODE */ TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u0\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u01\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u012\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u/000\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\uG000\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u0/00\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u0G00\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u0/00\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u00G0\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u000/\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u000G\""); TESTER(JSON_PARSE_INVALID_UNICODE, "\"\\u 123\""); /* Test for PARSE_INVALID_UNICODE_SURROGATE */ TESTER(JSON_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uD800\""); TESTER(JSON_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uDBFF\""); TESTER(JSON_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uD800\\\\\""); TESTER(JSON_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uD800\\uDBFF\""); TESTER(JSON_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uD800\\uE000\""); /* Test for invalid value in array */ TESTER(JSON_PARSE_INVALID_VALUE,"[1,]"); TESTER(JSON_PARSE_INVALID_VALUE,"[\"a\", nul]"); /* Test for PARSE_UNCOMPLETE_ARRAY_FORMAT */ TESTER(JSON_PARSE_UNCOMPLETE_ARRAY_FORMAT,"[1"); TESTER(JSON_PARSE_UNCOMPLETE_ARRAY_FORMAT,"[1}"); TESTER(JSON_PARSE_UNCOMPLETE_ARRAY_FORMAT,"[1 3"); TESTER(JSON_PARSE_UNCOMPLETE_ARRAY_FORMAT,"[[]"); /*TESTER(JSON_PARSE_UNCOMPLETE_ARRAY_FORMAT,"[\"a\",\"b\",\"c\"]");*/ /*TESTER(JSON_PARSE_UNCOMPLETE_ARRAY_FORMAT,"[1,\"a\",3]");*/ /* Test for PARSE_KEY_NOTFOUND */ TESTER(JSON_PARSE_KEY_NOTFOUND, "{:1,"); TESTER(JSON_PARSE_KEY_NOTFOUND, "{1:1,"); TESTER(JSON_PARSE_KEY_NOTFOUND, "{true:1,"); TESTER(JSON_PARSE_KEY_NOTFOUND, "{false:1,"); TESTER(JSON_PARSE_KEY_NOTFOUND, "{null:1,"); TESTER(JSON_PARSE_KEY_NOTFOUND, "{[]:1,"); TESTER(JSON_PARSE_KEY_NOTFOUND, "{{}:1,"); TESTER(JSON_PARSE_KEY_NOTFOUND, "{\"a\":1,"); /* Test for PARSE_MISS_COLON */ TESTER(JSON_PARSE_MISS_COLON,"{\"a\"}"); TESTER(JSON_PARSE_MISS_COLON,"{\"a\",\"b\"}"); /* Test for PARSE_UNCOMPLETE_OBJECT_FORMAT */ TESTER(JSON_PARSE_UNCOMPLETE_OBJECT_FORMAT,"{\"a\":1"); TESTER(JSON_PARSE_UNCOMPLETE_OBJECT_FORMAT,"{\"a\":1]"); TESTER(JSON_PARSE_UNCOMPLETE_OBJECT_FORMAT,"{\"a\":1 \"b\""); TESTER(JSON_PARSE_UNCOMPLETE_OBJECT_FORMAT,"{\"a\":{}"); } static void roundtrip_test() { /* Test for encoding true-false-null */ RT_TESTER("null"); RT_TESTER("false"); RT_TESTER("true"); /* Test for encoding number */ RT_TESTER("0"); RT_TESTER("-0"); RT_TESTER("1"); RT_TESTER("-1"); RT_TESTER("1.5"); RT_TESTER("-1.5"); RT_TESTER("3.25"); RT_TESTER("1e+020"); RT_TESTER("1.234e+020"); RT_TESTER("1.234e-020"); RT_TESTER("1.0000000000000002"); /* the smallest number > 1 */ RT_TESTER("4.9406564584124654e-324"); /* minimum denormal */ RT_TESTER("-4.9406564584124654e-324"); RT_TESTER("2.2250738585072009e-308"); /* Max subnormal double */ RT_TESTER("-2.2250738585072009e-308"); RT_TESTER("2.2250738585072014e-308"); /* Min normal positive double */ RT_TESTER("-2.2250738585072014e-308"); RT_TESTER("1.7976931348623157e+308"); /* Max double */ RT_TESTER("-1.7976931348623157e+308"); /* Test for encoding string */ RT_TESTER("\"\""); RT_TESTER("\"Hello\""); RT_TESTER("\"Hello\\nWorld\""); RT_TESTER("\"\\\" \\\\ / \\b \\f \\n \\r \\t\""); RT_TESTER("\"Hello\\u0000World\""); /* Test for encoding array */ RT_TESTER("[]"); RT_TESTER("[null,false,true,123,\"abc\",[1,2,3]]"); /* Test for encoding object */ RT_TESTER("{}"); RT_TESTER("{\"n\":null,\"f\":false,\"t\":true,\"i\":123,\"s\":\"abc\",\"a\":[1,2,3],\"o\":{\"1\":1,\"2\":2,\"3\":3}}"); } static void test_for_parse_number() { /* Test for different types of numbers */ /* TEST_NUMBER(0.0,"000"); */ TEST_NUMBER(0.0, "0"); TEST_NUMBER(0.0, "-0"); TEST_NUMBER(0.0, "-0.0"); TEST_NUMBER(1.0, "1"); TEST_NUMBER(-1.0, "-1"); TEST_NUMBER(1.5, "1.5"); TEST_NUMBER(-1.5, "-1.5"); TEST_NUMBER(3.1416, "3.1416"); TEST_NUMBER(1E10, "1E10"); TEST_NUMBER(1e10, "1e10"); TEST_NUMBER(1E+10, "1E+10"); TEST_NUMBER(1E-10, "1E-10"); TEST_NUMBER(-1E10, "-1E10"); TEST_NUMBER(-1e10, "-1e10"); TEST_NUMBER(-1E+10, "-1E+10"); TEST_NUMBER(-1E-10, "-1E-10"); TEST_NUMBER(1.234E+10, "1.234E+10"); TEST_NUMBER(1.234E-10, "1.234E-10"); TEST_NUMBER(0.0, "1e-10000"); /* must underflow */ TEST_NUMBER(1.0000000000000002, "1.0000000000000002"); /* the smallest number > 1 */ TEST_NUMBER( 4.9406564584124654e-324, "4.9406564584124654e-324"); /* minimum denormal */ TEST_NUMBER(-4.9406564584124654e-324, "-4.9406564584124654e-324"); TEST_NUMBER( 2.2250738585072009e-308, "2.2250738585072009e-308"); /* Max subnormal double */ TEST_NUMBER(-2.2250738585072009e-308, "-2.2250738585072009e-308"); TEST_NUMBER( 2.2250738585072014e-308, "2.2250738585072014e-308"); /* Min normal positive double */ TEST_NUMBER(-2.2250738585072014e-308, "-2.2250738585072014e-308"); TEST_NUMBER( 1.7976931348623157e+308, "1.7976931348623157e+308"); /* Max double */ TEST_NUMBER(-1.7976931348623157e+308, "-1.7976931348623157e+308"); } static void test_for_parse_string() { TEST_STRING("","\"\""); TEST_STRING("Hello", "\"Hello\""); TEST_STRING("Hello\nWorld", "\"Hello\\nWorld\""); TEST_STRING("\" \\ / \b \f \n \r \t", "\"\\\" \\\\ \\/ \\b \\f \\n \\r \\t\""); TEST_STRING("Hello\0World", "\"Hello\\u0000World\""); TEST_STRING("\x24", "\"\\u0024\""); /* Dollar sign U+0024 */ TEST_STRING("\xC2\xA2", "\"\\u00A2\""); /* Cents sign U+00A2 */ TEST_STRING("\xE2\x82\xAC", "\"\\u20AC\""); /* Euro sign U+20AC */ TEST_STRING("\xF0\x9D\x84\x9E", "\"\\uD834\\uDD1E\""); /* G clef sign U+1D11E */ TEST_STRING("\xF0\x9D\x84\x9E", "\"\\ud834\\udd1e\""); /* G clef sign U+1D11E */ } static void test_for_parse_array() { size_t i,j; json_node node; json_init(&node); TEST_INT(JSON_PARSE_SUCCESS,json_parse(&node,"[ ]")); TEST_INT(JSON_ARRAY,json_get_type(&node)); TEST_SIZE_T(0,json_get_array_size(&node)); json_free(&node); json_init(&node); TEST_INT(JSON_PARSE_SUCCESS, json_parse(&node, "[ null , false , true , 123 , \"abc\" ]")); TEST_INT(JSON_ARRAY, json_get_type(&node)); TEST_SIZE_T(5, json_get_array_size(&node)); TEST_INT(JSON_NULL, json_get_type(json_get_array_element_by_index(&node, 0))); TEST_INT(JSON_FALSE, json_get_type(json_get_array_element_by_index(&node, 1))); TEST_INT(JSON_TRUE, json_get_type(json_get_array_element_by_index(&node, 2))); TEST_INT(JSON_NUMBER, json_get_type(json_get_array_element_by_index(&node, 3))); TEST_INT(JSON_STRING, json_get_type(json_get_array_element_by_index(&node, 4))); TEST_DOUBLE(123.0, json_get_number(json_get_array_element_by_index(&node, 3))); TEST_STRING_IS_RIGHT("abc", json_get_string(json_get_array_element_by_index(&node, 4)), json_get_string_length(json_get_array_element_by_index(&node, 4))); json_free(&node); json_init(&node); TEST_INT(JSON_PARSE_SUCCESS, json_parse(&node, "[ [ ] , [ 0 ] , [ 0 , 1 ] , [ 0 , 1 , 2 ] ]")); TEST_INT(JSON_ARRAY, json_get_type(&node)); TEST_SIZE_T(4, json_get_array_size(&node)); for (i = 0; i < 4; i++) { json_node* a = json_get_array_element_by_index(&node, i); TEST_INT(JSON_ARRAY, json_get_type(a)); TEST_SIZE_T(i, json_get_array_size(a)); for (j = 0; j < i; j++) { json_node* e = json_get_array_element_by_index(a, j); TEST_INT(JSON_NUMBER, json_get_type(e)); TEST_DOUBLE((double)j, json_get_number(e)); } } json_free(&node); } static void test_for_parse_object() { json_node node; size_t i; json_init(&node); TEST_INT(JSON_PARSE_SUCCESS, json_parse(&node, " { } ")); TEST_INT(JSON_OBJECT, json_get_type(&node)); TEST_SIZE_T(0, json_get_object_size(&node)); json_free(&node); json_init(&node); TEST_INT(JSON_PARSE_SUCCESS, json_parse(&node, " { " "\"n\" : null , " "\"f\" : false , " "\"t\" : true , " "\"i\" : 123 , " "\"s\" : \"abc\", " "\"a\" : [ 1, 2, 3 ]," "\"o\" : { \"1\" : 1, \"2\" : 2, \"3\" : 3 }" " } " )); TEST_INT(JSON_OBJECT, json_get_type(&node)); TEST_SIZE_T(7, json_get_object_size(&node)); TEST_STRING_IS_RIGHT("n", json_get_object_key_by_index(&node, 0), json_get_object_key_len_by_index(&node, 0)); TEST_INT(JSON_NULL, json_get_type(json_get_object_value_by_index(&node, 0))); TEST_STRING_IS_RIGHT("f", json_get_object_key_by_index(&node, 1), json_get_object_key_len_by_index(&node, 1)); TEST_INT(JSON_FALSE, json_get_type(json_get_object_value_by_index(&node, 1))); TEST_STRING_IS_RIGHT("t", json_get_object_key_by_index(&node, 2), json_get_object_key_len_by_index(&node, 2)); TEST_INT(JSON_TRUE, json_get_type(json_get_object_value_by_index(&node, 2))); TEST_STRING_IS_RIGHT("i", json_get_object_key_by_index(&node, 3), json_get_object_key_len_by_index(&node, 3)); TEST_INT(JSON_NUMBER, json_get_type(json_get_object_value_by_index(&node, 3))); TEST_DOUBLE(123.0, json_get_number(json_get_object_value_by_index(&node, 3))); TEST_STRING_IS_RIGHT("s", json_get_object_key_by_index(&node, 4), json_get_object_key_len_by_index(&node, 4)); TEST_INT(JSON_STRING, json_get_type(json_get_object_value_by_index(&node, 4))); TEST_STRING_IS_RIGHT("abc", json_get_string(json_get_object_value_by_index(&node, 4)), json_get_string_length(json_get_object_value_by_index(&node, 4))); TEST_STRING_IS_RIGHT("a", json_get_object_key_by_index(&node, 5), json_get_object_key_len_by_index(&node, 5)); TEST_INT(JSON_ARRAY, json_get_type(json_get_object_value_by_index(&node, 5))); TEST_SIZE_T(3, json_get_array_size(json_get_object_value_by_index(&node, 5))); for (i = 0; i < 3; i++) { json_node* e = json_get_array_element_by_index(json_get_object_value_by_index(&node, 5), i); TEST_INT(JSON_NUMBER, json_get_type(e)); TEST_DOUBLE(i + 1.0, json_get_number(e)); } TEST_STRING_IS_RIGHT("o", json_get_object_key_by_index(&node, 6), json_get_object_key_len_by_index(&node, 6)); { json_node* o = json_get_object_value_by_index(&node, 6); TEST_INT(JSON_OBJECT, json_get_type(o)); for (i = 0; i < 3; i++) { json_node* ov = json_get_object_value_by_index(o, i); TEST_TRUE('1' + i == json_get_object_key_by_index(o, i)[0]); TEST_SIZE_T(1, json_get_object_key_len_by_index(o, i)); TEST_INT(JSON_NUMBER, json_get_type(ov)); TEST_DOUBLE(i + 1.0, json_get_number(ov)); } } json_free(&node); } static void test_for_access_null() { json_node node; json_init(&node); json_set_string(&node,"a",1); json_set_null(&node); TEST_INT(JSON_NULL,json_get_type(&node)); json_free(&node); } static void test_for_access_bool() { json_node node; json_init(&node); json_set_string(&node,"a",1); json_set_bool(&node,1); TEST_TRUE(json_get_bool(&node)); json_set_bool(&node,0); TEST_FALSE(json_get_bool(&node)); json_free(&node); } static void test_for_access_number() { json_node node; json_init(&node); json_set_string(&node,"a",1); json_set_number(&node,1234.5); TEST_DOUBLE(1234.5,json_get_number(&node)); json_free(&node); } static void test_for_access_string() { json_node node; json_init(&node); json_set_string(&node,"",0); TEST_STRING_IS_RIGHT("",json_get_string(&node),json_get_string_length(&node)); json_set_string(&node,"hello",5); TEST_STRING_IS_RIGHT("hello",json_get_string(&node),json_get_string_length(&node)); json_free(&node); } static void test_parse() { test_for_error(); test_for_parse_null(); test_for_parse_true(); test_for_parse_false(); test_for_parse_number(); test_for_access_string(); test_for_access_null(); test_for_access_bool(); test_for_access_number(); test_for_access_string(); test_for_parse_array(); test_for_parse_object(); roundtrip_test(); } static void test_for_visit_easy_structure() { /* Read JSON */ const char* json = "{\"name\":\"SeeJSON\"}"; /* Parse JSON Into json_node */ json_node node; json_init(&node); json_decode(&node,json); /* Use json.getValue() to visit it */ printf("name:%s\n",getString(&node,"name")); } static void test_for_complex_demand() { /* Read JSON from file */ json_node node = read_json_from_file("test.json"); const char* name = getString(&node,"Name"); const char* date = getString(&node,"Date"); printf("Name:%s\n",name); printf("Date:%s\n",date); const json_node object = getObject(&node,"Object"); const double _number = getNumber(&object,"Number"); const int _boolean = getBoolean(&object,"Boolean"); const char* _null = getNull(&object,"Null"); const char* _str = getString(&object,"String"); printf("Number:%lf\n",_number); printf("String:%s\n",_str); printf("Null:%s\n",_null); printf("Boolean:%d\n",_boolean); const json_node* arr = getArray(&object,"Array"); printf("Array_String:%s\n",getString(&arr[0],"")); printf("Array_Number:%lf\n",getNumber(&arr[1],"")); printf("Array_Null:%s\n",getNull(&arr[2],"")); } static void test_for_visitor() { /* Read JSON from file */ /* Use Visitor to visit this node */ } static void test_for_visit_directly() { /* Read JSON from file */ json_node node; node = read_json_from_file("city.json"); printf("area:%s\n",node.value.object.member[1].node.value.object.member[1].node.value.array.element[1].value.string.value); } int main() { SeeJSON_Version(); test_parse(); printf("%d/%d (%3.2f%%) Cases Passed. \n\n",cases_passed,cases_total,cases_passed*100.0/cases_total); /* test_for_visit_easy_structure(); */ test_for_complex_demand(); /* test_for_visit_directly(); */ /* test_for_visitor(); */ #ifdef _WIN32 system("pause"); #endif // _WIN32 return status; }
lrx0014/SeeJson
src/SeeJSON.c
<filename>src/SeeJSON.c /* SeeJSON.c */ /* SeeJSON @Ryann */ /* Under Development */ /* 2018/3/16 Updated */ #include "SeeJSON.h" #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <errno.h> /* errno, ERANGE */ #include <math.h> /* HUGE_VAL */ #include <string.h> #ifndef JSON_PARSE_STACK_INIT_SIZE #define JSON_PARSE_STACK_INIT_SIZE 256 #endif #ifndef JSON_ENCODE_INIT_SIZE #define JSON_ENCODE_INIT_SIZE 256 #endif #define bool int #define true 1 #define false 0 #define CHECK(context,ch) \ do{ \ assert(*context->json==(ch)); \ context->json++; \ }while(0) #define PUTC(c, ch) do { *(char*)json_context_push(c, sizeof(char)) = (ch); } while(0) #define PUTS(c, s, len) memcpy(json_context_push(c, len), s, len) /* JSON String */ typedef struct{ const char* json; char* stack; size_t size,top; }json_context; /* Forward Declaration */ static int json_parse_value(json_context* con,json_node* node); static bool isDigit(const char ch) { if(ch>='0' && ch<='9') { return true; } return false; } static bool isOneToNine(const char ch) { if(ch>='1' && ch<='9') { return true; } return false; } static void* json_context_push(json_context* con,size_t size) { void *ret; assert(size>0); if(con->top + size >= con->size) { if(con->size==0) { con->size = JSON_PARSE_STACK_INIT_SIZE; } while(con->top + size >= con->size) { con->size += con->size >> 1; } con->stack = (char*)realloc(con->stack,con->size); } ret = con->stack + con->top; con->top += size; return ret; } static void* json_context_pop(json_context* con,size_t size) { assert(con->top >= size); return con->stack + (con->top -= size); } static void json_parse_space(json_context* con) { const char *p = con->json; while(*p==' ' || *p=='\t' || *p=='\n' || *p=='\r') { p++; } con->json = p; } static int json_parse_true(json_context* con,json_node* node) { CHECK(con,'t'); if(con->json[0]!='r' || con->json[1]!='u' || con->json[2]!='e') { return JSON_PARSE_INVALID_VALUE; } con->json += 3; node->type = JSON_TRUE; return JSON_PARSE_SUCCESS; } static int json_parse_false(json_context* con, json_node* node) { CHECK(con, 'f'); if (con->json[0] != 'a' || con->json[1] != 'l' || con->json[2] != 's' || con->json[3] != 'e') return JSON_PARSE_INVALID_VALUE; con->json += 4; node->type = JSON_FALSE; return JSON_PARSE_SUCCESS; } static int json_parse_null(json_context* con, json_node* node) { CHECK(con, 'n'); if (con->json[0] != 'u' || con->json[1] != 'l' || con->json[2] != 'l') return JSON_PARSE_INVALID_VALUE; con->json += 3; node->type = JSON_NULL; return JSON_PARSE_SUCCESS; } static int json_parse_number(json_context* con,json_node* node) { const char* p = con->json; if(*p=='-') { p++; } if(*p=='0') p++; else{ if(!isOneToNine(*p)) { return JSON_PARSE_INVALID_VALUE; } for(p++;isDigit(*p);p++); } if(*p=='.') { p++; if(!isDigit(*p)) { return JSON_PARSE_INVALID_VALUE; } for(p++;isDigit(*p);p++); } if(*p=='e' || *p=='E') { p++; if(*p=='+' || *p=='-') { p++; } if(!isDigit(*p)) { return JSON_PARSE_INVALID_VALUE; } for(p++;isDigit(*p);p++); } errno = 0; node->value.number = strtod(con->json,NULL); if(errno==ERANGE && (node->value.number==HUGE_VAL || node->value.number==-HUGE_VAL)) { return JSON_PARSE_NUMBER_OVERFLOW; } node->type = JSON_NUMBER; con->json = p; return JSON_PARSE_SUCCESS; } static const char* json_parse_hex4(const char* p,unsigned* u) { *u = 0; int i; for(i=0;i<4;i++) { char ch = *p++; *u<<=4; if(ch>='0' && ch<='9') { *u |= ch - '0'; } else if(ch>='A' && ch<='F') { *u |= ch - ('A'-10); } else if(ch>='a' && ch<='f') { *u |= ch-('a'-10); } else{ return NULL; } } return p; } static void json_utf8(json_context* con,unsigned u) { if(u<=0x7F) { PUTC(con,u & 0xFF); } else if(u<=0x7FF) { PUTC(con,0xC0 | ((u>>6)&0xFF)); PUTC(con,0x80 | ( u & 0x3F)); } else if(u<=0xFFFF) { PUTC(con, 0xE0 | ((u >> 12) & 0xFF)); PUTC(con, 0x80 | ((u >> 6) & 0x3F)); PUTC(con, 0x80 | ( u & 0x3F)); } else{ assert(u <= 0x10FFFF); PUTC(con, 0xF0 | ((u >> 18) & 0xFF)); PUTC(con, 0x80 | ((u >> 12) & 0x3F)); PUTC(con, 0x80 | ((u >> 6) & 0x3F)); PUTC(con, 0x80 | ( u & 0x3F)); } } static int json_parse_string_raw(json_context* con,char** str,size_t* len) { size_t head = con->top; const char* p; CHECK(con,'\"'); p = con->json; unsigned u1; unsigned u2; for(;;) { char ch = *p++; switch(ch) { case '\"': *len = con->top - head; *str = json_context_pop(con,*len); con->json = p; return JSON_PARSE_SUCCESS; case '\\': switch (*p++) { case '\"': PUTC(con, '\"'); break; case '\\': PUTC(con, '\\'); break; case '/': PUTC(con, '/' ); break; case 'b': PUTC(con, '\b'); break; case 'f': PUTC(con, '\f'); break; case 'n': PUTC(con, '\n'); break; case 'r': PUTC(con, '\r'); break; case 't': PUTC(con, '\t'); break; case 'u': if(!(p=json_parse_hex4(p,&u1))) { con->top = head; return JSON_PARSE_INVALID_UNICODE; } if(u1>=0xD800 && u1<=0xDBFF) { if(*p++ != '\\') { con->top = head; return JSON_PARSE_INVALID_UNICODE_SURROGATE; } if(*p++ != 'u') { con->top = head; return JSON_PARSE_INVALID_UNICODE_SURROGATE; } if(!(p=json_parse_hex4(p,&u2))) { con->top = head; return JSON_PARSE_INVALID_UNICODE; } if(u2<0xDC00 || u2>0xDFFF) { con->top = head; return JSON_PARSE_INVALID_UNICODE_SURROGATE; } u1 = (((u1-0xD800)<<10)|(u2-0xDC00))+0x10000; } json_utf8(con,u1); break; default: con->top = head; return JSON_PARSE_INVALID_STRING_ESCAPE; } break; case '\0': con->top = head; return JSON_PARSE_NO_QUOTATION_ERROR; default: if((unsigned char)ch < 0x20) { con->top = head; return JSON_PARSE_INVALID_STRING; } PUTC(con,ch); } } } static int json_parse_string(json_context* con,json_node* node) { int ret; char* s; size_t len; if((ret=json_parse_string_raw(con,&s,&len))==JSON_PARSE_SUCCESS) { json_set_string(node,s,len); } return ret; } static int json_parse_array(json_context* con,json_node* node) { size_t i; size_t size = 0; int ret; CHECK(con,'['); json_parse_space(con); if(*con->json==']') { con->json++; node->type = JSON_ARRAY; node->value.array.size = 0; node->value.array.element = NULL; return JSON_PARSE_SUCCESS; } for(;;) { json_node e; json_init(&e); if((ret=json_parse_value(con,&e))!=JSON_PARSE_SUCCESS) { break; } memcpy(json_context_push(con,sizeof(json_node)),&e,sizeof(json_node)); size++; json_parse_space(con); if(*con->json==',') { con->json++; json_parse_space(con); } else if(*con->json==']') { con->json++; node->type = JSON_ARRAY; node->value.array.size = size; size *= sizeof(json_node); memcpy(node->value.array.element=(json_node*)malloc(size),json_context_pop(con,size),size); return JSON_PARSE_SUCCESS; } else { ret = JSON_PARSE_UNCOMPLETE_ARRAY_FORMAT; break; } } for(i=0;i<size;i++) { json_free((json_node*)json_context_pop(con,sizeof(json_node))); } return ret; } static int json_parse_object(json_context* con,json_node* node) { size_t i,size; json_member member; int ret; CHECK(con,'{'); json_parse_space(con); if(*con->json=='}') { con->json++; node->type = JSON_OBJECT; node->value.object.member = 0; node->value.object.size = 0; return JSON_PARSE_SUCCESS; } member.key = NULL; size = 0; for(;;) { char* str; json_init(&member.node); if(*con->json!='"') { ret = JSON_PARSE_KEY_NOTFOUND; break; } if((ret=json_parse_string_raw(con,&str,&member.key_len))!=JSON_PARSE_SUCCESS) { break; } memcpy(member.key=(char*)malloc(member.key_len+1),str,member.key_len); member.key[member.key_len] = '\0'; json_parse_space(con); if(*con->json!=':') { ret = JSON_PARSE_MISS_COLON; break; } con->json++; json_parse_space(con); if((ret=json_parse_value(con,&member.node))!=JSON_PARSE_SUCCESS) { break; } memcpy(json_context_push(con,sizeof(json_member)),&member,sizeof(json_member)); size++; member.key = NULL; json_parse_space(con); if(*con->json==',') { con->json++; json_parse_space(con); } else if(*con->json=='}') { size_t s =sizeof(json_member)*size; con->json++; node->type = JSON_OBJECT; node->value.object.size = size; memcpy(node->value.object.member=(json_member*)malloc(s),json_context_pop(con,s),s); return JSON_PARSE_SUCCESS; } else{ ret = JSON_PARSE_UNCOMPLETE_OBJECT_FORMAT; break; } } free(member.key); for(i=0;i<size;i++) { json_member* member = (json_member*)json_context_pop(con,sizeof(json_member)); free(member->key); json_free(&member->node); } node->type = JSON_NULL; return ret; } static int json_parse_value(json_context* con,json_node* node) { switch(*con->json) { case 't' : return json_parse_true(con,node); case 'f' : return json_parse_false(con,node); case 'n' : return json_parse_null(con,node); case '\0': return JSON_PARSE_EXPECT_VALUE; case '"' : return json_parse_string(con,node); case '[' : return json_parse_array(con,node); case '{' : return json_parse_object(con,node); default : return json_parse_number(con,node); } } static void json_encode_string(json_context* con,const char* s,size_t len) { static const char hex_digits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; size_t i,size; char* head,*p; assert(s!=NULL); head = json_context_push(con,size=len*6+2); p = head; *p++ = '"'; for(i=0;i<len;i++) { unsigned char ch = (unsigned char)s[i]; switch(ch) { case '\"': *p++ = '\\'; *p++ = '\"'; break; case '\\': *p++ = '\\'; *p++ = '\\'; break; case '\b': *p++ = '\\'; *p++ = 'b'; break; case '\f': *p++ = '\\'; *p++ = 'f'; break; case '\n': *p++ = '\\'; *p++ = 'n'; break; case '\r': *p++ = '\\'; *p++ = 'r'; break; case '\t': *p++ = '\\'; *p++ = 't'; break; default: if (ch < 0x20) { *p++ = '\\'; *p++ = 'u'; *p++ = '0'; *p++ = '0'; *p++ = hex_digits[ch >> 4]; *p++ = hex_digits[ch & 15]; } else { *p++ = s[i]; } } } *p++ = '"'; con->top -= size - (p-head); } static void json_encode_value(json_context* con,const json_node* node) { size_t i; switch(node->type) { case JSON_NULL : PUTS(con,"null",4); break; case JSON_FALSE : PUTS(con,"false",5); break; case JSON_TRUE : PUTS(con,"true",4); break; case JSON_NUMBER: con->top -= 32 - sprintf(json_context_push(con,32),"%.17g",node->value.number); break; case JSON_STRING: json_encode_string(con,node->value.string.value,node->value.string.length); break; case JSON_ARRAY : PUTC(con,'['); for(i=0;i<node->value.array.size;i++) { if(i>0) { PUTC(con,','); } json_encode_value(con,&node->value.array.element[i]); } PUTC(con,']'); break; case JSON_OBJECT: PUTC(con,'{'); for(i=0;i<node->value.object.size;i++) { if(i>0) { PUTC(con,','); } json_encode_string(con,node->value.object.member[i].key,node->value.object.member[i].key_len); PUTC(con,':'); json_encode_value(con,&node->value.object.member[i].node); } PUTC(con,'}'); break; default: assert(0 && "INVALID TYPE ERROR..."); } } static const json_node* getValue(const json_node* this,const char* k) { int this_size = this->value.object.size; json_node* ret; int i; for(i=0;i<this_size;i++) { json_member* cur; cur = &(this->value.object.member[i]); if(strcmp(cur->key,k)==0) { ret = &cur->node; return ret; } } return NULL; } /********************************************************** Implements of Public APIs **********************************************************/ EXPORT void SeeJSON_Version(void) { printf("SeeJSON ( ver-alpha 1.0.0 ) 2018-01-30 \n\n"); } EXPORT void json_init(json_node* node) { node->type = JSON_NULL; node->getValue = getValue; } EXPORT void json_set_null(json_node* node) { json_free(node); } EXPORT int json_parse(json_node* node,const char* json) { json_context con; int status; assert(node!=NULL); con.json = json; con.stack = NULL; con.size = con.top = 0; json_init(node); json_parse_space(&con); if((status=json_parse_value(&con,node))==JSON_PARSE_SUCCESS) { json_parse_space(&con); if(*con.json!='\0') { node->type = JSON_NULL; status = JSON_PARSE_ROOT_ERROR; } } assert(con.top == 0); free(con.stack); return status; } EXPORT json_type json_get_type(const json_node* node) { assert(node!=NULL); return node->type; } EXPORT double json_get_number(const json_node* node) { assert(node!=NULL && node->type==JSON_NUMBER); return node->value.number; } EXPORT void json_set_number(json_node* node,double n) { json_free(node); node->value.number = n; node->type = JSON_NUMBER; } EXPORT void json_free(json_node* node) { assert(node!=NULL); size_t i; switch(node->type) { case JSON_STRING: free(node->value.string.value); break; case JSON_ARRAY: for(i=0;i<node->value.array.size;i++) { json_free(&node->value.array.element[i]); } free(node->value.array.element); break; case JSON_OBJECT: for(i=0;i<node->value.object.size;i++) { free(node->value.object.member[i].key); json_free(&node->value.object.member[i].node); } free(node->value.object.member); break; default:break; } node->type = JSON_NULL; } EXPORT int json_get_bool(const json_node* node) { assert(node!=NULL && (node->type==JSON_TRUE || node->type==JSON_FALSE)); return node->type == JSON_TRUE; } EXPORT void json_set_bool(json_node* node,int b) { json_free(node); node->type = b?JSON_TRUE:JSON_FALSE; } EXPORT const char* json_get_string(const json_node* node) { assert(node!=NULL && node->type==JSON_STRING); return node->value.string.value; } EXPORT size_t json_get_string_length(const json_node* node) { assert(node!=NULL && node->type==JSON_STRING); return node->value.string.length; } EXPORT void json_set_string(json_node* node,const char* str,size_t len) { assert(node!=NULL && (str!=NULL || len==0)); json_free(node); node->value.string.value = (char*)malloc(len+1); memcpy(node->value.string.value,str,len); node->value.string.value[len] = '\0'; node->value.string.length = len; node->type = JSON_STRING; } EXPORT size_t json_get_array_size(const json_node* node) { assert(node!=NULL && node->type==JSON_ARRAY); return node->value.array.size; } EXPORT json_node* json_get_array_element_by_index(const json_node* node,size_t index) { assert(node!=NULL && node->type==JSON_ARRAY); assert(index<node->value.array.size); return &node->value.array.element[index]; } EXPORT size_t json_get_object_size(const json_node* node) { assert(node!=NULL && node->type==JSON_OBJECT); return node->value.object.size; } EXPORT const char* json_get_object_key_by_index(const json_node* node,size_t index) { assert(node!=NULL && node->type==JSON_OBJECT); assert(index<node->value.object.size); return node->value.object.member[index].key; } EXPORT size_t json_get_object_key_len_by_index(const json_node* node,size_t index) { assert(node!=NULL && node->type==JSON_OBJECT); assert(index<node->value.object.size); return node->value.object.member[index].key_len; } EXPORT json_node* json_get_object_value_by_index(const json_node* node,size_t index) { assert(node!=NULL && node->type==JSON_OBJECT); assert(index<node->value.object.size); return &node->value.object.member[index].node; } EXPORT char* json_encode(const json_node* node,size_t* length) { json_context con; assert(node!=NULL); con.stack = (char*)malloc(con.size=JSON_ENCODE_INIT_SIZE); con.top = 0; json_encode_value(&con,node); if(length) { *length = con.top; } PUTC(&con,'\0'); return con.stack; } EXPORT int json_decode(json_node* node,const char* json_str) { return json_parse(node,json_str); } EXPORT const char* read_string_from_file(char* path) { assert(path!=NULL); FILE *fp; char *str; char txt[1000]; int filesize; if ((fp=fopen(path,"r"))==NULL) { printf("Open File:%s Error!!\n",path); return NULL; } fseek(fp,0,SEEK_END); filesize = ftell(fp); str=(char *)malloc(filesize); str[0]=0; rewind(fp); while((fgets(txt,1000,fp))!=NULL) { strcat(str,txt); } fclose(fp); return str; } EXPORT json_node read_json_from_file(char* path) { assert(path!=NULL); const char* str; str = read_string_from_file(path); json_node node; json_init(&node); if(str!=NULL) { json_decode(&node,str); }else{ node.type = JSON_NULL; } return node; } EXPORT const char* getString(const json_node* node,const char* key) { assert(node!=NULL); isGetErr = 0; if(strcmp(key,"")==0 && node->type==JSON_STRING) { return node->value.string.value; } const json_node* temp = node->getValue(node,key); if(temp->type != JSON_STRING) { isGetErr = JSON_GET_STRING_ERROR; return "{ERROR:This node does not contain a string!}"; } return temp->value.string.value; } EXPORT const double getNumber(const json_node* node,const char* key) { assert(node!=NULL); isGetErr = 0; if(strcmp(key,"")==0 && node->type==JSON_NUMBER) { return node->value.number; } const json_node* temp = node->getValue(node,key); if(temp->type != JSON_NUMBER) { isGetErr = JSON_GET_NUMBER_ERROR; return 0; } return temp->value.number; } EXPORT const int getBoolean(const json_node* node,const char* key) { assert(node!=NULL); isGetErr = 0; if(strcmp(key,"")==0 && (node->type==JSON_TRUE||node->type==JSON_FALSE)) { printf("aaa\n"); if(node->type==JSON_TRUE) { return 1; } if(node->type==JSON_FALSE) { return 0; } } const json_node* temp = node->getValue(node,key); if(temp->type!=JSON_FALSE || temp->type!=JSON_TRUE) { isGetErr = JSON_GET_BOOLEAN_ERROR; return false; } if(temp->type == JSON_TRUE) { return 1; } if(temp->type == JSON_FALSE) { return 0; } return -1; } EXPORT const char* getNull(const json_node* node,const char* key) { assert(node!=NULL); isGetErr = 0; if(strcmp(key,"")==0 && node->type==JSON_NULL) { return "null"; } const json_node* temp = node->getValue(node,key); if(temp->type != JSON_NULL) { isGetErr = JSON_GET_NULL_ERROR; return "{ERROR Type!}"; } return "null"; } EXPORT const json_node getObject(const json_node* node,const char* key) { assert(node!=NULL); isGetErr = 0; if(strcmp(key,"")==0 && node->type==JSON_OBJECT) { /* TODO */ } const json_node* temp = node->getValue(node,key); if(temp->type != JSON_OBJECT) { isGetErr = JSON_GET_OBJECT_ERROR; return *node; } return *temp; } EXPORT const json_node* getArray(const json_node* node,const char* key) { assert(node!=NULL); isGetErr = 0; if(strcmp(key,"")==0 && node->type==JSON_ARRAY) { /* TODO */ } const json_node* temp = node->getValue(node,key); if(temp->type != JSON_ARRAY) { isGetErr = JSON_GET_ARRAY_ERROR; return NULL; } return temp->value.array.element; }
TextZip/Dino-Game-Arduino-Edition
dino_FPS/sprite.c
<reponame>TextZip/Dino-Game-Arduino-Edition<gh_stars>0 #include <avr/pgmspace.h> const unsigned char body [] PROGMEM = { 0x00, 0x00, 0xff, 0xf0, 0x00, 0x03, 0xff, 0xf8, 0x00, 0x03, 0xff, 0xf8, 0x00, 0x03, 0xff, 0xf8, 0x00, 0x03, 0xff, 0xf8, 0x00, 0x03, 0xff, 0xf8, 0x00, 0x03, 0xff, 0xf8, 0x00, 0x03, 0xff, 0xf8, 0x00, 0x03, 0xfc, 0x00, 0x00, 0x03, 0xff, 0xc0, 0xc0, 0x07, 0xff, 0xc0, 0xc0, 0x07, 0xf8, 0x00, 0xc0, 0x1f, 0xf8, 0x00, 0xe0, 0xff, 0xff, 0x00, 0xe0, 0xff, 0xff, 0x00, 0xf9, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xf8, 0x00, 0xff, 0xff, 0xf8, 0x00, 0xff, 0xff, 0xf8, 0x00, 0x7f, 0xff, 0xe0, 0x00, 0x1f, 0xff, 0xe0, 0x00, 0x0f, 0xff, 0xc0, 0x00, 0x0f, 0xff, 0xc0, 0x00, 0x07, 0xff, 0x00, 0x00 // 0x00, 0x00, 0x03, 0xff, 0xfc, 0x00, 0x00, 0x03, 0xff, 0xfc, 0x00, 0x00, 0x0f, 0xff, 0xff, 0x00, // 0x00, 0x0f, 0xff, 0xff, 0x00, 0x00, 0x0f, 0xff, 0xff, 0x00, 0x00, 0x0f, 0xff, 0xff, 0x00, 0x00, // 0x0f, 0xff, 0xff, 0x00, 0x00, 0x0f, 0xff, 0xff, 0x00, 0x00, 0x0f, 0xff, 0xff, 0x00, 0x00, 0x0f, // 0xff, 0xff, 0x00, 0x00, 0x0f, 0xff, 0xff, 0x00, 0x00, 0x0f, 0xfc, 0x00, 0x00, 0x00, 0x0f, 0xfc, // 0x00, 0x00, 0x00, 0x0f, 0xff, 0xf0, 0x00, 0x00, 0x0f, 0xff, 0xf0, 0xc0, 0x00, 0x3f, 0xf0, 0x00, // 0xc0, 0x00, 0x3f, 0xf0, 0x00, 0xc0, 0x01, 0xff, 0xf0, 0x00, 0xc0, 0x01, 0xff, 0xf0, 0x00, 0xf0, // 0x0f, 0xff, 0xff, 0x00, 0xf0, 0x0f, 0xff, 0xff, 0x00, 0xfc, 0x3f, 0xff, 0xf3, 0x00, 0xfc, 0x3f, // 0xff, 0xf3, 0x00, 0xff, 0xff, 0xff, 0xf0, 0x00, 0xff, 0xff, 0xff, 0xf0, 0x00, 0xff, 0xff, 0xff, // 0xf0, 0x00, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x3f, 0xff, 0xff, 0xf0, 0x00, 0x3f, 0xff, 0xff, 0xc0, // 0x00, 0x0f, 0xff, 0xff, 0xc0, 0x00, 0x0f, 0xff, 0xff, 0xc0, 0x00, 0x03, 0xff, 0xff, 0x00, 0x00, // 0x03, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xfc, 0x00, 0x00, 0x00, 0xff, 0xfc, 0x00, 0x00 }; const unsigned char leg1 [] PROGMEM = { 0x01, 0xe7, 0x00, 0x00, 0x01, 0x87, 0x00, 0x00, 0x01, 0xe3, 0x00, 0x00, 0x01, 0xe3, 0x00, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x03, 0xc0, 0x00 // 0x00, 0x3c, 0x3c, 0x00, 0x00, 0x00, 0x30, 0x3c, 0x00, 0x00, 0x00, 0x30, 0x0c, 0x00, 0x00, 0x00, // 0x3c, 0x0c, 0x00, 0x00, 0x00, 0x3c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, // 0x0f, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00 }; const unsigned char leg2 [] PROGMEM = { 0x01, 0xf3, 0x00, 0x00, 0x01, 0xf3, 0x00, 0x00, 0x01, 0xe3, 0xc0, 0x00, 0x01, 0x83, 0xc0, 0x00, 0x01, 0xe0, 0x00, 0x00, 0x01, 0xe0, 0x00, 0x00 // 0x00, 0x3f, 0x0c, 0x00, 0x00, 0x00, 0x3f, 0x0c, 0x00, 0x00, 0x00, 0x3c, 0x0c, 0x00, 0x00, 0x00, // 0x3c, 0x0f, 0x00, 0x00, 0x00, 0x30, 0x0f, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x3c, // 0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00 }; const unsigned char cloud_small [] PROGMEM = { 0x1f, 0x00, 0x3f, 0x80, 0x7f, 0xe0, 0xff, 0xe0, 0xff, 0xe0, 0xff, 0xe0, 0xff, 0xe0, 0x7f, 0xe0 }; const unsigned char cloud_big [] PROGMEM = { 0x0f, 0x3c, 0x00, 0x1f, 0xfe, 0x00, 0x3f, 0xff, 0x80, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xc0, 0xff, 0xff, 0xc0, 0x7f, 0xff, 0xc0, 0x3f, 0xff, 0xc0 };
Kepler-Br/DukeNukem_map_converter
mapconverter.h
<filename>mapconverter.h #ifndef MAPCONVERTER_H #define MAPCONVERTER_H #include <string> #include <iostream> #include <fstream> #include <vector> #include <glm/glm.hpp> class MapConverter { struct sector { int16_t startWall; int16_t wallNum; int32_t ceilingHeight; int32_t floorHeigth; int16_t ceilingTextureIndex; int16_t floorTextureIndex; }; struct wall { int32_t x, y; int16_t point2; int16_t nextSector; int16_t textureIndex; uint8_t repeatX, repeatY; uint8_t panningX, panningY; }; struct player { int32_t posx, posy, posz; int16_t angle, startSector; }; int16_t readint8(std::fstream &file); int16_t readint16(std::fstream &file); int32_t readint32(std::fstream &file); uint8_t readuint8(std::fstream &file); uint16_t readuint16(std::fstream &file); uint32_t readuint32(std::fstream &file); void checkFileFlags(std::fstream &file); void readPlayerAttributes(std::fstream &file); void readSectors(std::fstream &file); void readWalls(std::fstream &file); void writeHeader(std::fstream &file, float coordinateDivider); void writeTexturePaths(std::fstream &file); void writeSectors(std::fstream &file, float coordinateDivider); void writeWalls(std::fstream &file, float coordinateDivider); player pl; std::vector<sector> sectors; std::vector<wall> walls; public: MapConverter() { } void read(const std::string &path); void convert(const std::string &path, const float coordinateDivider); }; #endif // MAPCONVERTER_H
t0mg/wordclock
software/wordclock/src/BrightnessController.h
<gh_stars>10-100 #pragma once #include <NeoPixelAnimator.h> #include <NeoPixelBus.h> #include "LDRReader.h" /* An 8-bit gamma-correction table from the Adafruit NeoPixel lib. Copy & paste this snippet into a Python REPL to regenerate: import math gamma=2.6 for x in range(256): print("{:3},".format(int(math.pow((x)/255.0,gamma)*255.0+0.5))), if x&15 == 15: print */ static const uint8_t PROGMEM gammaTable_[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 88, 89, 90, 92, 93, 94, 96, 97, 99,100,102,103,105,106,108,109,111,112,114,115,117,119,120, 122,124,125,127,129,130,132,134,136,137,139,141,143,145,146,148, 150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180, 182,184,186,188,191,193,195,197,199,202,204,206,209,211,213,215, 218,220,223,225,227,230,232,235,237,240,242,245,247,250,252,255}; // // Controls the brighness of a LED strip based on the light value of a // LDR Reader. // // Create this object and then call setup() to initialize it and then invoke // loop() as often as possible. // class BrightnessController { public: BrightnessController(); void setup(); void loop(); void setSensorSensitivity(int value) { lightSensor_.sensitivity = value; }; bool hasChanged() { bool res = changed_; changed_ = false; return res; }; void setOriginalColor(RgbColor color) { original_ = color; } RgbColor getCorrectedColor() { return corrected_; }; /*! @brief A gamma-correction function for RgbColor. Makes color transitions appear more perceptially correct. @param color RgbColor @return Gamma-adjusted RgbColor. */ static RgbColor gammaAdjust(RgbColor color) { return RgbColor(pgm_read_byte(&gammaTable_[color.R]), pgm_read_byte(&gammaTable_[color.G]), pgm_read_byte(&gammaTable_[color.B])); } private: // The target color at maximum brihtness. RgbColor original_ = RgbColor(255); // Original color dimmed according to the current sensor reading. RgbColor corrected_; // Dirty flag. bool changed_; // The light sensor. LDRReader lightSensor_; };
t0mg/wordclock
software/wordclock/src/Timer.h
<reponame>t0mg/wordclock #include <functional> #include <Arduino.h> /* * Basic ESP32 interrupt timer helper. */ class Timer { public: Timer(); // Must be called from the ino setup and loop. void setup(std::function<void()> callback, uint32_t delay_seconds); void loop(); void start(); void stop(); private: std::function<void()> callback_ = NULL; uint32_t delay_seconds_ = 1; hw_timer_t *timer_ = NULL; };
t0mg/wordclock
software/wordclock/src/LDRReader.h
<reponame>t0mg/wordclock #pragma once /* * Light sensor. Reads the ambient light and build a representative value * between 0.0 and 1.0. Smooth the reading by doing a moving average. */ class LDRReader { public: // Reaction speed must be greater than 0 and at most 1.0. This controls the // input smoothing, the higher the number the less smooth the data will be. // The pin number points to the pin the data line is soldered on. LDRReader(int pinNumber = 33, float reactionSpeed = .1, int sensitivity = 1); // Must be called from the ino setup and loop. void setup(); void loop(); // Returns a value between 0. (no light) and 1. (much lights) float reading(); int sensitivity; private: float _currentLDR; float _reactionSpeed; int _pin; };
t0mg/wordclock
software/wordclock/src/Display.h
#pragma once #include <NeoPixelAnimator.h> #include <NeoPixelBrightnessBus.h> #include "BrightnessController.h" #include "ClockFace.h" // The pin to control the matrix #define NEOPIXEL_PIN 32 // #define TIME_CHANGE_ANIMATION_SPEED 400 class Display { public: Display(ClockFace &clockFace, uint8_t pin = NEOPIXEL_PIN); void setup(); void loop(); void setColor(const RgbColor &color); // Sets the sensor sentivity of the brightness controller. int setSensorSentivity(int value) { _brightnessController.setSensorSensitivity(value); } // Sets whether to show AM/PM information on the display. void setShowAmPm(bool show_ampm) { _show_ampm = show_ampm; } // Starts an animation to update the clock to a new time if necessary. void updateForTime(int hour, int minute, int second, int animationSpeed = TIME_CHANGE_ANIMATION_SPEED); private: // Updates pixel color on the display. void _update(int animationSpeed = TIME_CHANGE_ANIMATION_SPEED); // To know which pixels to turn on and off, one needs to know which letter // matches which LED, and the orientation of the display. This is the job // of the clockFace. ClockFace &_clockFace; // Whether the display should show AM/PM information. bool _show_ampm = 0; // Color of the LEDs. Can be manipulated via Web configuration interface. RgbColor _color; // Addressable bus to control the LEDs. NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> _pixels; // Reacts to change in ambient light to adapt the power of the LEDs BrightnessController _brightnessController; // // Animation time management object. // Uses centiseconds as precision, so an animation can range from 1/100 of a // second to a little bit more than 10 minutes. // NeoPixelAnimator _animations; };
t0mg/wordclock
software/wordclock/src/logging.h
#pragma once // Define debug to turn on debug logging. // #define DEBUG 1 // DLOG and DLOGLN are equivalent of Serial.print and println, but turned off by // the DEBUG macro absence. // DCHECK only log if the first parameter is false. // setupLogin() must be called from setup() for everything to work. #if defined(DEBUG) #include <HardwareSerial.h> #define DLOG(...) Serial.print(__VA_ARGS__) #define DLOGLN(...) Serial.println(__VA_ARGS__) #define DCHECK(condition, ...) \ if (!(condition)) \ { \ DLOG("DCHECK Line "); \ DLOG(__LINE__); \ DLOG(": ("); \ DLOG(#condition); \ DLOG(") "); \ DLOGLN(__VA_ARGS__); \ } #define setupLogging() \ { \ Serial.begin(115200); \ delay(2000); \ DLOGLN("Logging started."); \ } #else #define DLOG(...) #define DLOGLN(...) #define DCHECK(condition, ...) #define setupLogging() #endif // defined(DEBUG)
t0mg/wordclock
software/wordclock/src/Iot.h
#ifndef _IOT_H_ #define _IOT_H_ #include "Display.h" #include "Timer.h" #include <IotWebConf.h> #include <RTClib.h> // Maximum length of a single IoT configuration value. #define IOT_CONFIG_VALUE_LENGTH 16 class Iot { public: Iot(Display *display, RTC_DS3231 *rtc); ~Iot(); Iot(const Iot &) = delete; Iot &operator=(const Iot &) = delete; Iot(Iot &&) = delete; Iot &operator=(Iot &&) = delete; void setup(); void loop(); private: // Clears the values of transient parameters. void clearTransientParams_(); // Updates word clock's state to match the current configuration values. void updateClockFromParams_(); // Checks for NTP setting and if enabled, attempts to update the RTC. void maybeSetRTCfromNTP_(); // Sets the RTC from manual input void setRTCfromConfig_(); // Handles HTTP requests to web server's "/" path. void handleHttpToRoot_(); // Handles configuration changes. void handleConfigSaved_(); // Handles wifi connexion success. void handleWifiConnection_(); // Whether IoT configuration was initialized. bool initialized_ = false; // Configuration portal's DNS server. DNSServer dns_server_; // Configuration portal's web server. WebServer web_server_; // Server for OTA firmware update. HTTPUpdateServer http_updater_; // Word clock display. Display *display_ = nullptr; // RTC. RTC_DS3231 *rtc_ = nullptr; // NTP poll timer; Timer ntp_poll_timer_; // Enables NTP time setting. IotWebConfParameter ntp_enabled_param_; // Value of the NTP setting option. char ntp_enabled_value_[IOT_CONFIG_VALUE_LENGTH]; // The timezone index from available options. IotWebConfParameter timezone_param_; // Index of the selected timezone. char timezone_value_[IOT_CONFIG_VALUE_LENGTH]; // Manual date setting. Transient. IotWebConfParameter manual_date_param_; // Date parameter value. char manual_date_value_[IOT_CONFIG_VALUE_LENGTH]; // Manual time setting. Transient. IotWebConfParameter manual_time_param_; // Time parameter value. char manual_time_value_[IOT_CONFIG_VALUE_LENGTH]; // Enable AM/PM display. IotWebConfParameter show_ampm_param_; // Value of the LDR sensitivity parameter. char show_ampm_value_[IOT_CONFIG_VALUE_LENGTH]; // Sensitivity parameter for the LDR. IotWebConfParameter ldr_sensitivity_param_; // Value of the LDR sensitivity parameter. char ldr_sensitivity_value_[IOT_CONFIG_VALUE_LENGTH]; // Text color parameter. IotWebConfParameter color_param_; // Value of the color parameter. char color_value_[IOT_CONFIG_VALUE_LENGTH]; // Config form separators. IotWebConfSeparator time_separator_; IotWebConfSeparator display_separator_; // IotWebConf interface handle. IotWebConf iot_web_conf_; }; #endif // _IOT_H_
donnywdavis/NOC-List
NOC List/MasterViewController.h
// // MasterViewController.h // NOC List // // Created by <NAME> on 1/28/15. // Copyright (c) 2015 The Iron Yard. All rights reserved. // #import <UIKit/UIKit.h> @interface MasterViewController : UITableViewController - (void)loadNocList; @end
CrushedPixel/Polyline2DPathRenderer
Source/MainComponent.h
#pragma once #include <JuceHeader.h> #include <Polyline2D/Polyline2D.h> class MainComponent : public OpenGLAppComponent { public: MainComponent(); ~MainComponent(); void initialise() override; void shutdown() override; void render() override; void paint(Graphics &g) override; void resized() override; private: GLuint vaoHandle, vboHandle, programHandle; GLuint posInAttribLocation; GLuint colorUniformLocation; /** * The current size of the VBO. */ GLsizei vboSize; /** * The path to render using OpenGL. */ juce::Path path; /** * Random instance with fixed seed, * used to consistently generate subpath colors. */ juce::Random random; juce::int64 randomSeed; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainComponent) };
ibelem/wasm
code/fibonacci2/fib2.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #if defined(WIN32) # define TIMEB _timeb # define ftime _ftime typedef __int64 TIME_T; #else #define TIMEB timeb typedef long long TIME_T; #endif double fibonacci(int n) { double a = 0; double b = 1; while (n > 1) { double t = b; b = a + b; a = t; n--; } return b; } int time_interval(int num) { struct TIMEB ts1,ts2; TIME_T t1,t2; int ti; printf("fibonacci(%d)\n", num); ftime(&ts1);//开始计时 printf("%f\n", fibonacci(num)); ftime(&ts2);//停止计时 t1=(TIME_T)ts1.time*1000+ts1.millitm; //printf("t1=%lld\n",t1); t2=(TIME_T)ts2.time*1000+ts2.millitm; //printf("t2=%lld\n",t2); ti=t2-t1;//获取时间间隔,ms为单位的 return ti; } void run(int num) { int ti=time_interval(num); printf("Elapsed time: %dms\n", ti); } int main() { run(1); run(2); run(3); run(10); run(20); run(40); run(60); run(80); run(100); run(200); run(400); run(800); run(1000); return 0; }
ibelem/wasm
code/add/add.c
<reponame>ibelem/wasm #include<stdio.h> int add(int a, int b){ return a + b; } int main() { printf("%d",add(1, 2)); }
ibelem/wasm
code/fibonacci1/fib1.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #if defined(WIN32) #define TIMEB _timeb #define ftime _ftime typedef __int64 TIME_T; #else #define TIMEB timeb typedef long long TIME_T; #endif double fibonacci(int n) { if (n <= 2) { return 1; } else return fibonacci(n - 1) + fibonacci(n - 2); } int time_interval(int num) { struct TIMEB ts1, ts2; TIME_T t1, t2; int ti; printf(".wasm fibonacci(%d):\n", num); ftime(&ts1); //开始计时 printf("%lf\n", fibonacci(num)); ftime(&ts2); //停止计时 t1 = (TIME_T)ts1.time * 1000 + ts1.millitm; //printf("t1=%lld\n",t1); t2 = (TIME_T)ts2.time * 1000 + ts2.millitm; //printf("t2=%lld\n",t2); ti = t2 - t1; //获取时间间隔,ms为单位的 return ti; } void run(int num) { int ti = time_interval(num); printf(">: %dms\n", ti); } int main() { run(31); return 0; }
oahul14/SPH-Simulations
includes/SPH_2D.h
<filename>includes/SPH_2D.h #pragma once #include <vector> #include <utility> #include <iterator> #include <cmath> #include <iostream> #include <string> #include <list> using namespace std; class SPH_main; struct pre_calc_values { double dist, dWdr, e_ij_1, e_ij_2, v_ij_1, v_ij_2; }; struct offset { double dx0 = 0; double dx1 = 0; double dv0 = 0; double dv1 = 0; double drho = 0; const offset operator+(const offset& other) const; const offset operator+(const offset&& other) const; const offset operator*(const double dt) const; void operator+=(const offset& other); }; class SPH_particle { public: SPH_particle(); SPH_particle(double rho, bool bound); /** * @brief velocity and position stored in two directions */ double x[2], v[2]; /** * @brief density rho and pressure p */ double rho, P; /** * @brief boolean to indicate boundary particle or not */ bool boundary_particle; /** * @brief link to SPH_main class so that it can be used in calc_index */ static SPH_main *main_data; static double B; /** * @brief index in neighbour finding array * */ int list_num[2]; /** * @brief mass for particle */ double m; /** * @brief Set the m object */ void set_m(); /** * @brief calculate the index for grids into list_num */ void calc_index(); /** * @brief update pressure using rho: tait equation */ void redef_P(); //function to update the Pressure /** * @brief operator overload for struct offset to update current stage * * @param delta offset variable storing dxdt, dvdt and drhodt */ void operator+=(const offset& delta); }; class SPH_main { public: enum timesteppers { forward_euler, improved_euler, AB2 }; /** * @brief create shapes enum for placing points: rectangle and shoaling */ enum shapes { rectangle, shoaling }; SPH_main(); /**s * @brief initialising min_x and max_x and max number of boxes of 2h */ void initialise_grid(); /** * @brief placing water cells within inner domain; placing boundary cells for outer domain * * @param min domain's minimum x and y coordinates for the entire domain (including boundary) * @param max domain's maximum x and y coordinates for the entire domain (including boundary) * @param shape boundary shape: including normal rectangle and shoaling */ void place_points(double *min, double *max, const shapes& shape = rectangle); //allocates all the points to the search grid (assumes that index has been appropriately updated) vector<vector<list<pair<SPH_particle*, list<SPH_particle*>::size_type>>>> search_grid(list<SPH_particle>& particle_list); vector<offset> calculate_offsets(list<SPH_particle>& particles); pair<offset, offset> calc_offset(const SPH_particle& p_i, const SPH_particle& p_j, const pre_calc_values& vals); list<offset> offsets(list<SPH_particle>& particle_list); void timestep(const timesteppers& ts = forward_euler); pair<double, double> dvdt(const SPH_particle& p_i, const SPH_particle& p_j, const pre_calc_values& vals); double drhodt(const SPH_particle& p_i, const SPH_particle& p_j, const pre_calc_values& vals); double W(const double r); double dW(const double r); void smooth(list<SPH_particle>& particles); void drag_back(SPH_particle& part); /** * @brief characteristic smoothing length */ double h; /** * @brief the factor to determine h: set to 1.3 */ double h_fac = 1.3; /** * @brief mesh resolution */ double dx = 0.1; /** * @brief initial density for both water and boundary cells, in kg/m3 */ double rho0 = 1000; /** * @brief viscosity constant in navier stokes equation */ double mu = 0.001; /** * @brief gravitational acceleration constant */ double g = 9.81; /** * @brief exponential for the ratio of current rho and initial rho * to provide stiff enough (slightly compressible) state */ int gamma = 7; /** * @brief artificial velocity of sound * selected to be larger than the speed sustained in the system */ double c0 = 20; /** * @brief Courant–Friedrichs–Lewy condition: should be in range [0.1, 0.3], set as 0.2 */ double Ccfl = 0.2; /** * @brief minimum x and y coordinates: initialised as the size of the inner domain */ double min_x[2] {0, 0}; /** * @brief maximum x and y coordinates: initialised as the size of the inner domain * */ double max_x[2] {20, 10}; double max_vij2, max_ai2, max_rho; /** * @brief current time state for the domain */ double t = 0; /** * @brief dynamic time step * */ double dt; /** * @brief get track of dt at previous stage */ double prev_dt = 0; int count = 0; /** * @brief set the smoothing intervel in fix number */ int smoothing_interval = 10; /** * @brief set the ouput intervel */ int output_intervval = 10; int max_list[2]; /** * @brief list to store all particles */ list<SPH_particle> particle_list; /** * @brief vector to keep track of the previous stage offsets */ vector<offset> previous_offsets; };
oahul14/SPH-Simulations
includes/file_writer.h
#pragma once #include <list> #include <string> #include "SPH_2D.h" int write_file(const string filename, const std::list<SPH_particle>& particle_list);
Ritchielambda/ECS
kylanliecs.h
<gh_stars>1-10 #pragma once #pragma once #include<unordered_map> #include <functional> #include<vector> #include<algorithm> #include<stdint.h> #include<type_traits> ///////////////////////////////////////////////// //masco about tick type #ifndef ECS_TICK_TYPE #define ECS_TICK_TYPE ECS::DefaultTickData #endif #ifndef ECS_ALLOCATOR_TYPE #define ECS_ALLOCATOR_TYPE std::allocator<ECS::Entity> #endif #ifndef ECS_NO_RTTI #include<typeindex> #include<typeinfo> #define ECS_TYPE_IMPLEMENTATION #else #define ECS_TYPE_IMPLEMENTATION\ ECS::TypeIndex ECS::Internal::TypeRegistry::nextIndex = 1;\ \ ECS_DEFINE_TYPE(ECS::Events::OnEntityCreated);\ ECS_DEFINE_TYPE(ECS::Events::OnEntityDestroyed);\ ////////////////////////////////////////////////////////////////////////// // CODE // ////////////////////////////////////////////////////////////////////////// #endif // !ECS_NO_RTTI namespace ECS { #ifndef ECS_NO_RTTI typedef std::type_index TypeIndex; #define ECS_DECLARE_TYPE #define ECS_DEFINE_TYPE(name) template<typename T> TypeIndex getTypeIndex() { return std::type_index(typeid(T)); } #else typedef uint32_t TypeIndex; namespace Internal { class TypeRegistry { public: TypeRegistry() { index = nextIndex; ++nextIndex; } TypeIndex getIndex() const { return index; } private: static TypeIndex nextIndex; TypeIndex index; }; } #define ECS_DECLATE_TYPE public: static ECS::Internal::TypeRegistry __ecs_type_reg #define ECS_DEFINE_TYPE(name) ECS::Internal::TypeRegistry name::__ecs__type_reg #endif class World; class Entity; typedef float DefaultTickData; typedef ECS_ALLOCATOR_TYPE Allocator; namespace Internal { template<typename... Types> class EntityComponentView; class EntityView; struct BaseComponentContainer { public: virtual ~BaseComponentContainer() {} virtual void destroy(World * world) = 0; virtual void removed(Entity* ent) = 0; }; class BaseEventSubscriber { public: virtual ~BaseEventSubscriber() {}; }; template<typename... Types> class EntityComponentIterator { public: EntityComponentIterator(World * world, size_t index, bool bIsEnd, bool bIncludePendingDestroy); size_t getIndex() const { return index; } bool isEnd() const; bool includePendingDestroy() const { return bIncludePendingDestroy; } World* getWorld() const { return world; } Entity* get() const; Entity* operator*() const { return get(); } bool operator==(const EntityComponentIterator<Types...>& other) const { if (world != other.world) return false; if (isEnd()) return other.isEnd(); return index == other.index; } bool operator!=(const EntityComponentIterator<Types...>& other) const { if (world != other.world) return true; if (isEnd()) return !other.isEnd(); return index != other.index; } EntityComponentIterator<Type...>& operator ++(); private: bool bIsEnd = false; size_t index; class ECS::World* world; bool bIncludePendingDestroy; }; template<typename...Types> class EntityComponentView { public: EntityComponentView(const EntityComponentIterator<Types...>& first, const EntityComponentIterator<Types...>& last); const EntityComponentIterator(Types...) & begin() const { return firstItr; } const EntityComponentIterator(Types...) & end() const { return lastItr; } private: EntityComponentIterator<Types...> firstItr; EntityComponentIterator<Types...> lastItr; }; } template<typename T> class ComponentHandle { public: ComponentHandle() :component(nullptr) { } T* operator->() const { return component; } operator bool() const { return isValid(); } T& get() { return component != nullptr; } private: T* component; }; class EntitySystem { public: virtual ~EntitySystem() {} virtual void configure(World * world) { } virtual void unconfigure(World* world) { } #ifdef ECS_TICK_TYPE_VOID virtual void tick(World * world) #else virtual void tick(World *world, ECS_TICK_TYPE data) #endif { } }; template<typename T> class EventSubscriber :public Internal::BaseEventSubscriber { public: virtual ~EventSubscriber() {} virtual void receive(World* world, const T& event) = 0; }; namespace Events { struct OnEntityCreated { ECS_DECLARE_TYPE; Entity* entity; }; struct OnEntityDestroyed { ECS_DECLARE_TYPE; Entity *entity; }; template<typename T> struct OnComponentAssigned { ECS_DECLARE_TYPE; Entity* entity; ComponentHandle<T> component; }; template<typename T> struct OnComponentRemoved { ECS_DECLARE_TYPE; Entity* entity; ComponentHandle<T> component; }; #ifdef ECS_NO_RTTI template<typename T> ECS_DEFINE_TYPE(ECS::Events::OnComponentAssigned<T>); template<typename T> ECS_DEFINE_TYPE(ECS::Events::OnComponentRemoved<T>); #endif } class Entity { public: friend class World; const static size_t InvalidEntityId = 0; Entity(World* world, size_t id) :world(world), id(id) { } ~Entity() { removeAll(); } World* getWorld() const { return world; } template<typename T> bool has() const { auto index = getTypeIndex<T>(); return components.find(index) != components.end(); } template<typename T, typename V, typename...Types> bool has() const { return has<T>() && has<V, Types..>(); } template<typename T, typename...Args> ComponentHandle<T> assign(Args&&... args); template<typename T> bool remove() { auto found = components.find(getTypeIndex<T>()); if (found != components.end()) { // to check found->second->removed(this); found->second->bPendigDestroy(world); components.erase(found); return true; } return false; } void removeAll() { for (auto pair : components) { pair.second->removed(this); pair.second->destroy(world); } components.clear(); } template<typename T> ComponentHandle<T> get(); template<typename...Types> bool with(typename std::common_type<std::function<void(ComponentHandle<Types>...)>>::type view) { if (!has<Types...>()) return false; view(get<Types>...)// to check return true; } size_t getEntityId()const { return id; } bool isPendingDestroy() const { return bPendingDestroy; } private: std::unordered_map<TypeIndex, Internal::BaseComponentContainer*> components; World* world; size_t id; bool bPendingDestroy = false; }; class World { }; }
yiwangxin/react-native-ywx-sign
ios/BjcaRNTools.h
<reponame>yiwangxin/react-native-ywx-sign // // BjcaTools.h // RNReactNativeYwxSign // // Created by 吴兴 on 2018/12/21. // Copyright © 2018 Facebook. All rights reserved. // 工具类 #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface BjcaRNTools : NSObject /** 获取顶层ctrl @return */ + (UIViewController *)getCurrentVC; @end NS_ASSUME_NONNULL_END
MasterZean/z2c-compiler-cpp
zide/zide.h
<filename>zide/zide.h #ifndef _zide_zide_h #define _zide_zide_h #include <CtrlLib/CtrlLib.h> #include <CodeEditorFork/CodeEditor.h> #include <TabBar/TabBar.h> using namespace Upp; #include "ItemDisplay.hpp" #include "AssemblyBrowser.hpp" #include "EditorManager.hpp" #define LAYOUTFILE <zide/zide.lay> #include <CtrlCore/lay.h> #include <z2clib/BuildMethod.h> #include <z2clib/StopWatch.h> class Console: public LineEdit { public: bool verbosebuild = false; Console() { SetReadOnly(); } Callback WhenLeft; virtual void LeftUp(Point p, dword flags) { LineEdit::LeftUp(p, flags); WhenLeft(); } void ScrollLineUp() { sb.LineUp(); } Console& operator<<(const String& s) { Append(s); return *this; } void Append(const String& s) { Insert(total, s); } }; class BuildMethodsWindow: public WithBuildMethodsLayout<TopWindow> { public: typedef BuildMethodsWindow CLASSNAME; BuildMethodsWindow(Vector<BuildMethod>& meth): methods(meth) { CtrlLayout(*this, "Build methods"); Sizeable(); lstMethods.NoRoundSize(); lstMethods.WhenAction = THISBACK(OnBuildMethodSelect); for (int i = 0; i < methods.GetCount(); i++) { BuildMethod& bm = methods[i]; lstMethods.Add(bm.Name + " " + bm.Arch); } lstLib.SetReadOnly(); btnOk.Ok(); Acceptor(btnOk, IDOK); } void OnBuildMethodSelect() { int index = lstMethods.GetCursor(); if (index == -1) return; BuildMethod& bm = methods[index]; edtName.SetText(bm.Name); if (bm.Type == BuildMethod::btGCC) { optGCC.Set(1); optMSC.Set(0); } else if (bm.Type == BuildMethod::btMSC) { optGCC.Set(0); optMSC.Set(1); } else { optGCC.Set(0); optMSC.Set(0); } edtCompiler.SetText(bm.Compiler); edtSdk.SetText(bm.Sdk); lstLib.Clear(); for (int i = 0; i < bm.Lib.GetCount(); i++) lstLib.Add(bm.Lib[i]); } private: Vector<BuildMethod>& methods; }; class Zide: public WithZideLayout<TopWindow> { public: typedef Zide CLASSNAME; MenuBar mnuMain; ToolBar tlbMain; Splitter splMain; SplitterFrame splBottom; SplitterFrame splExplore; SplitterFrame splOutput; WithExploreLayout<ParentCtrl> explore; ParentCtrl canvas; EditorManager tabs2; AssemblyBrowser asbAss; EditorManager tabs; Label lblLine; FrameTop<StaticBarArea> bararea; FrameBottom<Console> console; String lastPackage; String openDialogPreselect; Vector<String> openNodes; Index<String> recent; String openFile; SmartEditor edtDummy; bool running; int optimize; bool libMode; bool mirrorMode = false; bool toolbar_in_row; DropList lstBldConf; MultiButton mbtEntryPoint; MultiButton mbtBldMode; PopUpTable popMethodList; PopUpTable popTypeList; PopUpTable popArchList; StopWatch sw; Vector<String> packages; Settings settings; bool oShowPakPaths = true; String zcPath; RichTextCtrl annotation_popup; Zide(); void DoMainMenu(Bar& bar); void DoMenuFile(Bar& bar); void DoMenuEdit(Bar& bar); void DoMenuFormat(Bar& bar); void DoMenuBuild(Bar& bar); void HelpMenu(Bar& bar); void DoMenuRecent(Bar& bar); void MainToolbar(Bar& bar); void DoMenuOptimize(Bar& bar); void OnMenuFormatShowSettings(); void OnSelectSource(); void OnMenuFileLoadPackage(); void OnMenuFileLoadFile(); void OnMenuFileSaveFile(); void OnMenuFileSaveAll(); void OnMenuShowPackagePaths(); void OnMenuEditFind(); void OnMenuEditReplace(); void OnMenuEditFindNext(); void OnMenuEditFindPrevious(); void OnMenuBuildShowLog(); void OnMenuBuildKill(); void OnMenuBuildLibMode(); void OnMenuBuildMethods(); void OnMenuHelpAbout(); void OnMenuHelpRebuildDocs(); void OnFileRemoved(const String& file); void OnFileSaved(const String& file); bool OnRenameFiles(const Vector<String>& files, const String& oldPath, const String& newPath); void OoMenuRecent(const String& path); void OnToolO0(); void OnToolO1(); void OnToolO2(); void OnSelectMethod(); void OnAnnotation(); void OnAcDot(); void Serialize(Stream& s); void LoadModule(const String& mod, int color); void Load(Vector<String>& list, int id); void OnClose(); void SetupLast(); void OnMenuFormatMakeTabs(); void OnMenuFormatMakeSpaces(); void OnMenuFormatMakeLineEnds(); void OnMenuFormatDuplicateLine(); void OnEditChange(); void OnEditCursor(); void OnGoTo(); void OnMenuBuildBuild(); void OnMenuBuildFrontend(); void OnMenuBuildRun(bool newConsole); void OnMenuBuildMirror(); void OnOutputSel(); void OnExplorerClick(); void OnExplorerMenu(Bar& bar); void OnGenerateDocTemp(); void OnGenerateIndividualDoc(ZClass& cls, FileOut& f, FileOut& f2); void WriteDocEntry(FileOut& file, FileOut& f2, DocEntry& doc, Index<String>& links); void AddOutputLine(const String& str); void OutPutEnd(); SmartEditor& GetEditor(); OpenFileInfo* GetInfo(); void LoadNavigation(); void LoadNavigation(ZSource& source); void NavigationDone(ZSource* source, uint64 hash); String Build(const String& file, bool scu, bool& res, Point p = Point(-1, -1)); void ReadHlStyles(ArrayCtrl& hlstyle); void DropMethodList(); void DropTypeList(); void DropArchList(); void LoadPackage(const String& pak); bool IsVerbose() const; void PutConsole(const char *s); void PutVerbose(const char *s); private: bool editThread; bool pauseExplorer; void OnTabChange(); Vector<BuildMethod> methods; String method; String arch; bool canBuild = true; String rundir; String target; String runarg; String header; String footer; String docPath; Vector<int> colors; bool GetLineOfError(int ln); }; #endif
MasterZean/z2c-compiler-cpp
z2clib/Node.h
<reponame>MasterZean/z2c-compiler-cpp #ifndef _z2clib_Node_h_ #define _z2clib_Node_h_ #include "entities.h" class NodeType { public: enum Type { Invalid, Const, BinaryOp, UnaryOp, Memory, Cast, Temporary, Def, List, Construct, Ptr, Index, SizeOf, Destruct, Property, Deref, Intrinsic, Return, Var, Alloc, Array, Using, }; }; class MemNode; class Node: public ObjectInfo { public: Node* Next = nullptr; Node* Prev = nullptr; Node* First = nullptr; Node* Last = nullptr; NodeType::Type NT = NodeType::Invalid; bool IsCT = false; bool IsLiteral = false; bool IsSymbolic = false; bool HasSe = false; bool LValue = false; double DblVal = 0; int64 IntVal = 0; // TODO: fix int reg; void SetType(ObjectType* type, ZClass* efType, ZClass* sType) { Tt = *type; C1 = efType; C2 = sType; } void SetType(ObjectType* type) { Tt = *type; C1 = type->Class; C2 = nullptr; } void SetType(ObjectType type) { Tt = type; C1 = type.Class; C2 = nullptr; } void SetValue(int i, double d) { IntVal = i; DblVal = d; } void Add(Node* node) { if (First == NULL) { First = node; Last = node; } else { node->Prev = Last; Last->Next = node; Last = node; } } bool IsZero(Assembly& ass); void PromoteToFloatValue(Assembly& ass); MemNode* GetParam() const; bool IsLValue() const { return IsAddressable && IsConst == false; } }; class ConstNode: public Node { public: Constant* Const = nullptr; int Base = 10; ConstNode() { NT = NodeType::Const; } }; class ObjectNode: public Node { public: Node* Object = nullptr; Node* Parent = nullptr; }; class MemNode: public ObjectNode { public: String Mem; Variable* Var = nullptr; bool IsThis = false; bool IsThisNop = false; bool IsParam = false; bool IsLocal = false; bool IsClass = false; MemNode() { NT = NodeType::Memory; } Variable* GetFullMemberAssignment() { if (Object != nullptr) { if (Object->NT == NodeType::Memory && ((MemNode*)Object)->IsThis) { } else return nullptr; } if (Var && IsClass) return Var; if (Object == nullptr) return nullptr; if (Object->NT != NodeType::Memory) return nullptr; MemNode& mem = *(MemNode*)(Object); if (mem.IsThis == false) return nullptr; if (Var == nullptr) return nullptr; return Var; } }; class ReturnNode: public Node { public: Node* Object = nullptr; ReturnNode() { NT = NodeType::Return; } }; // abstract class ParamsNode: public Node { public: Vector<Node*> Params; }; class TempNode: public ParamsNode { public: ::Overload *Overload = nullptr; TempNode() { NT = NodeType::Temporary; } }; class RawArrayNode: public Node { public: Vector<Node*> Array; int Ellipsis = -1; RawArrayNode() { NT = NodeType::Array; } }; class VarNode: public Node { public: Variable* Var = nullptr; VarNode() { NT = NodeType::Var; } }; class CastNode: public Node { public: Node* Object = nullptr; bool Ptr = false; CastNode() { NT = NodeType::Cast; } }; class ListNode: public ParamsNode { public: ListNode() { NT = NodeType::List; } }; class SizeOfNode: public Node { public: SizeOfNode() { NT = NodeType::SizeOf; } }; class IndexNode: public Node { public: IndexNode() { NT = NodeType::Index; } }; class OpNode: public Node { public: enum Type { opNotSet = -1, opAdd = 0, opSub = 1, opMul = 2, opDiv = 3, opMod = 4, opShl = 5, opShr = 6, opLess = 7, opLessEq = 8, opMore = 9, opMoreEq = 10, opEq = 11, opNeq = 12, opBitAnd = 13, opBitXor = 14, opBitOr = 15, opLogAnd = 16, opLogOr = 17, opAssign = 18, opPlus = 19, opMinus = 20, opNot = 21, opComp = 22, opInc = 23, opDec = 24, opTernary = 25, }; Type Op = opNotSet; bool Construct = false; int Move = 0; bool Assign = false; Node* OpA = nullptr; Node* OpB = nullptr; Node* OpC = nullptr; OpNode() { NT = NodeType::BinaryOp; } }; class UnaryOpNode: public OpNode { public: bool Prefix = false; UnaryOpNode() { NT = NodeType::UnaryOp; } }; class DerefNode: public Node { public: Node* Object = nullptr; DerefNode() { NT = NodeType::Deref; } }; class IntNode: public ParamsNode { public: enum Type { itPtrFree, itPtrClone, itPtrCloneLim, itPtrRealloc, itDebugAssert, itTraceAssert, itPtrAllocVoid, itTraceError, itDebugError, itCArrayCopy, itDefaultCons, itDefaultCopyCons, itDefaultCopy, itDefaultMoveCons, itDefaultMove, itForIndex, itForCount, }; Type I; bool NOP = false; IntNode() { NT = NodeType::Intrinsic; } }; class UsingNode: public Node { public: Vector<Node*> List; Vector<String> Name; Node* Using = nullptr; UsingNode() { NT = NodeType::Using; } }; class ConstructNode: public ParamsNode { public: ::Overload *Overload = nullptr; Node* Object = nullptr; ConstructNode() { NT = NodeType::Construct; } }; class DestructNode: public ConstructNode { public: DestructNode() { NT = NodeType::Destruct; } }; class AllocNode: public Node { public: ZClass* Class = nullptr; Node* Count = nullptr; AllocNode() { NT = NodeType::Alloc; } }; class DefNode: public ParamsNode { public: ::Overload* Overload = nullptr; Node* Object = nullptr; bool Property = false; bool IsDestructor = false; DefNode() { NT = NodeType::Def; } }; class PtrNode: public Node { public: bool Ref = false; bool Move = false; bool Nop = false; PtrNode() { NT = NodeType::Ptr; } }; class PropertyNode: public ObjectNode { public: ::Def* Def = nullptr; int Qualified = 0; ObjectType* FType = nullptr; ::Overload* Overload = nullptr; bool UseAsGet = false; PropertyNode() { NT = NodeType::Property; } }; #endif
MasterZean/z2c-compiler-cpp
z2clib/BaseCompiler.h
<filename>z2clib/BaseCompiler.h #ifndef _z2clib_BaseCompiler_h_ #define _z2clib_BaseCompiler_h_ #include "Assembly.h" #include "Source.h" class BaseCompiler { public: enum PlatformType { WINDOWS32, POSIX, }; BaseCompiler(Assembly& aAss): ass(aAss) { #ifdef PLATFORM_WIN32 Platform = WINDOWS32; #endif #ifdef PLATFORM_POSIX Platform = POSIX; #endif } VectorMap<String, String> LookUp; PlatformType Platform; int LookUpClass(ZSource& source, const String& className); int LookUpClassInReferences(ZSource& source, const String& className); int LookUpQualifiedClass(const String& className); ZSource& LoadSource(ZSource& source); ZSource* FindSource(const String& aSourcePath); Assembly& GetAssembly() { return ass; } protected: Assembly& ass; ArrayMap<String, ZPackage> packages; int filesOpened = 0; }; #endif
MasterZean/z2c-compiler-cpp
z2clib/objecttype.h
<reponame>MasterZean/z2c-compiler-cpp<filename>z2clib/objecttype.h #ifndef _z2clib_ObjectType_h_ #define _z2clib_ObjectType_h_ #include <Core/Core.h> using namespace Upp; class ZClass; class Assembly; class Node; class ObjectType { public: ZClass* Class = nullptr; ObjectType* Next = nullptr; int Param = 0; ObjectType() { } ObjectType(ZClass& cls): Class(&cls) { } }; class ObjectInfo: Moveable<ObjectInfo> { public: ObjectType Tt; ZClass* C1 = nullptr; ZClass* C2 = nullptr; bool IsRef = false; bool IsAddressable = false; //bool IsIndirect = false; bool IsMove = false; bool IsConst = false; bool IsEfRef = false; bool IsEfRefHa = false; bool CanAssign(Assembly& ass, ObjectInfo& sec, bool isCt); bool CanAssign(Assembly& ass, Node* node); ObjectInfo() = default; ObjectInfo(ZClass* cls) { Tt.Class = cls; } ObjectInfo(ZClass* cls, bool ref) { Tt.Class = cls; IsRef = ref; } ObjectInfo(ObjectType* tt) { Tt = *tt; } }; inline bool operator==(const ObjectType& Tt, ObjectType* tt) { return Tt.Class == tt->Class; } inline bool operator==(const ObjectInfo& t1, const ObjectInfo& t2) { return t1.Tt.Class == t2.Tt.Class && t1.IsRef == t2.IsRef && /*t1.IsConst == t2.IsConst &&*/ t1.IsMove == t2.IsMove; } inline bool operator!=(const ObjectInfo& t1, const ObjectInfo& t2) { return !(t1 == t2); } class Result: public Moveable<Result> { public: int64 IVal; double DVal; ObjectInfo I; Result() { } }; class Entity: public Result, public Moveable<Entity> { public: enum AccessType { atPublic, atPrivate, atProtected }; enum EntityType { etConst, etVariable, }; String Name; Point Location; AccessType Access; EntityType Type; bool IsStatic; Entity() { IsStatic = false; Access = atPublic; Location = Point(-1, -1); } }; #endif
MasterZean/z2c-compiler-cpp
z2c/CommandLine.h
<filename>z2c/CommandLine.h #ifndef __COMMAND_LINE_HPP__ #define __COMMAND_LINE_HPP__ #include <Core/Core.h> namespace Z2 { using namespace Upp; class CommandLine { public: Index<String> Packages; String Path; String OutPath; String O; String BMName; String ARCH = "x86"; String BE = "c++"; bool CC = false; bool FF = false; bool SCU = false; bool LIB = false; bool CPP = false; bool BM = false; bool VASM = false; bool INT = false; bool LAZY = false; Point ACP = Point(-1, -1); String Class; bool Read(); }; } #endif
MasterZean/z2c-compiler-cpp
z2clib/Scanner.h
#ifndef _z2c_ScannerP1_h_ #define _z2c_ScannerP1_h_ #include <Core/Core.h> using namespace Upp; #include "Source.h" #include <z2clib/Assembly.h> class Def; class Scanner { public: Scanner(ZSource& aSrc, bool windows): source(aSrc), win(windows) { parser = ZParser(aSrc.Data); //parser.SkipNewLines(false); parser.NestComments(); parser.Mode = " scan"; parser.Source = &aSrc; } void Scan(bool cond = true); protected: ZParser parser; ZSource& source; String nameSpace; Entity::AccessType insertAccess; String bindName; bool win; bool isIntrinsic = false; bool isDllImport = false; bool isStdCall = false; bool isNoDoc = false; bool isForce = false; bool isCDecl = false; void ScanUsing(); void ScanClass(bool foreceStatic = false); void ScanEnum(); void ScanNamespace(); void ScanAlias(); void ScanVar(ZClass& cls, bool stat = false); void ScanProperty(ZClass& cls, bool stat = false); void ScanConst(ZClass& cls); Def& ScanDef(ZClass& cls, bool cons, bool stat = false, int virt = 0, bool cst = false); void ScanToken(); void ScanBlock(); void ClassLoop(ZClass& cls, bool cond = true, bool foreceStatic = false); void EnumLoop(ZClass& cls); void ScanType(); void ScanIf(); void ScanIf(ZClass& cls); void InterpretTrait(const String& trait); void ScanDefAlias(Overload& over); void TraitLoop(); }; #endif
MasterZean/z2c-compiler-cpp
z2c/Node.h
#ifndef _z2c2_Node_h_ #define _z2c2_Node_h_ #include <Core/Core.h> #include "ZParser.h" namespace Z2 { using namespace Upp; class ZClass; class Variable; class Assembly; class Overload; class NodeType { public: enum Type { Invalid, Const, BinaryOp, UnaryOp, Memory, Assign, Cast, //Temporary, Call, List, /*Construct, Ptr, Index, SizeOf, Destruct, Property, Deref, Intrinsic,*/ Return, Var, If, While, Goto, /*Alloc, Array,*/ Using, Block, }; }; class Node: Moveable<Node> { public: NodeType::Type NT = NodeType::Invalid; ZClass* Class = nullptr; ZClass* C1 = nullptr; ZClass* C2 = nullptr; ZClass* C3 = nullptr; bool IsReadOnly = false; bool IsCT = false; bool IsLiteral = false; bool IsTemporary = false; bool IsAddressable = false; bool HasSe = false; int64 IntVal = 0; double DblVal = 0; int OriginalLine = 0; void SetType(ZClass& cls) { Class = &cls; C1 = Class; } void SetType(ZClass* cls) { Class = cls; C1 = Class; } void SetType(ZClass* cls, ZClass* e1, ZClass* e2 = nullptr) { Class = cls; C1 = e1; C2 = e2; } bool IsZero(Assembly& ass); void PromoteToFloatValue(Assembly& ass); }; class ConstNode: public Node { public: int Base = 10; ConstNode() { NT = NodeType::Const; } }; class VarNode: public Node { public: Variable* Var = nullptr; VarNode() { NT = NodeType::Var; } }; class MemNode: public Node { public: Variable* Var = nullptr; MemNode() { NT = NodeType::Memory; } }; class BlockNode: public Node { public: bool SS = true; BlockNode() { NT = NodeType::Block; } }; class OpNode: public Node { public: enum Type { opNotSet = -1, opAdd = 0, opSub = 1, opMul = 2, opDiv = 3, opMod = 4, opShl = 5, opShr = 6, opLess = 7, opLessEq = 8, opMore = 9, opMoreEq = 10, opEq = 11, opNeq = 12, opBitAnd = 13, opBitXor = 14, opBitOr = 15, opLogAnd = 16, opLogOr = 17, opAssign = 18, opPlus = 19, opMinus = 20, opNot = 21, opBitNot = 22, opInc = 23, opDec = 24, opTernary = 25, }; Type Op = opNotSet; Node* OpA = nullptr; Node* OpB = nullptr; Node* OpC = nullptr; OpNode() { NT = NodeType::BinaryOp; } }; class UnaryOpNode: public OpNode { public: bool Prefix = false; UnaryOpNode() { NT = NodeType::UnaryOp; } }; class CastNode: public Node { public: Node* Object = nullptr; ZClass* Class = nullptr; bool MoveCast = false; CastNode() { NT = NodeType::Cast; } }; class CallNode: public Node { public: Overload* Over = nullptr; Vector<Node*> Params; CallNode() { NT = NodeType::Call; } }; class RetNode: public Node { public: Node* Value = nullptr; RetNode() { NT = NodeType::Return; } }; class IfNode: public Node { public: Node* Cond = nullptr; int JumpOnFalse = 0; IfNode() { NT = NodeType::If; } }; class WhileNode: public IfNode { public: WhileNode() { NT = NodeType::While; } }; class GotoNode: public Node { public: int Instruction = 0; bool Explicit = false; GotoNode() { NT = NodeType::Goto; } }; class AssignNode: public Node { public: Node* LS = nullptr; Node* RS = nullptr; OpNode::Type Op = OpNode::opNotSet; AssignNode() { NT = NodeType::Assign; } }; class ListNode: public Node { public: Vector<Node*> Params; ListNode() { NT = NodeType::List; } }; } #endif
MasterZean/z2c-compiler-cpp
z2clib/StopWatch.h
#ifndef __TIMESTOP_HPP__ #define __TIMESTOP_HPP__ #include <Core/Core.h> using namespace Upp; #ifdef PLATFORM_WIN32 class StopWatch : Moveable<StopWatch> { LARGE_INTEGER start; LARGE_INTEGER stop; LARGE_INTEGER freq; public: double Elapsed() { QueryPerformanceCounter(&stop); return (stop.QuadPart - start.QuadPart) * 1000.0 / freq.QuadPart; } double Seconds() { return (double)Elapsed() / 1000; } String ToString() { double time = Elapsed(); return Format("%d.%03d", int(time / 1000), int(time) % 1000); } void Reset() { QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&start); } StopWatch() { Reset(); } }; #endif #ifdef PLATFORM_POSIX #include <time.h> class StopWatch : Moveable<StopWatch> { timespec start; public: double Elapsed() { timespec end; clock_gettime(CLOCK_REALTIME, &end); return (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1000000.0; } double Seconds() { return (double)Elapsed() / 1000; } String ToString() { double time = Elapsed(); return Format("%d.%03d", int(time / 1000), int(time) % 1000); } void Reset() { clock_gettime(CLOCK_REALTIME, &start); } StopWatch() { Reset(); } }; #endif #endif
MasterZean/z2c-compiler-cpp
z2c/CppNodeWalker.h
<filename>z2c/CppNodeWalker.h<gh_stars>0 #ifndef _z2c2_CppNodeWalker_h_ #define _z2c2_CppNodeWalker_h_ #include <Core/Core.h> #include "Node.h" #include "Assembly.h" #include "IRGenerator.h" namespace Z2 { using namespace Upp; class CppNodeWalker { public: CppNodeWalker(Assembly& aAss, Stream& ss): ass(aAss), stream(ss) { } void Walk(Node* node); void WalkStatement(Node* node) { if (node->NT == NodeType::Block) Walk(node); else if (node->NT != NodeType::Goto) { SS(); Walk(node); if (node->NT != NodeType::If && node->NT != NodeType::While) stream << ";"; if (DebugOriginalLine && node->OriginalLine) stream << "\t\t\t\t // " << node->OriginalLine; if (node->NT != NodeType::If && node->NT != NodeType::While) NL(); else stream << " "; } } void WalkNode(ConstNode& node); void WalkNode(VarNode& node); void WalkNode(MemNode& node); void WalkNode(BlockNode& node); void WalkNode(OpNode& node); void WalkNode(UnaryOpNode& node); void WalkNode(CastNode& node); void WalkNode(CallNode& node); void WalkNode(RetNode& node); void WalkNode(AssignNode& node); void WalkNode(ListNode& node); void WalkNode(IfNode& node); void WalkNode(WhileNode& node); void WalkNode(GotoNode& node); void SS() { for (int i = 0; i < indent; i++) stream << "\t"; } void NL() { stream << "\r\n"; line++; } void ResetIndent(int ind = 0) { indent = ind; } bool CPP = true; bool DebugOriginalLine = false; void WriteClassName(const ZClass& ce) { stream << ce.BackendName; } void WriteClass(ZClass& cls); void WriteClassVars(ZClass& cls); void WriteClassStaticVars(ZClass& cls); void WriteVar(Variable& var); void WriteVarValue(Variable& var); void WriteOverloadDefinition(Overload &over); void WriteOverloadDeclaration(Overload &over); void OpenOverload() { stream << " {"; NL(); } void CloseOverload() { stream << "}"; NL(); NL(); } bool WriteReturnType(Overload &over); void WriteOverloadNameParams(Overload &over); void WriteParams(Overload &over); void WriteAssemblyParams(Stream& s, Overload &over); void WriteMangledParams(Overload &over); void WriteMethod(Method& m); void WriteOverloadBody(Overload& overload, int indent = 0); void WriteOverload(Overload& overload); bool CommentZMethod = false; bool CommentCMangled = false; bool IgnoreDupes = true; int CompilationUnitIndex = 0; bool PrintDupeErrors = true; bool WriteComments = true; private: Assembly& ass; Stream& stream; int indent = 0; int line = 1; }; } #endif
MasterZean/z2c-compiler-cpp
z2c/BuildMethod.h
<reponame>MasterZean/z2c-compiler-cpp #ifndef __BUILD_METHOD_HPP__ #define __BUILD_METHOD_HPP__ #include <Core/Core.h> namespace Z2 { using namespace Upp; class BuildMethod: public Moveable<BuildMethod> { public: enum Type { btMSC, btGCC, btUnknown, }; BuildMethod::Type Type; String Name; String Arch; String Compiler; String Tools; String Sdk; WithDeepCopy<Vector<String>> Lib; void Xmlize(XmlIO& xml) { xml("name", Name); xml("arch", Arch); if (xml.IsLoading()) { String s; xml("type", s); if (ToUpper(s) == "GCC") Type = BuildMethod::btGCC; else if (ToUpper(s) == "MSC") Type = BuildMethod::btMSC; else Type = BuildMethod::btUnknown; } else { if (Type == BuildMethod::btGCC) { String s = "GCC"; xml("type", s); } else if (Type == BuildMethod::btMSC) { String s = "MSC"; xml("type", s); } else { String s = "unknown"; xml("type", s); } } xml("compiler", Compiler); xml("tools", Tools); xml("sdk", Sdk); xml.List("lib", "path", Lib); } static void Get(Vector<BuildMethod>& methods, bool print = false); #ifdef PLATFORM_WIN32 static String Exe(const String& exe) { return exe + ".exe"; } static int ErrorCode(int code) { return code; } static int SuccessCode(int code) { return code; } static bool IsSuccessCode(int code) { return code >= 0; } #endif #ifdef PLATFORM_POSIX static String Exe(const String& exe) { return exe; } static int ErrorCode(int code) { byte c = (byte)code; if (c == 0) c = 1; return c; } static int SuccessCode(int code) { return 0; } static bool IsSuccessCode(int code) { return code == 0; } #endif bool TestLib(Vector<BuildMethod>& methods, const String& arch); private: #ifdef PLATFORM_WIN32 bool DetectMSC7_1(Vector<BuildMethod>& methods); bool DetectMSC8(Vector<BuildMethod>& methods); bool DetectMSC9(Vector<BuildMethod>& methods); bool DetectMSC10(Vector<BuildMethod>& methods); bool DetectMSC11(Vector<BuildMethod>& methods); bool DetectMSC12(Vector<BuildMethod>& methods); bool DetectMSC14(Vector<BuildMethod>& methods); #endif }; } #endif
MasterZean/z2c-compiler-cpp
z2clib/Assembly.h
<reponame>MasterZean/z2c-compiler-cpp #ifndef _z2c_Assembly_h_ #define _z2c_Assembly_h_ #include <Core/Core.h> using namespace Upp; #include "ZParser.h" #include "entities.h" #include "Source.h" class Compiler; class Assembly { public: ZClass* CCls = nullptr; ZClass* CDef = nullptr; ZClass* CVoid = nullptr; ZClass* CNull = nullptr; ZClass* CInt = nullptr; ZClass* CDWord = nullptr; ZClass* CBool = nullptr; ZClass* CByte = nullptr; ZClass* CSmall = nullptr; ZClass* CShort = nullptr; ZClass* CWord = nullptr; ZClass* CFloat = nullptr; ZClass* CDouble = nullptr; ZClass* CChar = nullptr; ZClass* CLong = nullptr; ZClass* CQWord = nullptr; ZClass* CPtrSize = nullptr; ZClass* CPtr = nullptr; ZClass* CString = nullptr; ZClass* CRaw = nullptr; ZClass* CStream = nullptr; ZClass* CIntrinsic = nullptr; ZClass* CSlice = nullptr; ZClass* CVect = nullptr; ArrayMap<String, ZClass> Classes; Index<String> StringConsts; VectorMap<String, int> ClassCounts; ArrayMap<String, ZClassAlias> Aliases; String TypeToString(ObjectType* type); String TypeToString(ObjectInfo* type, bool qual = true); String BTypeToString(ObjectInfo* type, bool qual = true); String CTypeToString(ObjectInfo* type, bool qual = true); String ClassToString(ObjectInfo* type, bool qual = true); void AddBuiltInClasses(); bool IsNumeric(const ObjectType& type) const { return type.Class->MIsNumeric; } bool IsInteger(const ObjectType& type) const { return type.Class->MIsInteger; } bool IsPtr(const ObjectType& ot) { return ot.Class == CPtr; } bool IsSignedInt(ObjectType* type) const; bool IsSignedInt(const ObjectType& type) const; bool IsFloat(ObjectType* type) const; bool IsFloat(const ObjectType& type) const; bool IsUnsignedInt(ObjectType* type) const; bool IsUnsignedInt(const ObjectType& type) const; ZClass& AddClass(const String& name, const String& nameSpace, ZParser& parser, const Point& pnt); ObjectType GetPtr(ObjectType* sub) { ObjectType obj; obj.Class = CPtr; obj.Param = 0; obj.Next = sub; return obj; } void AddClassCount(const String& cls) { int index = ClassCounts.Find(cls); if (index == -1) ClassCounts.Add(cls, 1); else ClassCounts[index]++; } int AddStringConst(const String& str) { return StringConsts.FindAdd(str); } ZClass& GetClass(const String& name, ZParser& parser) { Point p = parser.GetPoint(); int j = Classes.Find(name); if (j == -1) parser.Error(p, "undefined class: '\f" + name + "\f'"); return Classes[j]; } ZClass& Clone(ZClass& cls, const String& name, const String& bname); void AddSource(ZSource& src); void SetOwnership(ZClass& tclass); private: ZClass* AddCoreType(const String& ns, const String& name, const String& backendName, bool num = false, bool integer = false, bool core = true); void TypeToString(const ObjectType& type, String& str); }; #endif
MasterZean/z2c-compiler-cpp
z2c/OverloadResolver.h
#ifndef _z2c_OverloadResolver_h_ #define _z2c_OverloadResolver_h_ #include "Assembly.h" namespace Z2 { using namespace Upp; class GatherInfo { public: Overload* Rez = nullptr; int Count = 0; }; class OverloadResolver { public: OverloadResolver(Assembly& a): ass(a) { } Overload* Resolve(Method& def, Vector<Node*>& params, int limit, ZClass* spec = nullptr, bool conv = true); Overload* GatherParIndex(Vector<Overload*>& oo, Vector<Node*>& params, int pi); Overload* GatherNumeric(Vector<Overload*>& oo, Vector<Node*>& params, int pi, ZClass* cls); void GatherN(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, Variable::ParamType pt, ZClass* ot, ZClass* ot2 = nullptr); bool IsAmbig() const { return ambig; } int Score() const { return score; } private: Assembly& ass; int score = 0; bool ambig = false; bool conv = false; }; }; #endif
MasterZean/z2c-compiler-cpp
z2clib/entities.h
#ifndef _z2clib_enitites_h_ #define _z2clib_enitites_h_ #include "objecttype.h" #include "Source.h" class Constant: public Entity, public Moveable<Constant> { public: bool IsEvaluated = false; bool InUse = false; ZClass* Parent = nullptr; CParser::Pos Skip; int Base = 10; String StringValue(const Assembly& assembly) const; Constant() { Type = Entity::etConst; } }; class Variable: public Constant, Moveable<Variable> { public: Node* Body = nullptr; Node* List = nullptr; bool IsDeclared = false; bool FromTemplate = false; bool IsCppRef = false; bool IsTemp = false; Variable() { Type = Entity::etVariable; } Variable& operator=(const Node& o); bool IsVoid(Assembly& ass); ZClass& Class() { ASSERT(I.Tt.Class); return *I.Tt.Class; } const ZClass& Class() const { ASSERT(I.Tt.Class); return *I.Tt.Class; } }; class Block: Moveable<Block> { public: WithDeepCopy<VectorMap<String, Variable*>> Vars; int Temps = 0; }; class Def; class Overload: public Entity, public Moveable<Overload> { public: enum AutoMode { amNotAuto, amEqFull, amNeqFull, amEqAsNeqOpposite, amNeqAsEqOpposite, amLessEq, amMoreEq, amGetter, amSetter, amCopyCon, }; CParser::Pos CPosPar; CParser::Pos Skip; WithDeepCopy<Vector<Variable>> Params; WithDeepCopy<Vector<String>> ParamPreview; bool IsDeclared = false; int IsCons = 0; bool IsGenerated = false; bool IsStatic = false; bool IsEvaluated = false; bool IsConsidered = false; ObjectInfo Return; WithDeepCopy<Vector<Block>> Blocks; String Body; bool IsProp = false; bool IsGetter = false; bool IsIndex = false; bool IsNative = false; bool IsAlias = false; bool IsExtern = false; bool IsDeleted = false; bool IsIntrinsic = false; int IsIntrinsicType = -1; bool IsDllImport = false; bool IsStdCall = false; int IsVirtual = false; bool IsConst = false; bool IsNoDoc = false; bool IsCDecl = false; Def* Parent = nullptr; String BackendName; String BackendSuffix; String PSig; String PBSig; String PCSig; String BindName; bool BindForce = false; Point BindPoint; WithDeepCopy<Index<String>> Initializes; int IIndex = 0; bool IsDest = false; WithDeepCopy<Vector<ZClass*>> TParam; bool IsInline = true; bool FromTemplate = false; bool IsInClassBodyInline = false; bool IsOnlyZeroInit = false; bool IsVoidReturn = false; String PropVarName; AutoMode IsAuto = amNotAuto; String AliasClass; String AliasName; Overload* Alias = nullptr; Point AliasPos; int Score = 0; int Statements = 0; int Returns = 0; int Loops = 0; Variable* ZeroFirstVar = nullptr; WithDeepCopy<Index<ZClass*>> CDeps; WithDeepCopy<Array<Variable>> Variables; inline bool IsClassCopyCon() const; inline bool IsClassMoveCon() const; inline bool IsClassCopyOperator() const; inline bool IsClassMoveOperator() const; inline bool IsClassEqOperator() const; inline bool IsClassNeqOperator() const; inline ZClass& Class(); }; class Def: public Entity, public Moveable<Def> { public: Array<Overload> Overloads; String BackendName; ZClass* Class = nullptr; Array<CParser::Pos> Pos; Vector<int> PC; Array<CParser::Pos> BodyPos; Overload* HasPGetter = nullptr; Overload* HasPSetter = nullptr; bool Template = false; Vector<String> DTName; CParser::Pos CPosPar; VectorMap<String, int> SignatureHash; Def() = default; Def(const Def& def) { Name = def.Name; Location = def.Location; Access = def.Access; IsStatic = def.IsStatic; Class = def.Class; BackendName = def.BackendName; for (int i = 0; i < def.Overloads.GetCount(); i++) { if (!def.Overloads[i].FromTemplate) Overloads.Add(def.Overloads[i]); } Pos <<= def.Pos; PC <<= def.PC; SignatureHash <<= def.SignatureHash; HasPGetter = def.HasPGetter; HasPSetter = def.HasPSetter; Template = def.Template; BodyPos <<= def.BodyPos; DTName <<= def.DTName; } Overload& Add(const String& name, AccessType insertAccess, bool stat) { return Add(name, name, insertAccess, stat); } Overload& Add(const String& name, const String& bname, AccessType insertAccess, bool stat) { Overload& over = Overloads.Add(); over.IsDeclared = false; over.Access = insertAccess; over.Parent = this; over.Name = name; over.BackendName = bname; over.IsStatic = stat; return over; } }; ZClass& Overload::Class() { ASSERT(Parent); ASSERT(Parent->Class); return *Parent->Class; } class ZClassSuper { public: ZClass* Class = nullptr; String Name; String TName; ::Point Point; bool IsEvaluated = false; }; class ZClassScanInfo { public: String Name; String Namespace; String TName; bool HasDefaultCons = false; bool IsEnum = false; bool IsTemplate = false; bool HasVirtuals = false; }; class ZClassMeth { public: Overload* CopyCon = nullptr; Overload* MoveCon = nullptr; Overload* Copy = nullptr; Overload* Move = nullptr; Overload* Default = nullptr; Overload* Eq = nullptr; Overload* Neq = nullptr; }; class AST; class Compiler; class ZClass: Moveable<ZClass> { public: ZClassScanInfo Scan; ZClassMeth Meth; String BackendName; Point Position; ZSource* Source = nullptr; bool CoreSimple = false; bool IsDefined = true; ObjectType Tt; ObjectType Pt; bool IsEvaluated = false; bool FromTemplate = false; ZClass* ParamType = nullptr; ZClassSuper Super; int Index = -1; int RTTIIndex = 0; ZClass* T = nullptr; ZClass* TBase = nullptr; Point IPos; ::ZSource* ISource = nullptr; int HasEq = 0; int HasNeq = 0; int HasLess = 0; int HasMore = 0; int HasLessEq = 0; int HasMoreEq = 0; Overload* DefWrite = nullptr; bool IsPOD = true; ArrayMap<String, Constant> Constants; ArrayMap<String, Def> Defs; ArrayMap<String, Def> Props; ArrayMap<String, Def> Cons; Def* Dest = nullptr; ArrayMap<String, Variable> Vars; VectorMap<int, ObjectType*> Raws; Vector<ObjectType*> Temps; Vector<ZClass*> Children; bool MIsNumeric = false; bool MIsInteger = false; bool MIsRawVec = false; String MContName; int IsWritten = 0; ZClass() { IPos = Point(-1, -1); } ZClass(const ZClass& cls) { Position = cls.Position; BackendName = cls.BackendName; Position = cls.Position; Source = cls.Source; CoreSimple = cls.CoreSimple; IsDefined = cls.IsDefined; Tt = cls.Tt; Pt = cls.Pt; IsEvaluated = cls.IsEvaluated; Super = cls.Super; Index = cls.Index; IPos = cls.IPos; ISource = cls.ISource; T = cls.T; TBase = cls.TBase; ParamType = cls.ParamType; if (cls.Dest) Dest = new Def(*cls.Dest); else Dest = nullptr; Constants <<= cls.Constants; Defs <<= cls.Defs; Props <<= cls.Props; Cons <<= cls.Cons; Vars <<= cls.Vars; Raws <<= cls.Raws; Children <<= cls.Children; MIsNumeric = cls.MIsNumeric; MIsInteger = cls.MIsInteger; MIsRawVec = cls.MIsRawVec; MContName = cls.MContName; IsPOD = cls.IsPOD; HasEq = cls.HasEq; HasNeq = cls.HasNeq; HasLess = cls.HasLess; HasMore = cls.HasMore; HasLessEq = cls.HasLessEq; HasMoreEq = cls.HasMoreEq; RTTIIndex = cls.RTTIIndex; DefWrite = nullptr; Scan = cls.Scan; FromTemplate = cls.FromTemplate; } ~ZClass(); Overload* FindLength(); Overload* FindIndex(); void TestDup(const Entity& en, ZParser& parser, bool testName, bool testDef = true); void TestDup(const String& name, const Point& pos, ZParser& parser, bool testName, bool testDef = true); Overload* Get(Overload* over, const String& name, Node*& p1, Node*& p2, Node*& p3, ZClass*& cls, Assembly& ass, AST* ast, Compiler& cmp, const Point& p); Overload* Get(Overload* over, const String& name, Node*& p1, ZClass*& cls, Assembly& ass, AST* ast, Compiler& cmp, const Point& p); Overload* Get(Overload* over, const String& name, ZClass*& cls, Assembly& ass, AST* ast, Compiler& cmp, const Point& p); Def& FindDef(ZParser& parser, const String& name, const Point& pos, bool cons); void AddDefCons(ZParser& parser); Constant& AddConst(const String& name) { Constant& c = Constants.Add(name); c.Parent = this; c.Name = name; return c; } Variable& AddVar(const String& name) { Variable& c = Vars.Add(name); c.Parent = this; c.Name = name; return c; } }; bool Overload::IsClassCopyCon() const { return IsCons == 1 && Parent->Class->Meth.CopyCon == this; } bool Overload::IsClassMoveCon() const { return IsCons == 1 && Parent->Class->Meth.MoveCon == this; } bool Overload::IsClassCopyOperator() const { return IsCons == 0 && Parent->Class->Meth.Copy == this; } bool Overload::IsClassMoveOperator() const { return IsCons == 0 && Parent->Class->Meth.Move == this; } bool Overload::IsClassEqOperator() const { return IsCons == 0 && Parent->Class->Meth.Eq == this; } bool Overload::IsClassNeqOperator() const { return IsCons == 0 && Parent->Class->Meth.Neq == this; } #endif
MasterZean/z2c-compiler-cpp
z2clib/CppNodeWalker.h
#ifndef _z2clib_CppNodeWalker_h_ #define _z2clib_CppNodeWalker_h_ #include "NodeWalker.h" class BaseCppNodeWalker: public NodeWalker { public: bool WriteCtQual = false; bool EqOperator = true; bool OptimizeSlice = false; BaseCppNodeWalker(Assembly& ass, Stream& s): NodeWalker(ass, s) { } void Walk(ConstNode& node, Stream& stream); void WriteLocalCArrayLiteralElement(Stream& cs, const ZClass& ce, Node& n, const String& name, int index = -1); void WriteLocalCArrayLiteral(Stream& cs, const ZClass& ce, const RawArrayNode& list, const String& name, int count); void WriteClassName(const ZClass& ce) { if (!ce.CoreSimple) *cs << "::"; *cs << ce.BackendName; } void WriteOverloadDefinition(Stream& cs, Overload &over); void WriteOverloadDeclaration(Stream& cs, Overload &over); void WriteOverloadNameParams(Stream& cs, Overload &over); void WriteOverloadVoidingList(Stream& cs, Overload &over); bool WriteReturnType(Stream& cs, Overload &over); void WriteParams(Stream& cs, Overload& over, ZClass& cls, bool ths); protected: size_t rawIndex = -1; size_t rawSize = -1; }; #endif
MasterZean/z2c-compiler-cpp
z2clib/NodeWalker.h
#ifndef _z2c_NodeWalker_h_ #define _z2c_NodeWalker_h_ #include "Node.h" #include "Assembly.h" class Compiler; class NodeWalker { public: int indent = 0; Stream* cs; bool ClassConsts = false; Overload* Over = nullptr; Compiler* Comp = nullptr; String ForEachName = "_forIndex"; NodeWalker(Assembly& assembly, Stream& s): ass(assembly), cs(&s) { } void NL() { for (int i = 0; i < indent; i++) *cs << '\t'; } void EL() { *cs << '\n'; } void ES() { *cs << ";\n"; } virtual bool Traverse() { return false; } void Walk(Node* node, Stream& ss) { Stream* back = cs; cs = &ss; WalkNode(node); cs = back; } virtual void WalkNode(Node* node) { } virtual void WalkStatement(Node* node) { } protected: Assembly& ass; }; #endif
MasterZean/z2c-compiler-cpp
z2c/ErrorReporter.h
#ifndef _z2c2_ErrorReporter_h_ #define _z2c2_ErrorReporter_h_ #include <Core/Core.h> namespace Z2 { using namespace Upp; class Assembly; class ZClass; class Method; class Node; class Overload; class ZSyntaxError: Moveable<ZSyntaxError> { public: String Path; String Error; Point ErrorPoint; Overload* Context = nullptr; ZSyntaxError(const String& path, const Point& p, const String& error): Path(path), ErrorPoint(p), Error(error) { } void PrettyPrint(Stream& stream); }; class ErrorReporter { public: static void SyntaxError(const String& path, const Point& p, const String& text); static void InvalidNumericLiteral(const String& path, const Point& p); static void InvalidCharLiteral(const String& path, const Point& p); static void IntegerConstantTooBig(const String& path, const Point& p); static void IntegerConstantTooBig(const String& path, const String& cls, const Point& p); static void FloatConstantTooBig(const String& path, const Point& p); static void QWordWrongSufix(const String& path, const Point& p); static void LongWrongSufix(const String& path, const Point& p); static void UnsignedLeadingMinus(const String& path, const Point& p); static void ExpectedNotFound(const String& path, const Point& p, const String& expected, const String& found); static void ExpectCT(const String& path, const Point& p); static void EosExpected(const String& path, const Point& p, const String& found); static void IdentifierExpected(const String& path, const Point& p, const String& found); static void IdentifierExpected(const String& path, const Point& p, const String& id, const String& found); static void UndeclaredIdentifier(const String& path, const Point& p, const String& id); static void UndeclaredIdentifier(const String& path, const Point& p, const String& c1, const String& c2); static void UndeclaredClass(const String& path, const Point& p, const String& id); static void UnreachableCode(const String& path, const Point& p); static void ClassMustBeInstanciated(const String& path, const Point& p, const String& c); static void CantAssign(const String& path, const Point& p, const String& c1, const String& c2); static void AssignNotLValue(const String& path, const Point& p); static void NotLValue(const String& path, const Point& p); static void AssignConst(const String& path, const Point& p, const String& c); static void CantCreateClassVar(const String& path, const Point& p, const String& c); static void CondNotBool(const String& path, const Point& p, const String& c); static void NotStatic(const String& path, const Point& p, const String& c); static void CantCall(const String& path, const Point& p, Assembly& ass, ZClass* ci, Method* def, Vector<Node*>& params, int limit, bool cons = false); static void AmbigError(const String& path, const Point& p, Assembly& ass, ZClass* ci, Method* def, Vector<Node*>& params, int score); static void SomeOverloadsBad(const String& path, const Point& p, const String& f); static void DivisionByZero(const String& path, const Point& p); static void IncompatOperands(const String& path, const Point& p, const String& op, const String& text, const String& text2); static void IncompatUnary(const String& path, const Point& p, const String& text, const String& text2); static void Error(const String& path, const Point& p, const String& text); static void Dup(const String& path, const Point& p, const Point& p2, const String& text, const String& text2 = ""); static ZSyntaxError DupObject(const String& path, const Point& p, const Point& p2, const String& text, const String& text2 = ""); static void Warning(const String& path, const Point& p, const String& text); }; } #endif
MasterZean/z2c-compiler-cpp
z2c/Assembly.h
<filename>z2c/Assembly.h #ifndef _z2c2_Assembly_h_ #define _z2c2_Assembly_h_ #include <Core/Core.h> #include "ZParser.h" namespace Z2 { using namespace Upp; class Overload; class ZClass; class Node; class Method; class Entity: Moveable<Entity> { public: enum AccessType { atPublic, atPrivate, atProtected }; ZParser::Pos EntryPos; ZParser::Pos ExitPos; bool IsStatic = false; bool IsEvaluated = false; AccessType Access = Entity::atPublic; }; class Variable: public Entity, Moveable<Variable> { public: enum ParamType { tyAuto, tyRef, tyConstRef, tyVal, tyMove, }; String Name; Point SourcePoint = Point(-1, -1); bool MIsMember = false; int MIsParam = -1; bool IsReadOnly = false; bool IsCT = false; bool InUse = false; bool IsValid = false; ParamType PType = Variable::tyAuto; ZClass* OwnerClass = nullptr; Node* Value = nullptr; Node* Default = nullptr; ZClass* Class = nullptr; }; class Block: Moveable<Block> { public: WithDeepCopy<VectorMap<String, Variable*>> Variables; int Temps = 0; bool Returned = false; void AddVaribleRef(Variable& var) { Variables.Add(var.Name, &var); } }; class ZClass: public Entity, Moveable<ZClass> { public: String Name; String Namespace; String BackendName; String GlobalName; String MangledName; String ParamName; bool IsModule = false; bool IsTemplate = false; Point SourcePos = Point(-1, -1); bool MIsInteger = false; bool MIsFloat = false; bool MIsNumeric = false; int MIndex = -1; int MDecWritten = -1; Method& GetAddMethod(const String& name); Variable& AddVariable(const String& name); ArrayMap<String, Method> Methods; ArrayMap<String, Variable> Variables; }; class Method: Moveable<Method> { public: ZClass& OwnerClass; String Name; String BackendName; Method(ZClass& aClass, const String& name): OwnerClass(aClass), Name(name) { } Overload& AddOverload(); Overload& GetOverloadByPoint(const Point& p); Array<Overload> Overloads; Vector<int> OverloadCounts; }; class Overload: public Entity, Moveable<Overload> { public: ZClass& OwnerClass; Method& OwnerMethod; ZParser::Pos ParamPos; ZParser::Pos PostParamPos; String BackendName; Point NamePoint = Point(-1, -1); Point SourcePoint = Point(-1, -1); bool IsDestructor = false; bool IsVirtual = false; bool IsInline = false; bool IsConst = false; int IsCons = 0; int MDecWritten = 0; bool IsScanned = false; int Score = 0; int MinParams = -1; ZClass* Return; String Signature; String LogSig; String ParamSig; Array<Variable> Variables; ArrayMap<String, Variable> Params; VectorMap<String, ZClass*> TParam; WithDeepCopy<Array<Block>> Blocks; Vector<Node*> Nodes; Index<Overload*> DepOver; Index<ZClass*> DepClass; Overload(Method& aMethod): OwnerClass(aMethod.OwnerClass), OwnerMethod(aMethod), BackendName(aMethod.BackendName) { } Variable& AddVariable() { return Variables.Add(); } const String& Name() const { return OwnerMethod.Name; } }; class SubModule: public ZClass { public: SubModule() { IsModule = true; } }; class Assembly { public: ZClass* CCls = nullptr; ZClass* CDef = nullptr; ZClass* CVoid = nullptr; ZClass* CNull = nullptr; ZClass* CInt = nullptr; ZClass* CDWord = nullptr; ZClass* CBool = nullptr; ZClass* CByte = nullptr; ZClass* CSmall = nullptr; ZClass* CShort = nullptr; ZClass* CWord = nullptr; ZClass* CFloat = nullptr; ZClass* CDouble = nullptr; ZClass* CChar = nullptr; ZClass* CLong = nullptr; ZClass* CQWord = nullptr; ZClass* CPtrSize = nullptr; ZClass* CPtr = nullptr; ZClass* CString = nullptr; ZClass* CRaw = nullptr; ZClass* CStream = nullptr; ZClass* CIntrinsic = nullptr; ZClass* CSlice = nullptr; ZClass* CVect = nullptr; Assembly(); ZClass* AddCoreNumeric(const String& name, const String& backendName, const String& mangledName, int index); ZClass* AddCoreInteger(const String& name, const String& backendName, const String& mangledName, int index) { ZClass* cls = AddCoreNumeric(name, backendName, mangledName, index); cls->MIsInteger = true; return cls; } ZClass& AddClass(const String& name) { ZClass& cls = Classes.Add(name); cls.Name = name; cls.MIndex = Classes.GetCount() - 1; return cls; } bool CanAssign(ZClass* cls, Node* n); ArrayMap<String, ZClass> Classes; ArrayMap<String, SubModule> Modules; }; } #endif
MasterZean/z2c-compiler-cpp
z2c/Builder.h
<filename>z2c/Builder.h #ifndef __BUILDER_HPP__ #define __BUILDER_HPP__ #include <Core/Core.h> #include "BuildMethod.h" namespace Z2 { using namespace Upp; class Builder { public: Builder(const BuildMethod& abm): bm(abm) { } void ZCompilerPath(const String& azPath) { zPath = azPath; } void TargetRoot(const String& aroot) { target = aroot; } void Arch(const String& aarch) { arch = aarch; } void Optimize(const String& ao) { optimize = ao; } void CPP(bool aCpp) { cpp = aCpp; } bool Build(const String& path, const String& origPath); private: BuildMethod bm; String zPath; String target; String cppPath; String linkPath; String arch; String env; String optimize; bool cpp = true; bool BuildMSC(const String& path, const String& origPath); bool BuildGCC(const String& path, const String& origPath); void DoPathsMSC(); void DoEnvMSC(); void DoEnvGCC(); bool CompileMSC(const String& src, const String& out); bool CompileGCC(const String& src, const String& out); }; } #endif
MasterZean/z2c-compiler-cpp
z2clib/IR.h
<reponame>MasterZean/z2c-compiler-cpp #ifndef _z2clib_IR_h_ #define _z2clib_IR_h_ #include "Node.h" template<class Tt> class NodePool { private: Vector<Tt*> nodes; int count; public: NodePool() { count = 0; } ~NodePool() { for (int i = 0; i < nodes.GetCount(); i++) delete nodes[i]; } inline Tt* Get() { Tt* node; if (count >= nodes.GetCount()) node = nodes.Add(new Tt); else { node = nodes[count]; *node = Tt(); } count += 1; return node; //return new Tt(); } inline void Clear() { count = 0; } }; class Assembly; class Compiler; class IR { protected: Assembly& ass; NodePool<OpNode> opNodes; NodePool<UnaryOpNode> unaryOpNodes; NodePool<ConstNode> constNodes; NodePool<DerefNode> derefNodes; NodePool<ListNode> listNodes; NodePool<SizeOfNode> sizeOfNodes; NodePool<CastNode> castNodes; NodePool<ReturnNode> retNodes; NodePool<AllocNode> allocNodes; public: bool FoldConstants = true; Overload *Over = nullptr; Compiler* Comp = nullptr; IR(Assembly& ass): ass(ass) { } Assembly& GetAssembly() const { return ass; } void fillSignedTypeInfo(int64 l, Node* node, ZClass* cls = nullptr); void fillUnsignedTypeInfo(uint64 l, Node* node, ZClass* cls = nullptr); ConstNode* const_i(int64 l, ZClass* cls = nullptr, int base = 10); ConstNode* const_u(uint64 l, ZClass* cls = nullptr, int base = 10); ConstNode* const_r32(double l); ConstNode* const_r64(double l); ConstNode* const_bool(bool l); ConstNode* const_char(int l, int base = 10); ConstNode* const_void(); ConstNode* const_null(); ConstNode* const_str(int index); Node* opArit(Node* left, Node* right, OpNode::Type op, const Point& p); Node* opRel(Node* left, Node* right, OpNode::Type op, const Point& p); Node* opLog(Node* left, Node* right, OpNode::Type op); Node* op_bitand(Node* left, Node* right); Node* op_bitor(Node* left, Node* right); Node* op_bitxor(Node* left, Node* right); Node* minus(Node* node); Node* plus(Node* node); Node* op_not(Node* node); Node* bitnot(Node* node); Node* inc(Node* node, bool prefix = false); Node* dec(Node* node, bool prefix = false); Node* opTern(Node* cond, Node* left, Node* right); Node* add(Node* left, Node* right, const Point& p) { return opArit(left, right, OpNode::opAdd, p); } Node* sub(Node* left, Node* right, const Point& p) { return opArit(left, right, OpNode::opSub, p); } Node* mul(Node* left, Node* right, const Point& p) { return opArit(left, right, OpNode::opMul, p); } Node* div(Node* left, Node* right, const Point& p) { return opArit(left, right, OpNode::opDiv, p); } Node* mod(Node* left, Node* right, const Point& p) { return opArit(left, right, OpNode::opMod, p); } Node* eq(Node* left, Node* right, const Point& p) { return opRel(left, right, OpNode::opEq, p); } Node* neq(Node* left, Node* right, const Point& p) { return opRel(left, right, OpNode::opNeq, p); } Node* less(Node* left, Node* right, const Point& p) { return opRel(left, right, OpNode::opLess, p); } Node* lessEq(Node* left, Node* right, const Point& p) { return opRel(left, right, OpNode::opLessEq, p); } Node* more(Node* left, Node* right, const Point& p) { return opRel(left, right, OpNode::opMore, p); } Node* moreEq(Node* left, Node* right, const Point& p) { return opRel(left, right, OpNode::opMoreEq, p); } Node* shl(Node* left, Node* right, const Point& p); Node* shr(Node* left, Node* right, const Point& p); Node* deref(Node* node); Node* list(Node* node); Node* size(ZClass& cls); Node* cast(Node* left, ObjectType* tt, bool sc = true, bool ptr = false); ReturnNode* ret(Node* node); AllocNode* alloc(ZClass* cls, Node* count); Node* op(Node* left, Node* right, OpNode::Type op, const Point& p) { if (op <= OpNode::opMod) return opArit(left, right, op, p); else if (op <= OpNode::opShl) return shl(left, right, p); else if (op <= OpNode::opShr) return shr(left, right, p); else if (op <= OpNode::opNeq) return opRel(left, right, op, p); else if (op <= OpNode::opBitAnd) return op_bitand(left, right); else if (op <= OpNode::opBitXor) return op_bitxor(left, right); else if (op <= OpNode::opBitOr) return op_bitor(left, right); else if (op <= OpNode::opLogOr) return opLog(left, right, op); else { ASSERT(0); return nullptr; } } }; #endif
MasterZean/z2c-compiler-cpp
z2c/IRGenerator.h
#ifndef _z2c2_IRGenerator_h_ #define _z2c2_IRGenerator_h_ #include <Core/Core.h> #include "Node.h" namespace Z2 { using namespace Upp; class Assembly; template<class Tt> class NodePool { private: Vector<Tt*> nodes; int count; public: NodePool() { count = 0; } ~NodePool() { for (int i = 0; i < nodes.GetCount(); i++) delete nodes[i]; } inline Tt* Get() { Tt* node; if (count >= nodes.GetCount()) node = nodes.Add(new Tt); else { node = nodes[count]; *node = Tt(); } count += 1; return node; //return new Tt(); } inline void Clear() { count = 0; } }; class IRGenerator { public: IRGenerator(Assembly& aAss): ass(aAss) { } void fillSignedTypeInfo(int64 l, Node* node, ZClass* cls = nullptr); void fillUnsignedTypeInfo(uint64 l, Node* node, ZClass* cls = nullptr); ConstNode* constIntSigned(int64 l, int base, ZClass* cls = nullptr); ConstNode* constIntSigned(int64 l, ZClass* cls = nullptr) { return constIntSigned(l, 10, cls); } ConstNode* constIntUnsigned(uint64 l, int base = 10, ZClass* cls = nullptr); ConstNode* constIntUnsigned(int64 l, ZClass* cls = nullptr) { return constIntUnsigned(l, 10, cls); } ConstNode* constFloatSingle(double l); ConstNode* constFloatDouble(double l); ConstNode* constChar(int l, int base = 10); ConstNode* constBool(bool l); Node* constClass(ZClass* cls, Node* e = nullptr); ConstNode* constNull(); ConstNode* constVoid(); CastNode* cast(Node* object, ZClass* cls); BlockNode* openBlock(bool ss = true); BlockNode* closeBlock(); IfNode* ifNode(Node* cond); WhileNode* whileNode(Node* cond); GotoNode* gotoNode(int inst); VarNode* defineLocalVar(Variable& v); MemNode* mem(Variable& v); ListNode* list(Node* n); AssignNode* assign(Node* ls, Node* rs); Node* op(Node* left, Node* right, OpNode::Type op, const Point& p); Node* opArit(Node* left, Node* right, OpNode::Type op, const Point& p); Node* opShl(Node* left, Node* right, const Point& p); Node* opShr(Node* left, Node* right, const Point& p); Node* opRel(Node* left, Node* right, OpNode::Type op, const Point& p); Node* inc(Node* obj, bool prefix = false); Node* dec(Node* obj, bool prefix = false); Node* opAritCT(Node* left, Node* right, OpNode::Type op, ZClass* cls, ZClass* e, int64& dInt, double& dDouble); Node* opRelCT(Node* left, Node* right, OpNode::Type op, ZClass* e); Node* opBitAnd(Node* left, Node* right); Node* opBitOr(Node* left, Node* right); Node* opBitXor(Node* left, Node* right); Node* opBitAndCT(Node* left, Node* right, ZClass* e); Node* opBitOrCT(Node* left, Node* right, ZClass* e); Node* opBitXorCT(Node* left, Node* right, ZClass* e); Node* opLog(Node* left, Node* right, OpNode::Type op); Node* opLogCT(Node* left, Node* right, OpNode::Type op); Node* opMinus(Node* node); Node* opPlus(Node* node); Node* opNot(Node* node); Node* opBitNot(Node* node); Node* opInc(Node* node, bool prefix); Node* opDec(Node* node, bool prefix); CallNode* call(Overload& over); RetNode* ret(Node* value = nullptr); bool FoldConstants = false; private: Assembly& ass; NodePool<ConstNode> constNodes; NodePool<VarNode> varNodes; NodePool<MemNode> memNodes; NodePool<BlockNode> blockNodes; NodePool<OpNode> opNodes; NodePool<CastNode> castNodes; NodePool<CallNode> callNodes; NodePool<RetNode> retNodes; NodePool<AssignNode> assNodes; NodePool<UnaryOpNode> unaryNodes; NodePool<ListNode> listNodes; NodePool<IfNode> ifNodes; NodePool<WhileNode> whileNodes; NodePool<GotoNode> gotoNodes; }; } #endif
MasterZean/z2c-compiler-cpp
z2clib/ErrorReporter.h
#ifndef _z2clibex_ErrorReporter_h_ #define _z2clibex_ErrorReporter_h_ #include <z2clib/Source.h> class Overload; class Constant; class Def; class Node; class ObjectType; class Assembly; class ErrorReporter { public: static void CantAccess(const ZSource& src, const Point& p, Overload& over, const String& cls); static void CantAccess(const ZSource& src, const Point& p, Constant& over); static void Error(const ZSource& src, const Point& p, const String& text); static void Error(const ZClass& cls, const Point& p, const String& text); static void Dup(const ZSource& src, const Point& p, const Point& p2, const String& text, const String& text2 = ""); static void CallError(const ZClass& cls, Point& p, Assembly& ass, ObjectType* ci, Def* def, Vector<Node*>& params, bool cons = false); static void ErrItemCountMissing(const ZClass& cls, const Point& p, const String& text) { Error(cls, p, "\f'" + text + "'\f" + " can't be instantiated without an item count."); } static void ErrItemCountNegative(const ZClass& cls, const Point& p, const String& text) { Error(cls, p, "\f'" + text + "'\f" + " can only be instantiated with a greater than 0 item count."); } static void ErrItemCountNotInteger(const ZClass& cls, const Point& p, const String& text) { Error(cls, p, "\f'" + text + "'\f" + " can only be instantiated with a integer item count."); } static void ErrNotCompileTime(const ZClass& cls, const Point& p, const String& text) { Error(cls, p, "Compile time expression expected."); } static void ErrCArrayLiteralQualified(const ZClass& cls, const Point& p, const String& text, const String& text2) { Error(cls, p, "Fully qualified class '\f" + text + "\f' used as a vector literal. Remove the numeric qualifier: '\f" + text2 + "\f'."); } static void ErrCArrayNoQual(const ZClass& cls, const Point& p, const String& text) { Error(cls, p, "Explicitly specified type of \f'" + text + "'\f" + " must include an item count."); } static void ErrCArrayMoreElements(const ZClass& cls, const Point& p, const String& text, int c1, int c2) { Error(cls, p, "Literal '\f" + text + "\f' declared with an element count of '" + IntStr(c1) + "' initialized with '" + IntStr(c2) + "' (more) elements."); } static void ErrCArrayLessElements(const ZClass& cls, const Point& p, const String& text, int c1, int c2) { Error(cls, p, "Literal '\f" + text + "\f' declared with an element count of '" + IntStr(c1) + "' initialized with '" + IntStr(c2) + "' (less) elements."); } static void ErrEllipsisNocount(const ZClass& cls, const Point& p, const String& text) { Error(cls, p, "Vector literal '\f" + text + "\f' has ellipsis but no explicit item count."); } static void ErrIncompatOp(const ZClass& cls, const Point& p, const String& op, const String& text, const String& text2) { Error(cls, p, "Can't apply operator '" + op + "' on types: \n\t\t'\f" + text + "\f' and \n\t\t'\f" + text2 + "\f'"); } }; #endif
MasterZean/z2c-compiler-cpp
zide/build_info.h
#define bmYEAR 2015 #define bmMONTH 3 #define bmDAY 4 #define bmHOUR 17 #define bmMINUTE 34 #define bmSECOND 11 #define bmTIME Time(2015, 3, 4, 17, 34, 11) #define bmMACHINE "RAUL-THINK" #define bmUSER "Raul"
MasterZean/z2c-compiler-cpp
z2c/NodeRunner.h
<filename>z2c/NodeRunner.h #ifndef _z2c_NodeRunner_h_ #define _z2c_NodeRunner_h_ #include <Core/Core.h> #include "Node.h" #include "Assembly.h" #include "IRGenerator.h" namespace Z2 { using namespace Upp; class NodeRunner { public: NodeRunner(Assembly& aAss, Stream& ss): ass(aAss), stream(ss), irg(aAss) { irg.FoldConstants = true; } Node* ExecuteOverload(Overload& over); Node* Execute(Node* node); Node* ExecuteNode(ConstNode& node); Node* ExecuteNode(VarNode& node); Node* ExecuteNode(MemNode& node); Node* ExecuteNode(BlockNode& node); Node* ExecuteNode(OpNode& node); Node* ExecuteNode(UnaryOpNode& node); Node* ExecuteNode(CastNode& node); Node* ExecuteNode(CallNode& node); Node* ExecuteNode(RetNode& node); Node* ExecuteNode(AssignNode& node); Node* ExecuteNode(ListNode& node); Node* ExecuteNode(IfNode& node); Node* ExecuteNode(WhileNode& node); void WriteValue(Stream& stream, Node* node); void SS() { for (int i = 0; i < indent; i++) stream << "\t"; } void NL() { stream << "\r\n"; line++; } int CallDepth = 0; int StartCallDepth = 2; private: Assembly& ass; Stream& stream; IRGenerator irg; Vector<Node*>* paramList = nullptr; int indent = 0; int line = 0; }; } #endif
MasterZean/z2c-compiler-cpp
z2c/tables.h
<reponame>MasterZean/z2c-compiler-cpp<gh_stars>0 #ifndef _z2c_tables_h_ #define _z2c_tables_h_ #include <Core/Core.h> namespace Z2 { using namespace Upp; extern int TabCanAssign[][14]; extern int TabArithmetic[][14]; extern int TabShift[][14]; extern int TabRel[][14]; extern char tab1[]; extern char tab2[]; extern char tab3[]; extern String ops[]; extern String TabOpString[]; } #endif
MasterZean/z2c-compiler-cpp
z2c/StopWatch.h
<reponame>MasterZean/z2c-compiler-cpp #ifndef __TIMESTOP_HPP__ #define __TIMESTOP_HPP__ #include <Core/Core.h> namespace Z2 { using namespace Upp; #ifdef PLATFORM_WIN32 class StopWatch : Moveable<StopWatch> { LARGE_INTEGER start; LARGE_INTEGER stop; LARGE_INTEGER freq; public: double Elapsed() { QueryPerformanceCounter(&stop); return (stop.QuadPart - start.QuadPart) * 1000.0 / freq.QuadPart; } double Seconds() { return (double)Elapsed() / 1000; } String ToString() { double time = Elapsed(); return Format("%d.%03d", int(time / 1000), int(time) % 1000); } void Reset() { QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&start); } StopWatch() { Reset(); } }; #endif #ifdef PLATFORM_POSIX #include <time.h> class StopWatch : Moveable<StopWatch> { timespec start; public: double Elapsed() { timespec end; clock_gettime(CLOCK_REALTIME, &end); return (end.tv_sec - start.tv_sec) * 1000.0 + (end.tv_nsec - start.tv_nsec) / 1000000.0; } double Seconds() { return (double)Elapsed() / 1000; } String ToString() { double time = Elapsed(); return Format("%d.%03d", int(time / 1000), int(time) % 1000); } void Reset() { clock_gettime(CLOCK_REALTIME, &start); } StopWatch() { Reset(); } }; #endif } #endif
MasterZean/z2c-compiler-cpp
z2clib/source.h
<gh_stars>0 #ifndef _z2clib_ZFile_h_ #define _z2clib_ZFile_h_ #include <Core/Core.h> using namespace Upp; class ZSource; class ZParser; class ZClass; class ZClassAlias: Moveable<ZClassAlias> { public: CParser::Pos Context; ZClass* Class = nullptr; String Name; String Namespace; Point Location; ZSource* Source = nullptr; }; class ZClassAliasRef: Moveable<ZClassAliasRef> { public: ZClassAlias* Alias = nullptr; int Count = 0; }; class ZFile: Moveable<ZFile> { public: String Path; Time Modified; String Data = String::GetVoid(); Index<String> ClassNameList; Vector<String> References; Vector<Point> ReferencePos; VectorMap<String, ZClassAlias> Aliases; void Serialize(Stream& s) { s % Path % Modified % ClassNameList; } }; class ZPackage; class Assembly; class ZSource: public ZFile, Moveable<ZSource> { public: bool IsScaned = false; bool IsBuilt = false; bool SkipNewLines = true; ZPackage* Package = nullptr; ArrayMap<String, ZClass> ClassPrototypes; Vector<ZClass*> Declarations; void AddStdClassRefs(); void AddReference(const String& ns); ZClass& AddClass(const String& name, const String& nameSpace, const Point& pnt); int FindClassReference(const String& shortName, int start); }; class ZPackage: Moveable<ZPackage> { public: String Name; String Path; String CachePath; ArrayMap<String, ZSource> Files; void Serialize(Stream& s) { s % Name % Path % Files; } }; #endif
MasterZean/z2c-compiler-cpp
z2c/ZParser.h
#ifndef _z2c2_ZParser_h_ #define _z2c2_ZParser_h_ #include <Core/Core.h> namespace Z2 { using namespace Upp; class ZParser: public CParser { public: enum NumberType { ntInvalid, ntSmall, ntShort, ntInt, ntLong, ntByte, ntWord, ntDWord, ntQWord, ntFloat, ntDouble, ntPtrSize, }; String Path; ZParser() { skipspaces = false; } ZParser(const char* ptr) { skipspaces = false; Set(ptr); } Point GetPoint() { return Point(GetLine(), GetPos().GetColumn()); } String Identify(); bool IsZId(); NumberType ReadInt64(int64& oInt, double& oDub, int& base); void Expect(char ch); String ExpectId(); String ExpectZId(); String ExpectId(const String& id); void ExpectEndStat(); void SkipError(); bool WS() { return Spaces(); } bool WSCurrentLine(); bool IsCharConst() { return term[0] == '\''; } uint32 ReadChar(); String ReadZId(); int OpenCB = 0; private: uint64 ReadNumber64Core(Point& p, int base); NumberType ReadF(Point& p, int sign, double& oDub); NumberType ReadI(Point& p, int sign, int64& oInt); }; } #endif
MasterZean/z2c-compiler-cpp
z2clib/OverloadResolver.h
<gh_stars>0 #ifndef _z2clib_OverloadResolver_h_ #define _z2clib_OverloadResolver_h_ #include "Assembly.h" class GatherInfo { public: Overload* Rez = nullptr; int Count = 0; }; class OverloadResolver { public: OverloadResolver(Assembly& a): ass(a) { } Overload* Resolve(Def& def, Vector<Node*>& params, ZClass* spec = nullptr, bool conv = true); Overload* GatherParIndex(Vector<Overload*>& oo, Vector<Node*>& params, int pi); void GatherRef(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, Node& n, ObjectInfo& a, ObjectType* ot); void Gather(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, Node& n, ObjectInfo& a, ObjectType* ot); void Gather(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, Node& n, ObjectInfo& a, ObjectType* ot, ObjectType* ot2); void GatherD(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, Node& n, ObjectInfo& a); void GatherDRef(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, ObjectInfo& a); void GatherDConst(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, ObjectInfo& a); void GatherDMove(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, ObjectInfo& a); void GatherS(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, Node& n, ObjectInfo& a); void GatherR(Vector<Overload*>& oo, Vector<Node*>& params, int pi, GatherInfo& gi, ObjectInfo& a); Overload* GatherNumeric(Vector<Overload*>& oo, Vector<Node*>& params, int pi, ZClass* cls); static bool TypesEqualD(Assembly& ass, ObjectType* t1, ObjectType* t2); static bool TypesEqualS(Assembly& ass, ObjectType* t1, ObjectType* t2); static bool TypesEqualSD(Assembly& ass, ObjectType* t1, ObjectType* t2); bool IsAmbig() const { return ambig; } int Score() const { return score; } private: Assembly& ass; int score = 0; bool ambig = false; bool conv = false; }; #endif
MasterZean/z2c-compiler-cpp
z2c/Compiler.h
#ifndef _z2c2_Compiler_h_ #define _z2c2_Compiler_h_ #include <Core/Core.h> #include "ZParser.h" #include "Node.h" #include "IRGenerator.h" #include "Assembly.h" #include "CppNodeWalker.h" #include "ErrorReporter.h" #include "Scanner.h" namespace Z2 { using namespace Upp; class Compiler { public: enum PlatformType { WINDOWS32, POSIX, }; Compiler(Assembly& aAss): ass(aAss), irg(aAss), cpp(aAss, ss) { static bool tableSetup = false; if (!tableSetup) { SetupTables(); tableSetup = true; } #ifdef PLATFORM_WIN32 Platform = WINDOWS32; #endif #ifdef PLATFORM_POSIX Platform = POSIX; #endif } Overload* CompileSnipFunc(const String& snip); ZClass* CompileModule(ZSource& src); bool CompileSourceLoop(ZClass& conCls, ZParser& parser); void BuildSignature(ZClass& conCls, Overload& over); void BuildSignature(ZClass& conCls, Overload& over, ZParser& parser); bool CompileOverload(Overload& overload, ZParser& parser); bool CompileOverloadJump(Overload& overload); bool CompileBlock(ZClass& conCls, Overload& conOver, ZParser& parser, Vector<Node*>* nodePool, int level); bool CompileStatement(ZClass& conCls, Overload& conOver, ZParser& parser, Vector<Node*>* nodePool); Node* CompileExpression(ZClass& conCls, Overload* conOver, ZParser& parser); void CompileClass(ZClass& cls); Node* CompileSourceVar(ZClass& conCls, Overload* conOver, ZParser& parser, bool cst); void CompileSourceDef(ZClass& conCls, ZParser& parser); void CheckLocalVar(ZClass& conCls, Overload* conOver, const String& varName, const Point& p); Node* GetVarDefault(ZClass* cls); Node* CompileIfWhile(ZClass& conCls, Overload* conOver, ZParser& parser, Vector<Node*>* nodePool, bool isIf); Node* ParseExpression(ZClass& conCls, Overload* conOver, ZParser& parser); Node* ParseBin(ZClass& conCls, Overload* conOver, ZParser& parser, int prec, Node* left, CParser::Pos& backupPoint, bool secondOnlyAttempt = false); Node* ParseAtom(ZClass& conCls, Overload* conOver, ZParser& parser); Node* ParseId(ZClass& conCls, Overload* conOver, Overload* searchOver, ZParser& parser); Node* ParseNumeric(ZClass& conCls, ZParser& parser); Node* ParseTemporary(ZClass& conCls, Overload* conOver, ZParser& parser, const Point p, ZClass& cls); Node* ParseDef(ZClass& conCls, Overload* conOver, ZParser& parser, const Point& p, int methodIndex); Node* ParseDot(ZClass& conCls, Overload* conOver, ZParser& parser, Node* exp); String GetResult() { return ss.GetResult(); } Node* AssignOp(ZClass& conCls, Overload& conDef, Point p, Node* node, Node* rs, OpNode::Type op); ZClass* GetClass(ZClass& conCls, const Point& p, const String& name); ZClass* GetClass(const String& name); String GetErrors(); void FixupParams(Overload& over, Vector<Node*>& params); bool PrintErrors = true; void Sanitize(ZClass& cls); void Sanitize(Method& m); bool SkipUntilNL(ZParser& parser, bool cb = false); bool AddPackage(const String& aPath); void AddModule(int parent, const String& path, ZPackage& pak, ZPackage& temp); void AddModuleSource(ZPackage& pak, ZPackage& temp, FindFile& ff); ZSource& AddSource(ZPackage& aPackage, const String& aFile, bool populate = true); ZSource& LoadSource(ZSource& source, bool populate); void AddBindsFile(const String& path); static String GetName() { return ""; } String BuildProfile; String BuildPath; String OutPath; String OrigOutPath; bool MSC = false; String BMName; PlatformType Platform; private: Assembly& ass; IRGenerator irg; CppNodeWalker cpp; StringStream ss; int filesOpened = 0; Vector<ZSyntaxError> errors; Vector<Overload*> postOverloads; Vector<Overload*> compileStack; ArrayMap<String, ZPackage> packages; VectorMap<String, String> Binds; VectorMap<String, String>* Cache = nullptr; int GetPriority(CParser& parser, int& op, bool& opc); void GetParams(Vector<Node*>& params, ZClass& cls, Overload* def, ZParser& parser, char end = ')'); static Point OPS[256]; static bool OPCONT[256]; static void SetupTables(); }; } #endif
MasterZean/z2c-compiler-cpp
z2clib/ZParser.h
#ifndef _z2c_ZParser_h_ #define _z2c_ZParser_h_ #include <Core/Core.h> using namespace Upp; class ZSource; class ZClass; class Overload; class Def; class Context { public: ZClass* C1 = nullptr; ZClass* C2 = nullptr; Point P; Overload* O = nullptr; Def* D = nullptr; ZSource* S = nullptr; Context* Next = nullptr; Context* Prev = nullptr; }; class ZSyntaxError { public: String Path; String Error; ZSyntaxError(const String& path, const String& error): Path(path), Error(error) { } void PrettyPrint(Context* con, Stream& stream); }; class ZParser: public CParser { public: enum NumberType { ntInvalid, ntInt, ntDWord, ntLong, ntQWord, ntFloat, ntDouble, ntPtrSize, }; ZSource* Source = nullptr; String Mode; ZParser() { } ZParser(const char* ptr): CParser(ptr) { } Point GetPoint() { return Point(GetLine(), GetPos().GetColumn()); } String Identify(); String ErrorString(const Point& p, const String& text); void Error(const Point& p, const String& text); void Dup(const Point& p, const Point& p2, const String& text, const String& text2 = ""); void Ambig(const Point& p, const Point& p2, const String& text, const String& text2 = ""); void Warning(const Point& p, const String& text); String ExpectId(); String ExpectZId(); String ExpectId(const String& id); void Expect(char ch); void Expect(char ch, char ch2); int ExpectNum(); NumberType ReadInt64(int64& oInt, double& oDub, int& base); bool IsCharConst() { return term[0] == '\''; } void SetLine(int l) { line = l; } bool IsZId(); uint32 ReadChar(); bool EatIf(); bool EatElse(); bool EatEndIf(); bool IsElse(); bool IsEndIf(); void SkipBlock(); void ExpectEndStat(); void EatNewlines(); private: uint64 ReadNumber64Core(Point& p, int base); NumberType ReadF(Point& p, int sign, double& oDub); NumberType ReadI(Point& p, int sign, int64& oInt); }; #endif
MasterZean/z2c-compiler-cpp
z2c/Scanner.h
#ifndef _z2c_Scanner_h_ #define _z2c_Scanner_h_ #include <Core/Core.h> #include "Assembly.h" #include "ErrorReporter.h" #include "tables.h" namespace Z2 { using namespace Upp; class ZPackage; class ZFile: Moveable<ZFile> { public: String Path; Time Modified; String Data; void Serialize(Stream& s) { s % Path % Modified; } }; class ZSource: public ZFile, Moveable<ZSource> { public: bool IsScaned = false; ZPackage* Package = nullptr; String Namespace; SubModule Module; }; class ZPackage: Moveable<ZPackage> { public: String Name; String Path; String CachePath; ArrayMap<String, ZSource> Files; void Serialize(Stream& s) { s % Name % Path % Files; } }; class Scanner { public: enum PlatformType { WINDOWS32, POSIX, }; Scanner(Assembly& aAss): ass(aAss) { } void Scan(ZSource& src); void ScanClass(ZClass& conCls, ZParser& parser); void ScanDef(ZClass& conCls, ZParser& parser, bool ct, bool st = false); void ScanVar(ZClass& conCls, ZParser& parser, bool ct, bool st = false); void ScanToken(ZParser& parser); private: Assembly& ass; }; }; #endif
MasterZean/z2c-compiler-cpp
z2clib/BaseExprParser.h
#ifndef _z2clib_BaseExprParser_h_ #define _z2clib_BaseExprParser_h_ #include "ZParser.h" #include "Assembly.h" class Compiler; class AST; class BaseExprParser { public: bool ClassConsts; bool InVarMode; bool InConstMode; bool AllowArrays; BaseExprParser(Compiler& aCmp, ZParser& aSrc, AST& aIrg, Assembly& aAss, bool var = false, bool ct = false): comp(aCmp), irg(aIrg), ass(aAss), parser(aSrc), InVarMode(var), InConstMode(ct) { AllowArrays = false; } Node* ParseNumeric(ZClass& conClass, Overload* conOver); static bool TypesEqualD(Assembly& ass, ObjectType* t1, ObjectType* t2); protected: AST& irg; Assembly& ass; ZParser& parser; Compiler& comp; }; #endif
MasterZean/z2c-compiler-cpp
z2clib/BuildMethod.h
#ifndef __BUILD_METHOD_HPP__ #define __BUILD_METHOD_HPP__ #include <Core/Core.h> using namespace Upp; struct BuildMethod: public Moveable<BuildMethod> { enum Type { btMSC, btGCC, btUnknown, }; BuildMethod::Type Type; String Name; String Compiler; String Sdk; WithDeepCopy<Vector<String>> Lib32; WithDeepCopy<Vector<String>> Lib64; void Xmlize(XmlIO& xml) { xml("name", Name); if (xml.IsLoading()) { String s; xml("type", s); if (ToUpper(s) == "GCC") Type = BuildMethod::btGCC; else if (ToUpper(s) == "MSC") Type = BuildMethod::btMSC; else Type = BuildMethod::btUnknown; } else { if (Type == BuildMethod::btGCC) { String s = "GCC"; xml("type", s); } else if (Type == BuildMethod::btMSC) { String s = "MSC"; xml("type", s); } else { String s = "unknown"; xml("type", s); } } xml("compiler", Compiler); xml("sdk", Sdk); xml("lib-x86", Lib32); xml("lib-x64", Lib64); } static void Get(Vector<BuildMethod>& methods); static String Exe(const String& exe) { #ifdef PLATFORM_WIN32 return exe + ".exe"; #endif #ifdef PLATFORM_POSIX return exe; #endif } static int ErrorCode(int code) { #ifdef PLATFORM_WIN32 return code; #endif #ifdef PLATFORM_POSIX byte c = (byte)code; if (c == 0) c = 1; return c; #endif } static int SuccessCode(int code) { #ifdef PLATFORM_WIN32 return code; #endif #ifdef PLATFORM_POSIX return 0; #endif } static bool IsSuccessCode(int code) { #ifdef PLATFORM_WIN32 return code >= 0; #endif #ifdef PLATFORM_POSIX return code == 0; #endif } private: bool TestLib(bool px86, bool px64); #ifdef PLATFORM_WIN32 bool DetectMSC7_1(); bool DetectMSC8(); bool DetectMSC9(); bool DetectMSC10(); bool DetectMSC11(); bool DetectMSC12(); bool DetectMSC14(); #endif }; #endif
notjosh/NTJBilateralCIFilter
NTJBilateralCIFilteriOS/NTJBilateralCIFilteriOS.h
<filename>NTJBilateralCIFilteriOS/NTJBilateralCIFilteriOS.h // // NTJBilateralCIFilteriOS.h // NTJBilateralCIFilter // // Created by <NAME> on 17/10/17. // Copyright © 2017 nojo inc. All rights reserved. // #ifndef NTJBilateralCIFilteriOS_h #define NTJBilateralCIFilteriOS_h #import "NTJBilateralCIFilter.h" #endif /* NTJBilateralCIFilteriOS_h */
notjosh/NTJBilateralCIFilter
NTJBilateralCIFilter/NTJBilateralCIFilter.h
<reponame>notjosh/NTJBilateralCIFilter // // NTJBilateralCIFilter.h // NTJBilateralCIFilter // // Created by <NAME> on 6/06/2016. // Copyright © 2016 nojo inc. All rights reserved. // #import <CoreImage/CoreImage.h> @interface NTJBilateralCIFilter : CIFilter @property (strong) CIImage *inputImage; @property (strong) NSNumber *sigma_R; @property (strong) NSNumber *sigma_S; @end
notjosh/NTJBilateralCIFilter
NTJBilateralCIFilterDemo/AppDelegate.h
// // AppDelegate.h // NTJBilateralCIFilterDemo // // Created by <NAME> on 6/06/2016. // Copyright © 2016 nojo inc. All rights reserved. // #import <Cocoa/Cocoa.h> @interface AppDelegate : NSObject <NSApplicationDelegate> @end
notjosh/NTJBilateralCIFilter
NTJBilateralCIFilterDemo/NTJBilateralFilterRunner.h
// // NTJBilateralFilterRunner.h // BilateralFilter // // Created by <NAME> on 1/06/2016. // Copyright © 2016 nojo inc. All rights reserved. // #import <TargetConditionals.h> #if TARGET_OS_OSX #import <Cocoa/Cocoa.h> #define IMAGE NSImage #else #import <UIKit/UIKit.h> #define IMAGE UIImage #endif @interface NTJBilateralFilterRunner : NSObject - (id)initWithImageFileURL:(NSURL *)imageFileURL; - (void)read; - (void)prepareAsSize:(CGSize)size; - (IMAGE *)runWithSigma_R:(double)sigma_R sigma_S:(double)sigma_S; @end