repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
anji-plus/flutter_plugin | aj_flutter_scan/ios/Classes/FlashButton.h | //
// FlashButton.h
// aj_flutter_scan
//
// Created by kean_qi on 2019/7/18.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface FlashButton : UIButton
- (void)setNeedsDrawColor:(UIColor *)drawColor;
@end
NS_ASSUME_NONNULL_END
|
anji-plus/flutter_plugin | aj_flutter_plugin/ios/Classes/AjFlutterPlugin.h | #import <Flutter/Flutter.h>
#import <CoreLocation/CoreLocation.h>
@interface AjFlutterPlugin : NSObject<FlutterPlugin,CLLocationManagerDelegate>
//@property(nonatomic, retain) FlutterResult result;
@end
|
Reiqy/sudoku-solver | src/memory.h | <reponame>Reiqy/sudoku-solver
//
// Created by Reiqy on 01.07.2021.
//
#ifndef SUDOKUSOLVER_MEMORY_H
#define SUDOKUSOLVER_MEMORY_H
#include <stdlib.h>
void *allocate(size_t size);
void *deallocate(void *ptr);
void *reallocate(void *ptr, size_t new_size);
size_t growCapacity(size_t oldCapacity);
#endif //SUDOKUSOLVER_MEMORY_H
|
Reiqy/sudoku-solver | src/main.c | #include <stdio.h>
#include <stdlib.h>
#include "sudoku.h"
#include "solver.h"
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: '%s <sudoku>'\n", argv[0]);
exit(1);
}
else
{
Sudoku s = readSudokuFromFile(argv[1]);
printSudoku(&s);
solveSudoku(&s);
printf("Sudoku %s.\n", isSudokuSolved(&s) ? "was solved" : "could not be solved");
printSudoku(&s);
freeSudoku(&s);
}
return 0;
}
|
Reiqy/sudoku-solver | src/memory.c | //
// Created by Reiqy on 01.07.2021.
//
#include "memory.h"
#include <stdio.h>
void *allocate(size_t size)
{
void *ptr = malloc(size);
if (ptr == NULL)
{
fprintf(stderr, "Error: Out of memory!\n");
exit(EXIT_FAILURE);
}
return ptr;
}
void *deallocate(void *ptr)
{
free(ptr);
return NULL;
}
void *reallocate(void *ptr, size_t new_size)
{
if (new_size == 0)
{
return deallocate(ptr);
}
void *new = realloc(ptr, new_size);
if (new == NULL)
{
fprintf(stderr, "Error: Out of memory!\n");
exit(EXIT_FAILURE);
}
return new;
}
size_t growCapacity(size_t oldCapacity)
{
return (oldCapacity == 0) ? 8 : 2 * oldCapacity;
}
|
Reiqy/sudoku-solver | src/solver.h | <filename>src/solver.h
//
// Created by Reiqy on 01.07.2021.
//
#ifndef SUDOKUSOLVER_SOLVER_H
#define SUDOKUSOLVER_SOLVER_H
#include "sudoku.h"
typedef struct PossibleNumbers
{
size_t count;
uint8_t numbers[SUDOKU_SQUARE_SIZE];
} PossibleNumbers;
void initPossibleNumbers(PossibleNumbers *p_nums);
void addPossibleNumber(PossibleNumbers *p_nums, uint8_t number);
void findPossibleNumbers(Sudoku *s, PossibleNumbers *p_nums, size_t pos_x, size_t pos_y);
typedef struct Placement
{
size_t pos_x;
size_t pos_y;
uint8_t number;
} Placement;
typedef struct PlacementPath
{
size_t capacity;
size_t count;
Placement *path;
} PlacementPath;
void initPlacementPath(PlacementPath *path);
void freePlacementPath(PlacementPath *path);
void addPlacementPath(PlacementPath *path, Placement p);
typedef struct NondeterministicNode
{
int attempts;
struct NondeterministicNode *previous;
PlacementPath path;
} NondeterministicNode;
void initNondeterministicNode(NondeterministicNode *node, NondeterministicNode *previous);
void freeNondeterministicNode(NondeterministicNode *node);
typedef struct NodeManager
{
size_t capacity;
size_t count;
NondeterministicNode **nodes;
} NodeManager;
void initNodeManager(NodeManager *manager);
void freeNodeManager(NodeManager *manager);
NondeterministicNode * getNondeterministicNode(NodeManager *manager, NondeterministicNode *from_node);
bool findNextGuess(Sudoku *s, Placement *p, int attempt);
bool revertSudoku(Sudoku *s, NondeterministicNode *node);
bool solveSudoku(Sudoku *s);
bool solveDeterministically(Sudoku *s, PlacementPath *path);
bool solveNondeterministically(Sudoku *s);
#endif //SUDOKUSOLVER_SOLVER_H
|
Reiqy/sudoku-solver | src/sudoku.c | //
// Created by Reiqy on 01.07.2021.
//
#include "sudoku.h"
#include <stdio.h>
#include <ctype.h>
#include "memory.h"
void initSudoku(Sudoku *s)
{
s->numbers = allocate(sizeof(uint8_t) * SUDOKU_ARRAY_LENGTH);
}
void freeSudoku(Sudoku *s)
{
s->numbers = deallocate(s->numbers);
}
Sudoku readSudokuFromFile(const char *filename)
{
Sudoku result;
initSudoku(&result);
FILE *f = fopen(filename, "r");
if (f == NULL)
{
fprintf(stderr, "Error: Unable to open file '%s'!\n", filename);
exit(EXIT_FAILURE);
}
size_t number_count = 0;
int c;
while (((c = fgetc(f)) != EOF) && (number_count != SUDOKU_ARRAY_LENGTH))
{
if (isdigit(c))
{
result.numbers[number_count] = (c - '0');
number_count++;
}
}
if (ferror(f) != 0)
{
fprintf(stderr, "Error: Unable to read file '%s'!\n", filename);
exit(EXIT_FAILURE);
}
fclose(f);
if (number_count != SUDOKU_ARRAY_LENGTH)
{
fprintf(stderr, "Error: Not enough numbers in file '%s' to define sudoku!\n", filename);
exit(EXIT_FAILURE);
}
if (!isSudokuValid(&result))
{
fprintf(stderr, "Error: Sudoku defined in file '%s' is invalid!\n", filename);
exit(EXIT_FAILURE);
}
return result;
}
void printSudoku(Sudoku *s)
{
for (size_t i = 0; i < SUDOKU_SQUARE_SIZE; i++)
{
for (size_t j = 0; j < SUDOKU_SQUARE_SIZE; j++)
{
size_t current_element = i * SUDOKU_SQUARE_SIZE + j;
if (s->numbers[current_element] != 0)
{
printf("%i", s->numbers[current_element]);
}
else
{
printf("-");
}
if (j != (SUDOKU_SQUARE_SIZE - 1))
{
printf(" | ");
}
else
{
printf("\n");
}
}
}
}
bool isSudokuBounded(const Sudoku *s)
{
for (size_t i = 0; i < SUDOKU_ARRAY_LENGTH; i++)
{
if ((s->numbers[i] < 0) || (s->numbers[i] > 9))
{
return false;
}
}
return true;
}
bool isSudokuValid(const Sudoku *s)
{
if (!isSudokuBounded(s))
{
return false;
}
bool check_rows[9];
bool check_columns[9];
bool check_squares[9];
for (size_t i = 0; i < SUDOKU_SQUARE_SIZE; i++)
{
size_t current_square_origin_x = (i % SUDOKU_SMALL_SQUARE_SIZE) * SUDOKU_SMALL_SQUARE_SIZE;
size_t current_square_origin_y = (i / SUDOKU_SMALL_SQUARE_SIZE) * SUDOKU_SMALL_SQUARE_SIZE;
clearNumberSet(check_rows, SUDOKU_SQUARE_SIZE);
clearNumberSet(check_columns, SUDOKU_SQUARE_SIZE);
clearNumberSet(check_squares, SUDOKU_SQUARE_SIZE);
for (size_t j = 0; j < SUDOKU_SQUARE_SIZE; j++)
{
size_t current_element_row = i * SUDOKU_SQUARE_SIZE + j;
if (s->numbers[current_element_row] != 0)
{
if (isNumberPresent(check_rows, s->numbers[current_element_row], SUDOKU_SQUARE_SIZE))
{
return false;
}
addNumberSet(check_rows, s->numbers[current_element_row], SUDOKU_SQUARE_SIZE);
}
size_t current_element_column = j * SUDOKU_SQUARE_SIZE + i;
if (s->numbers[current_element_column] != 0)
{
if (isNumberPresent(check_columns, s->numbers[current_element_column], SUDOKU_SQUARE_SIZE))
{
return false;
}
addNumberSet(check_columns, s->numbers[current_element_column], SUDOKU_SQUARE_SIZE);
}
size_t current_square_offset_x = j % SUDOKU_SMALL_SQUARE_SIZE;
size_t current_square_offset_y = j / SUDOKU_SMALL_SQUARE_SIZE;
size_t current_square_x = current_square_origin_x + current_square_offset_x;
size_t current_square_y = current_square_origin_y + current_square_offset_y;
size_t current_element_square = current_square_y * SUDOKU_SQUARE_SIZE + current_square_x;
if (s->numbers[current_element_square] != 0)
{
if (isNumberPresent(check_squares, s->numbers[current_element_square], SUDOKU_SQUARE_SIZE))
{
return false;
}
addNumberSet(check_squares, s->numbers[current_element_square], SUDOKU_SQUARE_SIZE);
}
}
}
return true;
}
bool isSudokuComplete(const Sudoku *s)
{
for (size_t i = 0; i < SUDOKU_ARRAY_LENGTH; i++)
{
if (s->numbers[i] == 0)
{
return false;
}
}
return true;
}
bool isSudokuSolved(const Sudoku *s)
{
if (!isSudokuComplete(s))
{
return false;
}
if (!isSudokuValid(s))
{
return false;
}
return true;
}
void clearNumberSet(bool *set, size_t length)
{
for (size_t i = 0; i < length; i++)
{
set[i] = false;
}
}
void addNumberSet(bool *set, uint8_t number, size_t length)
{
if ((number <= 0) || (number > length))
{
fprintf(stderr, "Error: Trying to add to set number that is out of bounds!\n");
exit(EXIT_FAILURE);
}
set[number - 1] = true;
}
bool isNumberPresent(bool *set, uint8_t number, size_t length)
{
if ((number <= 0) || (number > length))
{
fprintf(stderr, "Error: Trying to check for set presence that is out of bounds!\n");
exit(EXIT_FAILURE);
}
return set[number - 1];
} |
Reiqy/sudoku-solver | src/sudoku.h | //
// Created by Reiqy on 01.07.2021.
//
#ifndef SUDOKUSOLVER_SUDOKU_H
#define SUDOKUSOLVER_SUDOKU_H
#include <stdint.h>
#include <stdbool.h>
#define SUDOKU_SQUARE_SIZE (9)
#define SUDOKU_SMALL_SQUARE_SIZE (3)
#define SUDOKU_ARRAY_LENGTH (SUDOKU_SQUARE_SIZE * SUDOKU_SQUARE_SIZE)
typedef struct Sudoku
{
uint8_t *numbers;
} Sudoku;
void initSudoku(Sudoku *s);
void freeSudoku(Sudoku *s);
Sudoku readSudokuFromFile(const char *filename);
void printSudoku(Sudoku *s);
bool isSudokuBounded(const Sudoku *s);
bool isSudokuValid(const Sudoku *s);
bool isSudokuComplete(const Sudoku *s);
bool isSudokuSolved(const Sudoku *s);
void clearNumberSet(bool *set, size_t length);
void addNumberSet(bool *set, uint8_t number, size_t length);
bool isNumberPresent(bool *set, uint8_t number, size_t length);
#endif //SUDOKUSOLVER_SUDOKU_H
|
Reiqy/sudoku-solver | src/solver.c | //
// Created by Reiqy on 01.07.2021.
//
#include <stdio.h>
#include "solver.h"
#include "memory.h"
void initPossibleNumbers(PossibleNumbers *p_nums)
{
p_nums->count = 0;
}
void addPossibleNumber(PossibleNumbers *p_nums, uint8_t number)
{
p_nums->numbers[p_nums->count] = number;
p_nums->count++;
}
bool solveSudoku(Sudoku *s)
{
if (solveDeterministically(s, NULL) == false)
{
return solveNondeterministically(s);
}
return true;
}
bool solveDeterministically(Sudoku *s, PlacementPath *path)
{
bool is_solvable;
do
{
is_solvable = false;
PossibleNumbers possible_numbers[SUDOKU_ARRAY_LENGTH];
for (size_t i = 0; i < SUDOKU_SQUARE_SIZE; i++)
{
for (size_t j = 0; j < SUDOKU_SQUARE_SIZE; j++)
{
size_t current_element = i * SUDOKU_SQUARE_SIZE + j;
if (s->numbers[current_element] == 0)
{
initPossibleNumbers(&possible_numbers[current_element]);
findPossibleNumbers(s, &possible_numbers[current_element], j, i);
is_solvable = (possible_numbers[current_element].count == 1) || is_solvable;
if (possible_numbers[current_element].count == 1)
{
s->numbers[current_element] = possible_numbers[current_element].numbers[0];
if (path != NULL)
{
Placement p = {.pos_x = j, .pos_y = i, .number = possible_numbers[current_element].numbers[0]};
addPlacementPath(path, p);
}
}
}
}
}
} while (is_solvable);
return isSudokuComplete(s);
}
bool solveNondeterministically(Sudoku *s)
{
NondeterministicNode root;
initNondeterministicNode(&root, NULL);
NondeterministicNode *current = &root;
NodeManager manager;
initNodeManager(&manager);
Placement p;
while (true)
{
if (!findNextGuess(s, &p, current->attempts))
{
if (!revertSudoku(s, current))
{
return false;
}
// NondeterministicNode *old = current;
current = current->previous;
// freeNondeterministicNode(old);
continue;
}
current = getNondeterministicNode(&manager, current);
addPlacementPath(¤t->path, p);
s->numbers[p.pos_y * SUDOKU_SQUARE_SIZE + p.pos_x] = p.number;
if (solveDeterministically(s, ¤t->path))
{
freeNondeterministicNode(&root);
freeNodeManager(&manager);
return true;
}
}
}
void findPossibleNumbers(Sudoku *s, PossibleNumbers *p_nums, size_t pos_x, size_t pos_y)
{
// TODO: keep track of possible numbers to limit it while solving nondeterministically and achieve contradictions faster, also helps finding guesses faster
size_t square_origin_x = (pos_x / SUDOKU_SMALL_SQUARE_SIZE) * SUDOKU_SMALL_SQUARE_SIZE;
size_t square_origin_y = (pos_y / SUDOKU_SMALL_SQUARE_SIZE) * SUDOKU_SMALL_SQUARE_SIZE;
uint8_t checked_number;
bool impossible_numbers[SUDOKU_SQUARE_SIZE];
clearNumberSet(impossible_numbers, SUDOKU_SQUARE_SIZE);
for (size_t i = 0; i < SUDOKU_SQUARE_SIZE; i++)
{
checked_number = s->numbers[pos_y * SUDOKU_SQUARE_SIZE + i];
if (checked_number != 0)
{
addNumberSet(impossible_numbers, checked_number, SUDOKU_SQUARE_SIZE);
}
checked_number = s->numbers[i * SUDOKU_SQUARE_SIZE + pos_x];
if (checked_number != 0)
{
addNumberSet(impossible_numbers, checked_number, SUDOKU_SQUARE_SIZE);
}
size_t square_offset_x = i % SUDOKU_SMALL_SQUARE_SIZE;
size_t square_offset_y = i / SUDOKU_SMALL_SQUARE_SIZE;
size_t square_current_x = square_origin_x + square_offset_x;
size_t square_current_y = square_origin_y + square_offset_y;
checked_number = s->numbers[square_current_y * SUDOKU_SQUARE_SIZE + square_current_x];
if (checked_number != 0)
{
addNumberSet(impossible_numbers, checked_number, SUDOKU_SQUARE_SIZE);
}
}
for (size_t i = 0; i < SUDOKU_SQUARE_SIZE; i++)
{
if (!impossible_numbers[i])
{
addPossibleNumber(p_nums, i + 1);
}
}
}
void initPlacementPath(PlacementPath *path)
{
path->capacity = 0;
path->count = 0;
path->path = NULL;
}
void freePlacementPath(PlacementPath *path)
{
path->capacity = 0;
path->count = 0;
path->path = deallocate(path->path);
}
void addPlacementPath(PlacementPath *path, Placement p)
{
if (path->capacity < path->count + 1)
{
path->capacity = growCapacity(path->capacity);
path->path = reallocate(path->path, sizeof(Placement) * path->capacity);
}
path->path[path->count] = p;
path->count++;
}
void initNondeterministicNode(NondeterministicNode *node, NondeterministicNode *previous)
{
node->attempts = 0;
node->previous = previous;
initPlacementPath(&node->path);
}
void freeNondeterministicNode(NondeterministicNode *node)
{
node->previous = NULL;
freePlacementPath(&node->path);
}
bool findNextGuess(Sudoku *s, Placement *p, int attempt)
{
PossibleNumbers possible_numbers[SUDOKU_ARRAY_LENGTH];
for (size_t i = 0; i < SUDOKU_SQUARE_SIZE; i++)
{
for (size_t j = 0; j < SUDOKU_SQUARE_SIZE; j++)
{
size_t current_element = i * SUDOKU_SQUARE_SIZE + j;
initPossibleNumbers(&possible_numbers[current_element]);
if (s->numbers[current_element] == 0)
{
findPossibleNumbers(s, &possible_numbers[current_element], j, i);
}
else
{
possible_numbers[current_element].count = 0;
}
}
}
size_t current_max_entropy = 2;
while (current_max_entropy <= SUDOKU_SQUARE_SIZE)
{
for (size_t i = 0; i < SUDOKU_SQUARE_SIZE; i++)
{
for (size_t j = 0; j < SUDOKU_SQUARE_SIZE; j++)
{
size_t current_element = i * SUDOKU_SQUARE_SIZE + j;
if (possible_numbers[current_element].count == current_max_entropy)
{
if (attempt < possible_numbers[current_element].count)
{
p->pos_x = j;
p->pos_y = i;
p->number = possible_numbers[current_element].numbers[attempt];
return true;
}
else
{
attempt -= (int) possible_numbers[current_element].count;
}
}
}
}
current_max_entropy++;
}
return false;
}
bool revertSudoku(Sudoku *s, NondeterministicNode *node)
{
if (node->previous == NULL)
{
return false;
}
PlacementPath *path = &node->path;
for (size_t i = path->count; i > 0; i--)
{
Placement *revert = &path->path[i - 1];
s->numbers[revert->pos_y * SUDOKU_SQUARE_SIZE + revert->pos_x] = 0;
}
return true;
}
void initNodeManager(NodeManager *manager)
{
manager->capacity = 0;
manager->count = 0;
manager->nodes = NULL;
}
void freeNodeManager(NodeManager *manager)
{
for (size_t i = 0; i < manager->count; i++)
{
freeNondeterministicNode(manager->nodes[i]);
}
manager->capacity = 0;
manager->count = 0;
manager->nodes = deallocate(manager->nodes);
}
NondeterministicNode *getNondeterministicNode(NodeManager *manager, NondeterministicNode *from_node)
{
if (manager->capacity < manager->count + 1)
{
manager->capacity = growCapacity(manager->capacity);
manager->nodes = reallocate(manager->nodes, sizeof(NondeterministicNode *) * manager->capacity);
}
from_node->attempts++;
NondeterministicNode *new = allocate(sizeof(NondeterministicNode));
initNondeterministicNode(new, from_node);
manager->nodes[manager->count] = new;
manager->count++;
return new;
}
|
markrad/eps32-ADXL355 | components/ADXL355/include/ADXL355.h | <gh_stars>1-10
#ifndef _ADXL355_H
#define _ADXL355_H
#include <cstdint>
#include <string>
#include <driver/i2c.h>
class ADXL355
{
private:
static const uint8_t DEVID_AD = 0x00;
static const uint8_t DEVID_MST = 0x01;
static const uint8_t PARTID = 0x02;
static const uint8_t REVID = 0x03;
static const uint8_t STATUS = 0x04;
static const uint8_t FIFO_ENTRIES = 0x05;
static const uint8_t I2CSPEED_INTPOLARITY_RANGE = 0x2c;
static const uint8_t POWER_CTL = 0x2d;
static const uint8_t RESET = 0x2f;
static const uint8_t RESET_VALUE = 0x52;
static const uint8_t TEMP2 = 0x06;
static const uint8_t TEMP1 = 0x07;
static const uint8_t XDATA3 = 0x08;
static const uint8_t XDATA2 = 0x09;
static const uint8_t XDATA1 = 0x0a;
static const uint8_t YDATA3 = 0x0b;
static const uint8_t YDATA2 = 0x0c;
static const uint8_t YDATA1 = 0x0d;
static const uint8_t ZDATA3 = 0x0e;
static const uint8_t ZDATA2 = 0x0f;
static const uint8_t ZDATA1 = 0x10;
static const uint8_t FIFO_DATA = 0x11;
static const uint8_t OFFSET_X_H = 0x1e;
static const uint8_t OFFSET_X_L = 0x1f;
static const uint8_t OFFSET_Y_H = 0x20;
static const uint8_t OFFSET_Y_L = 0x21;
static const uint8_t OFFSET_Z_H = 0x22;
static const uint8_t OFFSET_Z_L = 0x23;
static const uint8_t FILTER = 0x28;
enum POWER_CTL_VALUES
{
POWER_CTL_OFF = 0x01,
POWER_CTL_ON = ~POWER_CTL_OFF,
POWER_CTL_TEMP_OFF = 0x02,
POWER_CTL_TEMP_ON = ~POWER_CTL_TEMP_OFF
};
enum I2C_SPEED_VALUES
{
I2C_SPEED_FAST = 0x80,
I2C_SPEED_SLOW = 0x00
};
uint8_t _deviceAddress;
gpio_num_t _sdaPin;
gpio_num_t _sclPin;
i2c_config_t _conf;
class I2CCmdHandle
{
private:
i2c_cmd_handle_t _cmd;
public:
I2CCmdHandle()
{
_cmd = i2c_cmd_link_create();
}
~I2CCmdHandle()
{
i2c_cmd_link_delete(_cmd);
}
i2c_cmd_handle_t GetCmd()
{
return _cmd;
}
};
public:
enum STATUS_VALUES
{
NVM_BUSY = 0x10,
ACTIVITY = 0x08,
FIFO_OVERRUN = 0x04,
FIFO_FULL = 0x02,
DATA_READY = 0x01
};
enum RANGE_VALUES
{
RANGE_2G = 0x01,
RANGE_4G = 0x02,
RANGE_8G = 0x03,
RANGE_MASK = 0x03
};
enum HPF_CORNER
{
DISABLED = 0b000,
ODR_X_247 = 0b001,
ODR_X_62_084 = 0b010,
ODR_X_15_545 = 0b011,
ODR_X_3_862 = 0b100,
ODR_X_0_954 = 0b101,
ODR_X_0_238 = 0b110,
HPF_CORNER_MASK = 0b01110000
};
enum ODR_LPF
{
ODR_4000_AND_1000 = 0b0000,
ODR_2000_AND_500 = 0b0001,
ODR_1000_AND_250 = 0b0010,
ODR_500_AND_125 = 0b0011,
ODR_250_AND_62_5 = 0b0100,
ODR_125_AND_31_25 = 0b0101,
ODR_62_5_AND_15_625 = 0b0110,
ODR_31_25_AND_7_813 = 0b0111,
ODR_15_625_AND_3_906 = 0b1000,
ODR_7_813_AND_1_953 = 0b1001,
ODR_3_906_AND_0_977 = 0b1010,
ODR_LPF_MASK = 0b1111
};
ADXL355(uint8_t deviceAddress, gpio_num_t sdaPin, gpio_num_t sclPin);
uint8_t GetAnalogDevicesID();
uint8_t GetAnalogDevicesMEMSID();
uint8_t GetDeviceId();
uint8_t GetRevision();
STATUS_VALUES GetStatus();
bool IsFifoFull();
bool IsFifoOverrun();
bool IsDataReady();
RANGE_VALUES GetRange();
int SetRange(RANGE_VALUES value);
HPF_CORNER GetHpfCorner();
int SetHpfCorner(HPF_CORNER value);
ODR_LPF GetOdrLpf();
int SetOdrLpf(ODR_LPF value);
int GetTrim(int32_t *x, int32_t *y, int32_t *z);
int SetTrim(int32_t x, int32_t y, int32_t z);
bool IsRunning();
bool IsTempSensorOn();
void Reset();
double GetTemperatureC();
double GetTemperatureF();
int Start();
int Stop();
int StartTempSensor();
int StopTempSensor();
int GetRawAxes(int32_t *x, int32_t *y, int32_t *z);
int GetFifoCount();
// Output must be 96 entries
int ReadFifoEntries(long *output);
static double ValueToGals(int32_t rawValue, int decimals = 3);
static int64_t ValueToGalsInt(int32_t rawValue, int decimals = 3);
private:
esp_err_t ReadByte(uint8_t reg, uint8_t *data);
esp_err_t WriteByte(uint8_t reg, uint8_t data);
esp_err_t ReadBytes(uint8_t reg, uint8_t *data, size_t length);
esp_err_t WriteBytes(uint8_t reg, uint8_t *data, size_t length);
static esp_err_t CheckEspRc(const std::string &message, esp_err_t rc);
static int32_t TwosCompliment(uint32_t value);
};
#endif // ifndef _ADXL355_H
|
functionpointer/Pico-DMX | src/DmxInput.h | <gh_stars>0
/*
* Copyright (c) 2021 <NAME>
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef DMX_INPUT_H
#define DMX_INPUT_H
#include <dma.h>
#include <pio.h>
#define DMX_UNIVERSE_SIZE 512
#define DMX_SM_FREQ 1000000
#define DMXINPUT_BUFFER_SIZE(start_channel, num_channels) ((start_channel+num_channels+1)+((4-(start_channel+num_channels+1)%4)%4))
class DmxInput
{
uint _pin;
int32_t _start_channel;
int32_t _num_channels;
public:
/*
private properties that are declared public so the interrupt handler has access
*/
volatile uint8_t *_buf;
volatile PIO _pio;
volatile uint _sm;
volatile uint _dma_chan;
volatile unsigned long _last_packet_timestamp=0;
/*
All different return codes for the DMX class. Only the SUCCESS
Return code guarantees that the DMX output instance was properly configured
and is ready to run
*/
enum return_code
{
SUCCESS = 0,
// There were no available state machines left in the
// pio instance.
ERR_NO_SM_AVAILABLE = -1,
// There is not enough program memory left in the PIO to fit
// The DMX PIO program
ERR_INSUFFICIENT_PRGM_MEM = -2,
ERR_INSUFFICIENT_SDRAM = -3,
};
/*
Starts a new DMX input instance.
Param: pin
Any valid GPIO pin on the Pico
Param: pio
defaults to pio0. pio0 can run up to 3
DMX input instances. If you really need more, you can
run 3 more on pio1
Param: ring_size
sets number of dmx channels to receive.
ring_size==2 -> channels 0 through 3
ring_size==3 -> channels 0 through 7
ring_size==4 -> channels 0 through 15
ring_size==5 -> channels 0 through 31
ring_size==6 -> channels 0 through 63
ring_size==7 -> channels 0 through 127
ring_size==8 -> channels 0 through 255
ring_size==9 -> channels 0 through 511
Note that channel 0 is not really useful and should always have the value 0.
*/
return_code begin(uint pin, uint start_channel, uint num_channels, PIO pio = pio0);
/*
Wait until a new DMX frame is received. The data may be fetched using get_channel()
*/
void read(volatile uint8_t *buffer);
/*
Start async read process. This should only be called once. From then on, the buffer will always contain the latest DMX data.
*/
void read_async(volatile uint8_t *buffer);
/*
Get the timestamp (like millis()) from the moment the latest dmx packet was received.
May be used to detect if the dmx signal has stopped coming in.
*/
unsigned long latest_packet_timestamp();
/*
De-inits the DMX input instance. Releases PIO resources.
The instance can safely be destroyed after this method is called
*/
void end();
};
#endif |
functionpointer/Pico-DMX | src/DmxOutput.pio.h | // -------------------------------------------------- //
// This file is autogenerated by pioasm; do not edit! //
// -------------------------------------------------- //
#if !PICO_NO_HARDWARE
#include "hardware/pio.h"
#endif
// --------- //
// DmxOutput //
// --------- //
#define DmxOutput_wrap_target 3
#define DmxOutput_wrap 6
static const uint16_t DmxOutput_program_instructions[] = {
0xf035, // 0: set x, 21 side 0
0x0741, // 1: jmp x--, 1 [7]
0xbf42, // 2: nop side 1 [7]
// .wrap_target
0x9fa0, // 3: pull block side 1 [7]
0xf327, // 4: set x, 7 side 0 [3]
0x6001, // 5: out pins, 1
0x0245, // 6: jmp x--, 5 [2]
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program DmxOutput_program = {
.instructions = DmxOutput_program_instructions,
.length = 7,
.origin = -1,
};
static inline pio_sm_config DmxOutput_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + DmxOutput_wrap_target, offset + DmxOutput_wrap);
sm_config_set_sideset(&c, 2, true, false);
return c;
}
#endif
|
riturajshakti/SuperEasyInAppPurchase | ios/Classes/SuperEasyInAppPurchasePlugin.h | <reponame>riturajshakti/SuperEasyInAppPurchase<filename>ios/Classes/SuperEasyInAppPurchasePlugin.h<gh_stars>1-10
#import <Flutter/Flutter.h>
@interface SuperEasyInAppPurchasePlugin : NSObject<FlutterPlugin>
@end
|
y-okudera/Tony | App/Sandbox/SandboxCore/Sources/Resources/SandboxCore.h | //
// SandboxCore.h
// SandboxCore
//
// Created by <NAME> on 2022/03/22.
// Copyright © 2022 yuoku. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for SandboxCore.
FOUNDATION_EXPORT double SandboxCoreVersionNumber;
//! Project version string for SandboxCore.
FOUNDATION_EXPORT const unsigned char SandboxCoreVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <SandboxCore/PublicHeader.h>
|
y-okudera/Tony | App/TonyCore/Sources/Resources/TonyCore.h | <reponame>y-okudera/Tony
//
// TonyCore.h
// TonyCore
//
// Created by <NAME> on 2022/03/13.
//
#import <Foundation/Foundation.h>
//! Project version number for TonyCore.
FOUNDATION_EXPORT double TonyCoreVersionNumber;
//! Project version string for TonyCore.
FOUNDATION_EXPORT const unsigned char TonyCoreVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <TonyCore/PublicHeader.h>
|
y-okudera/Tony | App/Feature/SplashFeatures/Sources/Resources/SplashFeatures.h | //
// SplashFeatures.h
// SplashFeatures
//
// Created by <NAME> on 2022/03/14.
//
#import <Foundation/Foundation.h>
//! Project version number for SplashFeatures.
FOUNDATION_EXPORT double SplashFeaturesVersionNumber;
//! Project version string for SplashFeatures.
FOUNDATION_EXPORT const unsigned char SplashFeaturesVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <SplashFeatures/PublicHeader.h>
|
y-okudera/Tony | App/SharedResource/SharedResource.h | //
// SharedResource.h
// SharedResource
//
// Created by <NAME> on 2022/03/24.
// Copyright © 2022 yuoku. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for SharedResource.
FOUNDATION_EXPORT double SharedResourceVersionNumber;
//! Project version string for SharedResource.
FOUNDATION_EXPORT const unsigned char SharedResourceVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <SharedResource/PublicHeader.h>
|
y-okudera/Tony | App/Feature/SearchRepoFeatures/Sources/Resources/SearchRepoFeatures.h | <reponame>y-okudera/Tony<filename>App/Feature/SearchRepoFeatures/Sources/Resources/SearchRepoFeatures.h
//
// SearchRepoFeatures.h
// SearchRepoFeatures
//
// Created by <NAME> on 2022/03/13.
//
#import <Foundation/Foundation.h>
//! Project version number for SearchRepoFeatures.
FOUNDATION_EXPORT double SearchRepoFeaturesVersionNumber;
//! Project version string for SearchRepoFeatures.
FOUNDATION_EXPORT const unsigned char SearchRepoFeaturesVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <SearchRepoFeatures/PublicHeader.h>
|
septimomend/The-Snake | The Snake/The Snake/stdafx.h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <ctime>
#include <cstdlib>
// Keys
//
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
#define ESC 27
#define E 69
#define R 82
#define Y 89
#define N 78 |
septimomend/The-Snake | The Snake/The Snake/The Snake Dec.h | // The Snake Dec.h >> func declaration
#include "stdafx.h"
void Setup();
void Draw();
void GameOver();
void Input();
void Logic(); |
septimomend/The-Snake | The Snake/The Snake/Global.h | <filename>The Snake/The Snake/Global.h
#ifndef GLOBAL_H
#define GLOBAL_H
#include "stdafx.h"
// Global variables
//
extern bool gameOver; // end of game
extern bool isHard; // true if difficulty of game is hard
extern bool escape; // true if exit from game
extern const int width; // width of game window
extern const int height; // height of game windo
// variables for coordinate of snake, snake's tail and food
//
extern int x, y;
extern int foodX, foodY;
extern int tailX[100], tailY[100];
extern int score; // score is added when snake eats food
extern int nTail; // global variable is initialized as 0 if there is no initialization
// nTail is a size of snake
// enum structure represents direction
//
enum snakeDirection
{
STOP = 0,
LEFT,
RIGHT,
UP,
DOWN
};
extern snakeDirection dir; // enum object
#endif // !GLOBAL_H
|
JPWatson/Aeron | aeron-client/src/main/cpp/command/Flyweight.h | <filename>aeron-client/src/main/cpp/command/Flyweight.h
/*
* Copyright 2014 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_COMMON_FLYWEIGHT__
#define INCLUDED_AERON_COMMON_FLYWEIGHT__
#include <string>
#include <concurrent/AtomicBuffer.h>
namespace aeron { namespace command {
template<typename struct_t>
class Flyweight
{
public:
Flyweight (concurrent::AtomicBuffer& buffer, util::index_t offset)
: m_struct(buffer.overlayStruct<struct_t>(offset)),
m_buffer(buffer), m_baseOffset(offset)
{
}
protected:
struct_t& m_struct;
inline std::string stringGet(util::index_t offset) const
{
return m_buffer.getStringUtf8(m_baseOffset + offset);
}
inline util::index_t stringGetLength(util::index_t offset) const
{
return m_buffer.getStringUtf8Length(m_baseOffset + offset);
}
inline util::index_t stringPut(util::index_t offset, const std::string& s)
{
return m_buffer.putStringUtf8(m_baseOffset + offset, s);
}
inline util::index_t stringPutWithoutLength(util::index_t offset, const std::string& s)
{
return m_buffer.putStringUtf8WithoutLength(m_baseOffset + offset, s);
}
inline std::string stringGetWithoutLength(util::index_t offset, std::int32_t size) const
{
return m_buffer.getStringUtf8WithoutLength(m_baseOffset + offset, size);
}
template <typename struct_t2>
inline struct_t2& overlayStruct (util::index_t offset)
{
return m_buffer.overlayStruct<struct_t2>(m_baseOffset + offset);
}
template <typename struct_t2>
inline const struct_t2& overlayStruct (util::index_t offset) const
{
return m_buffer.overlayStruct<struct_t2>(m_baseOffset + offset);
}
private:
concurrent::AtomicBuffer m_buffer;
util::index_t m_baseOffset;
};
}}
#endif |
JPWatson/Aeron | aeron-client/src/main/cpp/concurrent/ringbuffer/RecordDescriptor.h | <gh_stars>0
/*
* Copyright 2014 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_CONCURRENT_RINGBUFFER_RECORD_DESCRIPTOR__
#define INCLUDED_AERON_CONCURRENT_RINGBUFFER_RECORD_DESCRIPTOR__
#include <util/Index.h>
#include <util/StringUtil.h>
namespace aeron { namespace concurrent { namespace ringbuffer {
/**
* Header length made up of fields for message length, message type, and then the encoded message.
* <p>
* Writing of the record length signals the message recording is complete.
* <pre>
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |R| Record Length |
* +-+-------------------------------------------------------------+
* | Type |
* +---------------------------------------------------------------+
* | Encoded Message ...
* ... |
* +---------------------------------------------------------------+
* </pre>
*/
namespace RecordDescriptor {
static const util::index_t HEADER_LENGTH = sizeof(std::int32_t) * 2;
static const util::index_t ALIGNMENT = HEADER_LENGTH;
static const std::int32_t PADDING_MSG_TYPE_ID = -1;
inline static util::index_t lengthOffset(util::index_t recordOffset)
{
return recordOffset;
}
inline static util::index_t typeOffset(util::index_t recordOffset)
{
return recordOffset + sizeof(std::int32_t);
}
inline static util::index_t encodedMsgOffset(util::index_t recordOffset)
{
return recordOffset + HEADER_LENGTH;
}
inline static std::int64_t makeHeader(std::int32_t length, std::int32_t msgTypeId)
{
return (((std::int64_t)msgTypeId & 0xFFFFFFFF) << 32) | (length & 0xFFFFFFFF);
}
inline static std::int32_t recordLength(std::int64_t header)
{
return (std::int32_t)header;
}
inline static std::int32_t messageTypeId(std::int64_t header)
{
return (std::int32_t)(header >> 32);
}
inline static void checkMsgTypeId(std::int32_t msgTypeId)
{
if (msgTypeId < 1)
{
throw util::IllegalArgumentException(
util::strPrintf("Message type id must be greater than zero, msgTypeId=%d", msgTypeId), SOURCEINFO);
}
}
};
}}}
#endif
|
JPWatson/Aeron | aeron-driver/src/main/cpp/media/SendChannelEndpoint.h | /*
* Copyright 2015 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_DRIVER_MEDIA_SENDCHANNELENDPOINT__
#define INCLUDED_AERON_DRIVER_MEDIA_SENDCHANNELENDPOINT__
#include <protocol/DataHeaderFlyweight.h>
#include <protocol/StatusMessageFlyweight.h>
#include "UdpChannelTransport.h"
namespace aeron { namespace driver { namespace media {
using namespace aeron::protocol;
class SendChannelEndpoint : public UdpChannelTransport
{
public:
inline SendChannelEndpoint(std::unique_ptr<UdpChannel>&& channel)
: UdpChannelTransport(channel, &channel->remoteControl(), &channel->localControl(), &channel->remoteData()),
m_dataHeaderFlyweight(receiveBuffer(), 0),
m_smFlyweight(receiveBuffer(), 0)
{
}
private:
DataHeaderFlyweight m_dataHeaderFlyweight;
StatusMessageFlyweight m_smFlyweight;
};
}}}
#endif //INCLUDED_AERON_DRIVER_MEDIA_SENDCHANNELENDPOINT__
|
JPWatson/Aeron | aeron-driver/src/main/cpp/DriverConductorProxy.h | /*
* Copyright 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AERON_DRIVERCONDUCTORPROXY_H
#define AERON_DRIVERCONDUCTORPROXY_H
#include <cstdint>
#include <media/InetAddress.h>
#include <media/ReceiveChannelEndpoint.h>
namespace aeron { namespace driver {
using namespace aeron::driver::media;
class DriverConductorProxy
{
public:
DriverConductorProxy() {}
inline COND_MOCK_VIRTUAL void createPublicationImage(
std::int32_t sessionId,
std::int32_t streamId,
std::int32_t initialTermId,
std::int32_t activeTermId,
std::int32_t termOffset,
std::int32_t termLength,
std::int32_t mtuLength,
InetAddress& controlAddress,
InetAddress& srcAddress,
ReceiveChannelEndpoint& channelEndpoint)
{
}
};
}};
#endif //AERON_DRIVERCONDUCTORPROXY_H
|
JPWatson/Aeron | aeron-client/src/main/cpp/concurrent/AtomicCounter.h | /*
* Copyright 2014 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_CONCURRENT_ATOMIC_COUNTER__
#define INCLUDED_AERON_CONCURRENT_ATOMIC_COUNTER__
#include <cstdint>
#include <memory>
#include <util/Index.h>
#include "AtomicBuffer.h"
#include "CountersManager.h"
namespace aeron { namespace concurrent {
class AtomicCounter
{
public:
typedef std::shared_ptr<AtomicCounter> ptr_t;
AtomicCounter(const AtomicBuffer buffer, std::int32_t counterId, CountersManager& countersManager) :
m_buffer(buffer),
m_counterId(counterId),
m_countersManager(countersManager),
m_offset(CountersManager::counterOffset(counterId))
{
m_buffer.putInt64(m_offset, 0);
}
~AtomicCounter()
{
m_countersManager.free(m_counterId);
}
inline static AtomicCounter::ptr_t makeCounter(CountersManager& countersManager, std::string& label)
{
return std::make_shared<AtomicCounter>(countersManager.valuesBuffer(), countersManager.allocate(label), countersManager);
}
inline void increment()
{
m_buffer.getAndAddInt64(m_offset, 1);
}
inline void orderedIncrement()
{
m_buffer.addInt64Ordered(m_offset, 1);
}
inline void set(std::int64_t value)
{
m_buffer.putInt64Atomic(m_offset, value);
}
inline void setOrdered(long value)
{
m_buffer.putInt64Ordered(m_offset, value);
}
inline void addOrdered(long increment)
{
m_buffer.addInt64Ordered(m_offset, increment);
}
inline std::int64_t get()
{
return m_buffer.getInt64Volatile(m_offset);
}
private:
AtomicBuffer m_buffer;
std::int32_t m_counterId;
CountersManager& m_countersManager;
util::index_t m_offset;
};
}}
#endif
|
JPWatson/Aeron | aeron-driver/src/main/cpp/PublicationImage.h | <gh_stars>0
/*
* Copyright 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AERON_PUBLICATIONIMAGE_H
#define AERON_PUBLICATIONIMAGE_H
#include <cstdint>
#include <concurrent/AtomicBuffer.h>
#include <concurrent/status/ReadablePosition.h>
#include <concurrent/status/UnsafeBufferPosition.h>
#include <util/MacroUtil.h>
#include "buffer/MappedRawLog.h"
#include "media/InetAddress.h"
#include "FeedbackDelayGenerator.h"
namespace aeron { namespace driver {
typedef std::function<long()> nano_clock_t;
using namespace aeron::concurrent;
using namespace aeron::concurrent::status;
using namespace aeron::driver::buffer;
using namespace aeron::driver::media;
enum PublicationImageStatus
{
INIT, ACTIVE, INACTIVE, LINGER
};
class PublicationImage
{
public:
typedef std::shared_ptr<PublicationImage> ptr_t;
PublicationImage(
const int64_t correlationId,
const int64_t imageLivenessTimeoutNs,
const int32_t sessionId,
const int32_t streamId,
const int32_t initialTermId,
const int32_t activeTermId,
const int32_t initialTermOffset,
const int32_t initialWindowLength,
const int32_t currentGain,
std::unique_ptr<MappedRawLog> rawLog,
std::shared_ptr<InetAddress> sourceAddress,
std::shared_ptr<InetAddress> controlAddress,
std::shared_ptr<ReceiveChannelEndpoint> channelEndpoint,
std::unique_ptr<std::vector<ReadablePosition<UnsafeBufferPosition>>> subscriberPositions,
std::unique_ptr<Position<UnsafeBufferPosition>> hwmPosition,
FeedbackDelayGenerator& feedbackDelayGenerator,
nano_clock_t nanoClock
)
: m_correlationId(correlationId), m_imageLivenessTimeoutNs(imageLivenessTimeoutNs),
m_sessionId(sessionId), m_streamId(streamId), m_initialTermId(initialTermId),
m_currentGain(currentGain), m_rawLog(std::move(rawLog)),
m_sourceAddress(sourceAddress), m_controlAddress(controlAddress), m_channelEndpoint(channelEndpoint),
m_subscriberPositions(std::move(subscriberPositions)), m_hwmPosition(std::move(hwmPosition)),
m_nanoClock(nanoClock)
{
// TODO: uncomment when we figure out how to mock MappedRawLog and UnsafeBufferPosition
// std::int32_t termLength = m_rawLog->termLength();
//
// long time = m_nanoClock();
// m_timeOfLastStatusChange = time;
// m_lastPacketTimestamp = time;
//
// m_currentWindowLength = termLength < initialWindowLength ? termLength : initialWindowLength;
// m_currentGain = m_currentWindowLength / 4;
//
// m_termLengthMask = termLength - 1;
// m_positionBitsToShift = BitUtil::numberOfTrailingZeroes(termLength);
//
// std::int64_t initialPosition =
// LogBufferDescriptor::computePosition(activeTermId, initialTermOffset, m_positionBitsToShift, initialTermId);
//
// m_lastStatusMessagePosition = initialPosition - (currentGain - 1);
// m_newStatusMessagePosition = m_lastStatusMessagePosition;
// m_rebuildPosition = initialPosition;
// m_hwmPosition->setOrdered(initialPosition);
}
virtual ~PublicationImage(){}
inline COND_MOCK_VIRTUAL std::int32_t sessionId()
{
return 0;
}
inline COND_MOCK_VIRTUAL std::int32_t streamId()
{
return 0;
}
inline COND_MOCK_VIRTUAL std::int32_t insertPacket(
std::int32_t termId, std::int32_t termOffset, AtomicBuffer& buffer, std::int32_t length)
{
return 0;
}
inline COND_MOCK_VIRTUAL void ifActiveGoInactive()
{
}
inline COND_MOCK_VIRTUAL void status(PublicationImageStatus status)
{
atomic::putValueVolatile(&m_status, status);
}
private:
// -- Cache-line padding
std::int64_t m_timeOfLastStatusChange = 0;
std::int64_t m_rebuildPosition = 0;
volatile std::int64_t m_beginLossChange = -1;
volatile std::int64_t m_endLossChange = -1;
std::int32_t m_lossTermId = 0;
std::int32_t m_lossTermOffset = 0;
std::int32_t m_lossLength = 0;
// -- Cache-line padding
std::int64_t m_lastPacketTimestamp = 0;
std::int64_t m_lastStatusMessageTimestamp = 0;
std::int64_t m_lastStatusMessagePosition = 0;
std::int64_t m_lastChangeNumber = -1;
// -- Cache-line padding
volatile std::int64_t m_newStatusMessagePosition;
volatile PublicationImageStatus m_status = PublicationImageStatus::INIT;
// -- Cache-line padding
const std::int64_t m_correlationId;
const std::int64_t m_imageLivenessTimeoutNs;
const std::int32_t m_sessionId;
const std::int32_t m_streamId;
std::int32_t m_positionBitsToShift;
std::int32_t m_termLengthMask;
const std::int32_t m_initialTermId;
std::int32_t m_currentWindowLength;
std::int32_t m_currentGain;
std::unique_ptr<MappedRawLog> m_rawLog;
std::shared_ptr<InetAddress> m_sourceAddress;
std::shared_ptr<InetAddress> m_controlAddress;
std::shared_ptr<ReceiveChannelEndpoint> m_channelEndpoint;
std::unique_ptr<std::vector<ReadablePosition<UnsafeBufferPosition>>> m_subscriberPositions;
std::unique_ptr<Position<UnsafeBufferPosition>> m_hwmPosition;
nano_clock_t m_nanoClock;
};
}};
#endif //AERON_PUBLICATIONIMAGE_H
|
JPWatson/Aeron | aeron-driver/src/main/cpp/media/InterfaceLookup.h | /*
* Copyright 2015 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_DRIVER_MEDIA_INTERFACELOOKUP_
#define INCLUDED_AERON_DRIVER_MEDIA_INTERFACELOOKUP_
#include <functional>
#include <tuple>
#include "InetAddress.h"
namespace aeron { namespace driver { namespace media {
using IPv4Result = std::tuple<Inet4Address&, const char*, unsigned int, std::uint32_t, unsigned int>;
using IPv4LookupCallback = std::function<void(IPv4Result&)>;
using IPv6Result = std::tuple<Inet6Address&, const char*, unsigned int, std::uint32_t, unsigned int>;
using IPv6LookupCallback = std::function<void(IPv6Result&)>;
class InterfaceLookup
{
public:
virtual void lookupIPv4(IPv4LookupCallback func) const = 0;
virtual void lookupIPv6(IPv6LookupCallback func) const = 0;
};
class BsdInterfaceLookup : public InterfaceLookup
{
public:
BsdInterfaceLookup(){}
virtual void lookupIPv4(IPv4LookupCallback func) const;
virtual void lookupIPv6(IPv6LookupCallback func) const;
static BsdInterfaceLookup& get()
{
static BsdInterfaceLookup instance;
return instance;
}
};
}}}
#endif //AERON_INTERFACELOOKUP_H
|
JPWatson/Aeron | aeron-client/src/main/cpp/concurrent/logbuffer/DataFrameHeader.h | <gh_stars>0
/*
* Copyright 2015 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AERON_DATAFRAMEHEADER_H
#define AERON_DATAFRAMEHEADER_H
#include <stddef.h>
#include <util/Index.h>
namespace aeron { namespace concurrent { namespace logbuffer {
namespace DataFrameHeader {
#pragma pack(push)
#pragma pack(4)
struct DataFrameHeaderDefn
{
std::int32_t frameLength;
std::int8_t version;
std::int8_t flags;
std::uint16_t type;
std::int32_t termOffset;
std::int32_t sessionId;
std::int32_t streamId;
std::int32_t termId;
std::int64_t reservedValue;
};
#pragma pack(pop)
static const util::index_t FRAME_LENGTH_FIELD_OFFSET = offsetof(DataFrameHeaderDefn, frameLength);
static const util::index_t VERSION_FIELD_OFFSET = offsetof(DataFrameHeaderDefn, version);
static const util::index_t FLAGS_FIELD_OFFSET = offsetof(DataFrameHeaderDefn, flags);
static const util::index_t TYPE_FIELD_OFFSET = offsetof(DataFrameHeaderDefn, type);
static const util::index_t TERM_OFFSET_FIELD_OFFSET = offsetof(DataFrameHeaderDefn, termOffset);
static const util::index_t SESSION_ID_FIELD_OFFSET = offsetof(DataFrameHeaderDefn, sessionId);
static const util::index_t STREAM_ID_FIELD_OFFSET = offsetof(DataFrameHeaderDefn, streamId);
static const util::index_t TERM_ID_FIELD_OFFSET = offsetof(DataFrameHeaderDefn, termId);
static const util::index_t RESERVED_VALUE_FIELD_OFFSET = offsetof(DataFrameHeaderDefn, reservedValue);
static const util::index_t DATA_OFFSET = sizeof(DataFrameHeaderDefn);
static const util::index_t LENGTH = DATA_OFFSET;
static const std::uint16_t HDR_TYPE_PAD = 0x00;
static const std::uint16_t HDR_TYPE_DATA = 0x01;
static const std::uint16_t HDR_TYPE_NAK = 0x02;
static const std::uint16_t HDR_TYPE_SM = 0x03;
static const std::uint16_t HDR_TYPE_ERR = 0x04;
static const std::uint16_t HDR_TYPE_SETUP = 0x05;
static const std::uint16_t HDR_TYPE_EXT = 0xFFFF;
static const std::int8_t CURRENT_VERSION = 0x0;
}
}}}
#endif //AERON_DATAFRAMEHEADER_H
|
JPWatson/Aeron | aeron-driver/src/main/cpp/MediaDriver.h | /*
* Copyright 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_DRIVER_MEDIADRIVER_H_
#define INCLUDED_AERON_DRIVER_MEDIADRIVER_H_
#include <map>
#include <string>
namespace aeron { namespace driver {
class MediaDriver
{
public:
class Context
{
};
MediaDriver(std::map<std::string, std::string>& properties);
MediaDriver(std::string& propertiesFile);
~MediaDriver();
private:
std::map<std::string, std::string> m_properties;
};
}};
#endif //AERON_MEDIADRIVER_H
|
JPWatson/Aeron | aeron-driver/src/main/cpp/concurrent/OneToOneConcurrentArrayQueue.h | <reponame>JPWatson/Aeron
/*
* Copyright 2015 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_DRIVER_ONETOONECONCURRENTARRAYQUEUE_
#define INCLUDED_AERON_DRIVER_ONETOONECONCURRENTARRAYQUEUE_
#include <cstdint>
#include <util/BitUtil.h>
#include <concurrent/Atomic64.h>
#include <array>
#include <atomic>
namespace aeron { namespace driver { namespace concurrent {
using namespace aeron::util;
using namespace aeron::concurrent::atomic;
template<typename T>
class OneToOneConcurrentArrayQueue
{
public:
OneToOneConcurrentArrayQueue(std::int32_t requestedCapacity) :
m_head(0), m_tail(0), m_capacity(BitUtil::findNextPowerOfTwo(requestedCapacity))
{
m_mask = m_capacity - 1;
m_buffer = new volatile std::atomic<T*>[m_capacity];
for (int i = 0; i < m_capacity - 1; i++)
{
m_buffer[i].store(nullptr, std::memory_order_relaxed);
}
m_buffer[m_capacity - 1].store(nullptr, std::memory_order_relaxed);
}
~OneToOneConcurrentArrayQueue()
{
delete[] m_buffer;
}
inline bool offer(T* t)
{
if (nullptr == t)
{
return false;
}
std::int64_t currentTail = m_tail.load(std::memory_order_seq_cst);
volatile std::atomic<T*>* source = &m_buffer[currentTail];
volatile T* ptr = source->load(std::memory_order_seq_cst);
if (nullptr == ptr)
{
source->store(t, std::memory_order_acq_rel);
m_tail.store(currentTail + 1, std::memory_order_acq_rel);
return true;
}
return false;
}
inline T* poll()
{
std::int64_t currentHead = m_head.load(std::memory_order_seq_cst);
int index = (int) (currentHead & m_mask);
volatile std::atomic<T*>* source = &m_buffer[index];
volatile T* t = source->load(std::memory_order_seq_cst);
if (nullptr != t)
{
source->store(nullptr, std::memory_order_acq_rel);
m_head.store(currentHead + 1, std::memory_order_acq_rel);
}
return const_cast<T*>(t);
}
private:
volatile std::atomic<T*>* m_buffer;
std::atomic<std::int64_t> m_head;
std::atomic<std::int64_t> m_tail;
std::int64_t m_mask;
std::int32_t m_capacity;
};
}}};
#endif //AERON_ONETOONECONCURRENTARRAYQUEUE_H
|
JPWatson/Aeron | aeron-client/src/main/cpp/CncFileDescriptor.h | /*
* Copyright 2014 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_CNC_FILE_DESCRIPTOR__
#define INCLUDED_AERON_CNC_FILE_DESCRIPTOR__
#include <util/Index.h>
#include <concurrent/AtomicBuffer.h>
#include <util/MemoryMappedFile.h>
namespace aeron {
using namespace aeron::util;
using namespace aeron::concurrent;
/**
* Description of the command and control file used between driver and clients
*
* File Layout
* <pre>
* +----------------------------+
* | Aeron CnC Version |
* +----------------------------+
* | Meta Data |
* +----------------------------+
* | to-driver Buffer |
* +----------------------------+
* | to-clients Buffer |
* +----------------------------+
* | Counter Metadata Buffer |
* +----------------------------+
* | Counter Values Buffer |
* +----------------------------+
* | Error Log |
* +----------------------------+
* </pre>
*
* Meta Data Layout (CnC Version 4)
* <pre>
* +----------------------------+
* | to-driver buffer length |
* +----------------------------+
* | to-clients buffer length |
* +----------------------------+
* | metadata buffer length |
* +----------------------------+
* | values buffer length |
* +----------------------------+
* | Client Liveness Timeout |
* | |
* +----------------------------+
* | Error Log length |
* +----------------------------+
* </pre>
*/
namespace CncFileDescriptor {
static const std::string CNC_FILE = "cnc.dat";
static const std::int32_t CNC_VERSION = 4;
#pragma pack(push)
#pragma pack(4)
struct MetaDataDefn
{
std::int32_t cncVersion;
std::int32_t toDriverBufferLength;
std::int32_t toClientsBufferLength;
std::int32_t counterMetadataBufferLength;
std::int32_t counterValuesBufferLength;
std::int64_t clientLivenessTimeout;
std::int32_t errorLogBufferLength;
};
#pragma pack(pop)
static const size_t VERSION_AND_META_DATA_LENGTH = BitUtil::align(sizeof(MetaDataDefn), BitUtil::CACHE_LINE_LENGTH * 2);
inline static std::int32_t cncVersion(MemoryMappedFile::ptr_t cncFile)
{
AtomicBuffer metaDataBuffer(cncFile->getMemoryPtr(), cncFile->getMemorySize());
const MetaDataDefn& metaData = metaDataBuffer.overlayStruct<MetaDataDefn>(0);
return metaData.cncVersion;
}
inline static AtomicBuffer createToDriverBuffer(MemoryMappedFile::ptr_t cncFile)
{
AtomicBuffer metaDataBuffer(cncFile->getMemoryPtr(), cncFile->getMemorySize());
const MetaDataDefn& metaData = metaDataBuffer.overlayStruct<MetaDataDefn>(0);
return AtomicBuffer(cncFile->getMemoryPtr() + VERSION_AND_META_DATA_LENGTH, metaData.toDriverBufferLength);
}
inline static AtomicBuffer createToClientsBuffer(MemoryMappedFile::ptr_t cncFile)
{
AtomicBuffer metaDataBuffer(cncFile->getMemoryPtr(), cncFile->getMemorySize());
const MetaDataDefn& metaData = metaDataBuffer.overlayStruct<MetaDataDefn>(0);
std::uint8_t* basePtr = cncFile->getMemoryPtr() + VERSION_AND_META_DATA_LENGTH + metaData.toDriverBufferLength;
return AtomicBuffer(basePtr, metaData.toClientsBufferLength);
}
inline static AtomicBuffer createCounterMetadataBuffer(MemoryMappedFile::ptr_t cncFile)
{
AtomicBuffer metaDataBuffer(cncFile->getMemoryPtr(), cncFile->getMemorySize());
const MetaDataDefn& metaData = metaDataBuffer.overlayStruct<MetaDataDefn>(0);
std::uint8_t* basePtr =
cncFile->getMemoryPtr() +
VERSION_AND_META_DATA_LENGTH +
metaData.toDriverBufferLength +
metaData.toClientsBufferLength;
return AtomicBuffer(basePtr, metaData.counterMetadataBufferLength);
}
inline static AtomicBuffer createCounterValuesBuffer(MemoryMappedFile::ptr_t cncFile)
{
AtomicBuffer metaDataBuffer(cncFile->getMemoryPtr(), cncFile->getMemorySize());
const MetaDataDefn& metaData = metaDataBuffer.overlayStruct<MetaDataDefn>(0);
std::uint8_t* basePtr =
cncFile->getMemoryPtr() +
VERSION_AND_META_DATA_LENGTH +
metaData.toDriverBufferLength +
metaData.toClientsBufferLength +
metaData.counterMetadataBufferLength;
return AtomicBuffer(basePtr, metaData.counterValuesBufferLength);
}
inline static AtomicBuffer createErrorLogBuffer(MemoryMappedFile::ptr_t cncFile)
{
AtomicBuffer metaDataBuffer(cncFile->getMemoryPtr(), cncFile->getMemorySize());
const MetaDataDefn& metaData = metaDataBuffer.overlayStruct<MetaDataDefn>(0);
std::uint8_t* basePtr =
cncFile->getMemoryPtr() +
VERSION_AND_META_DATA_LENGTH +
metaData.toDriverBufferLength +
metaData.toClientsBufferLength +
metaData.counterMetadataBufferLength +
metaData.counterValuesBufferLength;
return AtomicBuffer(basePtr, metaData.errorLogBufferLength);
}
inline static std::int64_t clientLivenessTimeout(MemoryMappedFile::ptr_t cncFile)
{
AtomicBuffer metaDataBuffer(cncFile->getMemoryPtr(), cncFile->getMemorySize());
const MetaDataDefn& metaData = metaDataBuffer.overlayStruct<MetaDataDefn>(0);
return metaData.clientLivenessTimeout;
}
}
};
#endif |
JPWatson/Aeron | aeron-driver/src/main/cpp/status/SystemCounters.h | <filename>aeron-driver/src/main/cpp/status/SystemCounters.h
/*
* Copyright 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AERON_SYSTEMCOUNTERS_H
#define AERON_SYSTEMCOUNTERS_H
#include <concurrent/AtomicCounter.h>
#include <concurrent/CountersManager.h>
#include <util/Exceptions.h>
#include "SystemCounterDescriptor.h"
namespace aeron { namespace driver { namespace status {
using namespace aeron::concurrent;
class SystemCounters
{
public:
inline SystemCounters(CountersManager& counterManager)
{
std::int32_t i = 0;
for (auto descriptor : SystemCounterDescriptor::VALUES)
{
if (i != descriptor.id())
{
throw util::IllegalStateException(
util::strPrintf(
"Invalid descriptor id for '%s': supplied=%d, expected=%d",
descriptor.label(), descriptor.id(), i),
SOURCEINFO);
}
counts[i++] = descriptor.newCounter(counterManager);
}
}
virtual ~SystemCounters()
{
for (auto counter : counts)
{
delete counter;
}
}
inline AtomicCounter* get(SystemCounterDescriptor descriptor)
{
return counts[descriptor.id()];
}
private:
AtomicCounter* counts[SystemCounterDescriptor::VALUES_SIZE];
SystemCounters(const SystemCounters& srcMyClass);
SystemCounters& operator=(const SystemCounters& srcMyClass);};
}}};
#endif //AERON_SYSTEMCOUNTERS_H
|
JPWatson/Aeron | aeron-driver/src/main/cpp/media/NetworkInterface.h | //
// Created by <NAME> on 06/10/15.
//
#ifndef INCLUDED_AERON_DRIVER_NETWORKINTERFACE__
#define INCLUDED_AERON_DRIVER_NETWORKINTERFACE__
#include <memory>
#include "InetAddress.h"
namespace aeron { namespace driver { namespace media {
class NetworkInterface
{
public:
NetworkInterface(std::unique_ptr<InetAddress> address, const char* name, unsigned int index)
: m_address(std::move(address)), m_name(name), m_index(index)
{}
inline InetAddress& address() const
{
return *m_address;
}
inline const char* name() const
{
return m_name;
}
inline unsigned int index() const
{
return m_index;
}
void setAsMulticastInterface(int socketFd) const;
private:
std::unique_ptr<InetAddress> m_address;
const char* m_name;
unsigned int m_index;
};
}}}
#endif //AERON_NETWORKINTERFACE_H
|
JPWatson/Aeron | aeron-client/src/main/cpp/concurrent/status/UnsafeBufferPosition.h | <reponame>JPWatson/Aeron
/*
* Copyright 2015 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AERON_UNSAFEBUFFERPOSITION_H
#define AERON_UNSAFEBUFFERPOSITION_H
#include <concurrent/AtomicBuffer.h>
#include <concurrent/CountersManager.h>
#include "Position.h"
namespace aeron { namespace concurrent { namespace status {
class UnsafeBufferPosition
{
public:
UnsafeBufferPosition(AtomicBuffer& buffer, std::int32_t id) :
m_buffer(buffer),
m_id(id),
m_offset(CountersManager::counterOffset(id))
{
}
UnsafeBufferPosition(const UnsafeBufferPosition& position)
{
m_buffer.wrap(position.m_buffer);
m_id = position.m_id;
m_offset = position.m_offset;
}
UnsafeBufferPosition() :
m_id(-1),
m_offset(0)
{
}
inline void wrap(const UnsafeBufferPosition& position)
{
m_buffer.wrap(position.m_buffer);
m_id = position.m_id;
m_offset = position.m_offset;
}
inline std::int32_t id()
{
return m_id;
}
inline std::int64_t get()
{
return m_buffer.getInt64(m_offset);
}
inline std::int64_t getVolatile()
{
return m_buffer.getInt64Volatile(m_offset);
}
inline void set(std::int64_t value)
{
m_buffer.putInt64(m_offset, value);
}
inline void setOrdered(std::int64_t value)
{
m_buffer.putInt64Ordered(m_offset, value);
}
inline void close()
{
}
private:
AtomicBuffer m_buffer;
std::int32_t m_id;
std::int32_t m_offset;
};
}}}
#endif //AERON_UNSAFEBUFFERPOSITION_H
|
JPWatson/Aeron | aeron-driver/src/main/cpp/FeedbackDelayGenerator.h | <reponame>JPWatson/Aeron
/*
* Copyright 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AERON_FEEDBACKDELAYGENERATOR_H
#define AERON_FEEDBACKDELAYGENERATOR_H
namespace aeron { namespace driver {
class FeedbackDelayGenerator
{
public:
FeedbackDelayGenerator(bool feedbackImmediately) : m_feedbackImmediately(feedbackImmediately)
{}
virtual ~FeedbackDelayGenerator() = default;
/**
* Generate a new delay value
*
* @return delay value in nanoseconds
*/
virtual std::int64_t generateDelay() = 0;
/**
* Should feedback be immediately sent?
*
* @return whether feedback should be immediate or not
*/
bool shouldFeedbackImmediately()
{
return false;
}
private:
bool m_feedbackImmediately;
};
class StaticFeedbackDelayGenerator : public FeedbackDelayGenerator
{
public:
StaticFeedbackDelayGenerator(std::int64_t delay, bool feedbackImmediately)
: FeedbackDelayGenerator(feedbackImmediately), m_delay(delay)
{
}
virtual std::int64_t generateDelay() override
{
return m_delay;
}
private:
std::int64_t m_delay;
};
}}
#endif //AERON_FEEDBACKDELAYGENERATOR_H
|
JPWatson/Aeron | aeron-driver/src/main/cpp/media/UdpChannelTransport.h | /*
* Copyright 2015 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_DRIVER_UDPCHANNELTRANSPORT__
#define INCLUDED_AERON_DRIVER_UDPCHANNELTRANSPORT__
#include <protocol/HeaderFlyweight.h>
#include <concurrent/AtomicBuffer.h>
#include <concurrent/logbuffer/FrameDescriptor.h>
#include <unistd.h>
#include "UdpChannel.h"
namespace aeron { namespace driver { namespace media {
using namespace aeron::concurrent;
using namespace aeron::concurrent::logbuffer;
using namespace aeron::protocol;
class UdpChannelTransport
{
public:
UdpChannelTransport(
std::unique_ptr<UdpChannel>& channel,
InetAddress* endPointAddress,
InetAddress* bindAddress,
InetAddress* connectAddress)
: m_channel(std::move(channel)),
m_endPointAddress(endPointAddress),
m_bindAddress(bindAddress),
m_connectAddress(connectAddress),
m_sendSocketFd(0),
m_receiveBuffer(m_receiveBufferBytes, m_receiveBufferLength)
{
m_receiveBuffer.setMemory(0, m_receiveBuffer.capacity(), 0);
}
virtual ~UdpChannelTransport()
{
if (0 != m_sendSocketFd)
{
close(m_sendSocketFd);
}
}
inline void output(std::ostream& out) const
{
out << "Channel: " << *m_channel <<
", endPoint: " << *m_endPointAddress <<
", bind: " << *m_bindAddress <<
", connect: ";
if (nullptr != m_connectAddress)
{
out << *m_connectAddress;
}
else
{
out << "N/A";
}
}
void openDatagramChannel();
void send(const void* data, const int32_t len);
std::int32_t recv(char* data, const int32_t len);
void setTimeout(timeval timeout);
InetAddress* receive(int32_t* pInt);
bool isMulticast();
UdpChannel& udpChannel();
protected:
inline AtomicBuffer& receiveBuffer()
{
return m_receiveBuffer;
}
inline bool isValidFrame(AtomicBuffer& buffer, std::int32_t length)
{
bool isValid = true;
if (FrameDescriptor::frameVersion(buffer, 0) != HeaderFlyweight::CURRENT_VERSION)
{
isValid = false;
}
else if (length < HeaderFlyweight::headerLength())
{
isValid = false;
}
return isValid;
}
private:
static const int m_receiveBufferLength = 4096;
std::unique_ptr <UdpChannel> m_channel;
InetAddress* m_endPointAddress;
InetAddress* m_bindAddress;
InetAddress* m_connectAddress;
int m_sendSocketFd;
int m_recvSocketFd;
std::uint8_t m_receiveBufferBytes[m_receiveBufferLength];
AtomicBuffer m_receiveBuffer;
};
inline std::ostream& operator<<(std::ostream& os, const UdpChannelTransport& dt)
{
dt.output(os);
return os;
}
}}}
#endif //AERON_UDPCHANNELTRANSPORT_H
|
JPWatson/Aeron | aeron-driver/src/main/cpp/DataPacketDispatcher.h | <reponame>JPWatson/Aeron<gh_stars>0
/*
* Copyright 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_DRIVER_DATAPACKETDISPATCHER__
#define INCLUDED_AERON_DRIVER_DATAPACKETDISPATCHER__
#include <unordered_map>
#include <utility>
#include <media/ReceiveChannelEndpoint.h>
#include <util/Exceptions.h>
#include <util/StringUtil.h>
#include "PublicationImage.h"
#include "Receiver.h"
#include "DriverConductorProxy.h"
namespace aeron { namespace driver {
using namespace aeron::concurrent;
using namespace aeron::driver;
using namespace aeron::driver::media;
using namespace aeron::protocol;
using namespace aeron::util;
enum SessionStatus
{
PENDING_SETUP_FRAME,
INIT_IN_PROGRESS,
ON_COOL_DOWN,
};
struct Hasher
{
std::size_t operator()(const std::pair<int, int>& val) const
{
std::hash<std::int32_t> hasher;
return 0x9e3779b9 + hasher(val.first) + hasher(val.second);
}
};
static inline bool isNotAlreadyInProgressOrOnCoolDown(
std::unordered_map<std::pair<std::int32_t, std::int32_t>, SessionStatus, Hasher>& ignoredSessions,
std::int32_t sessionId,
std::int32_t streamId)
{
auto ignoredSession = ignoredSessions.find({sessionId, streamId});
return ignoredSession == ignoredSessions.end() ||
(ignoredSession->second != INIT_IN_PROGRESS && ignoredSession->second != ON_COOL_DOWN);
}
class DataPacketDispatcher
{
public:
typedef std::unordered_map<std::pair<std::int32_t, std::int32_t>, SessionStatus, Hasher> ignored_sessions_t;
DataPacketDispatcher(
std::shared_ptr<DriverConductorProxy> driverConductorProxy,
std::shared_ptr<Receiver> receiver) :
m_receiver(std::move(receiver)),
m_driverConductorProxy(std::move(driverConductorProxy))
{}
inline std::int32_t onDataPacket(
ReceiveChannelEndpoint& channelEndpoint,
DataHeaderFlyweight& header,
AtomicBuffer& atomicBuffer,
const std::int32_t length,
InetAddress& srcAddress)
{
std::int32_t streamId = header.streamId();
if (m_sessionsByStreamId.find(streamId) != m_sessionsByStreamId.end())
{
std::unordered_map<int32_t, PublicationImage::ptr_t> &sessions = m_sessionsByStreamId[streamId];
std::int32_t sessionId = header.sessionId();
auto sessionItr = sessions.find(sessionId);
if (sessionItr != sessions.end())
{
std::int32_t termId = header.termId();
return sessionItr->second->insertPacket(termId, header.termOffset(), atomicBuffer, length);
}
else if (m_ignoredSessions.find({sessionId, streamId}) == m_ignoredSessions.end())
{
InetAddress& controlAddress =
channelEndpoint.isMulticast() ? channelEndpoint.udpChannel().remoteControl() : srcAddress;
m_ignoredSessions[{sessionId, streamId}] = PENDING_SETUP_FRAME;
channelEndpoint.sendSetupElicitingStatusMessage(controlAddress, sessionId, streamId);
m_receiver->addPendingSetupMessage(sessionId, streamId, channelEndpoint);
}
}
return 0;
}
inline void onSetupMessage(
ReceiveChannelEndpoint& channelEndpoint,
SetupFlyweight& header,
AtomicBuffer& atomicBuffer,
InetAddress& srcAddress)
{
std::int32_t streamId = header.streamId();
auto sessions = m_sessionsByStreamId.find(streamId);
if (sessions != m_sessionsByStreamId.end())
{
std::int32_t sessionId = header.sessionId();
std::int32_t initialTermId = header.initialTermId();
std::int32_t activeTermId = header.actionTermId();
auto session = sessions->second.find(sessionId);
if (session == sessions->second.end() &&
isNotAlreadyInProgressOrOnCoolDown(m_ignoredSessions, sessionId, streamId))
{
InetAddress& controlAddress =
channelEndpoint.isMulticast() ? channelEndpoint.udpChannel().remoteControl() : srcAddress;
m_ignoredSessions[{sessionId, streamId}] = INIT_IN_PROGRESS;
m_driverConductorProxy->createPublicationImage(
sessionId,
streamId,
initialTermId,
activeTermId,
header.termOffset(),
header.termLength(),
header.mtu(),
controlAddress,
srcAddress,
channelEndpoint
);
}
}
}
void removePendingSetup(std::int32_t sessionId, std::int32_t streamId);
inline void addSubscription(std::int32_t streamId)
{
if (m_sessionsByStreamId.find(streamId) == m_sessionsByStreamId.end())
{
std::unordered_map<std::int32_t,PublicationImage::ptr_t> session;
m_sessionsByStreamId.emplace(std::make_pair(streamId, session));
}
}
inline void removeSubscription(std::int32_t streamId)
{
auto sessionsItr = m_sessionsByStreamId.find(streamId);
if (sessionsItr == m_sessionsByStreamId.end())
{
throw UnknownSubscriptionException(
strPrintf("No subscription registered on stream %d", streamId), SOURCEINFO);
}
auto allSessionForStream = sessionsItr->second;
for (auto it = allSessionForStream.begin(); it != allSessionForStream.end(); ++it)
{
it->second->ifActiveGoInactive();
}
}
inline void addPublicationImage(PublicationImage::ptr_t image)
{
std::int32_t streamId = image->streamId();
std::int32_t sessionId = image->sessionId();
auto sessionsItr = m_sessionsByStreamId.find(streamId);
if (sessionsItr == m_sessionsByStreamId.end())
{
throw UnknownSubscriptionException(
strPrintf("No subscription registered on stream %d", streamId), SOURCEINFO);
}
sessionsItr->second[sessionId] = image;
m_ignoredSessions.erase({sessionId, streamId});
image->status(PublicationImageStatus::ACTIVE);
}
inline void removePublicationImage(PublicationImage::ptr_t image)
{
std::int32_t streamId = image->streamId();
std::int32_t sessionId = image->sessionId();
auto sessionsItr = m_sessionsByStreamId.find(streamId);
if (sessionsItr != m_sessionsByStreamId.end())
{
sessionsItr->second.erase(sessionId);
m_ignoredSessions.erase({sessionId, streamId});
}
image->ifActiveGoInactive();
m_ignoredSessions[{sessionId, streamId}] = ON_COOL_DOWN;
}
void removeCoolDown(std::int32_t sessionId, std::int32_t streamId);
private:
std::shared_ptr<Receiver> m_receiver;
std::shared_ptr<DriverConductorProxy> m_driverConductorProxy;
std::unordered_map<std::pair<std::int32_t, std::int32_t>, SessionStatus, Hasher> m_ignoredSessions;
std::unordered_map<std::int32_t,std::unordered_map<std::int32_t, PublicationImage::ptr_t>> m_sessionsByStreamId;
};
}}
#endif //AERON_DATAPACKETDISPATCHER_H
|
JPWatson/Aeron | aeron-client/src/main/cpp/concurrent/logbuffer/LogBufferPartition.h | <filename>aeron-client/src/main/cpp/concurrent/logbuffer/LogBufferPartition.h<gh_stars>0
/*
* Copyright 2014 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_CONCURRENT_LOGBUFFER_LOG_BUFFER__
#define INCLUDED_AERON_CONCURRENT_LOGBUFFER_LOG_BUFFER__
#include <algorithm>
#include <util/Index.h>
#include <concurrent/AtomicBuffer.h>
#include "LogBufferDescriptor.h"
namespace aeron { namespace concurrent { namespace logbuffer {
class LogBufferPartition
{
public:
inline LogBufferPartition(AtomicBuffer& termBuffer, AtomicBuffer& metaDataBuffer)
{
LogBufferDescriptor::checkTermLength(termBuffer.capacity());
LogBufferDescriptor::checkMetaDataBuffer(metaDataBuffer);
m_termBuffer.wrap(termBuffer);
m_metaDataBuffer.wrap(metaDataBuffer);
}
inline LogBufferPartition()
{
}
inline void wrap(AtomicBuffer&& termBuffer, AtomicBuffer&& metaDataBuffer)
{
LogBufferDescriptor::checkTermLength(termBuffer.capacity());
LogBufferDescriptor::checkMetaDataBuffer(metaDataBuffer);
m_termBuffer.wrap(termBuffer);
m_metaDataBuffer.wrap(metaDataBuffer);
}
inline AtomicBuffer& termBuffer()
{
return m_termBuffer;
}
inline AtomicBuffer& metaDataBuffer()
{
return m_metaDataBuffer;
}
inline void clean()
{
m_termBuffer.setMemory(0, m_termBuffer.capacity(), 0);
m_metaDataBuffer.setMemory(0, m_metaDataBuffer.capacity(), 0);
statusOrdered(LogBufferDescriptor::CLEAN);
}
inline int status() const
{
return m_metaDataBuffer.getInt32Volatile(LogBufferDescriptor::TERM_STATUS_OFFSET);
}
inline void statusOrdered(std::int32_t status)
{
m_metaDataBuffer.putInt32Ordered(LogBufferDescriptor::TERM_STATUS_OFFSET, status);
}
inline std::int32_t tailVolatile()
{
return std::min(m_metaDataBuffer.getInt32Volatile(LogBufferDescriptor::TERM_TAIL_COUNTER_OFFSET),
m_termBuffer.capacity());
}
inline std::int32_t rawTailVolatile()
{
return m_metaDataBuffer.getInt32Volatile(LogBufferDescriptor::TERM_TAIL_COUNTER_OFFSET);
}
inline std::int32_t tail()
{
return std::min(m_metaDataBuffer.getInt32(LogBufferDescriptor::TERM_TAIL_COUNTER_OFFSET),
m_termBuffer.capacity());
}
private:
AtomicBuffer m_termBuffer;
AtomicBuffer m_metaDataBuffer;
};
}}}
#endif
|
JPWatson/Aeron | aeron-client/src/main/cpp/concurrent/CountersManager.h | /*
* Copyright 2014 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_CONCURRENT_COUNTERS_MANAGER__
#define INCLUDED_AERON_CONCURRENT_COUNTERS_MANAGER__
#include <functional>
#include <cstdint>
#include <deque>
#include <memory>
#include <iostream>
#include <util/Exceptions.h>
#include <util/StringUtil.h>
#include <util/Index.h>
#include <util/BitUtil.h>
#include "AtomicBuffer.h"
#include "CountersReader.h"
namespace aeron { namespace concurrent {
class CountersManager : public CountersReader
{
public:
inline CountersManager(const AtomicBuffer& metadataBuffer, const AtomicBuffer& valuesBuffer) :
CountersReader(metadataBuffer, valuesBuffer)
{
}
std::int32_t allocate(
const std::string& label,
std::int32_t typeId,
const std::function<void(AtomicBuffer&)>& keyFunc)
{
std::int32_t counterId = nextCounterId();
if (label.length() > MAX_LABEL_LENGTH)
{
throw util::IllegalArgumentException("Label too long", SOURCEINFO);
}
if ((counterOffset(counterId) + COUNTER_LENGTH) > m_valuesBuffer.capacity())
{
throw util::IllegalArgumentException("Unable to allocated counter, values buffer is full", SOURCEINFO);
}
const util::index_t recordOffset = metadataOffset(counterId);
if ((recordOffset + METADATA_LENGTH) > m_metadataBuffer.capacity())
{
throw util::IllegalArgumentException("Unable to allocate counter, metadata buffer is full", SOURCEINFO);
}
CounterMetaDataDefn& record =
m_metadataBuffer.overlayStruct<CounterMetaDataDefn>(recordOffset);
record.typeId = typeId;
AtomicBuffer keyBuffer(m_metadataBuffer.buffer() + recordOffset + KEY_OFFSET, sizeof(CounterMetaDataDefn::key));
keyFunc(keyBuffer);
m_metadataBuffer.putStringUtf8(recordOffset + LABEL_LENGTH_OFFSET, label);
m_metadataBuffer.putInt32Ordered(recordOffset, RECORD_ALLOCATED);
return counterId;
}
inline std::int32_t allocate(const std::string& label)
{
return allocate(label, 0, [](AtomicBuffer&) { });
}
inline void free(std::int32_t counterId)
{
m_metadataBuffer.putInt32Ordered(counterOffset(counterId), RECORD_RECLAIMED);
m_freeList.push_back(counterId);
}
inline void setCounterValue(std::int32_t counterId, std::int64_t value)
{
m_valuesBuffer.putInt64Ordered(counterOffset(counterId), value);
}
private:
util::index_t m_highwaterMark = 0;
std::deque<std::int32_t> m_freeList;
inline std::int32_t nextCounterId()
{
if (m_freeList.empty())
{
return m_highwaterMark++;
}
std::int32_t id = m_freeList.front();
m_freeList.pop_front();
m_valuesBuffer.putInt64Ordered(counterOffset(id), 0L);
return id;
}
};
}}
#endif |
JPWatson/Aeron | aeron-driver/src/test/cpp/Mocks.h | #ifndef INCLUDED_AERON_DRIVER_MOCKS__
#define INCLUDED_AERON_DRIVER_MOCKS__
#define COND_MOCK 1
#include <gmock/gmock.h>
#include <media/ReceiveChannelEndpoint.h>
#include <PublicationImage.h>
#include <Receiver.h>
#include <DriverConductorProxy.h>
#include <FeedbackDelayGenerator.h>
namespace aeron { namespace driver { namespace media {
class MockReceiveChannelEndpoint : public ReceiveChannelEndpoint
{
public:
MockReceiveChannelEndpoint(std::unique_ptr<UdpChannel>&& channel) : ReceiveChannelEndpoint(std::move(channel))
{ }
virtual ~MockReceiveChannelEndpoint() = default;
MOCK_METHOD0(pollForData, std::int32_t());
MOCK_METHOD3(sendSetupElicitingStatusMessage, void(InetAddress &address, std::int32_t sessionId, std::int32_t streamId));
};
}}};
namespace aeron { namespace driver {
class MockPublicationImage : public PublicationImage
{
public:
MockPublicationImage() : PublicationImage(
0, 0, 0, 0, 0, 0, 0, 0, 0,
std::unique_ptr<MappedRawLog>(nullptr),
std::shared_ptr<InetAddress>(nullptr),
std::shared_ptr<InetAddress>(nullptr),
std::shared_ptr<ReceiveChannelEndpoint>(nullptr),
std::unique_ptr<std::vector<ReadablePosition<UnsafeBufferPosition>>>(nullptr),
std::unique_ptr<Position<UnsafeBufferPosition>>(nullptr),
m_delayGenerator,
mockCurrentTime
){}
virtual ~MockPublicationImage() = default;
MOCK_METHOD0(sessionId, std::int32_t());
MOCK_METHOD0(streamId, std::int32_t());
MOCK_METHOD4(insertPacket, std::int32_t(std::int32_t termId, std::int32_t termOffset, AtomicBuffer& buffer, std::int32_t length));
MOCK_METHOD0(ifActiveGoInactive, void());
MOCK_METHOD1(status, void(PublicationImageStatus status));
static long mockCurrentTime()
{
return 0;
}
private:
StaticFeedbackDelayGenerator m_delayGenerator{0, true};
};
class MockReceiver : public Receiver
{
public:
MockReceiver() : Receiver()
{}
virtual ~MockReceiver() = default;
MOCK_METHOD3(addPendingSetupMessage, void(std::int32_t sessionId, std::int32_t streamId, ReceiveChannelEndpoint& receiveChannelEndpoint));
};
class MockDriverConductorProxy : public DriverConductorProxy
{
public:
MOCK_METHOD10(createPublicationImage, void(std::int32_t sessionId, std::int32_t streamId, std::int32_t initialTermId, std::int32_t activeTermId, std::int32_t termOffset, std::int32_t termLength, std::int32_t mtuLength, InetAddress& controlAddress, InetAddress& srcAddress, ReceiveChannelEndpoint& channelEndpoint));
};
}};
#endif |
JPWatson/Aeron | aeron-client/src/main/cpp/command/ImageMessageFlyweight.h | /*
* Copyright 2014 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_COMMAND_CONNECTIONMESSAGEFLYWEIGHT__
#define INCLUDED_AERON_COMMAND_CONNECTIONMESSAGEFLYWEIGHT__
#include <cstdint>
#include <stddef.h>
#include "Flyweight.h"
namespace aeron { namespace command {
/**
* Control message flyweight for any message that needs to represent an image
*
* <p>
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Correlation ID |
* | |
* +---------------------------------------------------------------+
* | Stream ID |
* +---------------------------------------------------------------+
* | Channel Length |
* +---------------------------------------------------------------+
* | Channel ...
* ... |
* +---------------------------------------------------------------+
*/
#pragma pack(push)
#pragma pack(4)
struct ImageMessageDefn
{
std::int64_t correlationId;
std::int32_t streamId;
struct
{
std::int32_t channelLength;
std::int8_t channelData[1];
} channel;
};
#pragma pack(pop)
class ImageMessageFlyweight : public Flyweight<ImageMessageDefn>
{
public:
typedef ImageMessageFlyweight this_t;
inline ImageMessageFlyweight(concurrent::AtomicBuffer& buffer, util::index_t offset) :
Flyweight<ImageMessageDefn>(buffer, offset)
{
}
inline std::int64_t correlationId() const
{
return m_struct.correlationId;
}
inline this_t& correlationId(std::int64_t value)
{
m_struct.correlationId = value;
return *this;
}
inline std::int32_t streamId() const
{
return m_struct.streamId;
}
inline this_t& streamId(std::int32_t value)
{
m_struct.streamId = value;
return *this;
}
inline std::string channel() const
{
return stringGet(offsetof(ImageMessageDefn, channel));
}
inline this_t& channel(const std::string& value)
{
stringPut(offsetof(ImageMessageDefn, channel), value);
return *this;
}
inline std::int32_t length() const
{
return offsetof(ImageMessageDefn, channel.channelData) + m_struct.channel.channelLength;
}
};
}}
#endif |
JPWatson/Aeron | aeron-client/src/main/cpp/command/CorrelatedMessageFlyweight.h | /*
* Copyright 2014 - 2016 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_AERON_COMMAND_CORRELATEDMESSAGEFLYWEIGHT__
#define INCLUDED_AERON_COMMAND_CORRELATEDMESSAGEFLYWEIGHT__
#include <cstdint>
#include <stddef.h>
#include "Flyweight.h"
namespace aeron { namespace command {
/**
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Client ID |
* | |
* +---------------------------------------------------------------+
* | Correlation ID |
* | |
* +---------------------------------------------------------------+
*/
#pragma pack(push)
#pragma pack(4)
struct CorrelatedMessageDefn
{
std::int64_t clientId;
std::int64_t correlationId;
};
#pragma pack(pop)
static const util::index_t CORRELATED_MESSAGE_LENGTH = sizeof(struct CorrelatedMessageDefn);
class CorrelatedMessageFlyweight : public Flyweight<CorrelatedMessageDefn>
{
public:
typedef CorrelatedMessageFlyweight this_t;
inline CorrelatedMessageFlyweight (concurrent::AtomicBuffer& buffer, util::index_t offset)
: Flyweight<CorrelatedMessageDefn>(buffer, offset)
{
}
inline std::int64_t correlationId() const
{
return m_struct.correlationId;
}
inline this_t& correlationId(std::int64_t value)
{
m_struct.correlationId = value;
return *this;
}
inline std::int64_t clientId() const
{
return m_struct.clientId;
}
inline this_t& clientId(std::int64_t value)
{
m_struct.clientId = value;
return *this;
}
};
}};
#endif |
JPWatson/Aeron | aeron-client/src/main/cpp/concurrent/logbuffer/TermScanner.h | <filename>aeron-client/src/main/cpp/concurrent/logbuffer/TermScanner.h
//
// Created by <NAME> on 25/09/15.
//
#ifndef INCLUDED_AERON_CONCURRENT_LOGBUFFER_TERMSCANNER__
#define INCLUDED_AERON_CONCURRENT_LOGBUFFER_TERMSCANNER__
#include <util/BitUtil.h>
#include "FrameDescriptor.h"
namespace aeron { namespace concurrent { namespace logbuffer
{
namespace TermScanner
{
inline std::int64_t scanOutcome(std::int32_t padding, std::int32_t available)
{
return ((std::int64_t) padding) << 32 | available;
}
inline std::int32_t available(std::int64_t scanOutcome)
{
return (std::int32_t) scanOutcome;
}
inline std::int32_t padding(std::int64_t scanOutcome)
{
return (std::int32_t) (scanOutcome >> 32);
}
inline std::int64_t scanForAvailability(AtomicBuffer& termBuffer, std::int32_t offset, std::int32_t maxLength)
{
// maxLength = Math.min(maxLength, termBuffer.capacity() - offset);
// int available = 0;
// int padding = 0;
maxLength = std::min(maxLength, termBuffer.capacity() - offset);
std::int32_t available = 0;
std::int32_t padding = 0;
// do
// {
// final int frameOffset = offset + available;
// final int frameLength = frameLengthVolatile(termBuffer, frameOffset);
// if (frameLength <= 0)
// {
// break;
// }
//
// int alignedFrameLength = align(frameLength, FRAME_ALIGNMENT);
// if (isPaddingFrame(termBuffer, frameOffset))
// {
// padding = alignedFrameLength - HEADER_LENGTH;
// alignedFrameLength = HEADER_LENGTH;
// }
//
// available += alignedFrameLength;
//
// if (available > maxLength)
// {
// available -= alignedFrameLength;
// padding = 0;
// break;
// }
// }
// while ((available + padding) < maxLength);
//
// return scanOutcome(padding, available);
do
{
const util::index_t frameOffset = offset + available;
const util::index_t frameLength = FrameDescriptor::frameLengthVolatile(termBuffer, frameOffset);
if (frameLength <= 0)
{
break;
}
util::index_t alignedFrameLength = util::BitUtil::align(frameLength, FrameDescriptor::FRAME_ALIGNMENT);
if (FrameDescriptor::isPaddingFrame(termBuffer, frameOffset))
{
padding = alignedFrameLength - DataFrameHeader::LENGTH;
alignedFrameLength = DataFrameHeader::LENGTH;
}
available += alignedFrameLength;
if (available > maxLength)
{
available -= alignedFrameLength;
padding = 0;
break;
}
}
while ((available + padding) < maxLength);
return scanOutcome(padding, available);
}
}
}}};
#endif //AERON_TERMSCANNER_H
|
lojikil/29 | src/carmlc.c | <reponame>lojikil/29
/*
* @(#) the main carml/C compiler source code
* @(#) defines the REPL, some compiler stuff, and
* @(#) coördinates the general flow of the system
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <gc.h>
#include <carmlc.h>
/* probably should track unary vs binary
* but for now I think this is enough...
*/
const char *coperators[] = {
"sum", "+",
"add", "+",
"+", "+",
"sub", "-",
"-", "-",
"div", "/",
"/", "/",
"mul", "*",
"*", "*",
"mod", "%",
"%", "%",
"<", "<",
">", ">",
"<=", "<=",
">=", ">=",
"eq?", "==",
"!=", "!=",
"/=", "!=",
"<>", "!=",
"lshift", "<<",
"<<", "<<",
"rshift", ">>",
">>", ">>",
"xor", "^",
"^", "^",
"not", "!",
"!", "!",
"negate", "~",
"~", "~",
"land", "&&",
"logical-and", "&&",
"lor", "||",
"logical-or", "||",
"&&", "&&",
"||", "||",
"band", "&",
"bitwise-and", "&",
"&", "&",
"bor", "|",
"bitwise-or", "|",
"|", "|",
"set!", "=",
".", ".",
"->", "->",
"get", "get",
"make-struct", "make-struct",
"make-record", "make-record",
"make-deque", "make-deque",
"make-string", "make-string",
"make-array", "make-array",
"make", "make",
"stack-allocate", "stack-allocate",
"heap-allocate", "heap-allocate",
"region-allocate", "region-allocate",
"return", "return",
// allows a user to get some information
// about what constructor was used in an ADT
"of-constructor", "of-constructor",
"tag-of-constructor", "tag-of-constructor",
// logical connectives
"every", "every", // every logical case must pass
"one-of", "one-of", // any logical case must pass
"none-of", "none-of", // no logical case can pass
// these are meant to be used to chain states together,
// such as:
//
// (every (>= ch '0') (<= ch '9'))
// (one-of (is-numeric? ch) (eq? ch '.'))
//
// which is just `((ch >= '0') && (ch <= '9'))`
// where this becomes useful is large pipelines of
// logical tests, which are written into the logical
// connective cases of the language below
0
};
char *upcase(const char *, char *, int);
char *downcase(const char *, char *, int);
char *hstrdup(const char *);
int next(FILE *, char *, int);
void mung_variant_name(AST *, AST *, int, int);
void mung_guard(FILE *, AST *, AST *);
AST *mung_complex_type(AST *, AST*);
AST *mung_declare(const char **, const int **, int, int);
ASTOffset *mung_single_type(const char **, const int **, int, int, int);
ASTEither *readexpression(FILE *);
ASTEither *llreadexpression(FILE *, uint8_t);
ASTEither *ASTLeft(int, int, char *);
ASTEither *ASTRight(AST *);
ASTOffset *ASTOffsetLeft(int, int, char *, int);
ASTOffset *ASTOffsetRight(AST *, int);
AST *linearize_complex_type(AST *);
void llindent(FILE *, int, int);
void walk(FILE *, AST *, int);
void llcwalk(FILE *, AST *, int, int);
void llgwalk(FILE *, AST *, int, int);
void generate_type_value(FILE *, AST *, const char *); // generate a type/poly constructor
void generate_type_ref(FILE *, AST *, const char *); // generate a type/poly reference constructor
void generate_golang_type(FILE *, AST *, const char *); // generate a golang type
int compile(FILE *, FILE *);
int iswhite(int);
int isident(int);
int isbrace(int);
int istypeast(int);
int issimpletypeast(int);
int isbuiltincomplextypeast(int);
int iscomplextypeast(int);
int islambdatypeast(int);
int issyntacticform(int);
int isprimitivevalue(int);
int isvalueform(int);
int iscoperator(const char *);
int isprimitiveaccessor(const char *);
char *typespec2c(AST *, char *, char *, int);
char *typespec2g(AST *, char *, char *, int);
char *findtype(AST *);
int
main(int ac, char **al) {
ASTEither *ret = nil;
AST *tmp = nil;
FILE *fdin = nil, *fdout = nil;
int walkflag = 0, tc_flagp = 0, c_flagp = 0, ch = 0;
GC_INIT();
if(ac > 1) {
while((ch = getopt(ac, al, "scgmtiVvef:o:h")) != -1) {
switch(ch) {
case 's':
walkflag = 0;
break;
case 'c':
walkflag = 1;
break;
case 'g':
walkflag = 2;
break;
case 'm':
c_flagp = 1;
break;
case 't':
tc_flagp = 1;
break;
case 'e':
fdin = stdin;
break;
case 'i':
// eventually this should be for dumping interfaces from
// the file definition only...
break;
case 'V':
printf("carML/C 2021.2\n");
printf("(c) 2016-2021 lojikil, released under the ISC License.\n");
return 0;
case 'f':
if((fdin = fopen(optarg, "r")) == nil) {
printf("cannot open file \"%s\"\n", optarg);
return 1;
}
break;
case 'o':
if((fdout = fopen(optarg, "w")) == nil) {
printf("cannot open output file \"%s\"\n", optarg);
return 1;
}
break;
case '?':
case 'h':
default:
printf("carml/C: the carML compiler\n");
printf("usage:\n-h prints this help\n-s SExpression output (default)\n");
printf("-c turns on C output\n-g turns on Golang output\n");
printf("-m turns on the minicompiler\n-t turns on self-TCO\n");
printf("-V display version and exit\n-f the file to be compiled\n");
printf("-o the output file location\n-e read an expression from stdin\n");
return 0;
break;
}
}
if(fdin == nil) {
printf("no file specified; must use `-f` to specify a target file\n");
return 2;
}
if(fdout == nil) {
fdout = stdout;
}
do {
ret = readexpression(fdin);
if(ret->tag == ASTLEFT) {
printf("parse error: %s\n", ret->left.message);
break;
}
tmp = ret->right;
if(tmp->tag != TNEWL && tmp->tag != TEOF) {
if(tc_flagp && self_tco_p(tmp->value, tmp)) {
tmp = rewrite_tco(tmp);
}
if(walkflag == 1) {
cwalk(fdout, tmp, 0);
} else if(walkflag == 2) {
gwalk(fdout, tmp, 0);
} else {
walk(fdout, tmp, 0);
}
printf("\n");
}
} while(tmp->tag != TEOF);
fclose(fdin);
if(fdout != stdout) {
fclose(fdout);
}
} else {
fdout = stdout;
printf("\
___ ___ _ \n\
| \\/ || | \n\
___ __ _ _ __| . . || | \n\
/ __/ _` | '__| |\\/| || | \n\
| (_| (_| | | | | | || |____\n\
\\___\\__,_|_| \\_| |_/\\_____/\n");
printf("\t\tcarML/C 2021.2\n");
printf("(c) 2016-2021 lojikil, released under the ISC License.\n\n");
printf("%%c - turns on C code generation\n%%g - turns on Golang generation\n%%quit/%%q - quits\n");
printf("%%dir - dumps the current execution environment\n%%t/%%tco - turns on/off tail call detection\n");
printf("%%m - turns on the minicompiler\n%%M - compiles the entire known world with the minicompiler\n");
do {
printf(">>> ");
ret = readexpression(stdin);
//ret = next(stdin, &buf[0], 512);
//printf("%s %d\n", buf, ret);
if(ret->tag == ASTLEFT) {
printf("parse error: %s\n", ret->left.message);
} else {
tmp = ret->right;
if(tmp->tag == TEOF) {
break;
} else if(tmp->tag == TIDENT && !strncmp(tmp->value, "%quit", 4)) {
break;
} else if(tmp->tag == TIDENT && !strncmp(tmp->value, "%q", 2)) {
break;
} else if(tmp->tag == TIDENT && !strncmp(tmp->value, "%c", 2)) {
walkflag = !walkflag;
printf("[!] C generation is: %s", (walkflag ? "on" : "off"));
} else if(tmp->tag == TIDENT && !strncmp(tmp->value, "%m", 2)) {
c_flagp = !c_flagp;
printf("[!] minicompiler is: %s", (c_flagp ? "on" : "off"));
} else if(tmp->tag == TIDENT && !strncmp(tmp->value, "%g", 2)) {
if(walkflag != 2) {
walkflag = 2;
} else {
walkflag = 0;
}
printf("[!] Golang generation is: %s", (walkflag ? "on" : "off"));
} else if (tmp->tag == TIDENT && !strncmp(tmp->value, "%dir", 4)) {
// dump the environment currently known...
printf("[!] dumping the environment:\n");
} else if (tmp->tag == TIDENT && (!strncmp(tmp->value, "%t", 2) || !strncmp(tmp->value, "%tco", 4))) {
tc_flagp = !tc_flagp;
printf("[!] turning TCO detection: %s", (tc_flagp ? "on" : "off"));
} else if(tmp->tag != TNEWL) {
if(tc_flagp && tmp->tag == TDEF) {
printf("\n[!] this function is a tail call? %s", (self_tco_p(tmp->value, tmp)) ? "yes" : "no");
if(self_tco_p(tmp->value, tmp)) {
printf("... rewriting\n");
tmp = rewrite_tco(tmp);
} else {
printf("... skipping\n");
}
}
if(walkflag == 1) {
cwalk(fdout, tmp, 0);
} else if(walkflag == 2) {
gwalk(fdout, tmp, 0);
} else {
walk(fdout, tmp, 0);
}
}
printf("\n");
}
} while(1);
}
return 0;
}
ASTEither *
ASTLeft(int line, int error, char *message) {
/* CADT would be pretty easy here, but there's little
* point in doing what this compiler will do anyway eventually
* So I toil away, in the dark, writing out things I know how
* to automate, so that a brighter future may be created from
* those dark times when we languished in the C.
*/
ASTEither *head = (ASTEither *)hmalloc(sizeof(ASTEither));
head->tag = ASTLEFT;
head->left.line = line;
head->left.error = error;
head->left.message = hstrdup(message);
return head;
}
ASTEither *
ASTRight(AST *head) {
ASTEither *ret = (ASTEither *)hmalloc(sizeof(ASTEither));
ret->tag = ASTRIGHT;
ret->right = head;
return ret;
}
ASTOffset *
ASTOffsetLeft(int line, int error, char *message, int offset) {
/* CADT would be pretty easy here, but there's little
* point in doing what this compiler will do anyway eventually
* So I toil away, in the dark, writing out things I know how
* to automate, so that a brighter future may be created from
* those dark times when we languished in the C.
*/
ASTOffset *head = (ASTOffset *)hmalloc(sizeof(ASTOffset));
head->tag = ASTOFFSETLEFT;
head->left.line = line;
head->left.error = error;
head->left.message = hstrdup(message);
head->offset = offset;
return head;
}
ASTOffset *
ASTOffsetRight(AST *head, int offset) {
ASTOffset *ret = (ASTOffset *)hmalloc(sizeof(ASTOffset));
ret->tag = ASTOFFSETRIGHT;
ret->right = head;
ret->offset = offset;
return ret;
}
int
iswhite(int c){
/* newline (\n) is *not* whitespace per se, but a token.
* this is so that we can inform the parser of when we
* have hit a new line in things like a begin form.
*/
return (c == ' ' || c == '\r' || c == '\v' || c == '\t');
}
int
isbrace(int c) {
return (c == '{' || c == '}' || c == '(' || c == ')' || c == '[' || c == ']' || c == ';' || c == ',' || c == ':');
}
int
isident(int c){
return (!iswhite(c) && c != '\n' && c != ';' && c != '"' && c != '\'' && !isbrace(c));
}
int
istypeast(int tag) {
/* have to have some method
* of checking user types here...
* perhaps we should just use
* idents?
*/
//debugln;
switch(tag) {
case TARRAY:
case TINTT:
case TCHART:
case TDEQUET:
case TFLOATT:
case TTUPLET:
case TFUNCTIONT:
case TPROCEDURET:
case TCOMPLEXTYPE:
case TSTRT:
case TTAG: // user types
case TBOOLT:
case TREF:
case TLOW:
case TUNION:
case TANY:
return YES;
default:
return NO;
}
}
int
issimpletypeast(int tag) {
//debugln;
switch(tag) {
case TINTT:
case TCHART:
case TFLOATT:
case TSTRT:
case TBOOLT:
case TANY:
return YES;
default:
return NO;
}
}
int
isbuiltincomplextypeast(int tag) {
switch(tag) {
case TARRAY:
case TDEQUET:
case TTUPLET:
case TFUNCTIONT:
case TPROCEDURET:
// NOTE:
// are the following *actually
// built-in complex types?
// when we flatten arrays and such,
// it means that *ALL* things are
// just complex types. Could make
// a BUILT-IN complex type holder
// and then a more generic complex
// type
case TCOMPLEXTYPE:
case TREF:
case TLOW:
case TUNION:
return YES;
default:
return NO;
}
}
int
iscomplextypeast(int tag) {
//debugln;
switch(tag) {
case TARRAY:
case TDEQUET:
case TTUPLET:
case TFUNCTIONT:
case TPROCEDURET:
case TCOMPLEXTYPE:
case TREF:
case TLOW:
case TUNION:
case TTAG: // user types
return 1;
//case TARRAYLITERAL:
// really... need to iterate through
// the entire array to be sure here...
//return 1;
default:
return 0;
}
}
int
islambdatypeast(int tag) {
switch(tag) {
case TFUNCTIONT:
case TPROCEDURET:
return 1;
default:
return 0;
}
}
int
isprimitivevalue(int tag) {
switch(tag) {
case TINT:
case TFLOAT:
case TARRAYLITERAL:
case TSTRING:
case TCHAR:
case THEX:
case TOCT:
case TBIN:
case TTRUE:
case TFALSE:
return 1;
default:
return 0;
}
}
int
isvalueform(int tag) {
if(isprimitivevalue(tag)) {
return 1;
} else if(tag == TCALL) {
return 1;
} else if(tag == TIDENT) {
return 1;
} else if(tag == TTAG) {
return 1;
} else {
return 0;
}
}
int
iscoperator(const char *potential) {
int idx = 0;
while(coperators[idx] != nil) {
if(!strcmp(potential, coperators[idx])) {
return idx + 1;
}
idx += 2;
}
return -1;
}
int
isprimitiveaccessor(const char *potential) {
if(!strncmp(potential, "get", 3)) {
return YES;
} else if(!strncmp(potential, ".", 1)) {
return YES;
} else if(!strncmp(potential, "->", 2)) {
return YES;
} else if(!strncmp(potential, "of-constructor", 14)) {
return YES;
} else if(!strncmp(potential, "of-constructor", 17)) {
return YES;
} else {
return NO;
}
}
int
issyntacticform(int tag) {
switch(tag) {
case TVAL:
case TVAR:
case TLET:
case TLETREC:
case TWHEN:
case TDO:
case TMATCH:
case TWHILE:
case TFOR:
case TIF:
return 1;
default:
return 0;
}
}
// So currently the type parser will give us:
// (complex-type (type array)
// (tag Either)
// (array-literal (type ref) (array-literal (type integer))
// (type string)))
// for array[Either[ref[int] string]]
// which is wrong. We need to linearize those complex types better,
// and this function is meant to do that.
//
// this is a *really* terrible way of doing this; the better way
// would be to correctly parse types in the first place. However,
// I'm still thinking about how I want to handle some things within
// the type syntax, so until that is done, I think we can just leave
// this as is. The code is technically O(n^m): it iterates over each
// member of the array and then recurses the depths there of. The
// sole saving grace of this approach is that our types are small
// enough that this shouldn't matter: N should be < 10 worse case,
// and M wouldn't be much larger. That's the *only* reason why I'm
// not just diving into the types now. Fixing this, and fixing
// type parsing in general, won't be major undertakings once I am
// good with the type syntax & the associated calculus.
AST *
linearize_complex_type(AST *head) {
AST *stack[512] = {nil}, *tmp = nil, *flatten_target = nil;
int sp = 0;
dprintf("here? %d\n", __LINE__);
if(!iscomplextypeast(head->tag)){
dprintf("here? %d\n", __LINE__);
dwalk(fdout, head, 0);
return head;
}
dprintf("here? %d: ", __LINE__);
dwalk(fdout, head, 0);
dprintf("\n");
stack[sp] = head->children[0];
sp++;
for(int cidx = 1; cidx < head->lenchildren; cidx++) {
if(iscomplextypeast(head->children[cidx]->tag) && cidx < (head->lenchildren - 1) && head->children[cidx + 1]->tag == TARRAYLITERAL) {
flatten_target = head->children[cidx + 1];
dprintf("here? %d: ", __LINE__);
dwalk(fdout, flatten_target, 0);
dprintf("\n");
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TCOMPLEXTYPE;
tmp->lenchildren = 1 + flatten_target->lenchildren;
tmp->children = (AST **)hmalloc(sizeof(AST *) * flatten_target->lenchildren);
tmp->children[0] = head->children[cidx];
for(int midx = 1; midx <= flatten_target->lenchildren; midx++) {
dprintf("here? %d: ", __LINE__);
dwalk(fdout, flatten_target->children[midx - 1], 0);
dprintf("\n");
tmp->children[midx] = flatten_target->children[midx - 1];
}
dprintf("here? %d: ", __LINE__);
dwalk(fdout, tmp, 0);
dprintf("here? %d\n", __LINE__);
tmp = linearize_complex_type(tmp);
stack[sp] = tmp;
sp++;
cidx++; // skip the next item, we have already consumed it
} else {
dprintf("here? %d\n", __LINE__);
stack[sp] = head->children[cidx];
sp++;
}
}
dprintf("here? %d\n", __LINE__);
// ok, we have collapsed types, now linearize them into
// one TCOMPLEX TYPE
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TCOMPLEXTYPE;
tmp->lenchildren = sp;
tmp->children = (AST **)hmalloc(sizeof(AST *) * sp);
for(int cidx = 0; cidx <= sp; cidx++) {
tmp->children[cidx] = stack[cidx];
}
return tmp;
}
// find a type in a tree of complex types
// could be interesting to walk down...
char *
findtype(AST *head) {
AST *hare = head, *turtle = head;
char *stack[16] = {nil}, *typeval = nil;
int sp = 0, speclen = head->lenchildren, typeidx = 0;
int breakflag = 0, reslen = 0, pushf = 0;
if(turtle->tag == TCOMPLEXTYPE) {
hare = turtle->children[0];
}
while(!breakflag) {
switch(hare->tag) {
case TTAG:
// really should be Tag *...
typeval = hare->value;
breakflag = 1;
pushf = 1;
break;
case TINTT:
typeval = "int";
breakflag = 1;
pushf = 1;
break;
case TFLOATT:
typeval = "double";
breakflag = 1;
pushf = 1;
break;
case TSTRT:
typeval = "char *";
breakflag = 1;
pushf = 1;
break;
case TCHART:
typeval = "char";
breakflag = 1;
pushf = 1;
break;
case TBOOLT:
typeval = "uint8_t";
breakflag = 1;
pushf = 1;
break;
case TREF:
case TARRAY:
case TDEQUET:
typeval = "*";
pushf = 1;
break;
case TCOMPLEXTYPE:
turtle = turtle->children[typeidx];
hare = turtle->children[0];
typeidx = -1;
speclen = turtle->lenchildren;
pushf = 0;
break;
case TFUNCTIONT:
case TPROCEDURET:
default:
typeval = "void *";
breakflag = 1;
break;
}
// another great place to have Option types
// would be nice to be able to have the above
// set an Option[string] and have that matched
// here...
if(pushf) {
stack[sp] = hstrdup(typeval);
sp += 1;
}
// keep the length of the resulting
// string updated each time, and add
// one to the length for either a space
// in between members or a NUL at the
// end
reslen += strlen(typeval) + 1;
if(typeidx >= speclen) {
break;
} else if(breakflag) {
break;
} else {
typeidx++;
hare = turtle->children[typeidx];
}
}
typeval = (char *)hmalloc(sizeof(char) * reslen);
for(sp--; sp >= 0; sp--) {
strncat(typeval, stack[sp], reslen);
strncat(typeval, " ", reslen);
}
return typeval;
}
// yet another location where I'd rather
// return Option[String], sigh
// this works fine for function declarations, but
// not really for variable decs... need to work
// out what *type* of signature we're generating...
char *
typespec2c(AST *typespec, char *dst, char *name, int len) {
int strstart = 0, speclen = 0;
char *typeval = nil;
AST *tmp = nil;
// we use the type stack to capture each level of a type...
// probably should use a growable, but 16 levels deep of
// arrays/refs should be good for now...
// (famous last words)
if(typespec->lenchildren == 0 && istypeast(typespec->tag)) {
switch(typespec->tag) {
case TTAG:
typeval = typespec->value;
break;
case TINTT:
typeval = "int";
break;
case TFLOATT:
typeval = "double";
break;
case TARRAY:
typeval = "void *";
break;
case TREF:
typeval = "void *";
break;
case TSTRT:
typeval = "char *";
break;
case TCHART:
typeval = "char";
break;
case TBOOLT:
typeval = "uint8_t";
break;
case TFUNCTIONT:
case TPROCEDURET:
typeval = "void (*)(void)";
default:
typeval = "void *";
}
if(name != nil) {
snprintf(dst, len, "%s %s", typeval, name);
} else {
snprintf(dst, len, "%s", typeval);
}
return dst;
} else if(typespec->lenchildren == 1) {
if(typespec->children[0]->tag == TTAG) {
snprintf(dst, len, "%s", typespec->children[0]->value);
} else {
switch(typespec->children[0]->tag) {
case TSTRT:
snprintf(dst, 10, "char *");
break;
case TDEQUET:
snprintf(dst, 10, "deque *");
break;
case TFUNCTIONT:
case TPROCEDURET:
break;
case TARRAY:
case TREF:
default:
snprintf(dst, 10, "void *");
break;
}
}
if(name != nil) {
strstart = strnlen(dst, 512);
if(islambdatypeast(typespec->children[0]->tag)) {
// XXX this is incorrect for non-function parameter cases
snprintf(&dst[strstart], 512 - strstart, "void (*%s)(void)", name);
} else {
snprintf(&dst[strstart], 512 - strstart, "%s", name);
}
}
} else if(typespec->lenchildren > 1 && islambdatypeast(typespec->children[0]->tag)) {
// handle functions & procedures here.
char *frettype = nil, fnbuf[256] = {0};
int tlen = 0;
if(typespec->children[0]->tag == TFUNCTIONT) {
tlen = typespec->lenchildren - 1;
if(typespec->children[tlen]->tag == TUNIT) {
frettype = "void";
} else {
frettype = typespec2c(typespec->children[tlen], fnbuf, nil, 256);
frettype = hstrdup(fnbuf);
}
fnbuf[0] = 0;
} else if(typespec->children[0]->tag == TPROCEDURET) {
frettype = "void";
tlen = typespec->lenchildren;
}
// ok, get the return type, then iterate over the
// remaining list items and run typespec2c on each
if(name == nil) {
strstart = snprintf(dst, 512, "%s(*)(", frettype);
} else {
strstart = snprintf(dst, 512, "%s(*%s)(", frettype, name);
}
// we iterate from 1 instead of 0 because
// the first member of the type spec is the
// function/procedure type.
for(int cidx = 1; cidx < tlen; cidx++) {
frettype = typespec2c(typespec->children[cidx], fnbuf, nil, 256);
strncat(dst, frettype, 512);
if(cidx < (tlen - 1)) {
strncat(dst, ", ", 512);
}
}
strncat(dst, ")", 512);
} else {
speclen = typespec->lenchildren;
/* the type domination algorithm is as follows:
* 1. iterate through the type list
* 1. if we hit a tag, that's the stop item
* 1. if we hit a cardinal type, that's the stop
* 1. invert the list from start to stop
* 1. snprintf to C.
* so, for example:
* `array of array of Either of int` would become
* Either **; I'd like to make something fat to hold
* arrays, but for now we can just do it this way.
* Honestly, I'd love to Specialize types, at least
* to some degree, but for now...
*/
tmp = typespec;
typeval = findtype(typespec);
snprintf(&dst[strstart], (len - strstart), "%s", typeval);
strstart = strnlen(dst, len);
if(name != nil) {
snprintf(&dst[strstart], (len - strstart), "%s", name);
strstart = strnlen(dst, len);
}
}
return dst;
}
char *
typespec2g(AST *typespec, char *dst, char *name, int len) {
char tmpbuf[32] = {0};
int idx = 0, flag = 0;
if(name != nil) {
strcat(dst, name);
strncat(dst, " ", 1);
}
switch(typespec->tag) {
case TSTRT:
strncat(dst, "string", 6);
break;
case TFLOATT:
strncat(dst, "float", 5);
break;
case TINTT:
strncat(dst, "int", 3);
break;
case TCHART:
strncat(dst, "byte", 4);
break;
case TTAG:
if(!strncmp(typespec->value, "U8", 2)) {
strncat(dst, "uint8", 5);
} else if(!strncmp(typespec->value, "U16", 3)) {
strncat(dst, "uint16", 6);
} else if(!strncmp(typespec->value, "U32", 3)) {
strncat(dst, "uint32", 6);
} else if(!strncmp(typespec->value, "U64", 3)) {
strncat(dst, "uint64", 6);
} else if(!strncmp(typespec->value, "I8", 2)) {
strncat(dst, "int8", 5);
} else if(!strncmp(typespec->value, "I16", 3)) {
strncat(dst, "int16", 6);
} else if(!strncmp(typespec->value, "I32", 3)) {
strncat(dst, "int32", 6);
} else if(!strncmp(typespec->value, "I64", 3)) {
strncat(dst, "int64", 6);
} else {
strncat(dst, typespec->value, typespec->lenvalue);
}
break;
case TARRAY:
strncat(dst, "[]", 2);
break;
case TREF:
strncat(dst, "*", 1);
break;
case TANY:
strncat(dst, "interface{}", 11);
break;
case TBOOL:
strncat(dst, "bool", 4);
break;
case TCOMPLEXTYPE:
// iterate over types
if(typespec->children[0]->tag == TTUPLET) {
flag = 1;
strncat(dst, "struct {", 8);
idx = 1;
} else if(typespec->children[0]->tag == TFUNCTIONT || typespec->children[0]->tag == TPROCEDURET) {
strncat(dst, "func (", 6);
flag = 2;
idx = 1;
} else {
idx = 0;
}
for(; idx < typespec->lenchildren; idx ++) {
typespec2g(typespec->children[idx], tmpbuf, nil, 32);
strncat(dst, tmpbuf, 32);
if(flag == 1) {
strncat(dst, "; ", 2);
} else if(flag == 2) {
if(typespec->children[0]->tag == TFUNCTIONT && idx == (typespec->lenchildren - 2)) {
strncat(dst, ") ", 2);
} else if (idx < (typespec->lenchildren - 1)) {
strncat(dst, ", ", 2);
}
} else if(typespec->children[idx]->tag != TARRAY && typespec->children[idx]->tag != TREF){
strncat(dst, " ", 1);
}
tmpbuf[0] = nul;
}
if(flag == 1) {
flag = 0;
strncat(dst, "}", 1);
} else if(flag == 2 && typespec->children[0]->tag == TPROCEDURET) {
strncat(dst, ")", 1);
}
break;
default:
break;
}
return dst;
}
int
next(FILE *fdin, char *buf, int buflen) {
/* fetch the _next_ token from input, and tie it
* to a token type. fill buffer with the current
* item, so that we can return identifiers or
* numbers.
*/
int cur = 0, idx = 0, substate = 0, tagorident = TIDENT;
cur = fgetc(fdin);
/* we don't really care about whitespace other than
* #\n, so ignore anything that is whitespace here.
*/
if(iswhite(cur)) {
while(iswhite(cur)) {
cur = fgetc(fdin);
}
}
/* honestly, I'm just doing this because
* it's less ugly than a label + goto's
* below. Could just use calculated goto's
* but that would tie me into gcc entirely...
* well, clang too BUT STILL.
*/
while(1) {
switch(cur) {
case '\n':
return TNEWL;
case '(':
return TOPAREN;
case ')':
return TCPAREN;
case '{':
return TBEGIN;
case '}':
return TEND;
case '[':
return TOARR;
case ']':
return TCARR;
case ',':
return TCOMMA;
case '|':
cur = fgetc(fdin);
if(iswhite(cur) || isbrace(cur) || cur == '\n') {
buf[idx++] = '|';
buf[idx] = nul;
ungetc(cur, fdin);
return TIDENT;
} else if(cur == '>') {
return TPIPEARROW;
} else {
buf[idx++] = '|';
}
break;
case '=':
cur = fgetc(fdin);
if(iswhite(cur) || isbrace(cur) || cur == '\n') {
return TEQ;
} else if(cur == '>') {
return TFATARROW;
} else {
buf[idx++] = '=';
}
break;
case '$':
cur = fgetc(fdin);
if(cur == '(') {
return TCUT;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
return TDOLLAR;
} else {
/* same jazz here as above with '='. */
buf[idx++] = '$';
}
break;
case ';':
return TSEMI;
case ':':
cur = fgetc(fdin);
if(cur == '=') {
return TWALRUS;
} else if (cur == ':') {
return TMODNS;
} else {
ungetc(cur, fdin);
return TCOLON;
}
break;
case '@':
return TDECLARE;
case '#':
cur = fgetc(fdin);
while(cur != '\n' && idx < 512) {
buf[idx++] = cur;
cur = fgetc(fdin);
}
return TCOMMENT;
case '"':
cur = fgetc(fdin);
while(cur != '"') {
if(cur == '\\') {
cur = fgetc(fdin);
switch(cur) {
case 'n':
buf[idx++] = '\\';
buf[idx++] = 'n';
break;
case 'r':
buf[idx++] = '\\';
buf[idx++] = 'r';
break;
case 'b':
buf[idx++] = '\\';
buf[idx++] = 'b';
break;
case 't':
buf[idx++] = '\\';
buf[idx++] = 't';
break;
case 'v':
buf[idx++] = '\\';
buf[idx++] = 'v';
break;
case 'a':
buf[idx++] = '\\';
buf[idx++] = 'a';
break;
case '0':
buf[idx++] = '\\';
buf[idx++] = '0';
break;
case '"':
buf[idx++] = '\\';
buf[idx++] = '"';
break;
case '\\':
buf[idx++] = '\\';
buf[idx++] = '\\';
break;
default:
buf[idx++] = cur;
break;
}
} else {
buf[idx++] = cur;
}
cur = fgetc(fdin);
}
buf[idx] = '\0';
return TSTRING;
case '\'':
cur = fgetc(fdin);
if(cur == '\\') {
cur = fgetc(fdin);
switch(cur) {
case 'a':
buf[idx++] = '\a';
break;
case 'b':
buf[idx++] = '\b';
break;
case 'n':
buf[idx++] = '\n';
break;
case 'r':
buf[idx++] = '\r';
break;
case 't':
buf[idx++] = '\t';
break;
case 'v':
buf[idx++] = '\v';
break;
case '0':
buf[idx++] = '\0';
break;
case '\'':
buf[idx++] = '\'';
break;
default:
buf[idx++] = cur;
break;
}
} else {
buf[idx++] = cur;
}
cur = fgetc(fdin);
if(cur != '\'') {
strncpy(buf, "missing character terminator", 30);
return TERROR;
}
buf[idx] = '\0';
return TCHAR;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
substate = TINT;
while(1) {
switch(substate) {
case TINT:
if((cur >= '0' && cur <= '9')) {
buf[idx++] = cur;
} else if(cur == '.') {
buf[idx++] = cur;
substate = TFLOAT;
} else if(cur == 'x' || cur == 'X') {
idx--;
substate = THEX;
} else if(cur == 'b' || cur == 'B') {
idx--;
substate = TBIN;
} else if(cur == 'o' || cur == 'O') {
idx--;
substate = TOCT;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TINT;
} else {
strncpy(buf, "incorrectly formatted integer", 512);
return TERROR;
}
break;
case TFLOAT:
if(cur >= '0' && cur <= '9') {
buf[idx++] = cur;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TFLOAT;
} else {
strncpy(buf, "incorrectly formatted floating point numeral", 512);
return TERROR;
}
break;
case THEX:
if((cur >= '0' && cur <= '9') || (cur >= 'a' && cur <= 'f') || (cur >= 'A' && cur <= 'F')) {
buf[idx++] = cur;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return THEX;
} else {
strncpy(buf, "incorrectly formatted hex literal", 512);
return TERROR;
}
break;
case TOCT:
if(cur >= '0' && cur <= '7') {
buf[idx++] = cur;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TOCT;
} else {
strncpy(buf, "incorrectly formatted octal literal", 512);
return TERROR;
}
break;
case TBIN:
if(cur == '0' || cur == '1') {
buf[idx++] = cur;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TBIN;
} else {
strncpy(buf, "incorrectly formatted binary literal", 512);
return TERROR;
}
break;
default:
strncpy(buf, "incorrectly formatted numeral", 29);
return TERROR;
}
cur = fgetc(fdin);
}
/* should be identifiers down here... */
default:
while(1) {
if(feof(fdin)) {
return TEOF;
}
buf[idx++] = cur;
if(substate == LIDENT0 && (iswhite(cur) || cur == '\n' || isbrace(cur))) {
//debugln;
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
}
/* the vast majority of the code below is
* generated... that still doesn't mean it's
* very good. There is a _ton_ of reproduced
* code in between different states, and it
* would be easy to generate a state machine
* table that handles the transition in a more
* compact way. This will be the next rev of
* this subsystem here.
*/
switch(substate) {
case LSTART:
switch(cur) {
case 'a':
substate = LA0;
break;
case 'b':
substate = LB0;
break;
case 'c':
substate = LC0;
break;
case 'd':
substate = LD0;
break;
case 'e':
substate = LE0;
break;
case 'f':
substate = LF0;
break;
case 'g':
substate = LGIVEN0;
break;
case 'i':
substate = LI0;
break;
case 'l':
substate = LL0;
break;
case 'm':
substate = LM0;
break;
case 'o':
substate = LOF0;
break;
case 'p':
substate = LP0;
break;
case 'r':
substate = LR0;
break;
case 's':
substate = LSTRT0;
break;
case 't':
substate = LT0;
break;
case 'u':
substate = LU0;
break;
case 'v':
substate = LVAL0;
break;
case 'w':
substate = LW0;
break;
default:
if(cur >= 'A' && cur <= 'Z') {
substate = LTAG0;
} else {
substate = LIDENT0;
}
break;
}
break;
case LB0:
if(cur == 'e') {
substate = LBEGIN0;
} else if(cur == 'o') {
//debugln;
substate = LBOOL0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LBEGIN0:
if(cur == 'g') {
substate = LBEGIN1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LBEGIN1:
if(cur == 'i') {
substate = LBEGIN2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LBEGIN2:
if(cur == 'n') {
substate = LBEGIN3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LBEGIN3:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TBEGIN;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LBOOL0:
//debugln;
if(cur == 'o') {
//debugln;
substate = LBOOL1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LBOOL1:
if(cur == 'l') {
//debugln;
substate = LBOOL2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
//debugln;
break;
case LBOOL2:
if(isident(cur)) {
substate = LIDENT0;
/*} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;*/
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TBOOLT;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LC0:
if(cur == 'h') {
substate = LCHAR0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LCHAR0:
if(cur == 'a') {
substate = LCHAR1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LCHAR1:
if(cur == 'r') {
substate = LCHAR2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LCHAR2:
if(isident(cur)) {
substate = LIDENT0;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TCHART;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LD0:
if(cur == 'o') {
substate = LDO0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else if(cur == 'e') {
substate = LDE0;
} else {
substate = LIDENT0;
}
break;
case LDO0:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TDO;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LDE0:
if(cur == 'f') {
substate = LDEF0;
} else if(cur == 'q') {
substate = LDEQ0;
} else if(cur == 'c') {
substate = LDEC0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LDEQ0:
if(cur == 'u') {
substate = LDEQ1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LDEQ1:
if(cur == 'e') {
substate = LDEQ2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LDEQ2:
if(isident(cur)) {
substate = LIDENT0;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TDEQUET;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LDEC0:
if(cur == 'l') {
substate = LDEC1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LDEC1:
if(cur == 'a') {
substate = LDEC2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LDEC2:
if(cur == 'r') {
substate = LDEC3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LDEC3:
if(cur == 'e') {
substate = LDEC4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LDEC4:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TDECLARE;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LDEF0:
if(isident(cur)) {
substate = LIDENT0;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TDEF;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LE0:
if(cur == 'l') {
substate = LELSE0;
} else if(cur == 'n') {
substate = LEND0;
} else if(cur == 'x') {
substate = LEXTERN0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else substate = LIDENT0;
break;
case LELSE0:
if(cur == 's') {
substate = LELSE1;
} else {
substate = LIDENT0;
}
break;
case LELSE1:
if(cur == 'e') {
substate = LELSE2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LELSE2:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TELSE;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LEND0:
if(cur == 'd') {
substate = LEND1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LEND1:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TEND;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LEXTERN0:
if(cur == 't') {
substate = LEXTERN1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LEXTERN1:
if(cur == 'e') {
substate = LEXTERN2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LEXTERN2:
if(cur == 'r') {
substate = LEXTERN3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LEXTERN3:
if(cur == 'n') {
substate = LEXTERN4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LEXTERN4:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TEXTERN;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LF0:
if(cur == 'n') {
substate = LFN0;
} else if(cur == 'l') {
substate = LFLOATT0;
} else if(cur == 'a') {
substate = LFALSE0;
} else if(cur == 'o') {
substate = LFOR0;
} else if(cur == 'u') {
substate = LFUNCTIONT0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFUNCTIONT0:
if(cur == 'n') {
substate = LFUNCTIONT1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFUNCTIONT1:
if(cur == 'c') {
substate = LFUNCTIONT2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFUNCTIONT2:
if(cur == 't') {
substate = LFUNCTIONT3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFUNCTIONT3:
if(cur == 'i') {
substate = LFUNCTIONT4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFUNCTIONT4:
if(cur == 'o') {
substate = LFUNCTIONT5;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFUNCTIONT5:
if(cur == 'n') {
substate = LFUNCTIONT6;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFUNCTIONT6:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TFUNCTIONT;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LFOR0:
if(cur == 'r') {
substate = LFOR1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFOR1:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TFOR;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LFALSE0:
if(cur == 'l') {
substate = LFALSE1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFALSE1:
if(cur == 's') {
substate = LFALSE2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFALSE2:
if(cur == 'e') {
substate = LFALSE3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFALSE3:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TFALSE;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LFLOATT0:
if(cur == 'o') {
substate = LFLOATT1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFLOATT1:
if(cur == 'a') {
substate = LFLOATT2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFLOATT2:
if(cur == 't') {
substate = LFLOATT3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LFLOATT3:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TFLOATT;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LFN0:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TFN;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LGIVEN0:
if(cur == 'i') {
substate = LGIVEN1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LGIVEN1:
if(cur == 'v') {
substate = LGIVEN2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LGIVEN2:
if(cur == 'e') {
substate = LGIVEN3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LGIVEN3:
if(cur == 'n') {
substate = LGIVEN4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LGIVEN4:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TGIVEN;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LA0:
if(cur == 'r') {
substate = LARRAY1;
} else if(cur == 'n') {
substate = LAN0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LARRAY0:
if(cur == 'r') {
substate = LARRAY1;
} else {
substate = LIDENT0;
}
break;
case LI0:
if(cur == 'f') {
substate = LIF0;
} else if(cur == 'n') {
substate = LINTT0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LINTT0:
if(cur == 't') {
substate = LINTT1;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TIN;
} else {
substate = LIDENT0;
}
break;
case LINTT1:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TINTT;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LIF0:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TIF;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LL0:
if(cur == 'e') {
substate = LLET1;
} else if(cur == 'o') {
substate = LLOW0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LLET0:
if(cur == 'e') {
substate = LLET1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LLET1:
if(cur == 't') {
substate = LLET2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LLET2:
if(cur == 'r') {
substate = LLETREC0;
} else if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TLET;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LLETREC0:
if(cur == 'e') {
substate = LLETREC1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LLETREC1:
if(cur == 'c') {
substate = LLETREC2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LLETREC2:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TLETREC;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LLOW0:
if(cur == 'w') {
substate = LLOW1;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LLOW1:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TLOW;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LR0:
if(cur == 'e') {
substate = LRE0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LRE0:
if(cur == 'c') {
substate = LRECORD0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else if(cur == 'f') {
substate = LREF0;
} else {
substate = LIDENT0;
}
break;
case LRECORD0:
if(cur == 'o') {
substate = LRECORD1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LRECORD1:
if(cur == 'r') {
substate = LRECORD2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LRECORD2:
if(cur == 'd') {
substate = LRECORD3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LRECORD3:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TRECORD;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LREF0:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TREF;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LT0:
if(cur == 'h') {
//debugln;
substate = LTHEN0;
} else if(cur == 'y') {
substate = LTYPE0;
} else if(cur == 'r') {
substate = LTRUE0;
} else if(cur == 'u') {
substate = LTUPLE0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTHEN0:
if(cur == 'e') {
//debugln;
substate = LTHEN1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTHEN1:
if(cur == 'n') {
//debugln;
substate = LTHEN2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTHEN2:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
//debugln;
ungetc(cur, fdin);
return TTHEN;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LTYPE0:
if(cur == 'p') {
substate = LTYPE1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTYPE1:
if(cur == 'e') {
substate = LTYPE2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTYPE2:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TTYPE;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LTRUE0:
if(cur == 'u') {
substate = LTRUE1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTRUE1:
if(cur == 'e') {
substate = LTRUE2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTRUE2:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TTRUE;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LTUPLE0:
if(cur == 'p') {
substate = LTUPLE1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTUPLE1:
if(cur == 'l') {
substate = LTUPLE2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTUPLE2:
if(cur == 'e') {
substate = LTUPLE3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LTUPLE3:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TTUPLET;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LAN0:
if(cur == 'y') {
substate = LANY0;
} else if(cur == 'd') {
substate = LAND0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate= LIDENT0;
}
break;
case LANY0:
if(isident(cur)) {
substate = LIDENT0;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TANY;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LAND0:
if(isident(cur)) {
substate = LIDENT0;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TAND;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LARRAY1:
if(cur == 'r') {
substate = LARRAY2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate= LIDENT0;
}
break;
case LARRAY2:
if(cur == 'a') {
substate = LARRAY3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LARRAY3:
if(cur == 'y') {
substate = LARRAY4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LARRAY4:
if(isident(cur)) {
substate = LIDENT0;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx] = '\0';
return TARRAY;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LW0:
if(cur == 'h') {
substate = LWH0;
} else if(cur == 'i') {
substate = LWITH0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LWH0:
if(cur == 'e') {
substate = LWHEN1;
} else if(cur == 'i') {
substate = LWHILE1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LWHEN1:
if(cur == 'n') {
substate = LWHEN2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LWHEN2:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TWHEN;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LWHILE1:
if(cur == 'l') {
substate = LWHILE2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LWHILE2:
if(cur == 'e') {
substate = LWHILE3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LWHILE3:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TWHILE;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LWITH0:
if(cur == 't') {
substate = LWITH1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LWITH1:
if(cur == 'h') {
substate = LWITH2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LWITH2:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TWITH;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LOF0:
if(cur == 'f') {
substate = LOF1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LOF1:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TOF;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LPROCEDURET0:
if(cur == 'o') {
substate = LPROCEDURET1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPROCEDURET1:
if(cur == 'c') {
substate = LPROCEDURET2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPROCEDURET2:
if(cur == 'e') {
substate = LPROCEDURET3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPROCEDURET3:
if(cur == 'd') {
substate = LPROCEDURET4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPROCEDURET4:
if(cur == 'u') {
substate = LPROCEDURET5;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPROCEDURET5:
if(cur == 'r') {
substate = LPROCEDURET6;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPROCEDURET6:
if(cur == 'e') {
substate = LPROCEDURET7;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPROCEDURET7:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TPROCEDURET;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LP0:
if(cur == 'o') {
substate = LPOLY1;
} else if(cur == 'r') {
substate = LPROCEDURET0;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPOLY0:
if(cur == 'o') {
substate = LPOLY1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPOLY1:
if(cur == 'l') {
substate = LPOLY2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPOLY2:
if(cur == 'y') {
substate = LPOLY3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LPOLY3:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TPOLY;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LU0:
if(cur == 's') {
substate = LUSE1;
} else if(cur == 'n') {
substate = LUNION1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LUSE0:
if(cur == 's') {
substate = LUSE1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LUSE1:
if(cur == 'e') {
substate = LUSE2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LUSE2:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TUSE;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LUNION1:
if(cur == 'i') {
substate = LUNION2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LUNION2:
if(cur == 'o') {
substate = LUNION3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LUNION3:
if(cur == 'n') {
substate = LUNION4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LUNION4:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TUNION;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LVAL0:
//debugln;
if(cur == 'a') {
substate = LVAL1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LVAL1:
if(cur == 'l') {
substate = LVAL2;
} else if(cur == 'r') {
substate = LVAR2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LVAL2:
if(isident(cur)) {
//debugln;
substate = LIDENT0;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
//debugln;
ungetc(cur, fdin);
return TVAL;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LVAR2:
if(isident(cur)) {
//debugln;
substate = LIDENT0;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
//debugln;
ungetc(cur, fdin);
return TVAR;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LSTRT0:
if(cur == 't') {
substate = LSTRT1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LSTRT1:
if(cur == 'r') {
substate = LSTRT2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LSTRT2:
if(cur == 'i') {
substate = LSTRT3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LSTRT3:
if(cur == 'n') {
substate = LSTRT4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LSTRT4:
if(cur == 'g') {
substate = LSTRT5;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LSTRT5:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TSTRT;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LM0:
if(cur == 'a') {
substate = LMATCH1;
} else if (cur == 'o') {
substate = LMODULE1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LMATCH1:
if(cur == 't') {
substate = LMATCH2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LMATCH2:
if(cur == 'c') {
substate = LMATCH3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LMATCH3:
if(cur == 'h') {
substate = LMATCH4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LMATCH4:
if(isident(cur)) {
substate = LIDENT0;
}else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TMATCH;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LMODULE0:
if(cur == 'o') {
substate = LMODULE1;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LMODULE1:
if(cur == 'd') {
substate = LMODULE2;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LMODULE2:
if(cur == 'u') {
substate = LMODULE3;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LMODULE3:
if(cur == 'l') {
substate = LMODULE4;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LMODULE4:
if(cur == 'e') {
substate = LMODULE5;
} else if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TIDENT;
} else {
substate = LIDENT0;
}
break;
case LMODULE5:
if(isident(cur)) {
substate = LIDENT0;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
return TMODULE;
} else {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
case LTAG0:
tagorident = TTAG;
substate = LTAGIDENT;
if(iswhite(cur) || isbrace(cur) || cur == '\n') {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return TTAG;
}
break;
case LIDENT0:
tagorident = TIDENT;
substate = LTAGIDENT;
break;
case LTAGIDENT:
//printf("cur == %c\n", cur);
if(idx > 0 && (iswhite(buf[idx - 1]) || buf[idx - 1] == '\n' || isbrace(buf[idx - 1]))) {
//debugln;
ungetc(cur, fdin);
buf[idx - 1] = '\0';
//printf("idx: %d, buffer: %s\n", idx - 1, buf);
return tagorident;
} else if(iswhite(cur) || cur == '\n' || isbrace(cur)) {
ungetc(cur, fdin);
buf[idx - 1] = '\0';
return tagorident;
} else if(!isident(cur)) {
strncpy(buf, "malformed identifier", 512);
return TERROR;
}
break;
}
cur = fgetc(fdin);
}
}
}
}
/* currently, if there's a parse error mid-stream,
* the REPL keeps reading. I think a better way of
* handling that would be to lex tokens until we
* get a TEOF, and then use that _stream_ of
* tokens as input to a higher-level expressions
* builder. A bit more work, but it would make the
* REPL experience nicer.
*/
ASTEither *
readexpression(FILE *fdin) {
return llreadexpression(fdin, 0);
}
ASTEither *
llreadexpression(FILE *fdin, uint8_t nltreatment) {
/* _read_ from `fdin` until a single AST is constructed, or EOF
* is reached.
*/
AST *head = nil, *tmp = nil, *vectmp[128], *ctmp = nil;
ASTEither *sometmp = nil, *sometmp0 = nil;
int ltype = 0, ltmp = 0, idx = 0, flag = -1, typestate = 0, fatflag = 0;
char buffer[512] = {0};
char name[8] = {0};
char errbuf[512] = {0};
ltype = next(fdin, &buffer[0], 512);
switch(ltype) {
case TDOLLAR:
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TDOLLAR;
return ASTRight(tmp);
case TCOMMENT:
/* do we want return this, so that we can
* return documentation, &c.?
* ran into an interesting bug here.
* because `#` eats until the newline, it
* doesn't *return* a new line, which breaks
* llread for certain types of newline-sensitive
* operations, such as record members. So, we
* have to check what the nltreatment value is,
* and either convert this into a TNEWL or call
* read expression again.
*/
if(nltreatment) {
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TNEWL;
sometmp = ASTRight(tmp);
} else {
sometmp = readexpression(fdin);
}
return sometmp;
case TERROR:
return ASTLeft(0, 0, hstrdup(&buffer[0]));
case TEOF:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TEOF;
return ASTRight(head);
case TLET:
case TLETREC:
head = (AST *)hmalloc(sizeof(AST));
head->tag = ltype;
/* setup:
* - head->value = name binding
* - head->children[0] = value
* - head->children[1] = body
* - head->children[2] = type (optional)
*/
if(ltype == TLET) {
strncpy(name, "let", 3);
} else {
strncpy(name, "letrec", 6);
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
tmp = sometmp->right;
}
if(tmp->tag != TIDENT) {
snprintf(&errbuf[0],
512,
"%s's binding *must* be an IDENT: `%s IDENT = EXPRESION in EXPRESSION`",
name, name);
return ASTLeft(0, 0, hstrdup(&errbuf[0]));
}
head->value = hstrdup(tmp->value);
// add types here
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TEQ && sometmp->right->tag != TCOLON) {
snprintf(&errbuf[0], 512,
"%s's IDENT must be followed by an `=`: `%s IDENT = EXPRESSION in EXPRESSION`",
name, name);
return ASTLeft(0, 0, hstrdup(&errbuf[0]));
} else if(sometmp->right->tag == TCOLON) {
/* ok, the user is specifying a type here
* we have to consume the type, and then
* store it.
*/
head->lenchildren = 3;
head->children = (AST **)hmalloc(sizeof(AST *) * 3);
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(!istypeast(sometmp->right->tag)) {
return ASTLeft(0, 0, "a `:` form *must* be followed by a type definition...");
} else if(issimpletypeast(sometmp->right->tag) || sometmp->right->tag == TCOMPLEXTYPE) {
head->children[2] = sometmp->right;
} else {
/* complex *user* type...
*/
flag = idx;
/* we hit a complex type,
* now we're looking for
* either `of` or `=`.
*/
vectmp[idx] = sometmp->right;
idx++;
typestate = 1;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TARRAYLITERAL) {
tmp = sometmp->right;
AST *ctmp = (AST *)hmalloc(sizeof(AST));
ctmp->tag = TCOMPLEXTYPE;
ctmp->lenchildren = 1 + tmp->lenchildren;
ctmp->children = (AST **)hmalloc(sizeof(AST *) * ctmp->lenchildren);
ctmp->children[0] = vectmp[flag];
for(int cidx = 1, tidx = 0; cidx < ctmp->lenchildren; cidx++, tidx++) {
ctmp->children[cidx] = tmp->children[tidx];
}
ctmp = linearize_complex_type(ctmp);
vectmp[flag] = ctmp;
idx = flag;
flag = 0;
typestate = 2;
head->children[2] = ctmp;
} else if(sometmp->right->tag == TEQ) {
typestate = 3;
} else {
return ASTLeft(0, 0, "`:` *must* be followed by a type in let/letrec");
}
}
if(typestate != 3) {
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TEQ) {
return ASTLeft(0, 0, "a `let` type definition *must* be followed by an `=`...");
}
}
} else {
/* if we hit a TEQ, then we don't need any extra allocation,
* just two slots.
*/
head->lenchildren = 2;
head->children = (AST **)hmalloc(sizeof(AST *) * 2);
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
head->children[0] = sometmp->right;
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
tmp = sometmp->right;
}
/* really should check if this is an
* `and`, such that we can have multiple
* bindings...
*/
if(tmp->tag != TIN) {
snprintf(&errbuf[0], 512,
"%s's EXPR must be followed by an `in`: `%s IDENT = EXPRESSION in EXPRESSION`",
name, name);
return ASTLeft(0, 0, hstrdup(&errbuf[0]));
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
head->children[1] = sometmp->right;
}
return ASTRight(head);
case TDECLARE:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TDECLARE;
head->lenchildren = 2;
head->children = (AST **)hmalloc(sizeof(AST *) * 2);
// parse our name
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TIDENT) {
return ASTLeft(0, 0, "declare *must* be followed by an identifier");
} else {
head->children[0] = sometmp->right;
}
// get our colon...
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TCOLON) {
return ASTLeft(0, 0, "declare's ident *must* be followed by a colon");
}
// get our type
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TTAG) {
// a tag can be stand alone OR it can be
// a complex type, so we need to read one
// item here, and potentially smoosh them
// together into a complex type
sometmp0 = llreadexpression(fdin, YES);
if(sometmp0->tag == ASTLEFT) {
return sometmp0;
} else if(sometmp0->right->tag == TNEWL) {
head->children[1] = sometmp->right;
} else if(sometmp0->right->tag == TARRAYLITERAL) {
head->children[1] = mung_complex_type(sometmp->right, sometmp0->right);
} else {
return ASTLeft(0, 0, "declare *must* be followed by a type; Tag(ArrayLiteralTypes)");
}
} else if(!istypeast(sometmp->right->tag)) {
return ASTLeft(0, 0, "declare *must* be followed by a type");
} else {
head->children[1] = sometmp->right;
}
return ASTRight(head);
case TUSE:
head = (AST *) hmalloc(sizeof(AST));
head->tag = TUSE;
head->lenchildren = 0;
sometmp = readexpression(fdin);
tmp = sometmp->right;
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(tmp->tag != TIDENT && tmp->tag != TTAG && tmp->tag != TSTRING) {
return ASTLeft(0, 0, "`use` must be followed by an ident, a tag, or a string.");
}
head->value = sometmp->right->value;
return ASTRight(head);
case TFN:
case TDEF:
head = (AST *) hmalloc(sizeof(AST));
head->tag = ltype;
int loopflag = 1;
AST *params = nil, *returntype = nil;
if(ltype == TDEF){
ltmp = next(fdin, &buffer[0], 512);
if(ltmp != TIDENT) {
return ASTLeft(0, 0, "parser error");
}
head->value = hstrdup(buffer);
head->lenvalue = strnlen(buffer, 512);
}
/* the specific form we're looking for here is
* TDEF TIDENT (TIDENT *) TEQUAL TEXPRESSION
* that (TIDENT *) is the parameter list to non-nullary
* functions. I wonder if there should be a specific
* syntax for side-effecting functions...
*/
/*
* so, we have to change this a bit. Instead of reading
* in just a list of idents, we need to accept that there
* can be : and => in here as well. Basically, we want to
* be able to parse this:
*
* def foo x : int bar : array of int => int = {
* # ...
* }
*
* this same code could then be used to make @ work, even
* if the current stream idea in @ is nicer
* actually, should just steal the code from records for
* here... besides, the same code could then be used for
* declare...
*/
while(loopflag) {
switch(typestate) {
case 0:
sometmp = readexpression(fdin);
debugln;
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TIDENT) {
// name
debugln;
typestate = 1;
} else if(sometmp->right->tag == TFATARROW) {
// return type
debugln;
fatflag = idx;
typestate = 2;
} else if(sometmp->right->tag == TEQ) {
// body
//debugln;
typestate = 3;
} else {
//debugln;
//dprintf("tag == %d\n", sometmp->right->tag);
return ASTLeft(0, 0, "`def` must have either a parameter list, a fat-arrow, or an equals sign.");
}
debugln;
dprintf("typestate == %d\n", typestate);
break;
case 1: // TIDENT
debugln;
vectmp[idx] = sometmp->right;
flag = idx;
idx++;
sometmp = readexpression(fdin);
//debugln;
if(sometmp->tag == ASTLEFT) {
//debugln;
return sometmp;
} else if(sometmp->right->tag == TIDENT) {
//debugln;
typestate = 1;
} else if(sometmp->right->tag == TFATARROW) {
debugln;
fatflag = idx;
typestate = 2;
} else if(sometmp->right->tag == TEQ) {
//debugln;
typestate = 3;
} else if(sometmp->right->tag == TCOLON) {
//debugln;
//dprintf("sometmp type: %d\n", sometmp->right->tag);
typestate = 4;
} else {
//debugln;
//dprintf("tag == %d\n", sometmp->right->tag);
return ASTLeft(0, 0, "`def` identifiers *must* be followed by `:`, `=>`, or `=`");
}
debugln;
dprintf("tag == %d, typestate == %d\n", sometmp->right->tag, typestate);
break;
case 3: // TEQ, start function
/* mark the parameter list loop as closed,
* and begin to process the elements on the
* stack as a parameter list.
*/
//debugln;
loopflag = 0;
if(idx > 0) {
//debugln;
params = (AST *) hmalloc(sizeof(AST));
params->children = (AST **) hmalloc(sizeof(AST *) * idx);
for(int i = 0; i < idx; i++) {
params->children[i] = vectmp[i];
}
//debugln;
params->tag = TPARAMLIST;
params->lenchildren = idx;
//debugln;
}
break;
// part of the problem here is that
// I tried to simplify the states, but
// ended up with messier code and more
// stateful stuff. Undoing some of that
// now, by unwinding the fatflag code
case 2: // TFATARROW, return
debugln;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(!istypeast(sometmp->right->tag)) {
dprintf("somehow here, but... %d\n", sometmp->right->tag);
return ASTLeft(0, 0, "a `=>` form *must* be followed by a type definition...");
} else if(issimpletypeast(sometmp->right->tag) || sometmp->right->tag == TCOMPLEXTYPE) {
debugln;
returntype = sometmp->right;
typestate = 6;
} else { // complex *user* type
debugln;
vectmp[idx] = sometmp->right;
flag = idx;
idx++;
typestate = 21;
}
break;
case 21: // OF but for return
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TARRAYLITERAL) {
tmp = sometmp->right;
for(int tidx = 0; tidx < tmp->lenchildren; tidx++, idx++) {
vectmp[idx] = tmp->children[tidx];
}
returntype = (AST *)hmalloc(sizeof(AST));
returntype->tag = TCOMPLEXTYPE;
returntype->lenchildren = idx - flag;
returntype->children = (AST **)hmalloc(sizeof(AST *) * returntype->lenchildren);
for(int cidx = 0, tidx = flag, tlen = returntype->lenchildren; cidx < tlen; cidx++, tidx++) {
returntype->children[cidx] = vectmp[tidx];
}
// this is a hack; because of the current grammar construction,
// we end up with array-literals in positions that typespec2c
// cannot handle. This solves that, but terribly. This will
// be solved by changing the syntax such that there is no
// need for the `of` form when specifying complex types,
// and going full-Scala (get it???) on the type syntax.
returntype = linearize_complex_type(returntype);
idx = flag;
flag = 0;
typestate = 6;
} else if(sometmp->right->tag == TEQ) {
returntype = (AST *)hmalloc(sizeof(AST));
returntype->tag = TCOMPLEXTYPE;
returntype->lenchildren = idx - flag;
returntype->children = (AST **)hmalloc(sizeof(AST *) * returntype->lenchildren);
for(int cidx = 0, tidx = flag, tlen = returntype->lenchildren; cidx < tlen; cidx++, tidx++) {
returntype->children[cidx] = vectmp[tidx];
}
idx = flag;
flag = 0;
typestate = 3;
} else {
return ASTLeft(0, 0, "a complex type in `=>` must be followed by `of`, `=`, or an array of types.");
}
break;
case 4: // type
dprintf("%%debug: typestate = %d, sometmp->right->tag = %d\n", typestate, sometmp->right->tag);
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
//debugln;
return sometmp;
} else if(!istypeast(sometmp->right->tag) && sometmp->right->tag != TARRAYLITERAL) {
//dprintf("type: %d\n", sometmp->right->tag);
//debugln;
return ASTLeft(0, 0, "a `:` form *must* be followed by a type definition...");
} else if(issimpletypeast(sometmp->right->tag) || sometmp->right->tag == TCOMPLEXTYPE) { // simple type
if(typestate == 4) {
debugln;
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TPARAMDEF;
tmp->lenchildren = 2;
tmp->children = (AST **)hmalloc(sizeof(AST *) * 2);
tmp->children[0] = vectmp[idx - 1];
tmp->children[1] = sometmp->right;
vectmp[idx - 1] = tmp;
typestate = 0;
} else {
returntype = sometmp->right;
typestate = 6;
}
} else { // complex type
debugln
vectmp[idx] = sometmp->right;
idx++;
typestate = 5;
}
break;
case 5: // complex type "of" game
//walk(sometmp->right, 0);
//debugln;
sometmp = readexpression(fdin);
// need to collapse the complex type in
// the state transforms below, not just
// dispatch. It's close tho.
// this is why complex types aren't working in
// certain states (like `URL` as a stand alone)
// also need to trace down why other areas are
// failing too (like after `=>`). Very close
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TIDENT) {
debugln;
typestate = 1;
} else if(sometmp->right->tag == TEQ) {
typestate = 3;
} else if(sometmp->right->tag == TARRAYLITERAL) {
// which state here? need to check that the
// array only has types in it...
tmp = sometmp->right;
for(int cidx = 0; cidx < tmp->lenchildren; cidx++, idx++) {
vectmp[idx] = tmp->children[cidx];
}
typestate = 0;
} else if(sometmp->right->tag == TFATARROW) {
debugln;
fatflag = idx;
typestate = 2;
} else {
return ASTLeft(0, 0, "a complex type most be followed by an `of`, an ident, an array, a `=` or a `=>`");
}
// ok we have dispatched, now collapse
if(typestate != 7) {
debugln;
AST *ctmp = (AST *)hmalloc(sizeof(AST));
ctmp->tag = TCOMPLEXTYPE;
dprintf("typestate: %d, idx: %d, flag: %d\n", typestate, idx, flag);
ctmp->lenchildren = idx - flag - 1;
ctmp->children = (AST **)hmalloc(sizeof(AST *) * ctmp->lenchildren);
dprintf("len of children should be: %d\n", ctmp->lenchildren);
for(int tidx = flag + 1, cidx = 0; tidx < idx ; cidx++, tidx++) {
debugln;
ctmp->children[cidx] = vectmp[tidx];
}
ctmp = linearize_complex_type(ctmp);
if(fatflag && fatflag != idx) {
returntype = ctmp;
/*
* XXX: I think I fixed this the "correct" way mentioned below
* a long time ago, so this should all be reviewed and potentially
* purged...
* so the "correct" way of doing this would be to actually
* break out the state for return, and then duplicate the
* code there. It would be context-free, and would work
* nicely. I didn't do that tho. I chose to de-dupe the
* code, and just use flags. Best idea? Dunno, but the
* code is smaller, and means I have to change fewer
* locations. Honestly, this stuff should all be added
* to *ONE* location that I can pull around to the various
* places; right now records may not handle tags correctly,
* for example. However, I think adding a "streaming" interface
* in carML/carML (that is, self-hosting carML) would make
* this a lot nicer looking internally.
*/
debugln;
idx = fatflag + 1;
flag = fatflag + 1;
} else {
debugln;
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TPARAMDEF;
tmp->lenchildren = 2;
tmp->children = (AST **)hmalloc(sizeof(AST *) * 2);
tmp->children[0] = vectmp[flag];
tmp->children[1] = ctmp;
vectmp[flag] = tmp;
idx = flag + 1;
}
//debugln;
}
break;
case 6: // post-fatarrow
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TEQ) {
return ASTLeft(0, 0, "a `=>` return type must be followed by an `=`");
} else {
typestate = 3;
}
break;
}
}
/* ok, now that we have the parameter list and the syntactic `=` captured,
* we read a single expression, which is the body of the procedure we're
* defining.
*/
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
tmp = sometmp->right;
}
/* Now, we have to build our actual TDEF AST.
* a TDEF is technically a list:
* - TIDENT that is our name.
* - TPARAMLIST that holds our parameter names
* - and some TExpression that represents our body
*/
if(returntype != nil) {
head->children = (AST **)hmalloc(sizeof(AST *) * 3);
head->lenchildren = 3;
head->children[2] = returntype;
} else {
head->children = (AST **)hmalloc(sizeof(AST *) * 2);
head->lenchildren = 2;
}
head->children[0] = params;
head->children[1] = tmp;
return ASTRight(head);
case TWHILE:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TWHILE;
head->lenchildren = 2;
head->children = (AST **)hmalloc(sizeof(AST *) * 2);
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
head->children[0] = sometmp->right;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TDO) {
return ASTLeft(0, 0, "While form conditions *must* be followed by a `do`...");
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
head->children[1] = sometmp->right;
return ASTRight(head);
case TFOR:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TFOR;
head->lenchildren = 2;
head->children = (AST **)hmalloc(sizeof(AST *) * 2);
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} if(sometmp->right->tag != TIDENT) {
return ASTLeft(0, 0, "for-form's name must be an ident");
}
head->value = sometmp->right->value;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TIN) {
return ASTLeft(0, 0, "for-form binding *must* be followed by an `in`...");
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
head->children[0] = sometmp->right;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TDO) {
return ASTLeft(0, 0, "for-form conditions *must* be followed by a `do`...");
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
head->children[1] = sometmp->right;
return ASTRight(head);
break;
case TWITH:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TWITH;
head->lenchildren = 0;
return ASTRight(head);
break;
case TMATCH:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TMATCH;
head->lenchildren = 2;
head->children = (AST **)hmalloc(sizeof(AST *) * 2);
AST *mcond = nil, *mval = nil, *mstack[128] = {nil};
int msp = 0;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
head->children[0] = sometmp->right;
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TWITH) {
return ASTLeft(0, 0, "a `match` form's expression *must* be followed by a `with`.");
}
// ok, we have an expression, and with have a WITH, now
// we need to read our expressions.
// expression => expression
// else => expression
// end $
debugln;
while(1) {
sometmp = readexpression(fdin);
debugln;
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TCALL) {
mcond = sometmp->right;
if(mcond->children[0]->tag != TTAG) {
return ASTLeft(0, 0, "match can only decompose sum-types.");
}
} else if(sometmp->right->tag == TIDENT || sometmp->right->tag == TTAG || isprimitivevalue(sometmp->right->tag) || sometmp->right->tag == TELSE) {
mcond = sometmp->right;
} else if(sometmp->right->tag == TEND) {
break;
} else {
return ASTLeft(0, 0, "match cannot match against this value");
}
debugln;
sometmp = readexpression(fdin);
// need to figure out how to wedge guard clauses in here...
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
// we split this step so that we parse and
// consume a TWHEN guard clause. What we do
// here is shunt out when there's a when,
// consume it and the guard clause (which
// must be a TBOOL, a TIDENT, a TTAG, or
// a TCALL, and then continue on testing
// for the precense of a TFATARROW
// ...
// oh interesting, because we're parsing a
// full AST for TWHEN, we can't really do
// the below... hmmmm... new keyword, given?
// match x with
// y given (> x 10) => ...
// z given (<= x 10) => ...
// else => ...
// end
// I kinda like that...
// the shorthand in math for "given" is "|"
// ... I like that too. Need to make sure that
// lower-level math operators still work, but I
// like this...
if(sometmp->right->tag == TGIVEN) {
// read in a guard clause
// then check for a TFATARROW
sometmp = readexpression(fdin);
tmp = sometmp->right;
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(tmp->tag != TTRUE && tmp->tag != TFALSE && tmp->tag != TIDENT && tmp->tag != TTAG && tmp->tag != TCALL) {
return ASTLeft(0, 0, "a guard-clause must be a boolean, an ident, a tag, or a call.");
}
tmp = hmalloc(sizeof(AST));
tmp->tag = TGUARD;
tmp->lenchildren = 2;
tmp->children = (AST **) hmalloc(sizeof(AST *) * 2);
tmp->children[0] = mcond;
tmp->children[1] = sometmp->right;
mcond = tmp;
sometmp = readexpression(fdin);
}
if(sometmp->right->tag != TFATARROW) {
return ASTLeft(0, 0, "match conditions *must* be followed by a fat-arrow `=>`");
}
debugln;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
mval = sometmp->right;
}
debugln;
mstack[msp] = mcond;
mstack[msp + 1] = mval;
msp += 2;
debugln;
}
debugln;
tmp = (AST *)hmalloc(sizeof(AST));
tmp->lenchildren = msp;
tmp->children = (AST **)hmalloc(sizeof(AST *) * msp);
for(int cidx = 0; cidx < msp; cidx += 2) {
tmp->children[cidx] = mstack[cidx];
tmp->children[cidx + 1] = mstack[cidx + 1];
}
tmp->tag = TBEGIN;
head->children[1] = tmp;
return ASTRight(head);
break;
case TIF:
/* this code is surprisingly gross.
* look to clean this up a bit.
*/
head = (AST *)hmalloc(sizeof(AST));
head->tag = TIF;
head->children = (AST **)hmalloc(sizeof(AST *) * 3);
head->lenchildren = 3;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
head->children[0] = sometmp->right;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
tmp = sometmp->right;
if(tmp->tag != TTHEN) {
return ASTLeft(0, 0, "missing THEN keyword after IF conditional: if conditional then expression else expression");
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
head->children[1] = sometmp->right;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
tmp = sometmp->right;
if(tmp->tag != TELSE) {
return ASTLeft(0, 0, "missing ELSE keyword after THEN value: if conditional then expression else expression");
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
head->children[2] = sometmp->right;
return ASTRight(head);
case TMODULE:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TMODULE;
head->lenchildren = 2;
head->children = (AST **)hmalloc(sizeof(AST *));
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TTAG) {
return ASTLeft(0, 0, "module declarations *must* be followed by a tag");
}
head->children[0] = sometmp->right;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TBEGIN) {
return ASTLeft(0, 0, "module name *must* be followed by a BEGIN form");
}
head->children[1] = sometmp->right;
return ASTRight(head);
case TBEGIN:
while(1) {
//debugln;
sometmp = llreadexpression(fdin, 1); // probably should make a const for WANTNL
//debugln;
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
//debugln;
tmp = sometmp->right;
//debugln;
if(tmp->tag == TIDENT || tmp->tag == TTAG) {
/* NOTE: general strategy for emitting a CALL
* read values into vectmp, but mark the start
* of the TCALL (flag == 0), and when we hit
* a TSEMI (';') or TNEWL ('\n'), collapse
* them into a single TCALL AST node. This works
* in a similar vein for "()" code, but there
* we just read until a closing parenthesis is
* met (TSEMI should be a parse error there?
*/
if(flag == -1) {
/* set the TCALL flag, for collapsing later */
flag = idx;
}
} else if(flag != -1 && (tmp->tag == TSEMI || tmp->tag == TNEWL || tmp->tag == TEND)) {
if(tmp->tag == TEND) {
debugln;
fatflag = 1;
}
/* collapse the call into a TCALL
* this has some _slight_ problems, since it
* uses the same stack as the TBEGIN itself,
* so as we add items to the body, there will
* be less left over for intermediate calls...
* could add another stack, or could just do it
* this way to see how much of a problem it actually
* is...
*/
if((idx - flag) > 1) {
AST *tcall = (AST *)hmalloc(sizeof(AST));
// preprocess the call for `$` first
for(int tidx = idx - 1, flag = idx; tidx > 0; tidx--) {
debugln;
if(vectmp[tidx]->tag == TDOLLAR) {
debugln;
AST *res = (AST *)hmalloc(sizeof(AST));
res->tag = TCALL;
res->lenchildren = flag - tidx - 1;
res->children = (AST **)hmalloc(sizeof(AST *) * (flag - tidx));
for(int ctidx = tidx + 1, ttidx = 0; ctidx < flag; ctidx++, ttidx++) {
res->children[ttidx] = vectmp[ctidx];
}
debugln;
flag = tidx + 1;
idx = flag;
dprintf("idx == %d, flag == %d\n", idx, flag);
vectmp[tidx] = res;
} else if(vectmp[tidx]->tag == TMODNS) {
// NOTE we need to collapse a `::` name into a qualified named
// that we can look up from a module. This means we need to
// turn anything connected by `::` into a qualified name...
// I can think of three ideas here:
//
// 1. just smoosh them into a string, and parse again later
// 1. nest them arbitrarily, and pull them from the nested set
// 1. treat them like we do types, and add the name to the back
//
// I think the last one is the best idea, because we can just treat
// them like a list of names we need to resolve, in the even that
// people end up nesting modules, but we don't need to parse them
// again like the first answer would
//
// so, in that case, `Foo::Bar::some-call` would become:
// `(qualified-ident Foo Bar some-call)`
dprintf("module namespace collapse into qualified ident\n");
}
}
tcall->tag = TCALL;
tcall->lenchildren = idx - flag;
//printf("idx == %d, flag == %d\n", idx, flag);
tcall->children = (AST **)hmalloc(sizeof(AST *) * tcall->lenchildren);
//printf("len == %d\n", tcall->lenchildren);
for(int i = 0; i < tcall->lenchildren; i++) {
//printf("i == %d\n", i);
/*AST* ttmp = vectmp[flag + i];
walk(ttmp, 0);
printf("\n");*/
tcall->children[i] = vectmp[flag + i];
/*walk(tcall->children[i], 0);
printf("\n");*/
}
tmp = tcall;
} else {
tmp = vectmp[flag];
}
idx = flag;
flag = -1;
} else if(tmp->tag == TNEWL) {
continue;
}
/*walk(tmp, 0);
debugln;
printf("tmp->tag == %d\n", tmp->tag);*/
if(fatflag) {
vectmp[idx++] = tmp;
break;
} else if(tmp->tag == TEND) {
break;
} else {
vectmp[idx++] = tmp;
}
//printf("tmp == nil? %s\n", tmp == nil ? "yes" : "no");
}
head = (AST *)hmalloc(sizeof(AST));
head->tag = TBEGIN;
head->children = (AST **)hmalloc(sizeof(AST *) * idx);
head->lenchildren = idx;
for(int i = 0; i < idx; i++){
//printf("vectmp[i] == nil? %s\n", vectmp[i] == nil ? "yes" : "no");
head->children[i] = vectmp[i];
}
return ASTRight(head);
case TEND:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TEND;
return ASTRight(head);
case TIN:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TIN;
return ASTRight(head);
case TEQUAL:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TEQUAL;
return ASTRight(head);
case TCOREFORM:
break;
case TTAG:
case TIDENT:
head = (AST *)hmalloc(sizeof(AST));
head->value = hstrdup(buffer);
head->lenvalue = strlen(buffer);
head->tag = ltype;
return ASTRight(head);
case TCALL:
break;
case TCUT:
case TOPAREN:
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
tmp = sometmp->right;
if(tmp->tag == TCPAREN) {
if(ltype == TCUT){
return ASTLeft(0, 0, "illegal $() form");
}
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TUNIT;
return ASTRight(tmp);
} else if(tmp->tag != TIDENT && tmp->tag != TTAG) {
return ASTLeft(0, 0, "cannot call non-identifier object");
}
vectmp[idx++] = tmp;
while(1) {
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
tmp = sometmp->right;
if(tmp->tag == TCPAREN){
break;
} else if(tmp->tag == TSEMI) {
return ASTLeft(0, 0, "illegal semicolon within parenthetical call");
} else if(tmp->tag == TNEWL) {
continue;
} else {
vectmp[idx++] = tmp;
}
}
head = (AST *)hmalloc(sizeof(AST));
if(ltype == TCUT) {
head->tag = TCUT;
} else {
head->tag = TCALL;
}
// process these in *reverse*:
// each time you hit a $, add it
// to the stack...
// is it worth it? lemme work it.
// I put my stack down, flip it, and reverse it.
// Ti esrever dna, ti pilf, nwod kcats ym tup i.
// Ti esrever dna, ti pilf, nwod kcats ym tup i.
dprintf("idx == %d\n", idx);
for(int tidx = idx - 1, flag = idx; tidx > 0; tidx--) {
debugln;
if(vectmp[tidx]->tag == TDOLLAR) {
debugln;
AST *res = (AST *)hmalloc(sizeof(AST));
res->tag = TCALL;
res->lenchildren = flag - tidx - 1;
res->children = (AST **)hmalloc(sizeof(AST *) * (flag - tidx));
for(int ctidx = tidx + 1, ttidx = 0; ctidx < flag; ctidx++, ttidx++) {
res->children[ttidx] = vectmp[ctidx];
}
debugln;
flag = tidx + 1;
idx = flag;
dprintf("idx == %d, flag == %d\n", idx, flag);
vectmp[tidx] = res;
}
}
dprintf("idx == %d\n", idx);
head->lenchildren = idx;
head->children = (AST **)hmalloc(sizeof(AST *) * idx);
for(int i = 0; i < idx; i++) {
head->children[i] = vectmp[i];
}
return ASTRight(head);
case TCPAREN:
head = (AST *)hmalloc(sizeof(AST));
head->value = hstrdup(buffer);
head->tag = TCPAREN;
return ASTRight(head);
case TTHEN:
head = (AST *)hmalloc(sizeof(AST));
head->value = hstrdup(buffer);
head->tag = TTHEN;
return ASTRight(head);
case TELSE:
head = (AST *)hmalloc(sizeof(AST));
head->value = hstrdup(buffer);
head->tag = TELSE;
return ASTRight(head);
case TWHEN:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TWHEN;
head->children = (AST **)hmalloc(sizeof(AST *) * 2);
head->lenchildren = 2;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
head->children[0] = sometmp->right;
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
tmp = sometmp->right;
}
if(tmp->tag != TDO) {
return ASTLeft(0, 0, "missing `do` statement from `when`: when CONDITION do EXPRESSION");
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
head->children[1] = sometmp->right;
}
return ASTRight(head);
case TDO:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TDO;
return ASTRight(head);
case TOF:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TOF;
return ASTRight(head);
case TTYPE:
case TPOLY:
head = (AST *)hmalloc(sizeof(AST));
head->tag = ltype;
head->lenchildren = 2;
head->children = (AST **)hmalloc(sizeof(AST *) * 2);
AST *nstack[128] = {nil};
int nsp = 0;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TTAG) {
return ASTLeft(0, 0, "type/poly definition *must* be followed by a Tag name");
} else {
head->value = sometmp->right->value;
}
flag = idx;
/* type|poly Tag type-var* {
* (Tag-name type-member*)+
* }
* need to put this in a loop, so that
* we can read the various idents (typevars)
* before the begin...
*/
while(ltmp != TBEGIN) {
ltmp = next(fdin, &buffer[0], 512);
if(ltmp == TBEGIN) {
break;
} else if(ltmp == TTAG) {
debugln;
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TTAG;
tmp->value = hstrdup(buffer);
vectmp[idx] = tmp;
idx++;
} else {
return ASTLeft(0, 0, "record-definition *must* begin with BEGIN");
}
}
if(idx > flag) {
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TPARAMLIST;
tmp->lenchildren = idx - flag;
tmp->children = (AST **)hmalloc(sizeof(AST *) * tmp->lenchildren);
debugln;
for(int tidx = 0; flag < idx; flag++, tidx++) {
dprintf("%d %d\n", tidx, flag);
tmp->children[tidx] = vectmp[flag];
}
head->children[0] = tmp;
flag = 0;
idx = 0;
} else {
// AGAIN with the option types...
head->children[0] = nil;
}
typestate = -1;
/* here, we just need to read:
* 1. a Tag name
* 2. some number of variables
* Honestly, could almost lift the TDEF code instead...
*/
while(sometmp->right->tag != TEND) {
// so this below fixes the TNEWL
// bug noted in test-type, but it
// introduces another bug of blank
// constructors. I figured that would
// be a problem, because the state
// transition below seems a bit off
// anyway. So, more to fix there, but
// close...
sometmp = llreadexpression(fdin, 1);
//sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
switch(typestate) {
case -1:
if(sometmp->right->tag == TTAG) {
typestate = 0;
vectmp[idx] = sometmp->right;
idx++;
} else if(sometmp->right->tag == TEND || sometmp->right->tag == TNEWL || sometmp->right->tag == TSEMI){
typestate = -1;
} else {
return ASTLeft(0, 0, "type/poly constructors must be Tags.");
}
break;
case 0:
if(sometmp->right->tag == TIDENT) {
typestate = 1;
} else if(issimpletypeast(sometmp->right->tag) || sometmp->right->tag == TCOMPLEXTYPE) {
typestate = 0;
} else if(iscomplextypeast(sometmp->right->tag)) {
flag = idx; // start of complex type
typestate = 3;
} else if(sometmp->right->tag == TEND || sometmp->right->tag == TNEWL || sometmp->right->tag == TSEMI) {
typestate = -1;
} else {
return ASTLeft(0, 0, "constructor's must be followed by a name or a type.");
}
if(typestate != -1) {
debugln;
vectmp[idx] = sometmp->right;
idx++;
}
break;
case 1: // we had an ident, now need a type
if(sometmp->right->tag == TCOLON) {
typestate = 2;
} else {
return ASTLeft(0, 0, "constructor named vars must be followed by a colon and a type specifier.");
}
break;
case 2:
debugln;
if(issimpletypeast(sometmp->right->tag)) {
typestate = 0;
} else if(iscomplextypeast(sometmp->right->tag)) {
typestate = 3;
} else {
return ASTLeft(0, 0, "expecting type in user-type definition");
}
vectmp[idx] = sometmp->right;
idx++;
break;
case 3:
debugln;
if(sometmp->right->tag == TIDENT) {
debugln;
typestate = 1;
vectmp[idx] = sometmp->right;
idx++;
} else if(issimpletypeast(sometmp->right->tag) || sometmp->right->tag == TCOMPLEXTYPE) {
debugln;
typestate = 0;
vectmp[idx] = sometmp->right;
idx++;
} else if(iscomplextypeast(sometmp->right->tag)) {
debugln;
typestate = 3;
vectmp[idx] = sometmp->right;
idx++;
} else if(sometmp->right->tag == TARRAYLITERAL) {
debugln;
typestate = 0;
tmp = sometmp->right;
ctmp = (AST *)hmalloc(sizeof(AST));
ctmp->tag = TCOMPLEXTYPE;
ctmp->lenchildren = 1 + tmp->lenchildren;
ctmp->children = (AST **)hmalloc(sizeof(AST *) * ctmp->lenchildren);
ctmp->children[0] = vectmp[flag];
for(int tidx = 0, cidx = 1; cidx < ctmp->lenchildren; tidx++, cidx++) {
debugln;
ctmp->children[cidx] = tmp->children[tidx];
}
vectmp[flag] = ctmp;
idx = flag + 1;
flag = -1;
debugln;
} else if(sometmp->right->tag == TEND || sometmp->right->tag == TNEWL || sometmp->right->tag == TSEMI) {
debugln;
typestate = -1;
}
debugln;
break;
}
// ok, we got to the end of *something*
// collapse it here
if(typestate == -1 && idx > 0) {
params = (AST *) hmalloc(sizeof(AST));
params->lenchildren = idx;
params->children = (AST **)hmalloc(sizeof(AST *) * idx);
for(int i = 0; i < params->lenchildren; i++, flag++) {
params->children[i] = vectmp[i];
}
params->tag = TTYPEDEF;
nstack[nsp] = params;
flag = 0;
idx = flag;
nsp++;
debugln;
if(sometmp->right->tag == TEND) {
debugln;
break;
}
}
}
// oh, right
// it would be helpful to collect the above
// and make them into like... an AST
debugln;
params = (AST *)hmalloc(sizeof(AST));
dprintf("idx == %d\n", nsp);
params->lenchildren = nsp;
params->children = (AST **)hmalloc(sizeof(AST *) * nsp);
for(int cidx = 0; cidx < nsp; cidx++) {
params->children[cidx] = nstack[cidx];
}
params->tag = TBEGIN;
head->children[1] = params;
debugln;
return ASTRight(head);
break;
case TEXTERN:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TEXTERN;
head->lenchildren = 1;
head->children = (AST **)hmalloc(sizeof(AST *));
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TIDENT && sometmp->right->tag != TTAG) {
return ASTLeft(0, 0, "`extern` *must* be followed by an ident or a tag");
} else {
head->value = sometmp->right->value;
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TCOLON) {
return ASTLeft(0, 0, "`extern`'s name *must* be followed by a `:`");
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(!istypeast(sometmp->right->tag)) {
return ASTLeft(0, 0, "an `extern`'s `:` *must* be followed by a type.");
} else if(issimpletypeast(sometmp->right->tag)) {
head->children[0] = sometmp->right;
} else { // complex type
tmp = sometmp->right;
switch(tmp->tag) {
case TCOMPLEXTYPE:
head->children[0] = tmp;
break;
case TTAG:
default:
vectmp[idx] = tmp;
idx++;
sometmp = llreadexpression(fdin, YES);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TNEWL || sometmp->right->tag == TSEMI) {
tmp->children = (AST **)hmalloc(sizeof(AST *));
tmp->lenchildren = 1;
head->children[0] = tmp;
} else if(sometmp->right->tag != TARRAYLITERAL) {
return ASTLeft(0, 0, "tagged user data types *must* be followed by an array literal or a terminator (newline or semicolon)");
} else {
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TCOMPLEXTYPE;
ltmp = sometmp->right->lenchildren + 1;
tmp->children = (AST **)hmalloc(sizeof(AST *) * ltmp);
tmp->lenchildren = ltmp;
tmp->children[0] = vectmp[idx - 1];
for(int cidx = 1; cidx < ltmp; cidx++) {
tmp->children[cidx] = sometmp->right->children[cidx - 1];
}
head->children[0] = linearize_complex_type(tmp);
}
break;
}
}
return ASTRight(head);
case TVAL:
case TVAR:
head = (AST *)hmalloc(sizeof(AST));
head->tag = ltype;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TIDENT) {
return ASTLeft(0, 0, "val's name *must* be an identifier: `val IDENTIFIER = EXPRESSION`");
} else {
head->value = sometmp->right->value;
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TEQ && sometmp->right->tag != TCOLON){
printf("error: %d\n", sometmp->right->tag);
return ASTLeft(0, 0, "val's identifiers *must* be followed by an `=`: `val IDENTIFIER = EXPRESSION`");
} else if(sometmp->right->tag == TCOLON) {
/* ok, the user is specifying a type here
* we have to consume the type, and then
* store it.
*/
head->lenchildren = 2;
head->children = (AST **)hmalloc(sizeof(AST *) * 2);
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(!istypeast(sometmp->right->tag)) {
return ASTLeft(0, 0, "a `:` form *must* be followed by a type definition...");
} else if(issimpletypeast(sometmp->right->tag)) {
head->children[1] = sometmp->right;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TEQ) {
return ASTLeft(0, 0, "a `val` type definition *must* be followed by an `=`...");
}
} else {
tmp = sometmp->right;
switch(tmp->tag) {
case TCOMPLEXTYPE:
head->children[1] = tmp;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TEQ) {
return ASTLeft(0, 0, "a `val` type definition *must* be followed by an `=`...");
}
break;
case TTAG:
default:
vectmp[idx] = tmp;
idx++;
sometmp = llreadexpression(fdin, YES);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TEQ) {
tmp->children = (AST **)hmalloc(sizeof(AST *));
tmp->lenchildren = 1;
head->children[1] = tmp;
} else if(sometmp->right->tag != TARRAYLITERAL) {
return ASTLeft(0, 0, "tagged user data types *must* be followed by an array literal or a terminator (newline or semicolon)");
} else {
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TCOMPLEXTYPE;
ltmp = sometmp->right->lenchildren + 1;
tmp->children = (AST **)hmalloc(sizeof(AST *) * ltmp);
tmp->lenchildren = ltmp;
tmp->children[0] = vectmp[idx - 1];
for(int cidx = 1; cidx < ltmp; cidx++) {
tmp->children[cidx] = sometmp->right->children[cidx - 1];
}
head->children[1] = linearize_complex_type(tmp);
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TEQ) {
return ASTLeft(0, 0, "a `val` type definition *must* be followed by an `=`...");
}
}
break;
}
}
} else {
head->lenchildren = 1;
head->children = (AST **)hmalloc(sizeof(AST *));
}
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else {
head->children[0] = sometmp->right;
}
return ASTRight(head);
break;
case TOARR:
flag = idx;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
}
while(sometmp->right->tag != TCARR) {
if(sometmp->right->tag != TCOMMA) {
vectmp[idx++] = sometmp->right;
}
sometmp = readexpression(fdin);
}
head = (AST *)hmalloc(sizeof(AST));
head->tag = TARRAYLITERAL;
head->lenchildren = idx - flag;
head->children = (AST **)hmalloc(sizeof(AST *) * (idx - flag));
for(int cidx = 0; flag < idx; cidx++, flag++) {
head->children[cidx] = vectmp[flag];
}
return ASTRight(head);
case TCARR:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TCARR;
return ASTRight(head);
case TRECORD:
head = (AST *)hmalloc(sizeof(AST));
head->tag = TRECORD;
sometmp = llreadexpression(fdin, 1);
/* I like this 3-case block-style
* I think *this* should be the
* "expect" function, but it's
* close enough to have this pattern
* throughout...
*/
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TTAG) {
return ASTLeft(0, 0, "record's name *must* be an identifier: `record IDENTIFIER record-definition`");
} else {
tmp = sometmp->right;
head->value = tmp->value;
}
/* so now we are at the point where
* we have read the _name_ of the
* record, and we have read the
* `=`, so now we need to read
* the definition of the record.
* I have some thought that we may
* want to allow a record definition
* to be <ident (: type)> | { <ident (: type)> + }
* but I also don't know if there
* will be a huge number of
* use-cases for single-member
* records...
*/
ltmp = next(fdin, &buffer[0], 512);
if(ltmp != TBEGIN) {
return ASTLeft(0, 0, "record-definition *must* begin with BEGIN");
}
/* here, we just need to read:
* 1. an ident.
* 2. either a `:` or #\n
* 3. if `:`, we then need to read a type.
*/
while(tmp->tag != TEND) {
sometmp = llreadexpression(fdin, 1);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TNEWL || sometmp->right->tag == TSEMI) {
continue;
} else if(sometmp->right->tag != TIDENT && sometmp->right->tag != TEND) {
printf("%d", sometmp->right->tag);
return ASTLeft(0, 0, "a `record`'s members *must* be identifiers: `name (: type)`");
} else if(sometmp->right->tag == TEND) {
break;
} else {
tmp = sometmp->right;
}
vectmp[idx++] = tmp;
sometmp = llreadexpression(fdin, 1);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TCOLON) {
sometmp = llreadexpression(fdin, 1);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} if(!istypeast(sometmp->right->tag)) {
return ASTLeft(0, 0, "a `:` form *must* be followed by a type definition...");
} else if(issimpletypeast(sometmp->right->tag) || sometmp->right->tag == TCOMPLEXTYPE) {
vectmp[idx] = sometmp->right;
sometmp = llreadexpression(fdin, 1);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TNEWL && sometmp->right->tag != TSEMI) {
return ASTLeft(0, 0, "a simple type *must* be followed by a new line or semi-colon...");
}
/* we have determined a `val <name> : <simple-type>` form
* here, so store them in the record's definition.
*/
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TRECDEF;
tmp->lenchildren = 2;
tmp->children = (AST **)hmalloc(sizeof(AST *) * 2);
tmp->children[0] = vectmp[idx - 1];
tmp->children[1] = vectmp[idx];
vectmp[idx - 1] = tmp;
} else {
/* complex *user* type...
*/
flag = idx;
vectmp[idx++] = sometmp->right;
sometmp = llreadexpression(fdin, YES);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag == TNEWL || sometmp->right->tag == TSEMI) {
(void)1;
} else if(sometmp->right->tag == TARRAYLITERAL) {
tmp = sometmp->right;
for(int tidx = 0; tidx < tmp->lenchildren; tidx++, idx++) {
vectmp[idx] = tmp->children[tidx];
}
} else {
return ASTLeft(0, 0, "a complex user type must be followed by either an array literal of types or a newline/semi-colon");
}
/* collapse the above type states here... */
AST *ctmp = (AST *) hmalloc(sizeof(AST));
ctmp->tag = TCOMPLEXTYPE;
ctmp->lenchildren = idx - flag;
ctmp->children = (AST **) hmalloc(sizeof(AST *) * ctmp->lenchildren);
for(int cidx = 0, tidx = flag, tlen = ctmp->lenchildren; cidx < tlen; cidx++, tidx++) {
ctmp->children[cidx] = vectmp[tidx];
}
ctmp = linearize_complex_type(ctmp);
/* create the record field definition holder */
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TRECDEF;
tmp->lenchildren = 2;
tmp->children = (AST **)hmalloc(sizeof(AST *) * 2);
tmp->children[0] = vectmp[flag - 1];
tmp->children[1] = ctmp;
vectmp[flag - 1] = tmp;
idx = flag;
flag = 0;
}
} else if(sometmp->right->tag == TNEWL || sometmp->right->tag == TSEMI) {
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = TRECDEF;
tmp->lenchildren = 1;
tmp->children = (AST **)hmalloc(sizeof(AST *));
tmp->children[0] = vectmp[idx - 1];
vectmp[idx - 1] = tmp;
} else {
/* we didn't see a `:` or a #\n, so that's
* an error.
*/
return ASTLeft(0, 0, "malformed record definition.");
}
}
/* so, we've constructed a list of record members.
* now, we just need to actually _make_ the record
* structure.
*/
head->lenchildren = idx;
head->children = (AST **)hmalloc(sizeof(AST *) * idx);
for(int i = 0; i < idx; i++){
head->children[i] = vectmp[i];
}
return ASTRight(head);
break;
case TARRAY:
case TREF:
case TDEQUET:
case TFUNCTIONT:
case TPROCEDURET:
case TTUPLET:
case TUNION:
case TLOW:
tmp = (AST *)hmalloc(sizeof(AST));
tmp->tag = ltype;
vectmp[idx] = tmp;
idx++;
sometmp = readexpression(fdin);
if(sometmp->tag == ASTLEFT) {
return sometmp;
} else if(sometmp->right->tag != TARRAYLITERAL) {
return ASTLeft(0, 0, "core complex types *must* have a type parameter.");
}
head = (AST *)hmalloc(sizeof(AST));
head->tag = TCOMPLEXTYPE;
ltmp = sometmp->right->lenchildren + 1;
head->lenchildren = ltmp;
head->children = (AST **)hmalloc(sizeof(AST *) * ltmp);
head->children[0] = vectmp[idx - 1];
// XXX: is this needed?
for(int cidx = 1, tidx = 0; tidx < (ltmp - 1); cidx++, tidx++) {
head->children[cidx] = sometmp->right->children[tidx];
}
head = linearize_complex_type(head);
return ASTRight(head);
case THEX:
case TOCT:
case TBIN:
case TINT:
case TFLOAT:
case TSTRING:
case TCHAR:
case TBOOL:
case TCOMMA:
case TANY:
case TAND:
case TFALSE:
case TTRUE:
case TEQ:
case TCHART:
case TSTRT:
case TINTT:
case TFLOATT:
case TBOOLT:
case TCOLON:
case TWALRUS:
case TMODNS:
case TSEMI:
case TFATARROW:
case TPIPEARROW:
case TGIVEN:
head = (AST *)hmalloc(sizeof(AST));
head->tag = ltype;
head->value = hstrdup(buffer);
return ASTRight(head);
case TNEWL:
if(!nltreatment) {
return llreadexpression(fdin, nltreatment);
} else {
head = (AST *)hmalloc(sizeof(AST));
head->tag = TNEWL;
return ASTRight(head);
}
}
return ASTLeft(0, 0, "unable to parse statement");
}
/* almost should be renamed, but I _think_ I want to try and
* rip out all the custom code used in `let`, `letrec`, and `val`
* in favor of this, which is why I included a type... For example,
* declare forms could break on TNEWL, whereas val could break on
* TEQ.
*/
AST *
mung_declare(const char **pdecls, const int **plexemes, int len, int haltstate) {
return nil;
}
/* read in a single type, and return it as an AST node
*/
ASTOffset *
mung_single_type(const char **pdecls, const int **plexemes, int len, int haltstate, int offset) {
return nil;
}
/* prints a variant condition, like (OptionInt.Some x) becomes
* foo.tag == TAG_OptionInt_SOME
*/
void
mung_variant_name(AST *name, AST *variant, int ref, int golang) {
char varname[128] = {0}, constructor[128] = {0}, *src = variant->value;
int loc = 0, idx = 0, namelen = strlen(src);
uint8_t flag = 0;
// separate the variant name and the constructor name
// in one pass; I'm using a deeply nested if to
// avoid some state tracking. Generally I dislike that
// deep of an if, but it works.
for(; loc < namelen; loc++, idx++) {
if(src[loc] == '.') {
varname[idx] = '\0';
flag = 1;
idx = -1; // the ++ above starts us on the wrong index
} else {
if(!flag) {
varname[idx] = src[loc];
} else {
constructor[idx] = src[loc];
}
}
}
constructor[idx] = '\0';
if(!golang) {
upcase((const char *)&constructor[0], (char *)&constructor[0], 128);
}
if(ref) {
printf("%s->tag == TAG_%s_%s", name->value, varname, constructor);
} else if (golang) {
if(!flag) {
printf("%s", varname);
} else {
printf("%s_%s", varname, constructor);
}
} else {
printf("%s.tag == TAG_%s_%s", name->value, varname, constructor);
}
}
int
check_guard(AST **children, int len_children) {
// a very simple function: walk the spine of children from a `match` form
// and return YES if we have found *any* guard clauses, and NO otherwise
// then, the code generation can make an informed decision.
//
// This is mostly a hack due to the fact that we don't process `match`
// forms into a lower-level form prior to ending up in the code generator
// The best way to solve this would be to transform the various types of
// match into lower-level forms, and then generate code for those.
// for example:
//
// ```
// match x with
// (Foo.Some y) => ...
// (Foo.None) => ...
// end
//
// match z with
// 10 => ...
// 11 => ...
// 12 => ...
// end
//
// match g with
// y given (> g 10) => ...
// z => ...
// end
// ```
//
// these three forms could all be written to different
// lower-level forms, the first a type-match, the second a
// case-match, and the third a guard-match, and then we
// easily know how to dispatch from there. My other thinking
// was how nice it would be to smash cases together and reduce
// the number of dispatches. To wit:
//
// ```
// match x with
// (Foo.Some y) given (> y 10) =>
// (Foo.Some z) => ...
// (Foo.None) => ...
// end
// ```
//
// The naive case would be to simply generate two cases there:
//
// ```c
// if(x.tag == Tag_FOO_SOME && x.m_1 > 10) {
// ...
// } else if (x.tag == TAG_FOO_SOME) {
// ...
// } else if (x.tag == Tag_FOO_NONE) {
// ...
// }
// ```
//
// Whilst this works, it means that we have redundant checks for
// the tag. Something like [Rust's MIR](https://blog.rust-lang.org/2016/04/19/MIR.html)
// would be really interesting...
for(int idx = 0; idx < len_children; idx += 2) {
if(children[idx]->tag == TGUARD) {
return YES;
}
}
return NO;
}
void
mung_guard(FILE *fdout, AST *name, AST *guard) {
AST *mcond = guard->children[0], *mguard = guard->children[1];
if(mcond->tag != TIDENT) {
fprintf(fdout, "(");
}
switch(mcond->tag) {
case TFLOAT:
case TINT:
case TTAG:
fprintf(fdout, "%s == %s", name->value, mcond->value);
break;
case TTRUE:
// could possibly use stdbool here as well
// but currently just encoding directly to
// integers
fprintf(fdout, "%s == 1", name->value);
break;
case TFALSE:
fprintf(fdout, "%s == 0", name->value);
break;
case TCHAR:
fprintf(fdout, "%s == ", name->value);
switch(mcond->value[0]) {
case '\n':
fprintf(fdout, "'\\n'");
break;
case '\r':
fprintf(fdout, "'\\r'");
break;
case '\v':
fprintf(fdout, "'\\v'");
break;
case '\t':
fprintf(fdout, "'\\t'");
break;
case '\b':
fprintf(fdout, "'\\b'");
break;
case '\0':
fprintf(fdout, "'\\0'");
break;
case '\'':
fprintf(fdout, "'\\''");
break;
case '\\':
fprintf(fdout, "'\\\\'");
break;
default:
fprintf(fdout, "'%c'", mcond->value[0]);
break;
}
break;
case TSTRING:
fprintf(fdout, "!strncmp(%s, \"%s\", %lu)", name->value, mcond->value, strlen(mcond->value));
break;
case THEX:
case TOCT:
case TBIN:
fprintf(fdout, "%s == ", name->value);
cwalk(fdout, mcond, 0);
break;
case TARRAYLITERAL:
case TIDENT:
break;
case TCALL:
mung_variant_name(name, mcond->children[0], NO, NO);
break;
default:
break;
}
if(mcond->tag != TIDENT) {
fprintf(fdout, ") && (");
} else {
fprintf(fdout, "(");
// rewrite the name here, need to do the
// same in the response as well...
//mguard = rewrite_ident(name, mguard);
}
cwalk(fdout, mguard, 0);
fprintf(fdout, ")");
}
AST *
mung_complex_type(AST *tag, AST *array) {
// we have here a type that we want to
// create, without having to do the
// lifting in situ elsewhere...
AST *ret = (AST *)hmalloc(sizeof(AST));
ret->tag = TCOMPLEXTYPE;
ret->lenchildren = 1 + array->lenchildren;
ret->children = (AST **)hmalloc(sizeof(AST *) * 2);
ret->children[0] = tag;
for(int idx = 1; idx < ret->lenchildren; idx++) {
ret->children[idx] = array->children[idx - 1];
}
ret = linearize_complex_type(ret);
return ret;
}
void
llindent(FILE *fdout, int level, int usetabsp) {
// should probably look to inline this
// basically what we are replacing is the
// inlined version of the same
for(int idx = 0; idx < level; idx++) {
if(usetabsp == YES) {
fprintf(fdout, "\t");
} else {
fprintf(fdout, " ");
}
}
}
// TODO: remove all the little loops in favor of indent
void
walk(FILE *fdout, AST *head, int level) {
int idx = 0;
AST *tmp = nil;
for(; idx < level; idx++) {
fprintf(fdout, " ");
}
if(head == nil) {
fprintf(fdout, "(nil)\n");
return;
}
switch(head->tag) {
case TFN:
case TDEF:
if(head->tag == TFN) {
fprintf(fdout, "(fn \n");
} else {
fprintf(fdout, "(define %s \n", head->value);
}
if(head->children[0] != nil) {
walk(fdout, head->children[0], level+1);
}
if(head->lenchildren == 3) {
// indent nicely
fprintf(fdout, "\n");
indent(fdout, level + 1);
fprintf(fdout, "(returns ");
walk(fdout, head->children[2], 0);
fprintf(fdout, ")");
}
fprintf(fdout, "\n");
walk(fdout, head->children[1], level + 1);
fprintf(fdout, ")");
break;
case TUSE:
fprintf(fdout, "(use %s)", head->value);
break;
case TEXTERN:
fprintf(fdout, "(extern %s ", head->value);
walk(fdout, head->children[0], 0);
fprintf(fdout, ")");
break;
case TVAL:
case TVAR:
if(head->tag == TVAL) {
fprintf(fdout, "(define-value %s ", head->value);
} else {
fprintf(fdout, "(define-mutable-value %s ", head->value);
}
walk(fdout, head->children[0], 0);
if(head->lenchildren == 2) {
fprintf(fdout, " ");
walk(fdout, head->children[1], 0);
}
fprintf(fdout, ")");
break;
case TDECLARE:
fprintf(fdout, "(declare ");
walk(fdout, head->children[0], 0);
fprintf(fdout, " ");
walk(fdout, head->children[1], 0);
fprintf(fdout, ")");
break;
case TLET:
case TLETREC:
if(head->tag == TLET) {
fprintf(fdout, "(let ");
} else {
fprintf(fdout, "(letrec ");
}
fprintf(fdout, "%s ", head->value);
walk(fdout, head->children[0], 0);
if(head->lenchildren == 3) {
/* if we have a type,
* go ahead and print it.
*/
fprintf(fdout, " ");
walk(fdout, head->children[2], 0);
}
fprintf(fdout, "\n");
walk(fdout, head->children[1], level + 1);
fprintf(fdout, ")");
break;
case TWHEN:
fprintf(fdout, "(when ");
walk(fdout, head->children[0], 0);
fprintf(fdout, "\n");
walk(fdout, head->children[1], level + 1);
fprintf(fdout, ")");
break;
case TWHILE:
fprintf(fdout, "(while ");
walk(fdout, head->children[0], 0);
fprintf(fdout, "\n");
walk(fdout, head->children[1], level + 1);
fprintf(fdout, ")");
break;
case TFOR:
fprintf(fdout, "(for %s ", head->value);
walk(fdout, head->children[0], 0);
fprintf(fdout, "\n");
walk(fdout, head->children[1], level + 1);
fprintf(fdout, ")");
break;
case TPARAMLIST:
fprintf(fdout, "(parameter-list ");
for(idx = 0;idx < head->lenchildren; idx++) {
walk(fdout, head->children[idx], 0);
if(idx < (head->lenchildren - 1)){
fprintf(fdout, " ");
}
}
fprintf(fdout, ") ");
break;
case TPARAMDEF:
fprintf(fdout, "(parameter-definition ");
walk(fdout, head->children[0], 0);
fprintf(fdout, " ");
walk(fdout, head->children[1], 0);
fprintf(fdout, ")");
break;
case TTYPE:
case TPOLY:
if(head->tag == TPOLY) {
fprintf(fdout, "(polymorphic-type ");
} else {
fprintf(fdout, "(type ");
}
fprintf(fdout, "%s ", head->value);
if(head->children[0] != nil)
{
walk(fdout, head->children[0], 0);
}
fprintf(fdout, "\n");
for(int cidx = 0; cidx < head->children[1]->lenchildren; cidx++) {
walk(fdout, head->children[1]->children[cidx], level + 1);
if(cidx < (head->children[1]->lenchildren - 1)) {
fprintf(fdout, "\n");
}
}
fprintf(fdout, ")\n");
break;
case TTYPEDEF:
fprintf(fdout, "(type-constructor ");
for(int cidx = 0; cidx < head->lenchildren; cidx++) {
walk(fdout, head->children[cidx], 0);
if(cidx < (head->lenchildren - 1)) {
fprintf(fdout, " ");
}
}
fprintf(fdout, ")");
break;
case TARRAY:
fprintf(fdout, "(type array)");
break;
case TDEQUET:
fprintf(fdout, "(type deque)");
break;
case TFUNCTIONT:
fprintf(fdout, "(type function)");
break;
case TPROCEDURET:
fprintf(fdout, "(type procedure)");
break;
case TTUPLET:
fprintf(fdout, "(type tuple)");
break;
case TREF:
fprintf(fdout, "(type ref)");
break;
case TLOW:
fprintf(fdout, "(type low)");
break;
case TUNION:
fprintf(fdout, "(type union)");
break;
case TCOMPLEXTYPE:
fprintf(fdout, "(complex-type ");
for(;idx < head->lenchildren; idx++) {
walk(fdout, head->children[idx], 0);
if(idx < (head->lenchildren - 1)){
fprintf(fdout, " ");
}
}
fprintf(fdout, ") ");
break;
case TARRAYLITERAL:
fprintf(fdout, "(array-literal ");
for(int cidx = 0; cidx < head->lenchildren; cidx++) {
walk(fdout, head->children[cidx], 0);
if(cidx < (head->lenchildren - 1)){
fprintf(fdout, " ");
}
}
fprintf(fdout, ") ");
break;
case TCALL:
fprintf(fdout, "(call ");
for(int i = 0; i < head->lenchildren; i++) {
walk(fdout, head->children[i], 0);
if(i < (head->lenchildren - 1)) {
fprintf(fdout, " ");
}
}
fprintf(fdout, ")");
break;
case TMATCH:
debugln;
fprintf(fdout, "(match ");
walk(fdout, head->children[0], 0);
fprintf(fdout, "\n");
tmp = head->children[1];
for(int cidx = 0; cidx < tmp->lenchildren; cidx += 2) {
if(tmp->children[cidx]->tag == TELSE) {
indent(fdout, level + 1);
fprintf(fdout, "else");
} else {
walk(fdout, tmp->children[cidx], level + 1);
}
fprintf(fdout, " => ");
walk(fdout, tmp->children[cidx + 1], 0);
if(cidx < (tmp->lenchildren - 2)) {
fprintf(fdout, "\n");
}
}
fprintf(fdout, ")");
break;
case TGUARD:
fprintf(fdout, "(guarded-condition ");
walk(fdout, head->children[0], 0);
fprintf(fdout, " ");
walk(fdout, head->children[1], 0);
fprintf(fdout, ")");
break;
case TIF:
fprintf(fdout, "(if ");
walk(fdout, head->children[0], 0);
fprintf(fdout, "\n");
walk(fdout, head->children[1], level + 1);
fprintf(fdout, "\n");
walk(fdout, head->children[2], level + 1);
fprintf(fdout, ")");
break;
case TIDENT:
fprintf(fdout, "(identifier %s)", head->value);
break;
case TTAG:
fprintf(fdout, "(tag %s)", head->value);
break;
case TBOOL:
fprintf(fdout, "(bool ");
if(head->value[0] == 0) {
fprintf(fdout, "true)");
} else {
fprintf(fdout, "false)");
}
break;
case TCHAR:
fprintf(fdout, "(character #\\");
switch(head->value[0]) {
case '\a':
fprintf(fdout, "bell");
break;
case '\b':
fprintf(fdout, "backspace");
break;
case '\n':
fprintf(fdout, "newline");
break;
case '\r':
fprintf(fdout, "carriage");
break;
case '\v':
fprintf(fdout, "vtab");
break;
case '\t':
fprintf(fdout, "tab");
break;
case '\0':
fprintf(fdout, "nul");
break;
default:
fprintf(fdout, "%s", head->value);
break;
}
fprintf(fdout, ")");
break;
case TFLOAT:
fprintf(fdout, "(float %s)", head->value);
break;
case TFALSE:
case TTRUE:
fprintf(fdout, "(boolean ");
if(head->tag == TFALSE) {
fprintf(fdout, "false)");
} else {
fprintf(fdout, "true)");
}
break;
case THEX:
fprintf(fdout, "(hex-integer %s)", head->value);
break;
case TOCT:
fprintf(fdout, "(octal-integer %s)", head->value);
break;
case TBIN:
fprintf(fdout, "(binary-integer %s)", head->value);
break;
case TINT:
fprintf(fdout, "(integer %s)", head->value);
break;
case TINTT:
fprintf(fdout, "(type integer)");
break;
case TFLOATT:
fprintf(fdout, "(type float)");
break;
case TBOOLT:
fprintf(fdout, "(type boolean)");
break;
case TCHART:
fprintf(fdout, "(type char)");
break;
case TANY:
fprintf(fdout, "(type any)");
break;
case TSTRT:
fprintf(fdout, "(type string)");
break;
case TSTRING:
fprintf(fdout, "(string \"%s\")", head->value);
break;
case TRECORD:
fprintf(fdout, "(define-record %s\n", head->value);
for(int i = 0; i < head->lenchildren; i++) {
walk(fdout, head->children[i], level + 1);
if(i < (head->lenchildren - 1)) {
fprintf(fdout, "\n");
}
}
fprintf(fdout, ")");
break;
case TRECDEF:
fprintf(fdout, "(record-member ");
walk(fdout, head->children[0], 0);
if(head->lenchildren == 2) {
fprintf(fdout, " ");
walk(fdout, head->children[1], 0);
}
fprintf(fdout, ")");
break;
case TMODULE:
fprintf(fdout, "(module %s\n", head->children[0]->value);
walk(fdout, head->children[1], level + 1);
fprintf(fdout, ")");
break;
case TBEGIN:
fprintf(fdout, "(begin\n");
for(idx = 0; idx < head->lenchildren; idx++){
walk(fdout, head->children[idx], level + 1);
if(idx < (head->lenchildren - 1)) {
fprintf(fdout, "\n");
}
}
fprintf(fdout, ")");
break;
case TEND:
break;
case TUNIT:
fprintf(fdout, "()");
break;
default:
fprintf(fdout, "(tag %d)", head->tag);
break;
}
return;
}
void
generate_type_value(FILE * fdout, AST *head, const char *name) {
int cidx = 0;
char buf[512] = {0}, *rtbuf = nil, rbuf[512] = {0};
char *member = nil, membuf[512] = {0};
// setup a nice definition...
fprintf(fdout, "%s\n%s_%s(", name, name, head->children[0]->value);
// dump our parameters...
for(cidx = 1; cidx < head->lenchildren; cidx++) {
snprintf(buf, 512, "m_%d", cidx);
rtbuf = typespec2c(head->children[cidx], rbuf, buf, 512);
if(cidx < (head->lenchildren - 1)) {
fprintf(fdout, "%s, ", rtbuf);
} else {
fprintf(fdout, "%s", rtbuf);
}
}
fprintf(fdout, ") {\n");
// define our return value...
indent(fdout, 1);
fprintf(fdout, "%s res;\n", name);
// grab the constructor name...
member = head->children[0]->value;
member = upcase(member, membuf, 512);
// tag our type
indent(fdout, 1);
fprintf(fdout, "res.tag = TAG_%s_%s;\n", name, member);
// set all members...
for(cidx = 1; cidx < head->lenchildren; cidx++) {
indent(fdout, 1);
snprintf(buf, 512, "m_%d", cidx);
fprintf(fdout, "res.members.%s_t.%s = %s;\n", member, buf, buf);
}
indent(fdout, 1);
fprintf(fdout, "return res;\n}\n");
}
void
generate_type_ref(FILE *fdout, AST *head, const char *name) {
int cidx = 0;
char buf[512] = {0}, *rtbuf = nil, rbuf[512] = {0};
char *member = nil, membuf[512] = {0};
// setup a nice definition...
fprintf(fdout, "%s *\n%s_%s_ref(", name, name, head->children[0]->value);
// dump our parameters...
for(cidx = 1; cidx < head->lenchildren; cidx++) {
snprintf(buf, 512, "m_%d", cidx);
rtbuf = typespec2c(head->children[cidx], rbuf, buf, 512);
if(cidx < (head->lenchildren - 1)) {
fprintf(fdout, "%s, ", rtbuf);
} else {
fprintf(fdout, "%s", rtbuf);
}
}
fprintf(fdout, ") {\n");
// define our return value...
indent(fdout, 1);
fprintf(fdout, "%s *res = (%s *)malloc(sizeof(%s));\n", name, name, name);
// grab the constructor name...
member = head->children[0]->value;
member = upcase(member, membuf, 512);
// tag our type
indent(fdout, 1);
fprintf(fdout, "res->tag = TAG_%s_%s;\n", name, member);
// set all members...
for(cidx = 1; cidx < head->lenchildren; cidx++) {
indent(fdout, 1);
snprintf(buf, 512, "m_%d", cidx);
fprintf(fdout, "res->members.%s_t.%s = %s;\n", member, buf, buf);
}
indent(fdout, 1);
fprintf(fdout, "return res;\n}\n");
}
void
generate_golang_type(FILE *fdout, AST *head, const char *parent) {
AST *ttmp = head->children[0];
int cidx = 1;
fprintf(fdout, "type %s_%s struct {\n", parent, ttmp->value);
for(; cidx < head->lenchildren; cidx++) {
gindent(fdout, 1);
fprintf(fdout, "m_%d ", cidx);
gwalk(fdout, head->children[cidx], 0);
fprintf(fdout, "\n");
}
fprintf(fdout, "}\n");
fprintf(fdout, "func (%s_%s) is%s() {}\n", parent, ttmp->value, parent);
}
void
llcwalk(FILE *fdout, AST *head, int level, int final) {
int idx = 0, opidx = -1, llflag = 0;
char *tbuf = nil, buf[512] = {0}, rbuf[512] = {0}, *rtbuf = nil;
AST *ctmp = nil, *htmp = nil;
// NOTE: currently here because we die when a return
// type is missing (aka is void/unit)
if(head == nil) {
return;
}
if(head->tag != TBEGIN) {
indent(fdout, level);
// if we have a value form (i.e. a call, an ident,
// a tag, or a literal), and we are in the final
// position of a syntactic block, prepend it with
// a return
if(isvalueform(head->tag) && final) {
fprintf(fdout, "return ");
}
}
if(head == nil) {
fprintf(fdout, "(nil)\n");
return;
}
switch(head->tag) {
case TFN:
case TDEF:
if(head->tag == TFN) {
// need to lift lambdas...
fprintf(fdout, "(fn ");
} else {
if(head->lenchildren == 3) {
if(head->children[2] == nil) {
fprintf(fdout, "void");
} else {
cwalk(fdout, head->children[2], 0);
}
} else {
fprintf(fdout, "void");
}
fprintf(fdout, "\n%s", head->value);
}
if(head->children[0] != nil) {
cwalk(fdout, head->children[0], level);
} else {
fprintf(fdout, "()");
}
fprintf(fdout, "{\n");
llcwalk(fdout, head->children[1], level + 1, YES);
if(isvalueform(head->children[1]->tag)) {
fprintf(fdout, ";\n}");
} else {
fprintf(fdout, "}");
}
break;
case TVAL:
case TVAR:
if(head->tag == TVAL) {
fprintf(fdout, "const ");
}
if(head->lenchildren == 2) {
if(head->children[1]->tag == TCOMPLEXTYPE) {
tbuf = typespec2c(head->children[1], buf, head->value, 512);
fprintf(fdout, "%s = ", tbuf);
} else {
cwalk(fdout, head->children[1], 0);
fprintf(fdout, " %s = ", head->value);
}
} else {
fprintf(fdout, "void *");
fprintf(fdout, " %s = ", head->value);
}
cwalk(fdout, head->children[0], 0);
fprintf(fdout, ";");
break;
case TEXTERN:
fprintf(fdout, "extern ");
if(head->children[0]->tag == TCOMPLEXTYPE) {
tbuf = typespec2c(head->children[0], buf, head->value, 512);
fprintf(fdout, "%s;", tbuf);
} else {
cwalk(fdout, head->children[0], 0);
fprintf(fdout, " %s;", head->value);
}
break;
case TDECLARE:
// so, the format of a TDECLARE is:
// 0. name
// 1. type
if(head->lenchildren == 1 || head->children[1] == nil) {
fprintf(fdout, "void %s", head->children[0]->value);
} else if(head->children[1]->tag == TCOMPLEXTYPE) {
tbuf = typespec2c(head->children[1], buf, head->children[0]->value, 512);
fprintf(fdout, "%s", tbuf);
} else {
cwalk(fdout, head->children[1], 0);
fprintf(fdout, " %s", head->children[0]->value);
}
fprintf(fdout, ";");
break;
case TLET:
case TLETREC:
// need to do name rebinding...
// but I think that's best meant
// for a nanopass...
if(head->tag == TLET) {
fprintf(fdout, "(let ");
} else {
fprintf(fdout, "(letrec ");
}
fprintf(fdout, "%s ", head->value);
cwalk(fdout, head->children[0], 0);
if(head->lenchildren == 3) {
/* if we have a type,
* go ahead and print it.
*/
fprintf(fdout, " ");
cwalk(fdout, head->children[2], 0);
}
fprintf(fdout, "\n");
cwalk(fdout, head->children[1], level + 1);
fprintf(fdout, ")");
break;
case TWHEN:
fprintf(fdout, "if(");
cwalk(fdout, head->children[0], 0);
fprintf(fdout, ") {\n");
// there are some ugly extra calls to
// indent in here, because there's some
// strange interactions between WHEN and
// BEGIN forms.
if(final) {
llcwalk(fdout, head->children[1], level + 1, YES);
if(isvalueform(head->children[1]->tag)) {
fprintf(fdout, ";\n");
}
} else {
cwalk(fdout, head->children[1], level + 1);
if(isvalueform(head->children[1]->tag)) {
fprintf(fdout, ";\n");
}
}
indent(fdout, level);
fprintf(fdout, "}\n");
break;
case TMATCH:
// there are several different strategies to
// use here...
// 1. simple if-then-else chain for things like string compares
// 2. switch block (can use FNV1a for strings => switch, straight for int/float)
// 3. unpacking ADTs means we have to detect tag & collate those cases together
if(head->children[0]->tag == TIDENT) {
ctmp = head->children[0];
} else {
ctmp = (AST *)hmalloc(sizeof(AST));
ctmp->tag = TIDENT;
snprintf(&buf[0], 512, "l%d", rand());
// need to demand a type here...
}
// TODO need to:
// demand a type from the results
// make sure it reifies
// generate if/else
// handle bindings
// for now, just roll with it
htmp = head->children[1];
for(int tidx = 0; tidx < htmp->lenchildren; tidx+=2) {
if(tidx == 0) {
fprintf(fdout, "if(");
} else if(htmp->children[tidx]->tag == TELSE) {
indent(fdout, level);
fprintf(fdout, "} else ");
} else {
indent(fdout, level);
fprintf(fdout, "} else if(");
}
if(htmp->children[tidx]->tag != TELSE) {
switch(htmp->children[tidx]->tag) {
case TFLOAT:
case TINT:
case TTAG:
fprintf(fdout, "%s == %s", ctmp->value, htmp->children[tidx]->value);
break;
case TTRUE:
// could possibly use stdbool here as well
// but currently just encoding directly to
// integers
fprintf(fdout, "%s == 1", ctmp->value);
break;
case TFALSE:
fprintf(fdout, "%s == 0", ctmp->value);
break;
case TCHAR:
fprintf(fdout, "%s == ", ctmp->value);
switch(htmp->children[tidx]->value[0]) {
case '\n':
fprintf(fdout, "'\\n'");
break;
case '\r':
fprintf(fdout, "'\\r'");
break;
case '\v':
fprintf(fdout, "'\\v'");
break;
case '\t':
fprintf(fdout, "'\\t'");
break;
case '\a':
fprintf(fdout, "'\\a'");
break;
case '\b':
fprintf(fdout, "'\\b'");
break;
case '\0':
fprintf(fdout, "'\\0'");
break;
case '\'':
fprintf(fdout, "'\\''");
break;
case '\\':
fprintf(fdout, "'\\\\'");
break;
default:
fprintf(fdout, "'%c'", htmp->children[tidx]->value[0]);
break;
}
break;
case TSTRING:
fprintf(fdout, "!strncmp(%s, \"%s\", %lu)", ctmp->value, htmp->children[tidx]->value, strlen(htmp->children[tidx]->value));
break;
case THEX:
case TOCT:
case TBIN:
fprintf(fdout, "%s == ", ctmp->value);
cwalk(fdout, htmp->children[tidx], 0);
break;
case TARRAYLITERAL:
case TIDENT:
break;
case TCALL:
mung_variant_name(ctmp, htmp->children[tidx]->children[0], NO, NO);
break;
case TGUARD:
mung_guard(fdout, ctmp, htmp->children[tidx]);
break;
default:
break;
}
fprintf(fdout, ") ");
}
fprintf(fdout, "{\n");
if(final) {
llcwalk(fdout, htmp->children[tidx + 1], level + 1, YES);
} else {
cwalk(fdout, htmp->children[tidx + 1], level + 1);
}
// this is probably wrong for certain forms
// need to check this more thoroughly...
fprintf(fdout, ";\n");
}
indent(fdout, level);
fprintf(fdout, "}\n");
break;
case TWHILE:
fprintf(fdout, "while(");
cwalk(fdout, head->children[0], 0);
fprintf(fdout, "){\n");
// FIXME: I think this is wrong;
// we're not detecting if this is the
// final block here, and thus we end up
// in a situation wherein a while cannot
// have a return properly...
// XXX: I actually think the FIXME above is
// wrong hahah. a `while` loop shouldn't care
// if it is in the final position, it's almost
// always wrong to reach into one and attempt
// to determine if it's the final block...
llcwalk(fdout, head->children[1], level + 1, NO);
if(isvalueform(head->children[1]->tag)) {
fprintf(fdout, ";\n");
}
indent(fdout, level);
fprintf(fdout, "}\n");
break;
case TFOR:
// so:
// the head->value is either an integral index OR
// some other iterative type. We need to have a
// special case for checking things like:
//
// for x in (range 0 10) do ...
//
// or
//
// for x in (iota 10) do ...
//
// so as to fuse these and remove interstitial
// objects for now, I guess it is safe to assume
// that head->value is an int, but i *really*
// need to get the type system *actually* rolling
break;
case TPARAMLIST:
fprintf(fdout, "(");
for(;idx < head->lenchildren; idx++) {
AST *dc_type = nil, *dc_name = nil;
if(head->children[idx]->tag == TIDENT) {
dc_name = head->children[idx];
fprintf(fdout, "void *%s", dc_name->value);
} else if(istypeast(head->children[idx]->tag)) {
tbuf = typespec2c(head->children[idx],buf, nil, 512);
fprintf(fdout, "%s", tbuf);
} else {
// now we've reached a TPARAMDEF
// so just dump whatever is returned
// by typespec2c
dc_type = head->children[idx]->children[1];
dc_name = head->children[idx]->children[0];
tbuf = typespec2c(dc_type, buf, dc_name->value, 512);
if(tbuf != nil) {
fprintf(fdout, "%s", tbuf);
} else {
fprintf(fdout, "void *");
}
}
if(idx < (head->lenchildren - 1)){
fprintf(fdout, ", ");
}
}
fprintf(fdout, ")");
break;
case TPARAMDEF:
cwalk(fdout, head->children[1], 0);
fprintf(fdout, " ");
cwalk(fdout, head->children[0], 0);
break;
case TARRAY:
fprintf(fdout, "(type array)");
break;
case TCOMPLEXTYPE:
tbuf = typespec2c(head, buf, nil, 512);
if(tbuf != nil) {
fprintf(fdout, "%s", tbuf);
} else {
fprintf(fdout, "void *");
}
break;
case TTYPE:
case TPOLY:
// setup our name
tbuf = upcase(head->value, &buf[0], 512);
htmp = head->children[1];
// generate our enum for the various tags for this
// type/poly (forEach constructor thereExists |Tag|)
fprintf(fdout, "enum Tags_%s {\n", tbuf);
for(int cidx = 0; cidx < htmp->lenchildren; cidx++) {
indent(fdout, level + 1);
// I hate this, but it works
rtbuf = upcase(htmp->children[cidx]->children[0]->value, rbuf, 512);
fprintf(fdout, "TAG_%s_%s,\n", head->value, rtbuf);
}
fprintf(fdout, "};\n");
// generate the rough structure to hold all
// constructor members
fprintf(fdout, "typedef struct %s_t {\n", tbuf);
indent(fdout, level + 1);
fprintf(fdout, "int tag;\n");
indent(fdout, level + 1);
fprintf(fdout, "union {\n");
// first pass:
// - dump all constructors into a union struct.
// - upcase the constructor name
// TODO: move structs to top-level structs?
// TODO: optimization for null members (like None in Optional)
// TODO: naming struct members based on names given by users
// TODO: inline records
for(int cidx = 0; cidx < htmp->lenchildren; cidx++) {
debugln;
indent(fdout, level + 2);
fprintf(fdout, "struct {\n");
ctmp = htmp->children[cidx];
debugln;
for(int midx = 1; midx < ctmp->lenchildren; midx++) {
debugln;
dprintf("type tag of ctmp: %d\n", ctmp->tag);
dprintf("midx: %d, len: %d\n", midx, ctmp->lenchildren);
indent(fdout, level + 3);
snprintf(buf, 512, "m_%d", midx);
debugln;
dprintf("walking children...\n");
pwalk(ctmp->children[midx], level);
dprintf("done walking children...\n");
dprintf("ctmp->children[%d] == null? %s\n", midx, ctmp->children[midx] == nil ? "yes" : "no");
rtbuf = typespec2c(ctmp->children[midx], rbuf, buf, 512);
fprintf(fdout, "%s;\n", rtbuf);
debugln;
}
indent(fdout, level + 2);
tbuf = upcase(ctmp->children[0]->value, buf, 512);
fprintf(fdout, "} %s_t;\n", buf);
}
indent(fdout, level + 1);
fprintf(fdout, "} members;\n");
fprintf(fdout, "} %s;\n", head->value);
// ok, now we have generated the structure, now we
// need to generate the constructors.
// we need to do two passes at that:
// - one pass with values
// - one pass with references
for(int cidx = 0; cidx < htmp->lenchildren; cidx++) {
generate_type_value(fdout, htmp->children[cidx], head->value);
generate_type_ref(fdout, htmp->children[cidx], head->value);
}
break;
case TARRAYLITERAL:
fprintf(fdout, "{");
for(int cidx = 0; cidx < head->lenchildren; cidx++) {
cwalk(fdout, head->children[cidx], 0);
if(cidx < (head->lenchildren - 1)){
fprintf(fdout, ", ");
}
}
fprintf(fdout, "}");
break;
case TCALL:
// do the lookup of idents here, and if we have
// a C operator, use that instead
opidx = iscoperator(head->children[0]->value);
if(head->children[0]->tag == TIDENT && opidx != -1) {
// low-level construtors like `make-struct` and
// company need to be optimized here... also,
// how oppinionated should they be? `make-struct`
// is generally meant for just laying out a struct
// on stack; if a user defines a memory model of
// heap, should we abide? also it's dumb; a user
// might use `make-struct` to layout something that
// is actually going to a `ref[SomeStruct]`, is that
// going to be a pain in the rear to fix?
if(!strncmp(head->children[0]->value, "return", 6)) {
if(!final) {
fprintf(fdout, "return ");
}
if(head->lenchildren == 2) {
cwalk(fdout, head->children[1], 0);
}
} else if(!strncmp(head->children[0]->value, "make-struct", 11) ||
!strncmp(head->children[0]->value, "make-record", 11)) {
fprintf(fdout, "{ ");
// NOTE (lojikil) make-struct now accepts the name of the
// struct, just like make-array does, but we don't need
// it in C, only in Golang
for(int cidx = 2; cidx < head->lenchildren; cidx++) {
cwalk(fdout, head->children[cidx], 0);
if(cidx < (head->lenchildren - 1)) {
fprintf(fdout, ", ");
}
}
fprintf(fdout, "}");
} else if(!strncmp(head->children[0]->value, "make-deque", 10)) {
} else if(!strncmp(head->children[0]->value, "make-string", 11)) {
} else if(!strncmp(head->children[0]->value, "make-array", 10)) {
// TODO: this is a hack, to get carML lifted into itself
// eventually, we need to actually detect what is going on,
// and use the correct allocator. What I did here was to
// basically assume that the user typed `heap-allocate`
fprintf(fdout, "(");
cwalk(fdout, head->children[1], 0);
fprintf(fdout, "*)hmalloc(sizeof(");
cwalk(fdout, head->children[1], 0);
fprintf(fdout, ") * %s)", head->children[2]->value);
} else if(!strncmp(head->children[0]->value, "make", 4)) {
} else if(!strncmp(head->children[0]->value, "stack-allocate", 14)) {
} else if(!strncmp(head->children[0]->value, "heap-allocate", 13)) {
fprintf(fdout, "(%s *)hmalloc(sizeof(%s) * %s)", head->children[1]->value, head->children[1]->value, head->children[2]->value);
} else if(!strncmp(head->children[0]->value, "region-allocate", 15)) {
} else if(!strncmp(head->children[0]->value, "not", 3)) {
fprintf(fdout, "!");
cwalk(fdout, head->children[1], 0);
} else if(!strncmp(head->children[0]->value, "every", 5)) {
for(int ctidx = 1; ctidx < head->lenchildren; ctidx++) {
fprintf(fdout, "(");
cwalk(fdout, head->children[ctidx], 0);
fprintf(fdout, ")");
if(ctidx < (head->lenchildren - 1)) {
fprintf(fdout, " && ");
}
}
} else if(!strncmp(head->children[0]->value, "one-of", 6)) {
for(int ctidx = 1; ctidx < head->lenchildren; ctidx++) {
fprintf(fdout, "(");
cwalk(fdout, head->children[ctidx], 0);
fprintf(fdout, ")");
if(ctidx < (head->lenchildren - 1)) {
fprintf(fdout, " || ");
}
}
} else if(!strncmp(head->children[0]->value, "none-of", 7)) {
for(int ctidx = 1; ctidx < head->lenchildren; ctidx++) {
fprintf(fdout, "!(");
cwalk(fdout, head->children[ctidx], 0);
fprintf(fdout, ")");
if(ctidx < (head->lenchildren - 1)) {
fprintf(fdout, " && ");
}
}
} else if((!strncmp(head->children[0]->value, "of-constructor", 14) ||
!strncmp(head->children[0]->value, "tag-of-constructor", 17))) {
// need to support reference & value versions here...
fprintf(fdout, "%s->tag",head->children[1]->value);
} else {
if(!strncmp(head->children[0]->value, ".", 2)) {
cwalk(fdout, head->children[1], 0);
fprintf(fdout, "%s", coperators[opidx]);
cwalk(fdout, head->children[2], 0);
} else if(!strncmp(head->children[0]->value, "->", 2)) {
cwalk(fdout, head->children[1], 0);
fprintf(fdout, "%s", coperators[opidx]);
cwalk(fdout, head->children[2], 0);
} else if(!strncmp(head->children[0]->value, "get", 3)) {
cwalk(fdout, head->children[1], 0);
fprintf(fdout, "[");
cwalk(fdout, head->children[2], 0);
fprintf(fdout, "]");
} else {
// NOTE the simplest way to handle this is just to wrap all
// expressions in `()`, but we can also make it a little more
// natural by detecting what sort of expression we have on each
// side of the call, and going from there; it makes the code
// here a little more dense, but makes the code that the enduser
// sees a little nicer
llflag = (head->children[1]->tag == TCALL && !isprimitiveaccessor(head->children[1]->children[0]->value));
if(llflag){
fprintf(fdout, "(");
}
cwalk(fdout, head->children[1], 0);
if(llflag){
fprintf(fdout, ")");
}
fprintf(fdout, " %s ", coperators[opidx]);
llflag = (head->children[2]->tag == TCALL
&& !isprimitiveaccessor(head->children[2]->children[0]->value)
&& (iscoperator(head->children[2]->children[0]->value) > 0));
if(llflag){
fprintf(fdout, "(");
}
cwalk(fdout, head->children[2], 0);
if(llflag){
fprintf(fdout, ")");
}
}
}
} else if(head->lenchildren == 1) {
fprintf(fdout, "%s()", head->children[0]->value);
} else {
fprintf(fdout, "%s(", head->children[0]->value);
for(int i = 1; i < head->lenchildren; i++) {
cwalk(fdout, head->children[i], 0);
if(i < (head->lenchildren - 1)) {
fprintf(fdout, ", ");
}
}
fprintf(fdout, ")");
}
break;
case TIF:
fprintf(fdout, "if(");
cwalk(fdout, head->children[0], 0);
fprintf(fdout, ") {\n");
if(final) {
llcwalk(fdout, head->children[1], level + 1, YES);
} else {
cwalk(fdout, head->children[1], level + 1);
fprintf(fdout, ";");
}
if(isvalueform(head->children[1]->tag)) {
fprintf(fdout, ";\n");
} else {
fprintf(fdout, "\n");
}
indent(fdout, level);
fprintf(fdout, "} else {\n");
if(final) {
llcwalk(fdout, head->children[2], level + 1, YES);
} else {
cwalk(fdout, head->children[2], level + 1);
}
if(isvalueform(head->children[2]->tag)) {
fprintf(fdout, ";\n");
} else {
fprintf(fdout, "\n");
}
indent(fdout, level);
fprintf(fdout, "}\n");
break;
case TIDENT:
case TTAG:
fprintf(fdout, "%s", head->value);
break;
case TBOOL:
/* really, would love to introduce a higher-level
* boolean type, but not sure I care all that much
* for the initial go-around in C...
*/
if(head->value[0] == 0) {
fprintf(fdout, "1");
} else {
fprintf(fdout, "0");
}
break;
case TCHAR:
switch(head->value[0]) {
case '\n':
fprintf(fdout, "'\\n'");
break;
case '\r':
fprintf(fdout, "'\\r'");
break;
case '\t':
fprintf(fdout, "'\\t'");
break;
case '\v':
fprintf(fdout, "'\\v'");
break;
case '\a':
fprintf(fdout, "'\\a'");
break;
case '\b':
fprintf(fdout, "'\\b'");
break;
case '\0':
fprintf(fdout, "'\\0'");
break;
case '\'':
fprintf(fdout, "'\\''");
break;
default:
fprintf(fdout, "'%c'", head->value[0]);
break;
}
break;
case TFLOAT:
fprintf(fdout, "%sf", head->value);
break;
case TFALSE:
case TTRUE:
if(head->tag == TFALSE) {
fprintf(fdout, "false");
} else {
fprintf(fdout, "true");
}
break;
case THEX:
fprintf(fdout, "0x%s", head->value);
break;
case TOCT:
fprintf(fdout, "0%s", head->value);
break;
case TBIN:
fprintf(fdout, "%lu", strtol(head->value, NULL, 2));
break;
case TINT:
fprintf(fdout, "%s", head->value);
break;
case TINTT:
fprintf(fdout, "int");
break;
case TFLOATT:
fprintf(fdout, "float");
break;
case TBOOLT:
fprintf(fdout, "bool");
break;
case TCHART:
fprintf(fdout, "char");
break;
case TSTRT:
/* make a fat version of this?
* or just track the length every
* where?
*/
fprintf(fdout, "char *");
break;
case TSTRING:
fprintf(fdout, "\"%s\"", head->value);
break;
case TRECORD:
fprintf(fdout, "typedef struct %s %s;\nstruct %s {\n", head->value, head->value, head->value);
for(int i = 0; i < head->lenchildren; i++) {
cwalk(fdout, head->children[i], level + 1);
if(i < (head->lenchildren - 1)) {
fprintf(fdout, "\n");
}
}
fprintf(fdout, "\n};");
break;
case TRECDEF:
if(head->lenchildren == 2) {
cwalk(fdout, head->children[1], 0);
} else {
fprintf(fdout, "void *");
}
fprintf(fdout, " ");
cwalk(fdout, head->children[0], 0);
fprintf(fdout, ";");
break;
case TBEGIN:
// TODO: this code is super ugly & can be cleaned up
// clean up idea could be that there doesn't _really_
// need to be a special case for *0*, but rather only
// if we're final == YES and we're at the last member
// (which for a 1-ary BEGIN, that would be 0)
// TODO: I think we need to majorly refactor what's
// going on here. Instead of handling "return" and
// co. within the individual forms, we should rather
// eat the cycles in an extra call to cwalk, and allow
// the value forms to decide if it's a return or the
// like instead. Furthermore, this will allow us to
// just track some simple state here in each of the
// syntactic forms, rather than now where they are
// all rats nests of if's
for(idx = 0; idx < head->lenchildren; idx++) {
if(idx == (head->lenchildren - 1) && final) {
llcwalk(fdout, head->children[idx], level, YES);
} else {
llcwalk(fdout, head->children[idx], level, NO);
}
if(issyntacticform(head->children[idx]->tag)) {
fprintf(fdout, "\n");
} else {
fprintf(fdout, ";\n");
}
}
break;
case TSEMI:
case TEND:
break;
case TUNIT:
fprintf(fdout, "void");
break;
default:
fprintf(fdout, "(tag %d)", head->tag);
break;
}
return;
}
void
llgwalk(FILE *fdout, AST *head, int level, int final) {
int idx = 0, opidx = -1, guard_check = NO, llflag = 0;
char *tbuf = nil, buf[512] = {0};
AST *ctmp = nil, *htmp = nil;
if(head->tag != TBEGIN) {
gindent(fdout, level);
// if we have a value form (i.e. a call, an ident,
// a tag, or a literal), and we are in the final
// position of a syntactic block, prepend it with
// a return
if(isvalueform(head->tag) && final) {
fprintf(fdout, "return ");
}
}
if(head == nil) {
fprintf(fdout, "(nil)\n");
return;
}
switch(head->tag) {
case TFN:
case TDEF:
// print the declaration
fprintf(fdout, "func ");
// if we have a `def`, print the name
if(head->tag == TDEF) {
fprintf(fdout, "%s", head->value);
}
// walk the parameter list, print () if none
if(head->children[0] != nil) {
gwalk(fdout, head->children[0], level);
} else {
fprintf(fdout, "()");
}
fprintf(fdout, " ");
// generate the return type
if(head->lenchildren == 3) {
if(head->children[2] != nil) {
gwalk(fdout, head->children[2], 0);
}
}
fprintf(fdout, " {\n");
llgwalk(fdout, head->children[1], level + 1, YES);
if(isvalueform(head->children[1]->tag)) {
fprintf(fdout, "\n}");
} else {
fprintf(fdout, "}");
}
break;
case TVAL:
// unfortunately, Go actually requires constants
// to be fully constant in their rvalue, so we
// have to detect what's going on here. `val`
// forms subsequently need to be checked at the
// compiler level, not at the transpiled level
if(isprimitivevalue(head->children[0]->tag)) {
fprintf(fdout, "const %s = ", head->value);
} else {
fprintf(fdout, "%s := ", head->value);
}
gwalk(fdout, head->children[0], 0);
break;
case TVAR:
if(head->lenchildren == 2) {
if(head->children[1]->tag == TCOMPLEXTYPE) {
tbuf = typespec2g(head->children[1], buf, head->value, 512);
fprintf(fdout, "var %s = ", tbuf);
} else {
fprintf(fdout, "var %s ", head->value);
gwalk(fdout, head->children[1], 0);
fprintf(fdout, " = ");
}
} else {
fprintf(fdout, " %s := ", head->value);
}
gwalk(fdout, head->children[0], 0);
break;
case TEXTERN:
case TDECLARE:
// there are no externs or forward declarations in go
// *but* we can use this to declare a variable type
// without assigning it a value...
if(istypeast(head->children[1]->tag) && !islambdatypeast(head->children[1]->tag)) {
fprintf(fdout, "var ");
llgwalk(fdout, head->children[0], 0, NO);
fprintf(fdout, " ");
llgwalk(fdout, head->children[1], 0, NO);
}
break;
case TLET:
case TLETREC:
// need to do name rebinding...
// but I think that's best meant
// for a nanopass...
if(head->tag == TLET) {
fprintf(fdout, "(let ");
} else {
fprintf(fdout, "(letrec ");
}
fprintf(fdout, "%s ", head->value);
gwalk(fdout, head->children[0], 0);
if(head->lenchildren == 3) {
/* if we have a type,
* go ahead and print it.
*/
fprintf(fdout, " ");
gwalk(fdout, head->children[2], 0);
}
fprintf(fdout, "\n");
gwalk(fdout, head->children[1], level + 1);
fprintf(fdout, ")");
break;
case TWHEN:
fprintf(fdout, "if ");
gwalk(fdout, head->children[0], 0);
fprintf(fdout, " {\n");
// there are some ugly extra calls to
// gindent in here, because there's some
// strange interactions between WHEN and
// BEGIN forms.
if(final) {
llgwalk(fdout, head->children[1], level + 1, YES);
if(isvalueform(head->children[1]->tag)) {
fprintf(fdout, "\n");
}
} else {
gwalk(fdout, head->children[1], level + 1);
if(isvalueform(head->children[1]->tag)) {
fprintf(fdout, "\n");
}
}
gindent(fdout, level);
fprintf(fdout, "}\n");
break;
case TMATCH:
// there are several different strategies to
// use here...
// 1. simple if-then-else chain for things like string compares
// 2. switch block (can use FNV1a for strings => switch, straight for int/float)
// 3. unpacking ADTs means we have to detect tag & collate those cases together
if(head->children[0]->tag == TIDENT) {
ctmp = head->children[0];
} else {
// probably don't have to generate this for all
// calls, and probably can do some nice things
// with this in Go, need to explore that more...
ctmp = (AST *)hmalloc(sizeof(AST));
ctmp->tag = TIDENT;
snprintf(&buf[0], 512, "l%d", rand());
ctmp->value = hstrdup(buf);
fprintf(fdout, "%s := ", ctmp->value);
gwalk(fdout, head->children[0], 0);
fprintf(fdout, "\n");
gindent(fdout, level);
}
// TODO need to:
// demand a type from the results
// make sure it reifies
// generate if/else
// handle bindings
// for now, just roll with it
htmp = head->children[1];
if(htmp->children[0]->tag == TCALL) {
fprintf(fdout, "switch %s := %s.(type) {\n", ctmp->value, ctmp->value);
} else if(check_guard(htmp->children, htmp->lenchildren) == YES) {
fprintf(fdout, "switch {\n");
guard_check = YES;
} else {
fprintf(fdout, "switch %s {\n", ctmp->value);
}
for(int tidx = 0; tidx < htmp->lenchildren; tidx+=2) {
if(htmp->children[tidx]->tag != TELSE) {
gindent(fdout, level + 1);
fprintf(fdout, "case ");
switch(htmp->children[tidx]->tag) {
case TFLOAT:
case TINT:
case TTAG:
case TIDENT:
case TTRUE:
case TFALSE:
if(guard_check == YES) {
fprintf(fdout, "%s == ", ctmp->value);
}
fprintf(fdout, "%s", htmp->children[tidx]->value);
break;
case TCHAR:
//fprintf(fdout, "'%s'", htmp->children[tidx]->value);
if(guard_check == YES) {
fprintf(fdout, "%s == ", ctmp->value);
}
switch(htmp->children[tidx]->value[0]) {
case '\n':
fprintf(fdout, "'\\n'");
break;
case '\r':
fprintf(fdout, "'\\r'");
break;
case '\t':
fprintf(fdout, "'\\t'");
break;
case '\v':
fprintf(fdout, "'\\v'");
break;
case '\0':
fprintf(fdout, "'\\u0000'");
break;
case '\a':
fprintf(fdout, "'\\a'");
break;
case '\b':
fprintf(fdout, "'\\b'");
break;
case '\'':
fprintf(fdout, "'\\\''");
break;
case '\\':
fprintf(fdout, "'\\\\'");
break;
default:
fprintf(fdout, "'%c'", htmp->children[tidx]->value[0]);
break;
}
break;
case TSTRING:
if(guard_check == YES) {
fprintf(fdout, "%s == ", ctmp->value);
}
fprintf(fdout, "\"%s\"", htmp->children[tidx]->value);
break;
case THEX:
case TOCT:
case TBIN:
if(guard_check == YES) {
fprintf(fdout, "%s == ", ctmp->value);
}
gwalk(fdout, htmp->children[tidx], 0);
break;
case TARRAYLITERAL:
break;
case TCALL:
mung_variant_name(ctmp, htmp->children[tidx]->children[0], NO, YES);
break;
case TGUARD:
mung_guard(fdout, ctmp, htmp->children[tidx]);
break;
default:
break;
}
fprintf(fdout, ":\n");
} else {
gindent(fdout, level + 1);
fprintf(fdout, "default:\n");
}
if(final) {
llgwalk(fdout, htmp->children[tidx + 1], level + 2, YES);
} else {
gwalk(fdout, htmp->children[tidx + 1], level + 2);
}
fprintf(fdout, "\n");
}
gindent(fdout, level);
fprintf(fdout, "}\n");
break;
case TWHILE:
fprintf(fdout, "for ");
gwalk(fdout, head->children[0], 0);
fprintf(fdout, " {\n");
gwalk(fdout, head->children[1], level + 1);
if(isvalueform(head->children[1]->tag)) {
fprintf(fdout, ";\n");
}
gindent(fdout, level);
fprintf(fdout, "}\n");
break;
case TFOR:
// so:
// the head->value is either an integral index OR
// some other iterative type. We need to have a
// special case for checking things like:
//
// for x in (range 0 10) do ...
//
// or
//
// for x in (iota 10) do ...
//
// so as to fuse these and remove interstitial
// objects for now, I guess it is safe to assume
// that head->value is an int, but i *really*
// need to get the type system *actually* rolling
break;
case TPARAMLIST:
fprintf(fdout, "(");
for(;idx < head->lenchildren; idx++) {
AST *dc_type = nil, *dc_name = nil;
if(head->children[idx]->tag == TIDENT) {
dc_name = head->children[idx];
fprintf(fdout, "%s interface{}", dc_name->value);
} else if(istypeast(head->children[idx]->tag)) {
tbuf = typespec2g(head->children[idx],buf, nil, 512);
fprintf(fdout, "%s", tbuf);
tbuf[0] = nul;
} else {
// now we've reached a TPARAMDEF
// so just dump whatever is returned
// by typespec2c
dc_type = head->children[idx]->children[1];
dc_name = head->children[idx]->children[0];
tbuf = typespec2g(dc_type, buf, dc_name->value, 512);
if(tbuf != nil) {
fprintf(fdout, "%s", tbuf);
} else {
fprintf(fdout, "interface {}");
}
tbuf[0] = nul;
}
if(idx < (head->lenchildren - 1)){
fprintf(fdout, ", ");
}
}
fprintf(fdout, ")");
break;
case TPARAMDEF:
gwalk(fdout, head->children[1], 0);
fprintf(fdout, " ");
gwalk(fdout, head->children[0], 0);
break;
case TARRAY:
fprintf(fdout, "(type array)");
break;
case TCOMPLEXTYPE:
tbuf = typespec2g(head, buf, nil, 512);
if(tbuf != nil) {
fprintf(fdout, "%s", tbuf);
} else {
fprintf(fdout, "interface{}");
}
break;
case TTYPE:
// we need to:
// 1. Generate a top-level interface
// 2. Generate a struct per constructor
// 3. Generate a `isFoo`-style function for each struct to be of the interface type
// 4. Add any helper methods
fprintf(fdout, "type %s interface {\n", head->value);
gindent(fdout, level + 1);
fprintf(fdout, "is%s()\n}\n", head->value);
for(int cidx = 0; cidx < head->children[1]->lenchildren; cidx++) {
generate_golang_type(fdout, head->children[1]->children[cidx], head->value);
}
break;
case TPOLY:
// polymorphic ADTs need to be handled like the above, but
// with some monomorphizing in here somewhere, like Flyweight Go
// or the like, I think
break;
case TARRAYLITERAL:
fprintf(fdout, "{");
for(int cidx = 0; cidx < head->lenchildren; cidx++) {
gwalk(fdout, head->children[cidx], 0);
if(cidx < (head->lenchildren - 1)){
fprintf(fdout, ", ");
}
}
fprintf(fdout, "}");
break;
case TCALL:
// do the lookup of idents here, and if we have
// a C operator, use that instead
opidx = iscoperator(head->children[0]->value);
if(head->children[0]->tag == TIDENT && opidx != -1) {
// low-level construtors like `make-struct` and
// company need to be optimized here... also,
// how oppinionated should they be? `make-struct`
// is generally meant for just laying out a struct
// on stack; if a user defines a memory model of
// heap, should we abide? also it's dumb; a user
// might use `make-struct` to layout something that
// is actually going to a `ref[SomeStruct]`, is that
// going to be a pain in the rear to fix?
if(!strncmp(head->children[0]->value, "return", 6)) {
if(!final) {
fprintf(fdout, "return ");
}
gwalk(fdout, head->children[1], 0);
} else if(!strncmp(head->children[0]->value, "make-struct", 11) ||
!strncmp(head->children[0]->value, "make-record", 11)) {
// NOTE (lojikil) in Go we need to print the name of the struct
// when allocating it here...
mung_variant_name(nil, head->children[1], NO, YES);
fprintf(fdout, "{ ");
for(int cidx = 2; cidx < head->lenchildren; cidx++) {
gwalk(fdout, head->children[cidx], 0);
if(cidx < (head->lenchildren - 1)) {
fprintf(fdout, ", ");
}
}
fprintf(fdout, "}");
} else if(!strncmp(head->children[0]->value, "make-deque", 10)) {
} else if(!strncmp(head->children[0]->value, "make-string", 11)) {
fprintf(fdout, "string(");
gwalk(fdout, head->children[1], 0);
fprintf(fdout, ")");
} else if(!strncmp(head->children[0]->value, "make-array", 10)) {
// TODO: this is a hack, to get carML lifted into itself
// eventually, we need to actually detect what is going on,
// and use the correct allocator. What I did here was to
// basically assume that the user typed `heap-allocate`
fprintf(fdout, "make([]");
gwalk(fdout, head->children[1], 0);
fprintf(fdout, ", ");
gwalk(fdout, head->children[2], 0);
fprintf(fdout, ")");
} else if(!strncmp(head->children[0]->value, "make", 4)) {
} else if(!strncmp(head->children[0]->value, "stack-allocate", 14)) {
} else if(!strncmp(head->children[0]->value, "heap-allocate", 13)) {
} else if(!strncmp(head->children[0]->value, "region-allocate", 15)) {
} else if(!strncmp(head->children[0]->value, "not", 3)) {
fprintf(fdout, "!");
gwalk(fdout, head->children[1], 0);
} else if(!strncmp(head->children[0]->value, "every", 5)) {
for(int ctidx = 1; ctidx < head->lenchildren; ctidx++) {
fprintf(fdout, "(");
gwalk(fdout, head->children[ctidx], 0);
fprintf(fdout, ")");
if(ctidx < (head->lenchildren - 1)) {
fprintf(fdout, " && ");
}
}
} else if(!strncmp(head->children[0]->value, "one-of", 6)) {
for(int ctidx = 1; ctidx < head->lenchildren; ctidx++) {
fprintf(fdout, "(");
gwalk(fdout, head->children[ctidx], 0);
fprintf(fdout, ")");
if(ctidx < (head->lenchildren - 1)) {
fprintf(fdout, " || ");
}
}
} else if(!strncmp(head->children[0]->value, "none-of", 7)) {
for(int ctidx = 1; ctidx < head->lenchildren; ctidx++) {
fprintf(fdout, "!(");
gwalk(fdout, head->children[ctidx], 0);
fprintf(fdout, ")");
if(ctidx < (head->lenchildren - 1)) {
fprintf(fdout, " && ");
}
}
} else if(!strncmp(head->children[0]->value, "of-constructor", 14)) {
fprintf(fdout, "reflect.TypeOf(%s)", head->children[1]->value);
} else if(!strncmp(head->children[0]->value, "tag-of-constructor", 17)) {
fprintf(fdout, "reflect.TypeOf(%s).Name()", head->children[1]->value);
} else {
if(!strncmp(head->children[0]->value, ".", 2)) {
gwalk(fdout, head->children[1], 0);
fprintf(fdout, "%s", coperators[opidx]);
gwalk(fdout, head->children[2], 0);
} else if(!strncmp(head->children[0]->value, "->", 2)) {
gwalk(fdout, head->children[1], 0);
fprintf(fdout, "%s", coperators[opidx]);
gwalk(fdout, head->children[2], 0);
} else if(!strncmp(head->children[0]->value, "get", 3)) {
gwalk(fdout, head->children[1], 0);
fprintf(fdout, "[");
gwalk(fdout, head->children[2], 0);
fprintf(fdout, "]");
} else {
llflag = (head->children[1]->tag == TCALL
&& !isprimitiveaccessor(head->children[1]->children[0]->value));
if(llflag){
fprintf(fdout, "(");
}
gwalk(fdout, head->children[1], 0);
if(llflag){
fprintf(fdout, ")");
}
fprintf(fdout, " %s ", coperators[opidx]);
llflag = (head->children[2]->tag == TCALL
&& !isprimitiveaccessor(head->children[2]->children[0]->value)
&& (iscoperator(head->children[2]->children[0]->value) > 0));
if(llflag){
fprintf(fdout, "(");
}
gwalk(fdout, head->children[2], 0);
if(llflag){
fprintf(fdout, ")");
}
}
}
} else if(head->lenchildren == 1) {
fprintf(fdout, "%s()", head->children[0]->value);
} else {
fprintf(fdout, "%s(", head->children[0]->value);
for(int i = 1; i < head->lenchildren; i++) {
gwalk(fdout, head->children[i], 0);
if(i < (head->lenchildren - 1)) {
fprintf(fdout, ", ");
}
}
fprintf(fdout, ")");
}
break;
case TIF:
fprintf(fdout, "if ");
gwalk(fdout, head->children[0], 0);
fprintf(fdout, " {\n");
if(final) {
llgwalk(fdout, head->children[1], level + 1, YES);
} else {
gwalk(fdout, head->children[1], level + 1);
}
fprintf(fdout, "\n");
gindent(fdout, level);
fprintf(fdout, "} else {\n");
if(final) {
llgwalk(fdout, head->children[2], level + 1, YES);
} else {
gwalk(fdout, head->children[2], level + 1);
}
fprintf(fdout, "\n");
gindent(fdout, level);
fprintf(fdout, "}\n");
break;
case TIDENT:
fprintf(fdout, "%s", head->value);
break;
case TTAG:
tbuf = typespec2g(head, buf, nil, 512);
if(tbuf != nil) {
fprintf(fdout, "%s", tbuf);
} else {
fprintf(fdout, "interface{}");
}
break;
case TBOOL:
/* really, would love to introduce a higher-level
* boolean type, but not sure I care all that much
* for the initial go-around in C...
*/
if(head->value[0] == 0) {
fprintf(fdout, "true");
} else {
fprintf(fdout, "false");
}
break;
case TCHAR:
switch(head->value[0]) {
case '\n':
fprintf(fdout, "'\\n'");
break;
case '\r':
fprintf(fdout, "'\\r'");
break;
case '\t':
fprintf(fdout, "'\\t'");
break;
case '\v':
fprintf(fdout, "'\\v'");
break;
case '\a':
fprintf(fdout, "'\\a'");
break;
case '\b':
fprintf(fdout, "'\\b'");
break;
case '\0':
fprintf(fdout, "'\\u0000'");
break;
case '\'':
fprintf(fdout, "'\\\''");
break;
case '\\':
fprintf(fdout, "'\\\\'");
break;
default:
fprintf(fdout, "'%c'", head->value[0]);
break;
}
break;
case TFLOAT:
fprintf(fdout, "%sf", head->value);
break;
case TFALSE:
case TTRUE:
if(head->tag == TFALSE) {
fprintf(fdout, "false");
} else {
fprintf(fdout, "true");
}
break;
case THEX:
fprintf(fdout, "0x%s", head->value);
break;
case TOCT:
fprintf(fdout, "0%s", head->value);
break;
case TBIN:
fprintf(fdout, "%lu", strtol(head->value, NULL, 2));
break;
case TINT:
fprintf(fdout, "%s", head->value);
break;
case TINTT:
fprintf(fdout, "int");
break;
case TFLOATT:
fprintf(fdout, "float");
break;
case TBOOLT:
fprintf(fdout, "bool");
break;
case TCHART:
fprintf(fdout, "byte");
break;
case TSTRT:
/* make a fat version of this?
* or just track the length every
* where?
*/
fprintf(fdout, "string");
break;
case TSTRING:
fprintf(fdout, "\"%s\"", head->value);
break;
case TRECORD:
fprintf(fdout, "type %s struct {\n", head->value);
for(int i = 0; i < head->lenchildren; i++) {
gwalk(fdout, head->children[i], level + 1);
if(i < (head->lenchildren - 1)) {
fprintf(fdout, "\n");
}
}
fprintf(fdout, "\n}");
break;
case TRECDEF:
gwalk(fdout, head->children[0], 0);
fprintf(fdout, " ");
if(head->lenchildren == 2) {
gwalk(fdout, head->children[1], 0);
} else {
fprintf(fdout, "interface{}");
}
break;
case TBEGIN:
for(idx = 0; idx < head->lenchildren; idx++) {
if(idx == (head->lenchildren - 1) && final) {
llgwalk(fdout, head->children[idx], level, YES);
} else {
llgwalk(fdout, head->children[idx], level, NO);
}
fprintf(fdout, "\n");
}
break;
case TSEMI:
case TEND:
break;
case TUNIT:
fprintf(fdout, "interface {}");
break;
default:
fprintf(fdout, "(tag %d)", head->tag);
break;
}
return;
}
int
compile(FILE *fdin, FILE *fdout) {
/* _compile_ a file from `fdin`, using _read_, and generate some
* decent C code from it, which is written to `fdout`.
*/
return -1;
}
char *
hstrdup(const char *s)
{
char *ret = nil;
int l = 0, i = 0;
if(s == nil)
return nil;
l = strlen(s);
if((ret = (char *)hmalloc(sizeof(char) * l + 1)) == nil)
return nil;
for(;i < l;i++)
ret[i] = s[i];
ret[i] = nul;
return ret;
}
char *
upcase(const char *src, char *dst, int len) {
int idx = 0;
for(; idx < len; idx++) {
if(src[idx] == '\0') {
dst[idx] = '\0';
break;
} else if(idx == (len - 1)) {
dst[idx] = '\0';
break;
} else if(src[idx] >= 'a' && src[idx] <= 'z') {
dst[idx] = 'A' + (src[idx] - 'a');
} else {
dst[idx] = src[idx];
}
}
return dst;
}
char *
downcase(const char *src, char *dst, int len) {
int idx = 0;
for(; idx < len; idx++) {
if(src[idx] == '\0') {
dst[idx] = '\0';
break;
} else if(idx == (len - 1)) {
dst[idx] = '\0';
break;
} else if(src[idx] >= 'A' && src[idx] <= 'Z') {
dst[idx] = 'a' + (src[idx] - 'A');
} else {
dst[idx] = src[idx];
}
}
return dst;
}
|
CoollRock/ecflow | ACore/src/ecflow_version.h | #ifndef ecflow_version_config_h
#define ecflow_version_config_h
#define ECFLOW_VERSION "5.7.3"
#define ECFLOW_RELEASE "5"
#define ECFLOW_MAJOR "7"
#define ECFLOW_MINOR "3"
// available but not used
//PROJECT_VERSION=5.7.3
//PROJECT_VERSION_MAJOR=5
//PROJECT_VERSION_MINOR=7
//PROJECT_VERSION_PATCH=3
#endif
|
HamedKh99/git-workshop | temp/b.c | <reponame>HamedKh99/git-workshop
#include <stdio.h>
int main(){
printf("%d",9);
}
|
HamedKh99/git-workshop | a.c | #include <stdio.h>
int main(){
int a;
a = 5;
a = 6;
printf("salam");
}
|
victor-shepardson/av-turing-machines | src/ofApp.h | #pragma once
#include "ofMain.h"
#include "ofxXmlSettings.h"
#include "ofxVideoRecorder.h"
#include "ofxAVTuringMachine.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void close();
void audioOut(float * output, int bufferSize, int nChannels);
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
void beginVideoRecord();
void endVideoRecord();
void toggleVideoRecord();
bool recording;
vector<shared_ptr<ofxAVTuringMachine> > tm;
string ffmpeg_path;
ofxVideoRecorder recorder;
ofFbo readback_fbo;
int32_t shape;
// int32_t bits;
int32_t audio_sample_rate, video_frame_rate, audio_channels, audio_device, record_width, record_height;
bool print, fullscreen;
ofSoundStream ss;
};
|
Cybegon/SMA | src/memoryheaders.h | <reponame>Cybegon/SMA<filename>src/memoryheaders.h
//
// Created by Limaaron on 08.09.2020.
//
#ifndef SMA_MEMORY_HEADERS_H
#define SMA_MEMORY_HEADERS_H
#include "datatypes.h"
PACKED_BEGIN
typedef enum
{
PS_Free = 0x00,
PS_Allocated = 0x3F,
PS_Root = 0x7F
} PACKED PageStatus;
typedef struct
{
dsize size;
dsize pageSize;
dsize offset;
} PACKED MemoryHeader;
typedef struct
{
POINTER prevPage;
POINTER nextPage;
PageStatus status;
dsize offset;
} PACKED PageHeader;
PACKED_END
#endif //SMA_MEMORY_HEADERS_H
|
Cybegon/SMA | src/smalib.c | <filename>src/smalib.c
#include "smalib.h"
POINTER moveRight( POINTER ptr, dsize offset )
{
return POINTER_CAST( POINTER, POINTER_CAST( dpchar, ptr ) + offset );
}
POINTER moveLeft( POINTER ptr, dsize offset )
{
return POINTER_CAST( POINTER, POINTER_CAST( dpchar, ptr ) - offset );
}
|
Cybegon/SMA | src/public/datatypes.h | #ifndef DATATYPE_GLOBAL_HPP
#define DATATYPE_GLOBAL_HPP
#define KB(VALUE) VALUE * 1024;
#define MB(VALUE) VALUE * 1024 * 1024;
#define GB(VALUE) VALUE * 1024 * 1024 * 1024;
// If the build system not defined macros
// we try to get them using pre-processor methods
#if !defined(ARCH_64BITS) && !defined(ARCH_32BITS)
# if defined(__amd64__) || defined(_WIN64) || __SIZEOF_POINTER__ == 8 // 64 bits
# define ARCH_64BITS
# elif defined(__x86_64__) || defined(_WIN32) || __SIZEOF_POINTER__ == 4 // 32 bits
# define ARCH_32BITS
# else
# error Unsupported architecture
# endif
#endif
#if !defined(CYBEGON_COMPILER_GCC) && !defined(CYBEGON_COMPILER_MSVC)
# if defined(__GNUC__) || defined(__GNUG__)
# define CYBEGON_COMPILER_GCC
# elif defined(_MSC_VER)
# define CYBEGON_COMPILER_MSVC
# else
# error Unsupported compiler
# endif
#endif
#ifdef CYBEGON_COMPILER_GCC
# define PACKED_BEGIN
# define PACKED __attribute__((__packed__))
# define PACKED_END
#elif CYBEGON_COMPILER_MSVC
# define PACKED_BEGIN __pragma(pack(push, 1))
# define PACKED
# define PACKED_END __pragma(pack(pop))
#else
# error PACKED macros are not defined for this compiler
#endif
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
#ifdef SFML_LIBRARY
# include <System/String.hpp>
# define TEXT(STRING) sf::String(STRING)
#endif // SFML_LIBRARY
#ifdef __cplusplus
# define abstract
# define interface class
#endif
typedef char dchar;
typedef unsigned char duchar;
typedef unsigned short dushort;
typedef unsigned duint;
typedef unsigned long dulong;
typedef dchar *dpchar;
typedef duchar *dpuchar;
typedef int dint; // 32 bit signed
typedef unsigned int duint; // 32 bit unsigned
typedef unsigned char duint8; // 8 bit unsigned
typedef short dint16; // 16 bit signed
typedef unsigned short duint16; // 16 bit unsigned
typedef int dint32; // 32 bit signed
typedef signed char dint8; // 8 bit signed
typedef unsigned int duint32; // 32 bit unsigned
typedef long long dint64; // 64 bit signed
typedef unsigned long long duint64; // 64 bit unsigned
typedef unsigned char dBYTE;
#ifdef ARCH_64BITS
# ifdef __APPLE__
typedef dulong dsize;
# else
typedef duint64 dsize;
# endif
#elif ARCH_32BITS
typedef duint32 dsize;
#else
# error Unsupported architecture
#endif
typedef void* POINTER;
typedef POINTER MEMORY;
#endif // DATATYPE_GLOBAL_HPP
|
Cybegon/SMA | src/public/smalib.h | <filename>src/public/smalib.h
#ifndef SMA_LIB_HPP
#define SMA_LIB_HPP
#include "datatypes.h"
#ifdef __cplusplus
# include <cstdio>
# define POINTER_CAST(TYPE, POINTER) ( reinterpret_cast<TYPE>(POINTER) )
#else
# include <stdio.h>
# define POINTER_CAST(TYPE, POINTER) ( (TYPE) POINTER )
#endif
#define SMA_PRINT(...) printf(__VA_ARGS__)
POINTER moveRight( POINTER ptr, dsize offset );
POINTER moveLeft( POINTER ptr, dsize offset );
#endif // SMA_LIB_HPP
|
Cybegon/SMA | src/public/smallocator.h | <reponame>Cybegon/SMA
//
// Created by Limaaron on 08.09.2020.
//
#ifndef SMA_SMA_LLOCATOR_H
#define SMA_SMA_LLOCATOR_H
#include "smalib.h"
#include "datatypes.h"
typedef MEMORY (*AllocFunc)( dsize size );
typedef MEMORY (*ReAllocFunc)( MEMORY mem, dsize size );
typedef void (*FreeFunc)( MEMORY mem );
typedef enum SMA_ErrorType
{
smaNotInit = 0x01,
failAlloc = 0x02,
failReAlloc = 0x04,
failOutOfMem = 0x08
} SMA_ErrorType;
void SMA_InitDefault( duint *err );
void SMA_Init(duint *err,
AllocFunc allocator,
ReAllocFunc reAllocator,
FreeFunc free );
MEMORY SMA_Alloc( dsize size );
MEMORY SMA_ReAlloc( MEMORY mem, dsize size );
void SMA_Free( MEMORY mem );
dsize SMA_GetGlobalAllocated();
dsize SMA_GetAllocated( MEMORY mem );
dsize SMA_GetOffset( MEMORY mem );
void SMA_SetOffset( MEMORY mem, dsize offset );
void SMA_MoveLeftOffset( MEMORY mem, dsize size );
void SMA_MoveRightOffset( MEMORY mem, dsize size );
#endif // SMA_SMA_LLOCATOR_H
|
Cybegon/SMA | src/smallocator.c | //
// Created by Limaaron on 08.09.2020.
//
#include "smallocator.h"
#include "memoryheaders.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SMA_ErrorMessage( TEXT ) "[SMA] Error: %s", TEXT
static dsize m_uiAllocated = 0;
static duint *errorPtr = NULL;
static AllocFunc allocMem = NULL;
static ReAllocFunc reAllocMem = NULL;
static FreeFunc freeMem = NULL;
void SMA_Error( SMA_ErrorType errorType )
{
#ifdef SMA_MESSAGES
switch ( errorType )
{
case smaNotInit:
printf( SMA_ErrorMessage( "SMA Not initialized." ) );
break;
case failAlloc:
printf( SMA_ErrorMessage( "failed to allocate memory." ) );
break;
case failReAlloc:
printf( SMA_ErrorMessage( "failed to reallocate memory." ) );
break;
case failOutOfMem:
printf( SMA_ErrorMessage( "out of memory." ) );
default:
break;
}
#endif
*errorPtr |= errorType;
}
void SMA_InitDefault( duint *err )
{
errorPtr = err;
allocMem = malloc;
reAllocMem = realloc;
freeMem = free;
}
void SMA_Init( duint *err,
AllocFunc allocator,
ReAllocFunc reAllocator,
FreeFunc free )
{
errorPtr = err;
allocMem = allocator;
reAllocMem = reAllocator;
freeMem = free;
}
MEMORY SMA_Alloc( dsize size )
{
if (allocMem == NULL)
SMA_Error( smaNotInit );
dsize totalSize = size + sizeof( MemoryHeader );
MEMORY mem = allocMem( totalSize );
if ( mem == NULL )
SMA_Error( failAlloc );
memset( mem, 0, totalSize );
MemoryHeader memHeader;
memHeader.size = size;
memHeader.pageSize = 0;
memHeader.offset = 0;
memcpy( mem, &memHeader, sizeof( MemoryHeader ) );
mem = moveRight( mem, sizeof( MemoryHeader ) );
m_uiAllocated += totalSize;
return mem;
}
MEMORY SMA_ReAlloc( MEMORY mem, dsize size )
{
if (reAllocMem == NULL)
SMA_Error( smaNotInit );
mem = moveLeft( mem, sizeof( MemoryHeader ) );
MemoryHeader* memHeader = POINTER_CAST( MemoryHeader*, mem );
m_uiAllocated -= memHeader->size;
memHeader->size = size;
m_uiAllocated += size;
mem = reAllocMem( mem, size + sizeof( MemoryHeader ) );
if ( mem == NULL )
SMA_Error( failReAlloc );
return moveRight( mem, sizeof ( MemoryHeader ) );
}
void SMA_Free( MEMORY mem )
{
if ( freeMem == NULL )
SMA_Error( smaNotInit );
mem = moveLeft( mem, sizeof( MemoryHeader ) );
MemoryHeader *memHeader = POINTER_CAST( MemoryHeader*, mem );
m_uiAllocated -= memHeader->size + sizeof( MemoryHeader );
freeMem( mem );
}
dsize SMA_GetGlobalAllocated()
{
return m_uiAllocated;
}
dsize SMA_GetAllocated( MEMORY mem )
{
mem = moveLeft( mem, sizeof( MemoryHeader ) );
MemoryHeader *memHeader = POINTER_CAST( MemoryHeader*, mem );
return memHeader->size;
}
dsize SMA_GetOffset( MEMORY mem )
{
mem = moveLeft( mem, sizeof( MemoryHeader ) );
MemoryHeader *memHeader = POINTER_CAST( MemoryHeader*, mem );
return memHeader->offset;
}
void SMA_SetOffset( MEMORY mem, dsize _offset )
{
mem = moveLeft( mem, sizeof( MemoryHeader ) );
MemoryHeader *memHeader = POINTER_CAST( MemoryHeader*, mem );
if ( _offset > memHeader->size )
SMA_Error( failOutOfMem );
memHeader->offset = _offset;
}
void SMA_MoveLeftOffset( MEMORY mem, dsize size )
{
mem = moveLeft( mem, sizeof( MemoryHeader ) );
MemoryHeader *memHeader = POINTER_CAST( MemoryHeader*, mem );
if (memHeader->offset < size)
memHeader->offset = 0;
else
memHeader->offset -= size;
}
void SMA_MoveRightOffset( MEMORY mem, dsize size )
{
mem = moveLeft( mem, sizeof( MemoryHeader ) );
MemoryHeader *memHeader = POINTER_CAST( MemoryHeader*, mem );
if ( ( memHeader->offset + size ) > memHeader->size )
SMA_Error( failOutOfMem );
memHeader->offset += size;
}
|
ClubNix/man-terminal | Exemple/gcc/chat.c | <gh_stars>0
#include <stdio.h>
int main(){
printf("oh, un çhat\n");
return 0;
}
|
SpriteOvO/SchemaResolver | Source/Utils.h | #pragma once
#include <string>
#include <Windows.h>
#include <assert.h>
#include "Config.h"
#define SR_TO_STRING_INTERNAL(v) # v
#define SR_TO_STRING(v) SR_TO_STRING_INTERNAL(v)
#if defined _DEBUG
# define SR_ASSERT(condition) while(!(condition)) { __debugbreak(); }
#else
# define SR_ASSERT(condition) while(!(condition)) { MessageBoxW(NULL, L"An runtime error has occurred!\n\nCondition: " SR_TO_STRING(condition) "\nFunction: " __FUNCTION__ "\nLine: " SR_TO_STRING(__LINE__) "\nFile: " __FILE__, L"SchemaResolver v" SR_VERSION_STRING, MB_ICONERROR); std::terminate(); }
#endif
#define SR_UNUSED(...) __VA_ARGS__
#include "Native.h"
namespace std
{
#ifdef UNICODE
using tstring = std::wstring;
#else
using tstring = std::string;
#endif
} // namespace std
namespace System
{
namespace Version
{
bool IsXpOrGreater();
bool IsXpSp1OrGreater();
bool IsXpSp2OrGreater();
bool IsXpSp3OrGreater();
bool IsVistaOrGreater();
bool IsVistaSp1OrGreater();
bool IsVistaSp2OrGreater();
bool Is7OrGreater();
bool Is7Sp1OrGreater();
bool Is8OrGreater();
bool Is81OrGreater();
bool Is10OrGreater();
} // namespace Version
} // namespace System
namespace Text
{
std::wstring ToLower(const std::wstring &String);
} // namespace Text
namespace Thread
{
TebT* GetCurrentTeb();
} // namespace Thread
namespace Process
{
PebT* GetCurrentPeb();
} // namespace Process
|
SpriteOvO/SchemaResolver | Source/Native.h | <reponame>SpriteOvO/SchemaResolver<filename>Source/Native.h<gh_stars>1-10
#pragma once
#include "Utils.h"
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
using FnRtlGetVersionT = NTSTATUS(NTAPI*)(RTL_OSVERSIONINFOW *pVersionInformation);
struct PebT
{
void* ApiSetMap()
{
#if defined _WIN64
return *(void**)((uint8_t*)this + 0x68);
#else
return *(void**)((uint8_t*)this + 0x38);
#endif
}
};
struct TebT
{
PebT* Peb()
{
#if defined _WIN64
return *(PebT**)((uint8_t*)this + 0x60);
#else
return *(PebT**)((uint8_t*)this + 0x30);
#endif
}
};
namespace ApiSet
{
// Windows 10
//
namespace _10
{
struct NamespaceArrayT;
struct ValueEntryT
{
uint32_t Flags;
uint32_t NameOffset;
uint32_t NameLength;
uint32_t ValueOffset;
uint32_t ValueLength;
std::wstring HostName(NamespaceArrayT *pNamespaceArray)
{
SR_ASSERT(ValueLength % sizeof(wchar_t) == 0);
return std::wstring{(wchar_t*)((uint8_t*)pNamespaceArray + ValueOffset), ValueLength / 2};
}
};
struct ValueArrayT
{
uint32_t Flags;
uint32_t NameOffset;
uint32_t Unk;
uint32_t NameLength;
uint32_t DataOffset;
uint32_t Count;
ValueEntryT* Entry(NamespaceArrayT *pNamespaceArray, uint32_t Index)
{
return (ValueEntryT*)((uint8_t*)pNamespaceArray + DataOffset + Index * sizeof(ValueEntryT));
}
};
struct NamespaceEntryT
{
uint32_t Limit;
uint32_t Size;
};
struct NamespaceArrayT
{
uint32_t Version;
uint32_t Size;
uint32_t Flags;
uint32_t Count;
uint32_t Start;
uint32_t End;
uint32_t _Unknown[2];
NamespaceEntryT* Entry(uint32_t Index)
{
return (NamespaceEntryT*)((uint8_t*)this + End + Index * sizeof(NamespaceEntryT));
}
ValueArrayT* ValueArray(NamespaceEntryT *pEntry)
{
return (ValueArrayT*)((uint8_t*)this + Start + sizeof(ValueArrayT) * pEntry->Size);
}
std::wstring ApiName(NamespaceEntryT *pEntry)
{
ValueArrayT *pValueArray = ValueArray(pEntry);
SR_ASSERT(pValueArray->NameLength % sizeof(wchar_t) == 0);
return std::wstring{(wchar_t*)((uint8_t*)this + pValueArray->NameOffset), pValueArray->NameLength / 2};
}
};
} // namespace _10
// Windows 8.1
//
namespace _81
{
struct NamespaceArrayT;
struct ValueEntryT
{
uint32_t Flags;
uint32_t NameOffset;
uint32_t NameLength;
uint32_t ValueOffset;
uint32_t ValueLength;
std::wstring HostName(NamespaceArrayT *pNamespaceArray)
{
SR_ASSERT(ValueLength % sizeof(wchar_t) == 0);
return std::wstring{(wchar_t*)((uint8_t*)pNamespaceArray + ValueOffset), ValueLength / 2};
}
};
struct ValueArrayT
{
uint32_t Flags;
uint32_t Count;
ValueEntryT Array[ANYSIZE_ARRAY];
ValueEntryT* Entry(NamespaceArrayT *pNamespaceArray, uint32_t Index)
{
SR_UNUSED(pNamespaceArray);
return Array + Index;
}
};
struct NamespaceEntryT
{
uint32_t Flags;
uint32_t NameOffset;
uint32_t NameLength;
uint32_t AliasOffset;
uint32_t AliasLength;
uint32_t DataOffset;
};
struct NamespaceArrayT
{
uint32_t Version;
uint32_t Size;
uint32_t Flags;
uint32_t Count;
NamespaceEntryT Array[ANYSIZE_ARRAY];
NamespaceEntryT* Entry(uint32_t Index)
{
return Array + Index;
}
ValueArrayT* ValueArray(NamespaceEntryT *pEntry)
{
return (ValueArrayT*)((uint8_t*)this + pEntry->DataOffset);
}
std::wstring ApiName(NamespaceEntryT *pEntry)
{
SR_ASSERT(pEntry->NameLength % sizeof(wchar_t) == 0);
return std::wstring{(wchar_t*)((uint8_t*)this + pEntry->NameOffset), pEntry->NameLength / 2};
}
};
} // namespace _81
// Windows 7 or Windows 8
//
namespace _7_8
{
struct NamespaceArrayT;
struct ValueEntryT
{
uint32_t NameOffset;
uint32_t NameLength;
uint32_t ValueOffset;
uint32_t ValueLength;
std::wstring HostName(NamespaceArrayT *pNamespaceArray)
{
SR_ASSERT(ValueLength % sizeof(wchar_t) == 0);
return std::wstring{(wchar_t*)((uint8_t*)pNamespaceArray + ValueOffset), ValueLength / 2};
}
};
struct ValueArrayT
{
uint32_t Count;
ValueEntryT Array[ANYSIZE_ARRAY];
ValueEntryT* Entry(NamespaceArrayT *pNamespaceArray, uint32_t Index)
{
SR_UNUSED(pNamespaceArray);
return Array + Index;
}
};
struct NamespaceEntryT
{
uint32_t NameOffset;
uint32_t NameLength;
uint32_t DataOffset;
};
struct NamespaceArrayT
{
uint32_t Version;
uint32_t Count;
NamespaceEntryT Array[ANYSIZE_ARRAY];
NamespaceEntryT* Entry(uint32_t Index)
{
return Array + Index;
}
ValueArrayT* ValueArray(NamespaceEntryT *pEntry)
{
return (ValueArrayT*)((uint8_t*)this + pEntry->DataOffset);
}
std::wstring ApiName(NamespaceEntryT *pEntry)
{
SR_ASSERT(pEntry->NameLength % sizeof(wchar_t) == 0);
return std::wstring{(wchar_t*)((uint8_t*)this + pEntry->NameOffset), pEntry->NameLength / 2};
}
};
} // namespace _7_8
} // namespace ApiSet
|
SpriteOvO/SchemaResolver | Source/Config.h | #pragma once
#define SR_VERSION_STRING "0.1.0"
|
SpriteOvO/SchemaResolver | Source/IResolver.h | #pragma once
#include <string>
#include <vector>
#include <list>
class IResolver
{
public:
static IResolver& GetInstance();
IResolver();
bool ResolveSchemaModule(const std::wstring &SchemaModuleName, std::vector<std::wstring> &RedirectedModuleName);
private:
std::list<std::pair<std::wstring, std::vector<std::wstring>>> _ApiSchema;
void InitializeApiSchema();
template <class ApiSetMapT, class ApiSetEntryT, class HostArrayT, class HostEntryT>
void InitializeApiSchemaInternal();
};
|
SpriteOvO/SchemaResolver | Source/Logger.h | <filename>Source/Logger.h
#pragma once
#include <cstdint>
#include <string>
#include <Windows.h>
enum class ConCol : uint16_t
{
Bright = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY,
Yellow = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY,
Purple = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY,
Red = FOREGROUND_RED | FOREGROUND_INTENSITY,
Cyan = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
Green = FOREGROUND_GREEN | FOREGROUND_INTENSITY,
Blue = FOREGROUND_BLUE | FOREGROUND_INTENSITY,
Default = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED,
};
template <ConCol ConsoleColor = ConCol::Default, class ...ArgsT>
void Log(const std::wstring &Format, ArgsT &&...Args)
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, (uint16_t)ConsoleColor);
fwprintf(stdout, Format.c_str(), std::forward<ArgsT>(Args)...);
SetConsoleTextAttribute(hStdOut, (uint16_t)ConCol::Default);
}
|
end2endzone/libMidi | src/common/varlength.h | /**********************************************************************************
* MIT License
*
* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*********************************************************************************/
#ifndef VARIABLE_LENGTH_H
#define VARIABLE_LENGTH_H
#include <cstring> //for memset()
#include <cstdio> //for fwrite(), fopen(), ftell(), fclose()
#include <cstdlib> //for abs()
namespace libmidi
{
/// <summary>
/// Computes a 32-bits mask for reading the nth block of 7 bits long.
/// </summary>
/// <param name="iIndex">
/// The 0-based index of the 7-bits blocks. ie:
/// index 0 creates a mask for bit 0 to bit 6
/// index 1 creates a mask for bit 7 to bit 13
/// index 2 creates a mask for bit 14 to bit 20
/// </param>
/// <returns>Returns a 32-bits mask.</returns>
inline uint32_t getVariableLengthMask(int iIndex)
{
//size_t i = 1;
//i << ((index+1)*7);
//i--;
static const uint32_t MASK_TIMESTAMP_0 = ((1<<7)-1);
static const uint32_t MASK_TIMESTAMP_1 = ((1<<14)-1) - MASK_TIMESTAMP_0;
static const uint32_t MASK_TIMESTAMP_2 = ((1<<21)-1) - MASK_TIMESTAMP_1;
static const uint32_t MASK_TIMESTAMP_3 = ((1<<28)-1) - MASK_TIMESTAMP_2;
static const uint32_t masks[] = {
MASK_TIMESTAMP_0,
MASK_TIMESTAMP_1,
MASK_TIMESTAMP_2,
MASK_TIMESTAMP_3
};
return masks[iIndex];
}
/// <summary>
/// Writes a value as a Variable Length Quantity to a file.
/// </summary>
/// <remarks>
/// Variable Length Quantity numbers are represented as 7 bits per byte,
/// most significant bits first. All bytes except the last have bit 7
/// set, and the last byte has bit 7 clear. If the number is between 0
/// and 127, it is thus represented exactly as one byte.
/// For example:
///
/// Values Variable Length Quantity
/// 00000000 00
/// 00000040 40
/// 0000007F 7F
/// 00000080 81 00
/// 00002000 C0 00
/// 00003FFF FF 7F
/// 00004000 81 80 00
/// 00100000 C0 80 00
/// 001FFFFF FF FF 7F
/// 00200000 81 80 80 00
/// 08000000 C0 80 80 00
/// 0FFFFFFF FF FF FF 7F
/// </remarks>
/// <param name="iValue">The value to be written to file</param>
/// <param name="iMinOutputSize">The minimum output size in byte.
/// ie: Writing the value 0x00000000 is normaly written as 1 byte 0x00.
/// Forcing minimum byte to 2 result in the following bytes written:
/// 0x80 0x00 which is the same value.</param>
/// <param name="f">The FILE* handle</param>
/// <returns>Returns the number of bytes written to the file</returns>
template <typename T>
size_t fwriteVariableLength(const T & iValue, size_t iMinOutputSize, FILE * f)
{
size_t writeSize = 0;
//copy the input value since we will decrement it
T copy = iValue;
size_t inputSize = sizeof(T);
//define output buffer
size_t maxOutputSize = inputSize+1;
unsigned char * outputBuffer = new unsigned char[maxOutputSize];
memset(outputBuffer, 0, maxOutputSize);
size_t outputSize = 1; //number of characters to output
for(size_t i=0; i<inputSize; i++)
{
//move the next 7 bits from inputBuffer to outputBuffer
uint32_t mask = getVariableLengthMask(i);
outputBuffer[i] |= ((copy & mask) >> (i*7));
copy &= ~mask;
//is there some bits left in the input ?
if (copy > 0)
{
//yes, there will be another output character
outputSize++;
}
else
{
//no, no need to read furthur
break;
}
}
//deal with forced output size
if (outputSize < iMinOutputSize && iMinOutputSize <= maxOutputSize)
{
outputSize = iMinOutputSize;
}
//write all output characters
for(int i=(int)outputSize-1; i>=0; i--)
{
bool isLast = (i == 0);
unsigned char c = outputBuffer[i];
if (!isLast)
{
c |= 0x80;
}
writeSize += fwrite(&c, 1, 1, f);
}
delete[] outputBuffer;
return writeSize;
}
/// <summary>
/// Writes a value as a Variable Length Quantity to a file.
/// </summary>
/// <remarks>
/// Variable Length Quantity numbers are represented as 7 bits per byte,
/// most significant bits first. All bytes except the last have bit 7
/// set, and the last byte has bit 7 clear. If the number is between 0
/// and 127, it is thus represented exactly as one byte.
/// For example:
///
/// Values Variable Length Quantity
/// 00000000 00
/// 00000040 40
/// 0000007F 7F
/// 00000080 81 00
/// 00002000 C0 00
/// 00003FFF FF 7F
/// 00004000 81 80 00
/// 00100000 C0 80 00
/// 001FFFFF FF FF 7F
/// 00200000 81 80 80 00
/// 08000000 C0 80 80 00
/// 0FFFFFFF FF FF FF 7F
/// </remarks>
/// <param name="iValue">The value to be written to file</param>
/// <param name="f">The FILE* handle</param>
/// <returns>Returns the number of bytes written to the file</returns>
template <typename T>
size_t fwriteVariableLength(const T & iValue, FILE * f)
{
return fwriteVariableLength(iValue, 0, f);
}
}; //namespace libmidi
#endif //VARIABLE_LENGTH_H |
end2endzone/libMidi | include/libmidi/notes.h | /**********************************************************************************
* MIT License
*
* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*********************************************************************************/
#ifndef NOTES_H
#define NOTES_H
namespace libmidi
{
/// <summary>Finds a note frequency by name.</summary>
/// <param name="iName">The given name of the note.</param>
/// <returns>An identifier that matches the given note name.
/// Returns -1 if the name is unknown, NULL, or empty.
/// </returns>
int findNoteFrequency(const char * iName);
/// <summary>Get the note name that matches the given frequency.</summary>
/// <param name="iFreq">The frequency in Hz to search for. The frequency must match an exact note.</param>
/// <returns>Returns the note name matching the frequency. Returns NULL on invalid frequency.</returns>
const char * getNoteName(int iFreq);
/// <summary>Get the note name that 'best' matches the given frequency.</summary>
/// <param name="iFreq">The frequency in Hz to search for.</param>
/// <param name="iEpsilon">The epsilon value for tolerance.</param>
/// <returns>Returns the note name matching the frequency. Returns NULL when no note matches the given frequency.</returns>
const char * getNoteName(int iFreq, int iEpsilon);
}; //namespace libmidi
#endif //NOTES_H |
end2endzone/libMidi | include/libmidi/instruments.h | <filename>include/libmidi/instruments.h
/**********************************************************************************
* MIT License
*
* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*********************************************************************************/
#ifndef INSTRUMENTS_H
#define INSTRUMENTS_H
#include <stdint.h> //for int8_t
namespace libmidi
{
//
// Description:
// Instrument codes according to https://en.wikipedia.org/wiki/General_MIDI
//
static const char * gInstruments[] = {
"Acoustic Grand Piano",
"Bright Acoustic Piano",
"Electric Grand Piano",
"Honky-tonk Piano",
"Electric Piano 1",
"Electric Piano 2",
"Harpsichord",
"Clavinet",
"Celesta",
"Glockenspiel",
"Music Box",
"Vibraphone",
"Marimba",
"Xylophone",
"Tubular Bells",
"Dulcimer",
"Drawbar Organ",
"Percussive Organ",
"Rock Organ",
"Church Organ",
"Reed Organ",
"Accordion",
"Harmonica",
"Tango Accordion",
"Acoustic Guitar (nylon)",
"Acoustic Guitar (steel)",
"Electric Guitar (jazz)",
"Electric Guitar (clean)",
"Electric Guitar (muted)",
"Overdriven Guitar",
"Distortion Guitar",
"Guitar Harmonics",
"Acoustic Bass",
"Electric Bass (finger)",
"Electric Bass (pick)",
"Fretless Bass",
"Slap Bass 1",
"Slap Bass 2",
"Synth Bass 1",
"Synth Bass 2",
"Violin",
"Viola",
"Cello",
"Contrabass",
"Tremolo Strings",
"Pizzicato Strings",
"Orchestral Harp",
"Timpani",
"String Ensemble 1",
"String Ensemble 2",
"Synth Strings 1",
"Synth Strings 2",
"Choir Aahs",
"Voice Oohs",
"Synth Choir",
"Orchestra Hit",
"Trumpet",
"Trombone",
"Tuba",
"Muted Trumpet",
"French Horn",
"Brass Section",
"Synth Brass 1",
"Synth Brass 2",
"Soprano Sax",
"Alto Sax",
"Tenor Sax",
"Baritone Sax",
"Oboe",
"English Horn",
"Bassoon",
"Clarinet",
"Piccolo",
"Flute",
"Recorder",
"Pan Flute",
"Blown bottle",
"Shakuhachi",
"Whistle",
"Ocarina",
"Lead 1 (square)",
"Lead 2 (sawtooth)",
"Lead 3 (calliope)",
"Lead 4 chiff",
"Lead 5 (charang)",
"Lead 6 (voice)",
"Lead 7 (fifths)",
"Lead 8 (bass + lead)",
"Pad 1 (new age)",
"Pad 2 (warm)",
"Pad 3 (polysynth)",
"Pad 4 (choir)",
"Pad 5 (bowed)",
"Pad 6 (metallic)",
"Pad 7 (halo)",
"Pad 8 (sweep)",
"FX 1 (rain)",
"FX 2 (soundtrack)",
"FX 3 (crystal)",
"FX 4 (atmosphere)",
"FX 5 (brightness)",
"FX 6 (goblins)",
"FX 7 (echoes)",
"FX 8 (sci-fi)",
"Sitar",
"Banjo",
"Shamisen",
"Koto",
"Kalimba",
"Bagpipe",
"Fiddle",
"Shanai",
"Tinkle Bell",
"Agogo",
"Steel Drums",
"Woodblock",
"Taiko Drum",
"Melodic Tom",
"Synth Drum",
"Reverse Cymbal",
"Guitar Fret Noise",
"Breath Noise",
"Seashore",
"Bird Tweet",
"Telephone Ring",
"Helicopter",
"Applause",
"Gunshot"
};
typedef int8_t INSTRUMENT;
static const INSTRUMENT MIN_INSTRUMENT = (INSTRUMENT)0x00;
static const INSTRUMENT MAX_INSTRUMENT = (INSTRUMENT)0x7F;
static const INSTRUMENT INVALID_INSTRUMENT = (INSTRUMENT)0xFF;
/// <summary>Finds a MIDI intrument id by name.</summary>
/// <param name="iName">The given name of the intrument.</param>
/// <returns>An identifier that matches the given instrument name.
/// Returns INVALID_INSTRUMENT if the name is unknown, NULL, or empty.
/// </returns>
INSTRUMENT findInstrument(const char * iName);
/// <summary>Get the instrument name that matches the given intrument id.</summary>
/// <param name="iInstrument">The instrument id to search for.</param>
/// <returns>Returns the instrument name matching the given id. Returns NULL on invalid intrument id.</returns>
const char * getInstrumentName(INSTRUMENT iInstrument);
}; //namespace libmidi
#endif //INSTRUMENTS_H |
end2endzone/libMidi | include/libmidi/libmidi.h | /**********************************************************************************
* MIT License
*
* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*********************************************************************************/
#ifndef LIBMIDI_H
#define LIBMIDI_H
#include "libmidi/config.h"
#include "libmidi/version.h"
#include <stdint.h>
#include <vector>
#include <string>
namespace libmidi
{
/// <summary>
/// Defines the MidiFile class.
/// </summary>
class LIBMIDI_EXPORT MidiFile {
public:
/// <summary>
/// Defines track ending strategies
/// </summary>
enum TRACK_ENDING_PREFERENCE
{
/// <summary>Stop the previous playing note. Default value.</summary>
STOP_PREVIOUS_NOTE = 1,
/// <summary>Stop all playing notes.</summary>
STOP_ALL_NOTES = 2,
};
/// <summary>
/// Defines midi type or track type
/// </summary>
enum MIDI_TYPE
{
/// <summary>Type 0. Default value.</summary>
MIDI_TYPE_0 = 0,
/// <summary>Type 1.</summary>
MIDI_TYPE_1 = 1
};
/// <summary>
/// Construct a new instance of MidiFile.
/// </summary>
MidiFile(void);
/// <summary>
/// Sets the type of MIDI file.
/// Supported values are defines by <typeparamref name="MIDI_TYPE">MIDI_TYPE</typeparamref>
/// </summary>
/// <remarks>
/// The libMIDI library only supports a single track per MIDI file.
/// Changing the MIDI type does not affect the capabilities of the library
/// besides changing a single byte in the output file.
/// </remarks>
/// <param name="iType">The type of MIDI file.</param>
void setMidiType(MIDI_TYPE iType);
/// <summary>
/// Sets the melody name.
/// </summary>
/// <param name="iName">The name of the melody. Set to NULL or EMPTY to disable name.</param>
void setName(const char * iName);
/// <summary>Set current volume for the following notes.</summary>
/// <param name="iVolume">The volume value. min=0x00 max=0x7f</param>
void setVolume(int8_t iVolume);
/// <summary>Set current instrument.</summary>
/// <param name="iInstrument">The instrument's id.</param>
void setInstrument(int8_t iInstrument);
/// <summary>Set the number of ticks per quarter note.</summary>
/// <param name="iTicks">The ticks per quarter note.</param>
void setTicksPerQuarterNote(uint16_t iTicks);
/// <summary>Sets the number of beats per minute.</summary>
/// <param name="iBpm">The number of beats per minute.</param>
void setBeatsPerMinute(uint16_t iBpm);
/// <summary>Sets the tempo in microseconds per quarter note.</summary>
/// <param name="iTempo">The tempo in usec per second.</param>
void setTempo(uint32_t iTempo);
/// <summary>Defines if a MIDI track should end
/// with a <typeparamref name="STOP_PREVIOUS_NOTE">STOP_PREVIOUS_NOTE</typeparamref> message
/// or a <typeparamref name="STOP_ALL_NOTES">STOP_ALL_NOTES</typeparamref> message.
/// </summary>
/// <param name="iTrackEndingPreference">The prefered track ending method.</param>
void setTrackEndingPreference(TRACK_ENDING_PREFERENCE iTrackEndingPreference);
/// <summary>Adds a note to the current melody.</summary>
/// <param name="iFrequency">The frequency in Hz of the note.</param>
/// <param name="iDurationMs">The duration of the note in milliseconds.</param>
void addNote(uint16_t iFrequency, uint16_t iDurationMs);
/// <summary>Adds a delay (silent note) to the current melody.</summary>
/// <param name="iDurationMs">The delay duration in milliseconds.</param>
void addDelay(uint16_t iDurationMs);
/// <summary>Saves the current melody to a file.</summary>
/// <param name="iFile">The path location where the file is to be saved.</param>
/// <returns>True when the file is successfully saved. False otherwise.</returns>
bool save(const char * iFile);
public:
//public values & enums
static const uint8_t DEFAULT_INSTRUMENT = 0x00;
static const uint16_t DEFAULT_BPM = 120;
static const uint32_t DEFAULT_TEMPO = 500000;
static const uint32_t DEFAULT_TICKS_PER_QUARTER_NOTE = 480;
static const uint32_t MIN2USEC = 60*1000*1000;
public:
//static methods
/// <summary>Convert a beat per minute (BPM) to a MIDI tempo.</summary>
/// <param name="iBpm">The BPM value to convert.</param>
/// <returns>A tempo value in BPM matching the given beat per minute.</returns>
static uint32_t bpm2tempo(uint16_t iBpm);
/// <summary>Converts a MIDI tempo to a beat per minute (BPM)</summary>
/// <param name="iTempo">The tempo value to convert</param>
/// <returns>A beat per minute value matching the given tempo.</returns>
static uint16_t tempo2bpm(uint32_t iTempo);
/// <summary>Converts a note duration to a number of ticks based on a given ticks per quarter note and a tempo.</summary>
/// <param name="iDurationMs">The duration to convert in milliseconds.</param>
/// <param name="iTicksPerQuarterNote">The given number of ticks per quarter notes.</param>
/// <param name="iTempo">The given tempo.</param>
/// <returns>A number of ticks matching the given duration.</returns>
static uint16_t duration2ticks(uint16_t iDurationMs, uint16_t iTicksPerQuarterNote, uint32_t iTempo);
/// <summary>Converts an amount of ticks to a duration.</summary>
/// <param name="iTicks">The number of ticks to convert.</param>
/// <param name="iTicksPerQuarterNote">The given number of ticks per quarter notes.</param>
/// <param name="iTempo">The given tempo.</param>
/// <returns>A duration in milliseconds matching the given number of ticks.</returns>
static uint16_t ticks2duration(uint16_t iTicks, uint16_t iTicksPerQuarterNote, uint32_t iTempo);
private:
//private methods
/// <summary>Converts a note duration to a number of ticks based on the melody's ticks per quarter note and tempo.</summary>
/// <param name="iDurationMs">The duration to convert in milliseconds.</param>
/// <returns>A number of ticks matching the given duration.</returns>
uint16_t duration2ticks(uint16_t iDurationMs);
/// <summary>Converts an amount of ticks to a duration based on the melody's ticks per quarter note and tempo.</summary>
/// <param name="iTicks">The number of ticks to convert.</param>
/// <returns>A duration in milliseconds matching the given number of ticks.</returns>
uint16_t ticks2duration(uint16_t iTicks);
private:
//private attributes
struct NOTE
{
uint16_t frequency;
uint16_t durationMs;
int8_t volume;
};
typedef std::vector<NOTE> NoteList;
uint16_t mTicksPerQuarterNote;
uint32_t mTempo; //usec per quarter note
std::string mName;
NoteList mNotes;
int8_t mVolume; //from 0x00 to 0x7f
int8_t mInstrument; //from 0x00 to 0x7f
TRACK_ENDING_PREFERENCE mTrackEndingPreference;
MIDI_TYPE mType;
};
}; //namespace libmidi
#endif //LIBMIDI_H |
end2endzone/libMidi | include/libmidi/pitches.h | /**********************************************************************************
* MIT License
*
* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*********************************************************************************/
#ifndef MIDIPITCHES_H
#define MIDIPITCHES_H
namespace libmidi
{
/*************************************************
* Notes Constants
*************************************************/
#define NOTE_REST 0
#define NOTE_SILENCE 0
#define NOTE_C0 16
#define NOTE_CS0 17
#define NOTE_D0 18
#define NOTE_DS0 19
#define NOTE_E0 21
#define NOTE_F0 22
#define NOTE_FS0 23
#define NOTE_G0 24
#define NOTE_GS0 26
#define NOTE_A0 28
#define NOTE_AS0 29
#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978
#define NOTE_E8 5274
#define NOTE_F8 5588
#define NOTE_FS8 5920
#define NOTE_G8 6272
#define NOTE_GS8 6645
#define NOTE_A8 7040
#define NOTE_AS8 7459
#define NOTE_B8 7902
#define NOTE_C9 8372
#define NOTE_CS9 8870
#define NOTE_D9 9397
#define NOTE_DS9 9956
#define NOTE_E9 10548
#define NOTE_F9 11175
#define NOTE_FS9 11840
#define NOTE_G9 12544
#define NOTE_GS9 13290
#define NOTE_A9 ?
#define NOTE_AS9 ?
#define NOTE_B9 ?
//Duplicated note with same frequency.
//Obtained from the following code:
// for(char o='0'; o<='9'; o++)
// {
// for(char letter='A'; letter<='G'; letter++)
// {
// // #define NOTE_DB7 NOTE_CS7
// printf("#define NOTE_%cB%c NOTE_%cS%c\n", (letter+1 == 'H'? 'A' : letter+1), o, letter, o);
// }
// }
#define NOTE_BB0 NOTE_AS0
#define NOTE_CB0 NOTE_BS0
#define NOTE_DB0 NOTE_CS0
#define NOTE_EB0 NOTE_DS0
#define NOTE_FB0 NOTE_ES0
#define NOTE_GB0 NOTE_FS0
#define NOTE_AB0 NOTE_GS0
#define NOTE_BB1 NOTE_AS1
#define NOTE_CB1 NOTE_BS1
#define NOTE_DB1 NOTE_CS1
#define NOTE_EB1 NOTE_DS1
#define NOTE_FB1 NOTE_ES1
#define NOTE_GB1 NOTE_FS1
#define NOTE_AB1 NOTE_GS1
#define NOTE_BB2 NOTE_AS2
#define NOTE_CB2 NOTE_BS2
#define NOTE_DB2 NOTE_CS2
#define NOTE_EB2 NOTE_DS2
#define NOTE_FB2 NOTE_ES2
#define NOTE_GB2 NOTE_FS2
#define NOTE_AB2 NOTE_GS2
#define NOTE_BB3 NOTE_AS3
#define NOTE_CB3 NOTE_BS3
#define NOTE_DB3 NOTE_CS3
#define NOTE_EB3 NOTE_DS3
#define NOTE_FB3 NOTE_ES3
#define NOTE_GB3 NOTE_FS3
#define NOTE_AB3 NOTE_GS3
#define NOTE_BB4 NOTE_AS4
#define NOTE_CB4 NOTE_BS4
#define NOTE_DB4 NOTE_CS4
#define NOTE_EB4 NOTE_DS4
#define NOTE_FB4 NOTE_ES4
#define NOTE_GB4 NOTE_FS4
#define NOTE_AB4 NOTE_GS4
#define NOTE_BB5 NOTE_AS5
#define NOTE_CB5 NOTE_BS5
#define NOTE_DB5 NOTE_CS5
#define NOTE_EB5 NOTE_DS5
#define NOTE_FB5 NOTE_ES5
#define NOTE_GB5 NOTE_FS5
#define NOTE_AB5 NOTE_GS5
#define NOTE_BB6 NOTE_AS6
#define NOTE_CB6 NOTE_BS6
#define NOTE_DB6 NOTE_CS6
#define NOTE_EB6 NOTE_DS6
#define NOTE_FB6 NOTE_ES6
#define NOTE_GB6 NOTE_FS6
#define NOTE_AB6 NOTE_GS6
#define NOTE_BB7 NOTE_AS7
#define NOTE_CB7 NOTE_BS7
#define NOTE_DB7 NOTE_CS7
#define NOTE_EB7 NOTE_DS7
#define NOTE_FB7 NOTE_ES7
#define NOTE_GB7 NOTE_FS7
#define NOTE_AB7 NOTE_GS7
#define NOTE_BB8 NOTE_AS8
#define NOTE_CB8 NOTE_BS8
#define NOTE_DB8 NOTE_CS8
#define NOTE_EB8 NOTE_DS8
#define NOTE_FB8 NOTE_ES8
#define NOTE_GB8 NOTE_FS8
#define NOTE_AB8 NOTE_GS8
#define NOTE_BB9 NOTE_AS9
#define NOTE_CB9 NOTE_BS9
#define NOTE_DB9 NOTE_CS9
#define NOTE_EB9 NOTE_DS9
#define NOTE_FB9 NOTE_ES9
#define NOTE_GB9 NOTE_FS9
#define NOTE_AB9 NOTE_GS9
}; //namespace libmidi
#endif //MIDIPITCHES_H |
jbdallastx/level-zero | include/extensions/ze_graph_ext.h | /*
*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "ze_api.h"
///////////////////////////////////////////////////////////////////////////////
/// @brief Handle of driver's graph object
typedef struct _ze_graph_handle_t *ze_graph_handle_t;
///////////////////////////////////////////////////////////////////////////////
/// @brief Supported graph creation input formats
typedef enum _ze_graph_format_t
{
ZE_GRAPH_FORMAT_IL_MCM = 0, ///< Format is MCM IL format
ZE_GRAPH_FORMAT_NATIVE, ///< Format is device native format
} ze_graph_format_t;
///////////////////////////////////////////////////////////////////////////////
/// @brief Graph descriptor
typedef struct _ze_graph_desc_t
{
ze_graph_format_t format; ///< [in] Graph format passed in with pInputGraph
size_t inputSize; ///< [in] Size of graph in bytes
const uint8_t* pInputGraph; ///< [in] Pointer to graph IL or native binary
} ze_graph_desc_t;
///////////////////////////////////////////////////////////////////////////////
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGraphCreate(
ze_device_handle_t hDevice, ///< [in] handle of the device
const ze_graph_desc_t* desc, ///< [in] pointer to graph descriptor
ze_graph_handle_t* phGraph ///< [out] pointer to handle of graph object created
);
///////////////////////////////////////////////////////////////////////////////
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGraphDestroy(
ze_graph_handle_t hGraph ///< [in][release] handle of graph object to destroy
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Graph properties
typedef struct _ze_graph_properties_t
{
uint32_t numGraphArgs; ///< [out] number of graph arguments
} ze_graph_properties_t;
///////////////////////////////////////////////////////////////////////////////
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGraphGetProperties(
ze_graph_handle_t hGraph, ///< [in] handle of the graph object
ze_graph_properties_t* pGraphProperties ///< [in,out] query result for graph properties.
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Graph argument properties
typedef enum _ze_graph_argument_type_t
{
ZE_GRAPH_ARGUMENT_TYPE_INPUT,
ZE_GRAPH_ARGUMENT_TYPE_OUTPUT,
} ze_graph_argument_type_t;
///////////////////////////////////////////////////////////////////////////////
/// @brief Graph argument properties
typedef enum _ze_graph_argument_dimension_t
{
ZE_GRAPH_ARGUMENT_DIMENSION_N,
ZE_GRAPH_ARGUMENT_DIMENSION_C,
ZE_GRAPH_ARGUMENT_DIMENSION_H,
ZE_GRAPH_ARGUMENT_DIMENSION_W,
ZE_GRAPH_ARGUMENT_DIMENSION_D,
ZE_GRAPH_ARGUMENT_DIMENSION_MAX,
} ze_graph_argument_dimension_t;
///////////////////////////////////////////////////////////////////////////////
/// @brief Graph argument properties
typedef enum _ze_graph_argument_precision_t
{
ZE_GRAPH_ARGUMENT_PRECISION_UNKNOWN,
ZE_GRAPH_ARGUMENT_PRECISION_FP32,
ZE_GRAPH_ARGUMENT_PRECISION_FP16,
ZE_GRAPH_ARGUMENT_PRECISION_UINT16,
ZE_GRAPH_ARGUMENT_PRECISION_UINT8,
ZE_GRAPH_ARGUMENT_PRECISION_INT32,
ZE_GRAPH_ARGUMENT_PRECISION_INT16,
ZE_GRAPH_ARGUMENT_PRECISION_INT8,
ZE_GRAPH_ARGUMENT_PRECISION_BIN,
} ze_graph_argument_precision_t;
///////////////////////////////////////////////////////////////////////////////
/// @brief Graph argument properties
typedef enum _ze_graph_argument_layout_t
{
ZE_GRAPH_ARGUMENT_LAYOUT_ANY = 0x00,
ZE_GRAPH_ARGUMENT_LAYOUT_NCHW,
ZE_GRAPH_ARGUMENT_LAYOUT_NHWC,
ZE_GRAPH_ARGUMENT_LAYOUT_NCDHW,
ZE_GRAPH_ARGUMENT_LAYOUT_NDHWC,
ZE_GRAPH_ARGUMENT_LAYOUT_OIHW = 0x40,
ZE_GRAPH_ARGUMENT_LAYOUT_C = 0x60,
ZE_GRAPH_ARGUMENT_LAYOUT_CHW = 0x80,
ZE_GRAPH_ARGUMENT_LAYOUT_HW = 0xC0,
ZE_GRAPH_ARGUMENT_LAYOUT_NC,
ZE_GRAPH_ARGUMENT_LAYOUT_CN,
ZE_GRAPH_ARGUMENT_LAYOUT_BLOCKED = 0xC8
} ze_graph_argument_layout_t;
///////////////////////////////////////////////////////////////////////////////
#ifndef ZE_MAX_GRAPH_ARGUMENT_NAME
/// @brief Maximum device name string size
#define ZE_MAX_GRAPH_ARGUMENT_NAME 256
#endif // ZE_MAX_GRAPH_ARGUMENT_NAME
///////////////////////////////////////////////////////////////////////////////
#ifndef ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE
/// @brief Maximum device name string size
#define ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE ZE_GRAPH_ARGUMENT_DIMENSION_MAX
#endif // ZE_MAX_GRAPH_ARGUMENT_SIZE
///////////////////////////////////////////////////////////////////////////////
/// @brief Graph argument properties
typedef struct _ze_graph_argument_properties_t
{
char name[ZE_MAX_GRAPH_ARGUMENT_NAME]; ///< [out] Graph argument name
ze_graph_argument_type_t type;
uint32_t dims[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE];
ze_graph_argument_precision_t precision;
ze_graph_argument_layout_t layout;
} ze_graph_argument_properties_t;
///////////////////////////////////////////////////////////////////////////////
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGraphGetArgumentProperties(
ze_graph_handle_t hGraph, ///< [in] handle of the graph object
uint32_t argIndex, ///< [in] index of the argument to get properties
ze_graph_argument_properties_t* pGraphArgumentProperties ///< [in,out] query result for graph argument properties.
);
///////////////////////////////////////////////////////////////////////////////
ZE_APIEXPORT ze_result_t ZE_APICALL
zeGraphSetArgumentValue(
ze_graph_handle_t hGraph,
uint32_t argIndex,
const void* pArgValue
);
///////////////////////////////////////////////////////////////////////////////
ZE_APIEXPORT ze_result_t ZE_APICALL
zeAppendGraphInitialize(
ze_command_list_handle_t hCommandList, ///< [in] handle of the command list
ze_graph_handle_t hGraph ///< [in] handle of the graph
);
///////////////////////////////////////////////////////////////////////////////
ZE_APIEXPORT ze_result_t ZE_APICALL
zeAppendGraphExecute(
ze_command_list_handle_t hCommandList, ///< [in] handle of the command list
ze_graph_handle_t hGraph ///< [in] handle of the graph
);
///////////////////////////////////////////////////////////////////////////////
typedef ze_result_t (ZE_APICALL *ze_pfnGraphCreate_ext_t)(
ze_device_handle_t hDevice, ///< [in] handle of the device
const ze_graph_desc_t* desc, ///< [in] pointer to graph descriptor
ze_graph_handle_t* phGraph ///< [out] pointer to handle of graph object created
);
///////////////////////////////////////////////////////////////////////////////
typedef ze_result_t (ZE_APICALL *ze_pfnGraphDestroy_ext_t)(
ze_graph_handle_t hGraph ///< [in][release] handle of graph object to destroy
);
///////////////////////////////////////////////////////////////////////////////
typedef ze_result_t (ZE_APICALL *ze_pfnGraphGetProperties_ext_t)(
ze_graph_handle_t hGraph, ///< [in] handle of the graph object
ze_graph_properties_t* pGraphProperties ///< [in,out] query result for graph properties.
);
///////////////////////////////////////////////////////////////////////////////
typedef ze_result_t (ZE_APICALL *ze_pfnGraphGetArgumentProperties_ext_t)(
ze_graph_handle_t hGraph, ///< [in] handle of the graph object
uint32_t argIndex, ///< [in] index of the argument to get properties
ze_graph_argument_properties_t* pGraphArgumentProperties ///< [in,out] query result for graph argument properties.
);
///////////////////////////////////////////////////////////////////////////////
typedef ze_result_t (ZE_APICALL *ze_pfnGraphSetArgumentValue_ext_t)(
ze_graph_handle_t hGraph,
uint32_t argIndex,
const void* pArgValue
);
///////////////////////////////////////////////////////////////////////////////
typedef ze_result_t (ZE_APICALL *ze_pfnAppendGraphInitialize_ext_t)(
ze_command_list_handle_t hCommandList, ///< [in] handle of the command list
ze_graph_handle_t hGraph ///< [in] handle of the graph
);
///////////////////////////////////////////////////////////////////////////////
typedef ze_result_t (ZE_APICALL *ze_pfnAppendGraphExecute_ext_t)(
ze_command_list_handle_t hCommandList, ///< [in] handle of the command list
ze_graph_handle_t hGraph ///< [in] handle of the graph
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Table of Graph functions pointers
typedef struct _ze_graph_dditable_ext_t
{
ze_pfnGraphCreate_ext_t pfnCreate;
ze_pfnGraphDestroy_ext_t pfnDestroy;
ze_pfnGraphGetProperties_ext_t pfnGetProperties;
ze_pfnGraphGetArgumentProperties_ext_t pfnGetArgumentProperties;
ze_pfnGraphSetArgumentValue_ext_t pfnSetArgumentValue;
ze_pfnAppendGraphInitialize_ext_t pfnAppendGraphInitialize;
ze_pfnAppendGraphExecute_ext_t pfnAppendGraphExecute;
} ze_graph_dditable_ext_t; |
jbdallastx/level-zero | include/extensions/ze_fence_ext.h | <reponame>jbdallastx/level-zero
/*
*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "ze_api.h"
///////////////////////////////////////////////////////////////////////////////
/// @brief Function-pointer for zeFenceDeviceSignal_ext
typedef ze_result_t (ZE_APICALL *ze_pfnFenceDeviceSignal_ext_t)(
ze_fence_handle_t,
uint64_t
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Function-pointer for zeFenceDeviceSynchronize_ext
typedef ze_result_t (ZE_APICALL *ze_pfnFenceDeviceSynchronize_ext_t)(
ze_command_queue_handle_t,
ze_fence_handle_t,
uint64_t
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Table of Fence extension functions pointers
typedef struct _ze_fence_dditable_ext_t
{
ze_pfnFenceDeviceSignal_ext_t pfnDeviceSignal;
ze_pfnFenceDeviceSynchronize_ext_t pfnDeviceSynchronize;
} ze_fence_dditable_ext_t; |
baolanlequang/jcamp-viewer-ios | JcampViewer/Pods/JcampConverter/JcampConverter/JcampConverter/JcampConverter.h | //
// JcampConverter.h
// JcampConverter
//
// Created by <NAME> on 02.02.22.
//
#import <Foundation/Foundation.h>
//! Project version number for JcampConverter.
FOUNDATION_EXPORT double JcampConverterVersionNumber;
//! Project version string for JcampConverter.
FOUNDATION_EXPORT const unsigned char JcampConverterVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <JcampConverter/PublicHeader.h>
|
novaELLIAS/HYAsstSTM32 | Core/Inc/MPU6050/MPU6050.h |
#include "main.h"
#define MPU_SELF_TESTX_REG 0X0D
#define MPU_SELF_TESTY_REG 0X0E
#define MPU_SELF_TESTZ_REG 0X0F
#define MPU_SELF_TESTA_REG 0X10
#define MPU_SAMPLE_RATE_REG 0X19
#define MPU_CFG_REG 0X1A
#define MPU_GYRO_CFG_REG 0X1B
#define MPU_ACCEL_CFG_REG 0X1C
#define MPU_MOTION_DET_REG 0X1F
#define MPU_FIFO_EN_REG 0X23
#define MPU_I2CMST_CTRL_REG 0X24
#define MPU_I2CSLV0_ADDR_REG 0X25
#define MPU_I2CSLV0_REG 0X26
#define MPU_I2CSLV0_CTRL_REG 0X27
#define MPU_I2CSLV1_ADDR_REG 0X28
#define MPU_I2CSLV1_REG 0X29
#define MPU_I2CSLV1_CTRL_REG 0X2A
#define MPU_I2CSLV2_ADDR_REG 0X2B
#define MPU_I2CSLV2_REG 0X2C
#define MPU_I2CSLV2_CTRL_REG 0X2D
#define MPU_I2CSLV3_ADDR_REG 0X2E
#define MPU_I2CSLV3_REG 0X2F
#define MPU_I2CSLV3_CTRL_REG 0X30
#define MPU_I2CSLV4_ADDR_REG 0X31
#define MPU_I2CSLV4_REG 0X32
#define MPU_I2CSLV4_DO_REG 0X33
#define MPU_I2CSLV4_CTRL_REG 0X34
#define MPU_I2CSLV4_DI_REG 0X35
#define MPU_I2CMST_STA_REG 0X36
#define MPU_INTBP_CFG_REG 0X37
#define MPU_INT_EN_REG 0X38
#define MPU_INT_STA_REG 0X3A
#define MPU_ACCEL_XOUTH_REG 0X3B
#define MPU_ACCEL_XOUTL_REG 0X3C
#define MPU_ACCEL_YOUTH_REG 0X3D
#define MPU_ACCEL_YOUTL_REG 0X3E
#define MPU_ACCEL_ZOUTH_REG 0X3F
#define MPU_ACCEL_ZOUTL_REG 0X40
#define MPU_TEMP_OUTH_REG 0X41
#define MPU_TEMP_OUTL_REG 0X42
#define MPU_GYRO_XOUTH_REG 0X43
#define MPU_GYRO_XOUTL_REG 0X44
#define MPU_GYRO_YOUTH_REG 0X45
#define MPU_GYRO_YOUTL_REG 0X46
#define MPU_GYRO_ZOUTH_REG 0X47
#define MPU_GYRO_ZOUTL_REG 0X48
#define MPU_I2CSLV0_DO_REG 0X63
#define MPU_I2CSLV1_DO_REG 0X64
#define MPU_I2CSLV2_DO_REG 0X65
#define MPU_I2CSLV3_DO_REG 0X66
#define MPU_I2CMST_DELAY_REG 0X67
#define MPU_SIGPATH_RST_REG 0X68
#define MPU_MDETECT_CTRL_REG 0X69
#define MPU_USER_CTRL_REG 0X6A
#define MPU_PWR_MGMT1_REG 0X6B
#define MPU_PWR_MGMT2_REG 0X6C
#define MPU_FIFO_CNTH_REG 0X72
#define MPU_FIFO_CNTL_REG 0X73
#define MPU_FIFO_RW_REG 0X74
#define MPU_DEVICE_ID_REG 0X75
#define MPU_ADDR 0X68
#define MPU_READ 0XD1
#define MPU_WRITE 0XD0
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
u8 MPU_Init(void);
u8 MPU_Write_Len(u8 reg, u8 len, u8 *buf);
u8 MPU_Read_Len(u8 reg, u8 len, u8 *buf);
u8 MPU_Write_Byte(u8 reg, u8 data);
u8 MPU_Read_Byte(u8 reg);
u8 MPU_Set_Gyro_Fsr(u8 fsr);
u8 MPU_Set_Accel_Fsr(u8 fsr);
u8 MPU_Set_LPF(u16 lpf);
u8 MPU_Set_Rate(u16 rate);
u8 MPU_Set_Fifo(u8 sens);
float MPU_Get_Temperature(void);
u8 MPU_Get_Gyroscope(short *gx, short *gy, short *gz);
u8 MPU_Get_Accelerometer(short *ax, short *ay, short *az);
|
novaELLIAS/HYAsstSTM32 | Core/Inc/LED_Functions/LED_OUTPUT.h | <reponame>novaELLIAS/HYAsstSTM32<filename>Core/Inc/LED_Functions/LED_OUTPUT.h
void LED_PC13_INIT ();
void LED_PC13_BLINK (register int);
void LED_PC13_BREATHE (register int);
void LED_OUTPUT_INIT ();
#define LED_TEST_Toggle() HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13)
#define LED_TEST_OFF() HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_RESET)
#define LED_TEST_ON() HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_SET)
#define LED_GPSRFS_Toggle() HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_7)
#define LED_GPSRFS_OFF() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, GPIO_PIN_RESET)
#define LED_GPSRFS_ON() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, GPIO_PIN_SET)
#define LED_DATUPD_Toggle() HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_6)
#define LED_DATUPD_OFF() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_6, GPIO_PIN_RESET)
#define LED_DATUPD_ON() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_6, GPIO_PIN_SET)
#define LED_ALERT_Toggle() HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5)
#define LED_ALERT_OFF() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET)
#define LED_ALERT_ON() HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET)
void LED_OUTPUT_TEST ();
|
novaELLIAS/HYAsstSTM32 | Core/Inc/MPU6050/Kalman.h |
#include "main.h"
void getAccelgyroData(double *tagX, double *tagY, double *tagZ, double *Acc);
|
novaELLIAS/HYAsstSTM32 | Core/Src/MPU6050/MPU6050.c |
#include "MPU6050/MPU6050.h"
u8 MPU_Init(void) {
u8 res;
extern I2C_HandleTypeDef hi2c1;
HAL_I2C_Init(&hi2c1);
MPU_Write_Byte(MPU_PWR_MGMT1_REG, 0X80);
MPU_Write_Byte(MPU_PWR_MGMT1_REG, 0X00);
MPU_Set_Gyro_Fsr(3);
MPU_Set_Accel_Fsr(0);
MPU_Set_Rate(50);
MPU_Write_Byte(MPU_INT_EN_REG, 0X00);
MPU_Write_Byte(MPU_USER_CTRL_REG, 0X00);
MPU_Write_Byte(MPU_FIFO_EN_REG, 0X00);
MPU_Write_Byte(MPU_INTBP_CFG_REG, 0X80);
res = MPU_Read_Byte(MPU_DEVICE_ID_REG);
if (res == MPU_ADDR) {
MPU_Write_Byte(MPU_PWR_MGMT1_REG, 0X01);
MPU_Write_Byte(MPU_PWR_MGMT2_REG, 0X00);
MPU_Set_Rate(50);
} else return 1;
return 0;
}
u8 MPU_Set_Gyro_Fsr(u8 fsr) {
return MPU_Write_Byte(MPU_GYRO_CFG_REG, fsr<<3);
}
u8 MPU_Set_Accel_Fsr(u8 fsr) {
return MPU_Write_Byte(MPU_ACCEL_CFG_REG, fsr<<3);
}
u8 MPU_Set_LPF(u16 lpf) {
u8 data = 0;
if (lpf >= 188) data = 1;
else if(lpf>=98) data = 2;
else if(lpf>=42) data = 3;
else if(lpf>=20) data = 4;
else if(lpf>=10) data = 5;
else data = 6;
return MPU_Write_Byte(MPU_CFG_REG, data);
}
u8 MPU_Set_Rate(u16 rate) {
u8 data;
if (rate > 1000) rate = 1000;
if (rate < 4) rate = 4;
data = 1000/rate - 1;
data = MPU_Write_Byte(MPU_SAMPLE_RATE_REG, data);
return MPU_Set_LPF(rate/2);
}
float MPU_Get_Temperature(void) {
unsigned char buf[2];
short raw;
float temp;
MPU_Read_Len(MPU_TEMP_OUTH_REG, 2, buf);
raw = (buf[0]<<8) | buf[1];
temp = (36.53+((double)raw)/340)*100;
return temp / 100.0f;
}
u8 MPU_Get_Gyroscope(short *gx, short *gy, short *gz) {
u8 buf[6], res;
res = MPU_Read_Len(MPU_GYRO_XOUTH_REG, 6, buf);
if(res==0) {
*gx = ((u16)buf[0]<<8) | buf[1];
*gy = ((u16)buf[2]<<8) | buf[3];
*gz = ((u16)buf[4]<<8) | buf[5];
} return res;
}
u8 MPU_Get_Accelerometer(short *ax, short *ay, short *az) {
u8 buf[6], res;
res = MPU_Read_Len(MPU_ACCEL_XOUTH_REG, 6, buf);
if(res == 0) {
*ax = ((u16)buf[0]<<8) | buf[1];
*ay = ((u16)buf[2]<<8) | buf[3];
*az = ((u16)buf[4]<<8) | buf[5];
} return res;
}
u8 MPU_Write_Len(u8 reg, u8 len, u8 *buf) {
extern I2C_HandleTypeDef hi2c1;
HAL_I2C_Mem_Write(&hi2c1, MPU_WRITE, reg, I2C_MEMADD_SIZE_8BIT, buf, len, 0xfff);
HAL_Delay(100); return 0;
}
u8 MPU_Read_Len(u8 reg, u8 len, u8 *buf) {
extern I2C_HandleTypeDef hi2c1;
HAL_I2C_Mem_Read (&hi2c1, MPU_READ, reg, I2C_MEMADD_SIZE_8BIT, buf, len, 0xfff);
HAL_Delay(100); return 0;
}
u8 MPU_Write_Byte(u8 reg, u8 data) {
extern I2C_HandleTypeDef hi2c1;
unsigned char W_Data = data;
HAL_I2C_Mem_Write(&hi2c1, MPU_WRITE, reg, I2C_MEMADD_SIZE_8BIT, &W_Data, 1, 0xfff);
HAL_Delay(100); return 0;
}
u8 MPU_Read_Byte(u8 reg) {
extern I2C_HandleTypeDef hi2c1;
unsigned char R_Data = 0;
HAL_I2C_Mem_Read(&hi2c1, MPU_READ, reg, I2C_MEMADD_SIZE_8BIT, &R_Data, 1, 0xfff);
HAL_Delay(100); return R_Data;
}
|
novaELLIAS/HYAsstSTM32 | Core/Src/MPU6050/Accident_Alert.c |
#include "main.h"
#include "MPU6050/Kalman.h"
#include "MPU6050/MPU6050.h"
#include "GPS_Decoder/GPSdecode.h"
#include "LED_Functions/LED_OUTPUT.h"
#define ACCIDENT_ACCE 2 //Minimal acceleration to trigger accident report
#define ACCIDENT_ANGLE 90 //Minimal dip angle to trigger accident report
#define ACCIDENT_ALERT_SPEED 25
void accidentMonitorSetup (void) {MPU_Init();}
double Abs (double a) {return a<0? -a:a;}
double agx, agy, agz, acc;
#define durVal 500
double tmpAgx[durVal], tmpAgy[durVal], tmpAgz[durVal];
int pos, totx, toty, totz;
long long timer = 0;
double avgx, avgy, avgz, prespd;
int accidentJudge (gps_data *GPSdata) {
//timer = HAL_GetTick();
getAccelgyroData(&agx, &agy, &agz, &acc);
register int flag = (acc>ACCIDENT_ACCE) && ((GPSdata->speed - prespd)/(double)HAL_GetTick()>ACCIDENT_ACCE);
timer = HAL_GetTick(); prespd = GPSdata->speed;
if (Abs(agx-avgx)>ACCIDENT_ANGLE || Abs(agy-avgy)>ACCIDENT_ANGLE || Abs(agz-avgz)>ACCIDENT_ANGLE) flag = 1;
totx -= tmpAgx[pos], toty -= tmpAgy[pos], totz -= tmpAgz[pos];
tmpAgx[pos] = agx, tmpAgy[pos]= agy, tmpAgz[pos] = agz;
totx += agx, toty += agy, totz += agz;
avgx = (double)totx/(1.0*durVal), avgy = (double)toty/(1.0*durVal), avgz = (double)totz/(1.0*durVal);
pos = (pos+1)%(durVal); if (GPSdata->speed <= ACCIDENT_ALERT_SPEED) flag = 0;
if (flag) LED_ALERT_ON();
return flag;
}
#undef durVal
|
novaELLIAS/HYAsstSTM32 | Core/Src/MQTT/AT.c | <reponame>novaELLIAS/HYAsstSTM32<gh_stars>1-10
#include "MQTT/AT.h"
#include "MQTT/utility.h"
#include <stdio.h>
#include <string.h>
#include "main.h"
struct tok tok;
struct at_cmd_hanld_t at_cmd_hanld[] = {
{"AT+CFUN", AT_Send, AT_Return},
{"AT+CPIN", AT_Send, AT_Return},
{"AT+CSQ", AT_Send, AT_Return},
{"AT+CGATT", AT_Send, AT_Return},
{"AT+CEREG", AT_Send, AT_Return},
{"AT+CMQNEW", AT_Send, AT_Return},
{"AT+CMQCON", AT_Send, AT_Return},
{"AT+CMQSUB", AT_Send, AT_Return},
{"AT+CMQPUB", AT_Send, AT_Return},
{"AT+CMQUNSUB", AT_Send, AT_Return},
{"AT+CMQDISCON", AT_Send, AT_Return},
{"AT+CREVHEX", AT_Send, AT_Return},
{NULL, NULL , NULL}
};
char Buff[2048];
int SIM7020_state = LNW_INIT;
int AT_CMD_Dispose(struct tok *tok) {
struct at_cmd_hanld_t *atcmd, *match = NULL;
char name[32];
atcmd = at_cmd_hanld;
stringCapitalize(name, tok->name);
while(atcmd->atcmd) {
if(strcmp(atcmd->atcmd, name) == 0) {
match = atcmd; break;
} atcmd ++;
} if(match) return match->send_hanld(match->atcmd, tok);
else {return 1;}
}
void CMD_Send(char *buff, char *atcmd, struct tok *tok) {
int i = 0; char temp[256];
sprintf (buff, "%s", atcmd);
if (tok->num != 0) {
for (i=0; i<tok->num; i++) {
if(i == 0 && tok->sendstr[i][0] == '?') {
sprintf(temp,"%s",tok->sendstr[i]);
strcat(buff,temp);
} else if(i == 0 && tok->sendstr[i][0] != '?') {
sprintf(temp,"=%s",tok->sendstr[i]);
strcat(buff,temp);
} else {
sprintf(temp,",%s",tok->sendstr[i]);
strcat(buff,temp);
}
}
} strcat(buff,"\r\n");
}
int AT_Send(char *atcmd, struct tok *tok) {
int i; char buff[256];
for(i=0; i<Retime; ++ i) {
CMD_Send(buff, atcmd, tok);
HAL_UART_Transmit_IT(&huart6, (uint8_t*)buff, strlen(buff));
if(!AT_Return(tok->ret, 1)) {return 0;}
} return 1;
}
int AT_Return(char *str, int flag) {
uint32_t Time_count = 2;
Time_count = Timeout;
memset(Buff, 0, sizeof Buff);
while(Time_count --) {
if (flag) HAL_UART_Receive(&huart6, (uint8_t *)Buff, sizeof Buff, 100);
//printf("AT_Return: %s\r\n", Buff);
if(strstr((const char *)Buff,str)!=NULL) {return 0;}
HAL_Delay(1);
} return 1;
}
void Buff_clear(struct tok *tok) {
tok->num = 0;
memset(tok->sendstr, 0, sizeof(tok->sendstr));
memset(tok->ret, 0, sizeof(tok->ret));
memset(Buff, 0, sizeof(Buff));
}
|
novaELLIAS/HYAsstSTM32 | Core/Src/MPU6050/Kalman.c |
#include "MPU6050/Kalman.h"
#include "MPU6050/MPU6050.h"
#include <math.h>
unsigned long now, lastTime = 0;
double dt;
int16_t ax, ay, az, gx, gy, gz;
double aax=0, aay=0,aaz=0, agx=0, agy=0, agz=0;
double accx, accy, accz;
long axo = 0, ayo = 0, azo = 0, gxo = 0, gyo = 0, gzo = 0;
double pi = 3.1415926, AcceRatio = 16384.0, GyroRatio = 131.0;
long long n_sample = 8;
double aaxs[8]={0}, aays[8]={0}, aazs[8]={0};
long long aax_sum, aay_sum,aaz_sum;
double a_x[10]={0}, a_y[10]={0}, a_z[10]={0}, g_x[10]={0}, g_y[10]={0}, g_z[10]={0};
double Px=1, Rx, Kx, Sx, Vx, Qx, Py=1, Ry, Ky, Sy, Vy, Qy, Pz=1, Rz, Kz, Sz, Vz, Qz;
#define sq(x) ((x)*(x))
void getAccelgyroData(double *tagX, double *tagY, double *tagZ, double *Acc) {
unsigned long now = HAL_GetTick();
dt = (now - lastTime) / 1000.0;
lastTime = now;
MPU_Get_Gyroscope(&gx, &gy, &gz);
MPU_Get_Accelerometer(&ax, &ay, &az);
accx = ax / AcceRatio, accy = ay / AcceRatio, accz = az / AcceRatio;
*Acc = sqrt(sq(accx) + sq(accy) + sq(accz));
aax = atan(accy / accz) * (-180) / pi;
aay = atan(accx / accz) * 180 / pi;
aaz = atan(accz / accy) * 180 / pi;
aax_sum = aay_sum = aaz_sum = 0;
for (register int i=1; i ^ n_sample; ++ i) {
aaxs[i-1] = aaxs[i], aax_sum += aaxs[i] * i;
aays[i-1] = aays[i], aay_sum += aays[i] * i;
aazs[i-1] = aazs[i], aaz_sum += aazs[i] * i;
}
aaxs[n_sample-1] = aax, aax_sum += aax * n_sample, aax = (aax_sum / (11 * n_sample / 2.0)) * 9 / 7.0;
aays[n_sample-1] = aay, aay_sum += aay * n_sample, aay = (aay_sum / (11 * n_sample / 2.0)) * 9 / 7.0;
aazs[n_sample-1] = aaz, aaz_sum += aaz * n_sample, aaz = (aaz_sum / (11 * n_sample / 2.0)) * 9 / 7.0;
double gyrox = -(gx - gxo) / GyroRatio * dt;
double gyroy = -(gy - gyo) / GyroRatio * dt;
double gyroz = -(gz - gzo) / GyroRatio * dt;
agx += gyrox, agy += gyroy, agz += gyroz;
Sx = Rx = Sy = Ry = Sz = Rz = 0;
for (int i = 1; i ^ 10; ++ i) {
a_x[i - 1] = a_x[i], Sx += a_x[i];
a_y[i - 1] = a_y[i], Sy += a_y[i];
a_z[i - 1] = a_z[i], Sz += a_z[i];
} a_x[9] = aax, Sx += aax, Sx /= 10, a_y[9] = aay, Sy += aay, Sy /= 10, a_z[9] = aaz, Sz += aaz, Sz /= 10;
for (register int i=0; i^10; ++ i) Rx += sq(a_x[i] - Sx), Ry += sq(a_y[i] - Sy), Rz += sq(a_z[i] - Sz);
Rx = Rx / 9, Ry = Ry / 9, Rz = Rz / 9;
Px = Px + 0.0025, Kx = Px / (Px + Rx), agx = agx + Kx * (aax - agx), Px = (1 - Kx) * Px;
Py = Py + 0.0025, Ky = Py / (Py + Ry), agy = agy + Ky * (aay - agy), Py = (1 - Ky) * Py;
Pz = Pz + 0.0025, Kz = Pz / (Pz + Rz), agz = agz + Kz * (aaz - agz), Pz = (1 - Kz) * Pz;
*tagX = agx, *tagY = agy, *tagZ = agz;
}
|
novaELLIAS/HYAsstSTM32 | Core/Inc/MQTT/utility.h | <filename>Core/Inc/MQTT/utility.h
#include "main.h"
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
void intToString (u16 n, u8 *str);
int stringToInt (char *str);
int getIntLen (int a);
void stringCapitalize (char *dest, char *str);
void strToHex (char *dst, char *src);
|
novaELLIAS/HYAsstSTM32 | Core/Src/MQTT/utility.c | <gh_stars>1-10
#include <MQTT/utility.h>
#include <stdio.h>
#include <string.h>
void intToString (u16 n, u8 *str) {
u8 len = 0; u16 tmp = n;
while (tmp/=10) {++ len;}
do {str[len --] = n%10+'0';}
while (n/=10); return;
}
int stringToInt (char *str) {
int ret = 0;
while (*str ^ '\0') {
ret = (ret<<1) + (ret<<3);
ret += *str ^ '0';
str ++;
} return ret;
}
int getIntLen (int a) {
int ret = 1;
while (a /= 10) ++ ret;
return ret;
}
void stringCapitalize (char *dest, char *str) {
int pos = 0, len = strlen (str);
for (; pos<len; ++ pos) {
if (str[pos]<='z' && str[pos]>='a') dest[pos]=str[pos]-32;
else dest[pos] = str[pos];
} dest[pos] = '\0';
}
int num[2048];
const char hex[16]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
void strToHex (char *dst, char *src) {
int len = strlen(src), i, pos = 0, top = 0;
char tmp;
for (i=0; i<len; ++ i) {
tmp = src[i], top = 0;
while (tmp) {
num[top ++] = tmp % 16;
tmp >>= 4;
} for (top=top-1; top>=0; -- top) dst[pos ++] = hex[num[top]];
} dst[pos] = '\0';
}
|
novaELLIAS/HYAsstSTM32 | Core/Src/GPS_Decoder/GPSdecode.c | <reponame>novaELLIAS/HYAsstSTM32
#include <stdio.h>
#include <string.h>
#include "GPS_Decoder/GPSdecode.h"
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
u8 NMEA_Comma_Pos (u8 *buf, u8 cx) {
u8 *p = buf;
while (cx) {
if (*buf=='*' || *buf<' ' || *buf>'z') return 0xFF;
if (*buf==',') {-- cx;} buf ++;
} return buf - p;
}
u32 NMEA_Pow (u32 a, u8 n) {
u32 ret = 1;
while (n) {
if(n&1) ret *= a;
a *= a, n >>= 1;
} return ret;
}
int NMEA_StrToNum (u8 *buf, u8*dx) {
u8 *p = buf;
u32 ires = 0, fres = 0;
u8 ilen = 0, flen = 0, flag = 0, i;
int ret;
while (1) {
if (*p=='-') {flag |= 0x02; p ++;}
if (*p==',' || *p=='*') {break;}
if (*p=='.') {flag |= 0x01; p ++;}
else if (*p<'0' || *p>'9') {
ilen = 0; flen = 0; break;
} if (flag&0x01) {++ flen;}
else {++ ilen;} p ++;
} if (flag&0x02) {buf ++;}
for (i=0; i<ilen; ++ i) {
ires += NMEA_Pow(10, ilen-i-1)*(buf[i]^'0');
} if (flen>5) {flen = 5;} *dx = flen;
for (i=0; i<flen; ++ i) {
fres += NMEA_Pow(10, flen-i-1)*(buf[ilen+i+1]^'0');
} ret = ires * NMEA_Pow(10, flen) + fres;
return (flag&0x02)? -ret:ret;
}
void NMEA_GPGSV_Analysis (nmea_msg *gpsx, u8 *buf) {
u8 *p, *p1, dx;
u8 len, i, j, slx = 0;
u8 posx; p = buf;
p1 = (u8*)strstr((const char *)p, "$GPGSV");
len = p1[7] ^ '0';
posx = NMEA_Comma_Pos(p1, 3);
if (posx^0XFF) gpsx->svnum = NMEA_StrToNum(p1+posx, &dx);
for (i=0; i<len; ++ i) {
p1 = (u8*)strstr((const char *)p, "$GPGSV");
for (j=0; j<4; ++ j) {
posx = NMEA_Comma_Pos(p1, 4+j*4);
if (posx^0XFF) gpsx->slmsg[slx].num = NMEA_StrToNum(p1+posx, &dx);
else break;
posx = NMEA_Comma_Pos(p1, 5+j*4);
if (posx^0XFF) gpsx->slmsg[slx].eledeg = NMEA_StrToNum(p1+posx, &dx);
else break;
posx = NMEA_Comma_Pos(p1, 6+j*4);
if (posx^0XFF) gpsx->slmsg[slx].azideg = NMEA_StrToNum(p1+posx, &dx);
else break;
posx = NMEA_Comma_Pos(p1, 7+j*4);
if (posx^0XFF) gpsx->slmsg[slx].sn = NMEA_StrToNum(p1+posx, &dx);
else break;
++ slx;
} p = p1+1;
}
}
void NMEA_GPVTG_Analysis(nmea_msg *gpsx,u8 *buf) {
u8 *p1, dx; u8 posx;
p1 = (u8*)strstr((const char *)buf, "$GPVTG");
posx = NMEA_Comma_Pos(p1, 7);
if(posx^0XFF) {
gpsx->speed = NMEA_StrToNum(p1+posx, &dx);
if (dx < 3) gpsx->speed *= NMEA_Pow(10, 3-dx);
}
}
void NMEA_GPGGA_Analysis (nmea_msg *gpsx,u8 *buf) {
u8 *p1, dx;
u8 posx;
p1 = (u8*)strstr((const char *)buf, "$GPGGA");
posx = NMEA_Comma_Pos(p1, 6);
if (posx^0XFF) gpsx->gpssta = NMEA_StrToNum(p1+posx, &dx);
// posx = NMEA_Comma_Pos(p1, 7);
// if (posx^0XFF) gpsx->posslnum = NMEA_StrToNum(p1+posx, &dx);
// posx = NMEA_Comma_Pos(p1, 9);
// if (posx^0XFF) gpsx->altitude = NMEA_StrToNum(p1+posx, &dx);
}
void NMEA_GPGSA_Analysis (nmea_msg *gpsx, u8 *buf) {
u8 *p1, dx;
u8 posx;
p1 = (u8*)strstr((const char *)buf, "$GPGSA");
// posx = NMEA_Comma_Pos(p1, 2); u8 i;
// if (posx^0XFF) gpsx->fixmode = NMEA_StrToNum(p1+posx, &dx);
// for (i=0; i<12; ++ i) {
// posx = NMEA_Comma_Pos(p1, 3+i);
// if (posx^0XFF) gpsx->possl[i] = NMEA_StrToNum(p1+posx, &dx);
// else break;
// }
posx = NMEA_Comma_Pos(p1, 15);
if (posx^0XFF) gpsx->pdop = NMEA_StrToNum(p1+posx, &dx);
// posx = NMEA_Comma_Pos(p1, 16);
// if (posx^0XFF) gpsx->hdop = NMEA_StrToNum(p1+posx, &dx);
// posx = NMEA_Comma_Pos(p1, 17);
// if (posx^0XFF) gpsx->vdop = NMEA_StrToNum(p1+posx, &dx);
}
void NMEA_GPRMC_Analysis (nmea_msg *gpsx, u8 *buf) {
u8 *p1, dx;
u8 posx;
u32 temp;
float rs;
p1 = (u8*)strstr((const char *)buf, "$GPRMC");
posx = NMEA_Comma_Pos(p1, 1);
if (posx^0XFF) {
temp = NMEA_StrToNum(p1+posx, &dx) / NMEA_Pow(10, dx);
gpsx->utc.hour = temp/10000;
gpsx->utc.min = (temp/100)%100;
gpsx->utc.sec = temp%100;
}
posx = NMEA_Comma_Pos(p1, 3);
if (posx^0XFF) {
temp = NMEA_StrToNum(p1+posx, &dx);
gpsx->latitude = temp/NMEA_Pow(10, dx+2);
rs = temp%NMEA_Pow(10, dx+2);
gpsx->latitude = gpsx->latitude*100000+(rs*NMEA_Pow(10, 5-dx))/60;
}
posx = NMEA_Comma_Pos(p1, 4);
if (posx^0XFF) gpsx->nshemi = *(p1+posx);
if (gpsx->nshemi ^ 'N') gpsx->latitude *= -1;
posx = NMEA_Comma_Pos(p1,5);
if (posx^0XFF) {
temp = NMEA_StrToNum(p1+posx, &dx);
gpsx->longitude = temp/NMEA_Pow(10, dx+2);
rs = temp%NMEA_Pow(10, dx+2);
gpsx->longitude = gpsx->longitude*100000+(rs*NMEA_Pow(10, 5-dx))/60;
}
posx = NMEA_Comma_Pos(p1, 6);
if (posx^0XFF) gpsx->ewhemi = *(p1+posx);
if (gpsx->ewhemi ^ 'E') gpsx->longitude *= -1;
// posx = NMEA_Comma_Pos(p1, 9);
// if (posx^0XFF) {
// temp = NMEA_StrToNum(p1+posx, &dx);
// gpsx->utc.date = temp/10000;
// gpsx->utc.month = (temp/100)%100;
// gpsx->utc.year = 2000+temp%100;
// }
}
void NMEA_GPS_DATA_PHRASE (nmea_msg *gpsx, gps_data *gpst) {
gpst->latitude = (float)gpsx->latitude /100000;
gpst->longitude = (float)gpsx->longitude/100000;
gpst->speed = (float)gpsx->speed/1000;
gpst->pdop = (float)gpsx->pdop/10;
}
|
novaELLIAS/HYAsstSTM32 | Core/Src/MQTT/general_command.c | <reponame>novaELLIAS/HYAsstSTM32<gh_stars>1-10
#include "MQTT/general_command.h"
#include "MQTT/AT.h"
#include "MQTT/utility.h"
#include <string.h>
#include <stdio.h>
#include "main.h"
extern struct tok tok;
extern char Buff[2048];
void Restart_Module(void) {
strcpy(tok.name,"AT+CFUN");
tok.num = 2;
strcpy(tok.sendstr[0],"1");
strcpy(tok.sendstr[1],"1");
strcpy(tok.ret,"OK\r\n");
AT_CMD_Dispose(&tok);
Buff_clear(&tok);
HAL_Delay(10000);
}
int Query_Signal_Quality(void) {
int ret, i=0;
char signal[5];
char *temp;
strcpy(tok.name,"AT+CSQ");
tok.num = 0;
strcpy(tok.ret,"+CSQ");
ret = AT_CMD_Dispose(&tok);
if(!ret) {
HAL_UART_Receive(&huart6, (uint8_t *)Buff, sizeof Buff, 100);
temp = strstr((const char *)Buff,"+CSQ:"); temp += 6;
while(*temp!=0x2C) {signal[i] = *temp; temp++; i++; signal[i] = '\0';}
printf("Query_Signal_Quality::Signal: \r\n%s\r\n", signal);
if(stringToInt(signal) < 10 || stringToInt(signal) == 99) {ret = 1;}
} Buff_clear(&tok);
return ret;
}
int Read_SIM_Card(void) {
strcpy(tok.name,"AT+CPIN");
tok.num = 1;
strcpy(tok.sendstr[0],"?");
strcpy(tok.ret,"OK\r\n");
if(!AT_CMD_Dispose(&tok)) {
if(!AT_Return("+CPIN: READY", 1)) {printf("SIM Ready.\r\n");}
Buff_clear(&tok); return 0;
} else {
printf("Read_SIM_Card Fail.\r\n");
Buff_clear(&tok); return 1;
}
}
int GET_LNW_State(void) {
int ret;
strcpy(tok.name,"AT+CEREG");
tok.num = 1;
strcpy(tok.sendstr[0],"?");
strcpy(tok.ret,"OK");
ret = AT_CMD_Dispose(&tok);
if(!ret) {
if(!AT_Return("+CEREG: 0,0", 1)) {
ret = 1; printf("Network_unregistered.\r\n");
} else if(!AT_Return("+CEREG: 0,1", 0)) {
ret = 0; printf("Network_registered.\r\n");
} else if(!AT_Return("+CEREG: 0,2", 0)) {
ret = 1; printf("Network_Registering..\r\n");
} else if(!AT_Return("+CEREG: 0,3", 0)) {
ret = 1; printf("Network_Register_Fail.\r\n");
} else if(!AT_Return("+CEREG: 0,4", 0)) {
ret = 1; printf("Network_Register_UKE.\r\n");
} else if(!AT_Return("+CEREG: 0,4", 0)) {
ret = 0; printf("Network_roaming.\r\n");
}
} Buff_clear(&tok); return ret;
}
int GET_LNW_Adhere(void) {
strcpy(tok.name,"AT+CGATT");
tok.num = 1;
strcpy(tok.sendstr[0],"?");
strcpy(tok.ret,"+CGATT: 1\r\n");
if(AT_CMD_Dispose(&tok)) {
printf("Network unattached.\r\n");
Buff_clear(&tok); return 1;
} Buff_clear(&tok); return 0;
}
int lte_init(void) {
if(Read_SIM_Card()) return 1;
if(GET_LNW_State()) return 2;
if(GET_LNW_Adhere()) return 3;
return 0;
}
|
novaELLIAS/HYAsstSTM32 | Core/Inc/GPS_Decoder/GPSdecode.h | <gh_stars>1-10
#include "main.h"
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef struct {
u8 num; //Satellite code
u8 eledeg; //Satellite elevation
u16 azideg; //Satellite azimuth
u8 sn; //Signal to noise ratio
} __attribute__((__packed__)) nmea_slmsg;
typedef struct {
u16 year;
u8 month;
u8 date;
u8 hour;
u8 min;
u8 sec;
} __attribute__((packed)) nmea_utc_time;
typedef struct {
u8 svnum; //Satellite visible
nmea_slmsg slmsg[12]; //NOTE: max 12 satellites
nmea_utc_time utc; //UTC time
u32 latitude; //Latitude * 100000
u8 nshemi; //South/North
u32 longitude; //Longitude * 100000
u8 ewhemi; //West/East
u8 gpssta;
/**
* GPS status:
* 0: no signal
* 1: non differential positioning
* 2: differentiation positioning
* 6: estimating
*/
u8 posslnum; //Satellite counter 0~12
u8 possl[12]; //Satellite Code locating
u8 fixmode;
/**
* Locating status:
* 1: non
* 2: 2D
* 3: 3D
*/
u16 pdop; //Position accuracy factor 0~500, to real 0~50.0
u16 hdop; //Horizontal precision factor 0~500, to real 0~50.0
u16 vdop; //Vertical precision factor 0~500, to real 0~50.0
int altitude; //Altitude * 10
u16 speed; //Speed * 1000
} __attribute__((packed)) nmea_msg;
typedef struct {
float latitude;
float longitude;
float speed;
float pdop;
} __attribute__((packed)) gps_data;
u8 NMEA_Comma_Pos (u8 *buf, u8 cx);
u32 NMEA_Pow (u32 a, u8 n);
int NMEA_StrToNum (u8 *buf, u8*dx);
void NMEA_GPGSV_Analysis (nmea_msg *gpsx, u8 *buf);
void NMEA_GPVTG_Analysis(nmea_msg *gpsx,u8 *buf);
void NMEA_GPGGA_Analysis (nmea_msg *gpsx,u8 *buf);
void NMEA_GPGSA_Analysis (nmea_msg *gpsx, u8 *buf);
void NMEA_GPRMC_Analysis (nmea_msg *gpsx, u8 *buf);
void NMEA_GPS_DATA_PHRASE (nmea_msg *gpsx, gps_data *gpst);
|
novaELLIAS/HYAsstSTM32 | Core/Src/LED_Functions/LED_OUTPUT.c | /**
******************************************************************************
* @file : LED_OUTPUT.c
* @author : ElliasKiriStuart
* @brief : LED_CONTROL_FUNCTIONS
******************************************************************************
* @attention
*
* Designed for STM32F411CEU6
* site: https://brynhild.online/
*
******************************************************************************
*/
#include "LED_Functions/LED_OUTPUT.h"
#include "main.h"
inline void LED_PC13_INIT () {
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_GPIOC_CLK_ENABLE();
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_SET);
GPIO_InitStruct.Pin = GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}
inline void LED_PC13_BLINK (register int delayTime) {
HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
HAL_Delay(delayTime);
HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
HAL_Delay(delayTime);
}
inline void LED_PC13_BREATHE (register int len) {
for (register int i=1; i<=len; ++ i) {
for (register int j=1; j<=i; ++ j) {
LED_TEST_ON(); HAL_Delay(4);
} for (register int j=1; j<=len-i; ++ j) {
LED_TEST_OFF(); HAL_Delay(4);
}
} for (register int i=1; i<=len; ++ i) {
for (register int j=1; j<=len-i; ++ j) {
LED_TEST_ON(); HAL_Delay(4);
} for (register int j=1; j<=i; ++ j) {
LED_TEST_OFF(); HAL_Delay(4);
}
}
}
inline void LED_OUTPUT_INIT () {
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_GPIOA_CLK_ENABLE();
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_6, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
LED_GPSRFS_OFF();
GPIO_InitStruct.Pin = GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
LED_DATUPD_OFF();
GPIO_InitStruct.Pin = GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
LED_ALERT_OFF();
}
inline void LED_OUTPUT_TEST () {
HAL_Delay(1000);
LED_GPSRFS_ON ();
LED_DATUPD_ON ();
LED_ALERT_ON ();
HAL_Delay(1000);
LED_GPSRFS_OFF();
LED_DATUPD_OFF();
LED_ALERT_OFF ();
HAL_Delay(1000);
}
|
novaELLIAS/HYAsstSTM32 | Core/Inc/MQTT/AT.h |
#include "main.h"
#include <stdio.h>
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
struct tok {
char name[32];
char num;
char sendstr[20][256];
char ret[256];
};
struct at_cmd_hanld_t {
char *atcmd;
int (*send_hanld) (char *atcmd, struct tok *tok);
int (*return_hanld) (char *str, int flag);
};
#define Timeout 10
#define Retime 2
#define LNW_INIT 0
#define SET_LNW_PARAMETER 1
#define CONNECT_OK 2
int AT_CMD_Dispose(struct tok *tok);
void CMD_Send(char *buff, char *atcmd, struct tok *tok);
int AT_Send(char *atcmd, struct tok *tok);
int AT_Return(char *str, int flag);
void Buff_clear(struct tok *tok);
|
novaELLIAS/HYAsstSTM32 | Core/Src/MQTT/MQTT.c | <gh_stars>1-10
#include "MQTT/MQTT.h"
#include "MQTT/utility.h"
#include "MQTT/general_command.h"
#include "MQTT/at.h"
#include "LED_Functions/LED_OUTPUT.h"
#include <stdio.h>
#include <string.h>
extern struct tok tok;
extern char Buff[256];
char ClientID[20] = "\"653000696\"";
char UserNAME[20] = "387253";
char Password[20] = "<PASSWORD>";
char TOPIC[20] = "\"$dp\"";
char RemoteIP[20] = "\"172.16.58.3\"";
char RemotePort[6] = "6002";
char hexToSend[256], strToSend[256];
int CONNECT_Server(void) {
int ret;
strcpy(tok.name, "AT+CMQNEW");
tok.num = 4;
strcpy(tok.sendstr[0],RemoteIP);
strcpy(tok.sendstr[1],RemotePort);
strcpy(tok.sendstr[2],"12000");
strcpy(tok.sendstr[3],"100");
strcpy(tok.ret,"OK");
ret = AT_CMD_Dispose(&tok);
Buff_clear(&tok);
if(ret) printf("OneNET Server Connection Fail.\r\n");
else printf("OneNET Server Connection Success.\r\n");
return ret;
}
int Registered_Plant(void) {
int ret;
strcpy(tok.name,"AT+CMQCON");
tok.num = 8;
strcpy(tok.sendstr[0],"0");
strcpy(tok.sendstr[1],"4");
strcpy(tok.sendstr[2],ClientID);
strcpy(tok.sendstr[3],"180");
strcpy(tok.sendstr[4],"0");
strcpy(tok.sendstr[5],"0");
strcpy(tok.sendstr[6],UserNAME);
strcpy(tok.sendstr[7],Password);
strcpy(tok.ret,"OK");
ret = AT_CMD_Dispose(&tok);
Buff_clear(&tok);
if(ret) printf("Device Register Fail.\r\n");
else printf("Device Register Success.\r\n");
return ret;
}
int SUB_Topic(void) {
int ret;
strcpy(tok.name,"AT+CMQSUB");
tok.num = 3;
strcpy(tok.sendstr[0],"0");
strcpy(tok.sendstr[1],TOPIC);
strcpy(tok.sendstr[2],"1");
strcpy(tok.ret,"OK");
ret = AT_CMD_Dispose(&tok);
Buff_clear(&tok);
if(ret) printf("Subscribe Fail.\r\n");
else printf("Subscribe Success.\r\n");
return ret;
}
int PUB_Messag(char *Messag) {
int ret, len = strlen(Messag) - 2;
char Messag_len[5];
memset(Messag_len, 0, sizeof Messag_len);
intToString(len,(uint8_t*)Messag_len);
strcpy(tok.name,"AT+CMQPUB");
tok.num = 7;
strcpy(tok.sendstr[0],"0");
strcpy(tok.sendstr[1],TOPIC);
strcpy(tok.sendstr[2],"0");
strcpy(tok.sendstr[3],"0");
strcpy(tok.sendstr[4],"0");
strcpy(tok.sendstr[5],Messag_len);
//printf("Message_len: %send\r\n",Messag_len);
strcpy(tok.sendstr[6],strToSend);
//printf("Message_TEST1\r\n");
strcpy(tok.ret,"OK");
ret = AT_CMD_Dispose(&tok);
//printf("Message_TEST2\r\n");
Buff_clear(&tok);
if(ret) printf("Message PUB Fail.\r\n");
else printf("Message PUB Success.\r\n");
return ret;
}
int UNSUB_Topic(void) {
int ret;
strcpy(tok.name,"AT+CMQUNSUB");
tok.num = 2;
strcpy(tok.sendstr[0],"0");
strcpy(tok.sendstr[1],TOPIC);
strcpy(tok.ret,"OK");
ret = AT_CMD_Dispose(&tok);
Buff_clear(&tok);
if(ret) printf("UNSUB Topic Fail.\r\n");
else printf("UNSUB Topic Success.\r\n");
return ret;
}
int Close_Server(void) {
int ret;
strcpy(tok.name,"AT+CMQDISCON");
tok.num = 1;
strcpy(tok.sendstr[0],"0");
strcpy(tok.ret,"OK");
ret = AT_CMD_Dispose(&tok);
Buff_clear(&tok);
if(ret) printf("ONENET Disconnect Fail.\r\n");
else printf("ONENET Disconnect Success.\r\n");
return ret;
}
int HEX_Mode_Enable(void) {
int ret;
strcpy(tok.name,"AT+CREVHEX");
tok.num = 1;
strcpy(tok.sendstr[0],"1");
strcpy(tok.ret,"OK");
ret = AT_CMD_Dispose(&tok);
Buff_clear(&tok);
if(ret) printf("HEX mode Fail.\r\n");
else printf("HEX mode Success.\r\n");
return ret;
}
void Messag_Analysis(char *buff) {
char *str1;
char *str2;
char top[64];
char Messag[64];
str1 = strstr(buff,"\"") + 1;
str2 = strstr(str1,"\"");
strncpy(top,str1,str2-str1);
top[str2-str1] = '\0';
str1 = strstr(str2+1,"\"") + 1;
str2 = strstr(str1,"\"");
strncpy(Messag,str1,str2-str1);
Messag[str2-str1] = '\0';
printf("TOP: %s\r\n",top);
printf("Message: %s\r\n",Messag);
}
int Messag_Bispose(void) {
if(!AT_Return("+CMQPUB:", 1)) {
Messag_Analysis(Buff);
Buff_clear(&tok); return 0;
} return 1;
}
void Messag_Builder (dataPoints *DP) {
sprintf(strToSend, "{\"La\":\"%.6f\",\"Lo\":\"%.6f\",\"S\":\"%.2f\",\"A\":\"%.1f\",\"F\":\"%d\"}", DP->latitude, DP->longitude, DP->speed, DP->pdop, DP->flag);
int len = strlen(strToSend);
//printf("Messag_Builder 1: %s\r\n", strToSend);
strToHex(hexToSend, strToSend);
sprintf(strToSend, "\"03%04X", len);
strcat(strToSend, hexToSend);
strcat(strToSend, "\"");
//printf("Messag_Builder 2: %s\r\n", strToSend);
}
void ONENET_MQTT(dataPoints *DP) {
switch(SIM7020_state) {
case LNW_INIT:
if(!lte_init()) SIM7020_state = SET_LNW_PARAMETER;
break;
case SET_LNW_PARAMETER:
Close_Server();
if(CONNECT_Server()) return;
if(Registered_Plant()) return;
if(SUB_Topic()) return;
SIM7020_state = CONNECT_OK;
break;
case CONNECT_OK:
LED_DATUPD_ON();
HEX_Mode_Enable();
Messag_Builder(DP);
PUB_Messag(strToSend);
LED_DATUPD_OFF();
}
}
|
novaELLIAS/HYAsstSTM32 | Core/Src/main.c |
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention designed for STM32F411CEU6
******************************************************************************
*/
#define SerialDebug
//#define SerialGPSdebug
//#define SerialDebugFloatTest
#include "main.h"
#include <stdio.h>
#include "LED_Functions/LED_OUTPUT.h"
#include "GPS_Decoder/GPSdecode.h"
#include "MPU6050/Accident_Alert.h"
#include "MQTT/general_command.h"
#include "MQTT/MQTT.h"
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_USART6_UART_Init(void);
static void MX_USART1_UART_Init(void);
// Serial output for Debug @ HUART1
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
PUTCHAR_PROTOTYPE {
HAL_UART_Transmit((UART_HandleTypeDef *)&huart1, (uint8_t*)&ch, 1, 0xFFFF);
return ch;
}
// GPS decoder
#define GPS_Delay_Time 1000
uint8_t gps_init;
uint8_t gps_uart[5000];
nmea_slmsg NMEAslmsg;
nmea_utc_time NMEAutctime;
nmea_msg NMEAmsg;
gps_data NMEAdata;
dataPoints DP;
int GPS_decode (void) {
HAL_UART_Receive(&huart2, gps_uart, sizeof(gps_uart), GPS_Delay_Time);
#ifdef SerialGPSdebug
//printf("USART data:\r\n%s\r\n", gps_uart);
#endif
NMEA_GPGGA_Analysis (&NMEAmsg, (uint8_t*) gps_uart);
if (!NMEAmsg.gpssta) {
LED_GPSRFS_ON();
#ifdef SerialDebug
printf("** GPS NO SIGNAL **\r\n");
#endif
return 1;
} else {
LED_GPSRFS_ON();
NMEA_GPRMC_Analysis (&NMEAmsg, (uint8_t*) gps_uart);
NMEA_GPGSA_Analysis (&NMEAmsg, (uint8_t*) gps_uart);
NMEA_GPVTG_Analysis (&NMEAmsg, (uint8_t*) gps_uart);
NMEA_GPRMC_Analysis (&NMEAmsg, (uint8_t*) gps_uart);
NMEA_GPS_DATA_PHRASE(&NMEAmsg, &NMEAdata);
DP.latitude = NMEAdata.latitude;
DP.longitude = NMEAdata.longitude;
DP.speed = NMEAdata.speed;
DP.pdop = NMEAdata.pdop;
#ifdef SerialGPSDebug
printf("\r\n** GPS Serial Debug **\r\n");
printf("GPS status: %s, PDOT: %f\r\n", NMEAmsg.gpssta^2? "3D":"2D", NMEAdata.pdop);
printf("UTC time: %02d:%02d:%02d\r\n", NMEAmsg.utc.hour, NMEAmsg.utc.min, NMEAmsg.utc.sec);
printf("Lat: %.6f, Log: %.6f, Spd: %.6f\r\n", NMEAdata.latitude, NMEAdata.longitude, NMEAdata.speed);
#endif
LED_GPSRFS_OFF();
return 0;
}
}
#undef GPS_Delay_Time
// main
signed main(void) {
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_I2C1_Init();
MX_USART2_UART_Init();
MX_USART6_UART_Init();
MX_USART1_UART_Init();
accidentMonitorSetup();
LED_OUTPUT_INIT();
LED_PC13_INIT();
LED_OUTPUT_TEST();
HAL_UART_Receive_IT(&huart2, &gps_init, 1);
#ifdef SerialDebugFloatTest
printf("initialization success.\r\n");
register float nnnnn = 114.514;
printf("\r\nFLOAT TEST\r\n%f\r\n", nnnnn);
nnnnn = 1919.810;
printf("%f\r\n\r\n", nnnnn);
#endif
register int ifGpsReady = 0;
//LED_DATUPD_ON(); LED_ALERT_ON();
LED_GPSRFS_ON(); LED_DATUPD_ON();
while (!ifGpsReady || (SIM7020_state^2)) {
if (!ifGpsReady && !Query_Signal_Quality()) {
ifGpsReady = 1; LED_GPSRFS_OFF();
} if (SIM7020_state^2) {
ONENET_MQTT(&DP); printf("SIM7020Searching..\r\n");
} else LED_DATUPD_OFF();
printf("GPS searching signal...\r\n"); HAL_Delay(1000);
}
/*
while (Query_Signal_Quality()) {
printf("Searching Signal...\r\n");
HAL_Delay(1000);
} printf("Signal Success.\r\n");
*/
LED_ALERT_OFF();
int GPSsta;
while (1) {
GPSsta = GPS_decode();
DP.flag = accidentJudge(&NMEAdata);
if (!GPSsta) ONENET_MQTT(&DP);
}
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void) {
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) {
Error_Handler();
}
}
/**
* @brief I2C1 Initialization Function
* @param None
* @retval None
*/
static void MX_I2C1_Init(void) {
/* USER CODE BEGIN I2C1_Init 0 */
/* USER CODE END I2C1_Init 0 */
/* USER CODE BEGIN I2C1_Init 1 */
/* USER CODE END I2C1_Init 1 */
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 400000;
hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c1) != HAL_OK) {
Error_Handler();
}
/* USER CODE BEGIN I2C1_Init 2 */
/* USER CODE END I2C1_Init 2 */
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void) {
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void) {
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 9600;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK) {
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
/**
* @brief USART6 Initialization Function
* @param None
* @retval None
*/
static void MX_USART6_UART_Init(void) {
/* USER CODE BEGIN USART6_Init 0 */
/* USER CODE END USART6_Init 0 */
/* USER CODE BEGIN USART6_Init 1 */
/* USER CODE END USART6_Init 1 */
huart6.Instance = USART6;
huart6.Init.BaudRate = 115200;
huart6.Init.WordLength = UART_WORDLENGTH_8B;
huart6.Init.StopBits = UART_STOPBITS_1;
huart6.Init.Parity = UART_PARITY_NONE;
huart6.Init.Mode = UART_MODE_TX_RX;
huart6.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart6.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart6) != HAL_OK) {
Error_Handler();
}
/* USER CODE BEGIN USART6_Init 2 */
/* USER CODE END USART6_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void) {
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void) {
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1) {
LED_PC13_BLINK(1000);
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line) {
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
novaELLIAS/HYAsstSTM32 | Core/Inc/MQTT/general_command.h | <filename>Core/Inc/MQTT/general_command.h
void Restart_Module(void);
int Query_Signal_Quality(void);
int Read_SIM_Card(void);
int GET_LNW_State(void);
int GET_LNW_Adhere(void);
int lte_init(void);
|
novaELLIAS/HYAsstSTM32 | Core/Inc/MPU6050/Accident_Alert.h | <reponame>novaELLIAS/HYAsstSTM32
void accidentMonitorSetup (void);
int accidentJudge (gps_data *GPSdata);
|
novaELLIAS/HYAsstSTM32 | Core/Inc/MQTT/MQTT.h |
extern int SIM7020_state;
typedef struct {
float latitude;
float longitude;
float speed;
float pdop;
int flag;
} __attribute__((packed)) dataPoints;
int CONNECT_Server(void);
int SUB_Topic(void);
int PUB_Messag(char *Messag);
int UNSUB_Topic(void);
int Close_Server(void);
int HEX_Mode_Enable(void);
void Messag_Analysis(char *buff);
int Messag_Bispose(void);
void ONENET_MQTT(dataPoints *DP);
|
udaypatial/FrankZappaUd | FrankZappaUd/FrankZappaUd.h | <gh_stars>0
//
// FrankZappaUd.h
// FrankZappaUd
//
// Created by <NAME> on 2022-03-22.
//
#import <Foundation/Foundation.h>
//! Project version number for FrankZappaUd.
FOUNDATION_EXPORT double FrankZappaUdVersionNumber;
//! Project version string for FrankZappaUd.
FOUNDATION_EXPORT const unsigned char FrankZappaUdVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <FrankZappaUd/PublicHeader.h>
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/TI-Header/csl_c6455_src/inc/cslr_cache.h | /* ============================================================================
* Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005
*
* Use of this software is controlled by the terms and conditions found in the
* license agreement under which this software has been supplied.
* ===========================================================================
*/
/** ============================================================================
* @file cslr_cache.h
*
* @path $(CSLPATH)\inc
*
* @desc This file contains the Register Descriptions for CACHE
*/
#ifndef _CSLR_CACHE_H_
#define _CSLR_CACHE_H_
#include <cslr.h>
#include <tistdtypes.h>
/**************************************************************************\
* Register Overlay Structure
\**************************************************************************/
typedef struct {
volatile Uint32 L2CFG;
volatile Uint8 RSVD0[28];
volatile Uint32 L1PCFG;
volatile Uint32 L1PCC;
volatile Uint8 RSVD1[24];
volatile Uint32 L1DCFG;
volatile Uint32 L1DCC;
volatile Uint8 RSVD2[16312];
volatile Uint32 L2WBAR;
volatile Uint32 L2WWC;
volatile Uint8 RSVD3[8];
volatile Uint32 L2WIBAR;
volatile Uint32 L2WIWC;
volatile Uint32 L2IBAR;
volatile Uint32 L2IWC;
volatile Uint32 L1PIBAR;
volatile Uint32 L1PIWC;
volatile Uint8 RSVD4[8];
volatile Uint32 L1DWIBAR;
volatile Uint32 L1DWIWC;
volatile Uint8 RSVD5[8];
volatile Uint32 L1DWBAR;
volatile Uint32 L1DWWC;
volatile Uint32 L1DIBAR;
volatile Uint32 L1DIWC;
volatile Uint8 RSVD6[4016];
volatile Uint32 L2WB;
volatile Uint32 L2WBINV;
volatile Uint32 L2INV;
volatile Uint8 RSVD7[28];
volatile Uint32 L1PINV;
volatile Uint8 RSVD8[20];
volatile Uint32 L1DWB;
volatile Uint32 L1DWBINV;
volatile Uint32 L1DINV;
volatile Uint8 RSVD9[12212];
volatile Uint32 MAR[256];
} CSL_CacheRegs;
/**************************************************************************\
* Overlay structure typedef definition
\**************************************************************************/
typedef volatile CSL_CacheRegs *CSL_CacheRegsOvly;
/**************************************************************************\
* Field Definition Macros
\**************************************************************************/
/* L2CFG */
#define CSL_CACHE_L2CFG_NUM_MM_MASK (0x07000000u)
#define CSL_CACHE_L2CFG_NUM_MM_SHIFT (0x00000018u)
#define CSL_CACHE_L2CFG_NUM_MM_RESETVAL (0x00000000u)
#define CSL_CACHE_L2CFG_MMID_MASK (0x00070000u)
#define CSL_CACHE_L2CFG_MMID_SHIFT (0x00000010u)
#define CSL_CACHE_L2CFG_MMID_RESETVAL (0x00000000u)
#define CSL_CACHE_L2CFG_IP_MASK (0x00000200u)
#define CSL_CACHE_L2CFG_IP_SHIFT (0x00000009u)
#define CSL_CACHE_L2CFG_IP_RESETVAL (0x00000000u)
#define CSL_CACHE_L2CFG_ID_MASK (0x00000100u)
#define CSL_CACHE_L2CFG_ID_SHIFT (0x00000008u)
#define CSL_CACHE_L2CFG_ID_RESETVAL (0x00000000u)
#define CSL_CACHE_L2CFG_L2CC_MASK (0x00000008u)
#define CSL_CACHE_L2CFG_L2CC_SHIFT (0x00000003u)
#define CSL_CACHE_L2CFG_L2CC_RESETVAL (0x00000000u)
/*----L2CC Tokens----*/
#define CSL_CACHE_L2CFG_L2CC_ENABLED (0x00000000u)
#define CSL_CACHE_L2CFG_L2CC_FREEZE (0x00000001u)
#define CSL_CACHE_L2CFG_MODE_MASK (0x00000007u)
#define CSL_CACHE_L2CFG_MODE_SHIFT (0x00000000u)
#define CSL_CACHE_L2CFG_MODE_RESETVAL (0x00000000u)
/*----MODE Tokens----*/
#define CSL_CACHE_L2CFG_MODE_OFF (0x00000000u)
#define CSL_CACHE_L2CFG_MODE_0K (0x00000000u)
#define CSL_CACHE_L2CFG_MODE_32K (0x00000001u)
#define CSL_CACHE_L2CFG_MODE_64K (0x00000002u)
#define CSL_CACHE_L2CFG_MODE_128K (0x00000003u)
#define CSL_CACHE_L2CFG_MODE_256K (0x00000004u)
#define CSL_CACHE_L2CFG_RESETVAL (0x00000000u)
/* L2WBAR */
#define CSL_CACHE_L2WBAR_ADDR_MASK (0xFFFFFFFFu)
#define CSL_CACHE_L2WBAR_ADDR_SHIFT (0x00000000u)
#define CSL_CACHE_L2WBAR_ADDR_RESETVAL (0x00000000u)
#define CSL_CACHE_L2WBAR_RESETVAL (0x00000000u)
/* L2WWC */
#define CSL_CACHE_L2WWC_RESERVED_MASK (0xFFFF0000u)
#define CSL_CACHE_L2WWC_RESERVED_SHIFT (0x00000010u)
#define CSL_CACHE_L2WWC_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L2WWC_CNT_MASK (0x0000FFFFu)
#define CSL_CACHE_L2WWC_CNT_SHIFT (0x00000000u)
#define CSL_CACHE_L2WWC_CNT_RESETVAL (0x00000000u)
#define CSL_CACHE_L2WWC_RESETVAL (0x00000000u)
/* L2WIBAR */
#define CSL_CACHE_L2WIBAR_ADDR_MASK (0xFFFFFFFFu)
#define CSL_CACHE_L2WIBAR_ADDR_SHIFT (0x00000000u)
#define CSL_CACHE_L2WIBAR_ADDR_RESETVAL (0x00000000u)
#define CSL_CACHE_L2WIBAR_RESETVAL (0x00000000u)
/* L2WIWC */
#define CSL_CACHE_L2WIWC_RESERVED_MASK (0xFFFF0000u)
#define CSL_CACHE_L2WIWC_RESERVED_SHIFT (0x00000010u)
#define CSL_CACHE_L2WIWC_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L2WIWC_CNT_MASK (0x0000FFFFu)
#define CSL_CACHE_L2WIWC_CNT_SHIFT (0x00000000u)
#define CSL_CACHE_L2WIWC_CNT_RESETVAL (0x00000000u)
#define CSL_CACHE_L2WIWC_RESETVAL (0x00000000u)
/* L2IBAR */
#define CSL_CACHE_L2IBAR_ADDR_MASK (0xFFFFFFFFu)
#define CSL_CACHE_L2IBAR_ADDR_SHIFT (0x00000000u)
#define CSL_CACHE_L2IBAR_ADDR_RESETVAL (0x00000000u)
#define CSL_CACHE_L2IBAR_RESETVAL (0x00000000u)
/* L2IWC */
#define CSL_CACHE_L2IWC_RESERVED_MASK (0xFFFF0000u)
#define CSL_CACHE_L2IWC_RESERVED_SHIFT (0x00000010u)
#define CSL_CACHE_L2IWC_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L2IWC_CNT_MASK (0x0000FFFFu)
#define CSL_CACHE_L2IWC_CNT_SHIFT (0x00000000u)
#define CSL_CACHE_L2IWC_CNT_RESETVAL (0x00000000u)
#define CSL_CACHE_L2IWC_RESETVAL (0x00000000u)
/* L1DWBAR */
#define CSL_CACHE_L1DWBAR_ADDR_MASK (0xFFFFFFFFu)
#define CSL_CACHE_L1DWBAR_ADDR_SHIFT (0x00000000u)
#define CSL_CACHE_L1DWBAR_ADDR_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DWBAR_RESETVAL (0x00000000u)
/* L1DWWC */
#define CSL_CACHE_L1DWWC_RESERVED_MASK (0xFFFF0000u)
#define CSL_CACHE_L1DWWC_RESERVED_SHIFT (0x00000010u)
#define CSL_CACHE_L1DWWC_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DWWC_CNT_MASK (0x0000FFFFu)
#define CSL_CACHE_L1DWWC_CNT_SHIFT (0x00000000u)
#define CSL_CACHE_L1DWWC_CNT_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DWWC_RESETVAL (0x00000000u)
/* L1DWIBAR */
#define CSL_CACHE_L1DWIBAR_ADDR_MASK (0xFFFFFFFFu)
#define CSL_CACHE_L1DWIBAR_ADDR_SHIFT (0x00000000u)
#define CSL_CACHE_L1DWIBAR_ADDR_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DWIBAR_RESETVAL (0x00000000u)
/* L1DWIWC */
#define CSL_CACHE_L1DWIWC_RESERVED_MASK (0xFFFF0000u)
#define CSL_CACHE_L1DWIWC_RESERVED_SHIFT (0x00000010u)
#define CSL_CACHE_L1DWIWC_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DWIWC_CNT_MASK (0x0000FFFFu)
#define CSL_CACHE_L1DWIWC_CNT_SHIFT (0x00000000u)
#define CSL_CACHE_L1DWIWC_CNT_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DWIWC_RESETVAL (0x00000000u)
/* L1DIBAR */
#define CSL_CACHE_L1DIBAR_ADDR_MASK (0xFFFFFFFFu)
#define CSL_CACHE_L1DIBAR_ADDR_SHIFT (0x00000000u)
#define CSL_CACHE_L1DIBAR_ADDR_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DIBAR_RESETVAL (0x00000000u)
/* L1DIWC */
#define CSL_CACHE_L1DIWC_RESERVED_MASK (0xFFFF0000u)
#define CSL_CACHE_L1DIWC_RESERVED_SHIFT (0x00000010u)
#define CSL_CACHE_L1DIWC_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DIWC_CNT_MASK (0x0000FFFFu)
#define CSL_CACHE_L1DIWC_CNT_SHIFT (0x00000000u)
#define CSL_CACHE_L1DIWC_CNT_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DIWC_RESETVAL (0x00000000u)
/* L1PIBAR */
#define CSL_CACHE_L1PIBAR_ADDR_MASK (0xFFFFFFFFu)
#define CSL_CACHE_L1PIBAR_ADDR_SHIFT (0x00000000u)
#define CSL_CACHE_L1PIBAR_ADDR_RESETVAL (0x00000000u)
#define CSL_CACHE_L1PIBAR_RESETVAL (0x00000000u)
/* L1PIWC */
#define CSL_CACHE_L1PIWC_RESERVED_MASK (0xFFFF0000u)
#define CSL_CACHE_L1PIWC_RESERVED_SHIFT (0x00000010u)
#define CSL_CACHE_L1PIWC_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1PIWC_CNT_MASK (0x0000FFFFu)
#define CSL_CACHE_L1PIWC_CNT_SHIFT (0x00000000u)
#define CSL_CACHE_L1PIWC_CNT_RESETVAL (0x00000000u)
#define CSL_CACHE_L1PIWC_RESETVAL (0x00000000u)
/* L1PCFG */
#define CSL_CACHE_L1PCFG_RESERVED_MASK (0xFFFFFFF8u)
#define CSL_CACHE_L1PCFG_RESERVED_SHIFT (0x00000003u)
#define CSL_CACHE_L1PCFG_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1PCFG_MODE_MASK (0x00000007u)
#define CSL_CACHE_L1PCFG_MODE_SHIFT (0x00000000u)
#define CSL_CACHE_L1PCFG_MODE_RESETVAL (0x00000000u)
/*----MODE Tokens----*/
#define CSL_CACHE_L1PCFG_MODE_OFF (0x00000000u)
#define CSL_CACHE_L1PCFG_MODE_0K (0x00000000u)
#define CSL_CACHE_L1PCFG_MODE_4K (0x00000001u)
#define CSL_CACHE_L1PCFG_MODE_8K (0x00000002u)
#define CSL_CACHE_L1PCFG_MODE_16K (0x00000003u)
#define CSL_CACHE_L1PCFG_MODE_32K (0x00000004u)
#define CSL_CACHE_L1PCFG_RESETVAL (0x00000000u)
/* L1DCFG */
#define CSL_CACHE_L1DCFG_RESERVED_MASK (0xFFFFFFF8u)
#define CSL_CACHE_L1DCFG_RESERVED_SHIFT (0x00000003u)
#define CSL_CACHE_L1DCFG_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DCFG_MODE_MASK (0x00000007u)
#define CSL_CACHE_L1DCFG_MODE_SHIFT (0x00000000u)
#define CSL_CACHE_L1DCFG_MODE_RESETVAL (0x00000000u)
/*----MODE Tokens----*/
#define CSL_CACHE_L1DCFG_MODE_OFF (0x00000000u)
#define CSL_CACHE_L1DCFG_MODE_0K (0x00000000u)
#define CSL_CACHE_L1DCFG_MODE_4K (0x00000001u)
#define CSL_CACHE_L1DCFG_MODE_8K (0x00000002u)
#define CSL_CACHE_L1DCFG_MODE_16K (0x00000003u)
#define CSL_CACHE_L1DCFG_MODE_32K (0x00000004u)
#define CSL_CACHE_L1DCFG_RESETVAL (0x00000000u)
/* L1PCC */
#define CSL_CACHE_L1PCC_RESERVED_MASK (0xFFFE0000u)
#define CSL_CACHE_L1PCC_RESERVED_SHIFT (0x00000011u)
#define CSL_CACHE_L1PCC_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1PCC_POPER_MASK (0x00010000u)
#define CSL_CACHE_L1PCC_POPER_SHIFT (0x00000010u)
#define CSL_CACHE_L1PCC_POPER_RESETVAL (0x00000000u)
/*----POPER Tokens----*/
#define CSL_CACHE_L1PCC_POPER_NORM (0x00000000u)
#define CSL_CACHE_L1PCC_POPER_FREEZE (0x00000001u)
#define CSL_CACHE_L1PCC_OPER_MASK (0x00000001u)
#define CSL_CACHE_L1PCC_OPER_SHIFT (0x00000000u)
#define CSL_CACHE_L1PCC_OPER_RESETVAL (0x00000000u)
/*----OPER Tokens----*/
#define CSL_CACHE_L1PCC_OPER_NORM (0x00000000u)
#define CSL_CACHE_L1PCC_OPER_FREEZE (0x00000001u)
#define CSL_CACHE_L1PCC_RESETVAL (0x00000000u)
/* L1DCC */
#define CSL_CACHE_L1DCC_RESERVED_MASK (0xFFFE0000u)
#define CSL_CACHE_L1DCC_RESERVED_SHIFT (0x00000011u)
#define CSL_CACHE_L1DCC_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DCC_POPER_MASK (0x00010000u)
#define CSL_CACHE_L1DCC_POPER_SHIFT (0x00000010u)
#define CSL_CACHE_L1DCC_POPER_RESETVAL (0x00000000u)
/*----POPER Tokens----*/
#define CSL_CACHE_L1DCC_POPER_NORM (0x00000000u)
#define CSL_CACHE_L1DCC_POPER_FREEZE (0x00000001u)
#define CSL_CACHE_L1DCC_OPER_MASK (0x00000001u)
#define CSL_CACHE_L1DCC_OPER_SHIFT (0x00000000u)
#define CSL_CACHE_L1DCC_OPER_RESETVAL (0x00000000u)
/*----OPER Tokens----*/
#define CSL_CACHE_L1DCC_OPER_NORM (0x00000000u)
#define CSL_CACHE_L1DCC_OPER_FREEZE (0x00000001u)
#define CSL_CACHE_L1DCC_RESETVAL (0x00000000u)
/* L2WB */
#define CSL_CACHE_L2WB_RESERVED_MASK (0xFFFFFFFEu)
#define CSL_CACHE_L2WB_RESERVED_SHIFT (0x00000001u)
#define CSL_CACHE_L2WB_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L2WB_CMDANDSTAT_MASK (0x00000001u)
#define CSL_CACHE_L2WB_CMDANDSTAT_SHIFT (0x00000000u)
#define CSL_CACHE_L2WB_CMDANDSTAT_RESETVAL (0x00000000u)
/*----CMDANDSTAT Tokens----*/
#define CSL_CACHE_L2WB_CMDANDSTAT_WB (0x00000001u)
#define CSL_CACHE_L2WB_CMDANDSTAT_DONE (0x00000000u)
#define CSL_CACHE_L2WB_CMDANDSTAT_NOTDONE (0x00000001u)
#define CSL_CACHE_L2WB_RESETVAL (0x00000000u)
/* L2WBINV */
#define CSL_CACHE_L2WBINV_RESERVED_MASK (0xFFFFFFFEu)
#define CSL_CACHE_L2WBINV_RESERVED_SHIFT (0x00000001u)
#define CSL_CACHE_L2WBINV_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L2WBINV_CMDANDSTAT_MASK (0x00000001u)
#define CSL_CACHE_L2WBINV_CMDANDSTAT_SHIFT (0x00000000u)
#define CSL_CACHE_L2WBINV_CMDANDSTAT_RESETVAL (0x00000000u)
/*----CMDANDSTAT Tokens----*/
#define CSL_CACHE_L2WBINV_CMDANDSTAT_WBINV (0x00000001u)
#define CSL_CACHE_L2WBINV_CMDANDSTAT_DONE (0x00000000u)
#define CSL_CACHE_L2WBINV_CMDANDSTAT_NOTDONE (0x00000001u)
#define CSL_CACHE_L2WBINV_RESETVAL (0x00000000u)
/* L2INV */
#define CSL_CACHE_L2INV_RESERVED_MASK (0xFFFFFFFEu)
#define CSL_CACHE_L2INV_RESERVED_SHIFT (0x00000001u)
#define CSL_CACHE_L2INV_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L2INV_CMDANDSTAT_MASK (0x00000001u)
#define CSL_CACHE_L2INV_CMDANDSTAT_SHIFT (0x00000000u)
#define CSL_CACHE_L2INV_CMDANDSTAT_RESETVAL (0x00000000u)
/*----CMDANDSTAT Tokens----*/
#define CSL_CACHE_L2INV_CMDANDSTAT_INV (0x00000001u)
#define CSL_CACHE_L2INV_CMDANDSTAT_DONE (0x00000000u)
#define CSL_CACHE_L2INV_CMDANDSTAT_NOTDONE (0x00000001u)
#define CSL_CACHE_L2INV_RESETVAL (0x00000000u)
/* L1DWB */
#define CSL_CACHE_L1DWB_RESERVED_MASK (0xFFFFFFFEu)
#define CSL_CACHE_L1DWB_RESERVED_SHIFT (0x00000001u)
#define CSL_CACHE_L1DWB_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DWB_CMDANDSTAT_MASK (0x00000001u)
#define CSL_CACHE_L1DWB_CMDANDSTAT_SHIFT (0x00000000u)
#define CSL_CACHE_L1DWB_CMDANDSTAT_RESETVAL (0x00000000u)
/*----CMDANDSTAT Tokens----*/
#define CSL_CACHE_L1DWB_CMDANDSTAT_WB (0x00000001u)
#define CSL_CACHE_L1DWB_CMDANDSTAT_DONE (0x00000000u)
#define CSL_CACHE_L1DWB_CMDANDSTAT_NOTDONE (0x00000001u)
#define CSL_CACHE_L1DWB_RESETVAL (0x00000000u)
/* L1DWBINV */
#define CSL_CACHE_L1DWBINV_RESERVED_MASK (0xFFFFFFFEu)
#define CSL_CACHE_L1DWBINV_RESERVED_SHIFT (0x00000001u)
#define CSL_CACHE_L1DWBINV_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DWBINV_CMDANDSTAT_MASK (0x00000001u)
#define CSL_CACHE_L1DWBINV_CMDANDSTAT_SHIFT (0x00000000u)
#define CSL_CACHE_L1DWBINV_CMDANDSTAT_RESETVAL (0x00000000u)
/*----CMDANDSTAT Tokens----*/
#define CSL_CACHE_L1DWBINV_CMDANDSTAT_WBINV (0x00000001u)
#define CSL_CACHE_L1DWBINV_CMDANDSTAT_DONE (0x00000000u)
#define CSL_CACHE_L1DWBINV_CMDANDSTAT_NOTDONE (0x00000001u)
#define CSL_CACHE_L1DWBINV_RESETVAL (0x00000000u)
/* L1DINV */
#define CSL_CACHE_L1DINV_RESERVED_MASK (0xFFFFFFFEu)
#define CSL_CACHE_L1DINV_RESERVED_SHIFT (0x00000001u)
#define CSL_CACHE_L1DINV_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1DINV_CMDANDSTAT_MASK (0x00000001u)
#define CSL_CACHE_L1DINV_CMDANDSTAT_SHIFT (0x00000000u)
#define CSL_CACHE_L1DINV_CMDANDSTAT_RESETVAL (0x00000000u)
/*----CMDANDSTAT Tokens----*/
#define CSL_CACHE_L1DINV_CMDANDSTAT_INV (0x00000001u)
#define CSL_CACHE_L1DINV_CMDANDSTAT_DONE (0x00000000u)
#define CSL_CACHE_L1DINV_CMDANDSTAT_NOTDONE (0x00000001u)
#define CSL_CACHE_L1DINV_RESETVAL (0x00000000u)
/* L1PINV */
#define CSL_CACHE_L1PINV_RESERVED_MASK (0xFFFFFFFEu)
#define CSL_CACHE_L1PINV_RESERVED_SHIFT (0x00000001u)
#define CSL_CACHE_L1PINV_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_L1PINV_CMDANDSTAT_MASK (0x00000001u)
#define CSL_CACHE_L1PINV_CMDANDSTAT_SHIFT (0x00000000u)
#define CSL_CACHE_L1PINV_CMDANDSTAT_RESETVAL (0x00000000u)
/*----CMDANDSTAT Tokens----*/
#define CSL_CACHE_L1PINV_CMDANDSTAT_INV (0x00000001u)
#define CSL_CACHE_L1PINV_CMDANDSTAT_DONE (0x00000000u)
#define CSL_CACHE_L1PINV_CMDANDSTAT_NOTDONE (0x00000001u)
#define CSL_CACHE_L1PINV_CMDANDSTAT_ (0x00000000u)
#define CSL_CACHE_L1PINV_RESETVAL (0x00000000u)
/* MAR */
#define CSL_CACHE_MAR_RESERVED_MASK (0xFFFFFFFEu)
#define CSL_CACHE_MAR_RESERVED_SHIFT (0x00000001u)
#define CSL_CACHE_MAR_RESERVED_RESETVAL (0x00000000u)
#define CSL_CACHE_MAR_PC_MASK (0x00000001u)
#define CSL_CACHE_MAR_PC_SHIFT (0x00000000u)
#define CSL_CACHE_MAR_PC_RESETVAL (0x00000000u)
#define CSL_CACHE_MAR_RESETVAL (0x00000000u)
#endif
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/TI-Header/csl_c64xplus_intc_src/src/intc/_csl_intcResource.c | /* ============================================================================
* Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005
*
* Use of this software is controlled by the terms and conditions found in the
* license agreement under which this software has been supplied.
* ===========================================================================
*/
/*
* @file _csl_intcResourceAlloc.c
*
* @brief File for functional layer of CSL API for intc resource allocation
*
* PATH $(CSLPATH)\src\intc
*/
/* =============================================================================
* Revision History
* ===============
* 12-Jun-2004 <NAME> File Created
*
* =============================================================================
*/
#include <csl_intc.h>
#include <_csl_intc.h>
#pragma DATA_SECTION (_CSL_intcAllocMask, ".bss:csl_section:intc");
CSL_BitMask32* _CSL_intcAllocMask = NULL;
#pragma DATA_SECTION (_CSL_intcCpuIntrTable, ".bss:csl_section:intc");
CSL_IntcVect _CSL_intcCpuIntrTable;
#pragma DATA_SECTION (_CSL_intcEventOffsetMap, ".bss:csl_section:intc");
Int8 *_CSL_intcEventOffsetMap = NULL;
#pragma DATA_SECTION (_CSL_intcNumEvents, ".bss:csl_section:intc");
Uint16 _CSL_intcNumEvents;
#pragma DATA_SECTION (_CSL_intcEventHandlerRecord, ".bss:csl_section:intc");
CSL_IntcEventHandlerRecord* _CSL_intcEventHandlerRecord;
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/FB_Example/irq.c | #include <csl.h>
#include <cslr_tmr.h>
#include <cslr_gpio.h>
#include <cslr_chip.h>
#include <cslr_edma3cc.h>
#include <soc.h>
#include <c6x.h>
#include "main.h"
#include "irq.h"
#include "MEA21_lib.h"
int num_tr_cross[HS1_CHANNELS/2];
int last_tr_cross[HS1_CHANNELS/2];
Uint32 reg_written;
Uint32 reg_value;
// Mailbox write interrupt
// use "#define USE_MAILBOX_IRQ" in global.h to enable this interrupt
interrupt void interrupt8(void)
{
reg_written = READ_REGISTER(0x428);
reg_value = READ_REGISTER(0x1000 + reg_written);
threshold = READ_REGISTER(0x1000);
deadtime = READ_REGISTER(0x1004);
// a write to a mailbox register occurred
}
// FPGA data available (do not use)
interrupt void interrupt4(void)
{
}
// I2C Interrupt
interrupt void interrupt5(void)
{
//handle_i2c_commands();
}
// DMA finished Interrupt
interrupt void interrupt6(void)
{
static int timestamp = 0; // exists only in this function but is created only once on the first function call (i.e. static)
static int segment = 0;
int i;
CSL_Edma3ccRegsOvly edma3ccRegs = (CSL_Edma3ccRegsOvly)CSL_EDMA3CC_0_REGS;
Int32* restrict adc_i_p = &adc_intern[0]; // we create here a pointer for compiler optimization reasons
Int32* restrict HS1_Data_p = (Int32 *)&MeaData[HS1_DATA_OFFSET];
// Int32* restrict IF_Data_p = (Int32 *)&MeaData[IF_DATA_OFFSET];
// Prepare DMA for next data transfer DO NOT CHANGE THE FOLLOWING LINE
CSL_FINST(edma3ccRegs->ICRH, EDMA3CC_ICRH_I52, CLEAR); // Clear pending interrupt for event 52
//
// Write to AUX register to see how long interrupt takes (set output to high, at the end set output to low)
WRITE_REGISTER(0x0310, 0x1); // set AUX 1 to value one
#if 0
// inititial setup
if (timestamp == 0) {
timestamp = 0;
for (i = 0; i < HS1_CHANNELS/2; i++)
{
num_tr_cross[i]=0;
last_tr_cross[i]=-deadtime;
}
}
// collect data
else if (timestamp < 5000)
{
for (i = 0; i < HS1_CHANNELS/2; i++)
{
*adc_i_p++ = *HS1_Data_p++;
}
for (i = 0; i < HS1_CHANNELS/2; i++)
{
if(adc_intern[i] < threshold && ((timestamp-last_tr_cross[i]) > deadtime) )
{
num_tr_cross[i]++;
last_tr_cross[i] = timestamp;
}
}
}
// analyze, might take longer
else if (timestamp == 5000)
{
int enable;
int mux;
int config;
int iMeanActivity = 0;
for (i = 0; i < HS1_CHANNELS/2; i++)
{
iMeanActivity = iMeanActivity + num_tr_cross[i];
}
iMeanActivity = iMeanActivity /(HS1_CHANNELS/2);
StimulusEnable[0] = 0;
StimulusEnable[1] = 0;
DAC_select[0] = 0;
DAC_select[1] = 0;
DAC_select[2] = 0;
DAC_select[3] = 0;
elec_config[0] = 0;
elec_config[1] = 0;
elec_config[2] = 0;
elec_config[3] = 0;
for (i = 0; i < HS1_CHANNELS/2; i++)
{
// if (num_tr_cross[i] <= iMeanActivity) {
if (num_tr_cross[i] > 0)
// if (i == 8 || i == 17)
{
enable = 1;
mux = 1; // Stimulation Source is DAC 1
config = 0; // Use Sidestream 1 for Stimulation Switch
}
else
{
enable = 0;
mux = 0; // Keep MUX at ground
config = 3; // Keep Switches static
}
StimulusEnable[i/30] |= (enable << i%30);
DAC_select[i/15] |= (mux << 2*(i%15));
elec_config[i/15] |= (config << 2*(i%15));
}
for (i = 0; i < 2; i++)
{
WRITE_REGISTER(0x9158+i*4, StimulusEnable[i]); // Enable Stimulation on STG
// WRITE_REGISTER(0x8140+i*4, StimulusEnable[i]); // Enable hard blanking for Stimulation Electrodes
}
for (i = 0; i < 4; i++)
{
WRITE_REGISTER(0x9160+i*4, DAC_select[i]); // Select DAC 1 for Stimulation Electrodes
WRITE_REGISTER(0x9120+i*4, elec_config[i]); // Configure Stimulation Electrodes to Listen to Sideband 1
}
WRITE_REGISTER(0x0218, segment << 16); // select segment for trigger 1
WRITE_REGISTER(0x0214, 0x00010001); // Start Trigger 1
segment = 1 - segment; // alternate between segment 0 and 1
// analyze data
// configure stim signal
}
// Wait for stimulation to finish
else if (timestamp < 100000)
{
// analyze data
// configure stim signal
}
else
{
// write result to mailbox
// timestamp = -1;
}
if (timestamp == 0)
{
WRITE_REGISTER(0x002C, 0x404); //switch on HS2 LED
}
else if (timestamp == 50000)
{
WRITE_REGISTER(0x002C, 0x400); //switch off HS2 LED
}
else if (timestamp == 100000)
{
timestamp =-1;
}
#endif
//MonitorData[0] = timestamp;
if ((int)MeaData[HS1_DATA_OFFSET + 0] > (int)threshold)
{
MonitorData[0] = MeaData[HS1_DATA_OFFSET + 0];
WRITE_REGISTER(FEEDBACK_REGISTER, 1);
}
else
{
MonitorData[0] = 0; //timestamp;
WRITE_REGISTER(FEEDBACK_REGISTER, 0);
}
MonitorData[1] = MeaData[HS1_DATA_OFFSET + 0];
CSL_FINST(edma3ccRegs->ESRH, EDMA3CC_ESRH_E53, SET); // Trigger DMA event 53
/*for (i = 0; i < HS2_CHANNELS; i++)
{
*adc_i_p++ = *HS2_Data_p++;
}
*/
/*for (i = 0; i < IF_CHANNELS; i++)
{
*adc_i_p++ = *IF_Data_p++;
}*/
WRITE_REGISTER(0x0310, 0x0); // set AUX 1 to value zero
// loop through electrode
// check for threshold crossing if passed deadtime (compare to timestamp that indicates last detected spike)
// if yes then add 1 to rate counter and save timestamp
// check static counter if 1 second in samples reached
// decide which electrodes to stimulate
// write stimulation to DACs
// MONITOR EXECUTION TIME WITH DIGITAL PULSE`
timestamp++;
}
// timer irq
interrupt void interrupt7(void)
{
static int led = 0;
CSL_FINS(gpioRegs->OUT_DATA, GPIO_OUT_DATA_OUT2, led); // LED
led = 1 - led;
}
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/TI-Header/csl_c6455/example/pwrdwn/src/Pwrdwn_example.c | <reponame>adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback
/* ============================================================================
* Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005
*
* Use of this software is controlled by the terms and conditions found in the
* license agreement under which this software has been supplied.
* ===========================================================================
*/
/* ============================================================================
* @file pwrdwnExample.c
*
* @path $(CSLPATH)\example\pwrdwn\src
*
* @desc Example for pwrdwn module
*
* ============================================================================
* @n Target Platform: EVM
* ============================================================================
* @n <b> Example Description </b>
* This function invokes example that prove functionalites of power down
* controller
* @n This example,
* 1. Initializes and opens the CSL PWRDWN module instance.
* 2. Sets up the hardware to setup parameters i.e.,
* CSL_pwrdwnHwSetup() is called for module configuration.
* 3. Puts page0 a port1 into sleep
* 4. Gets the page0 status
* 5. Wakes up the pageo of port1
* 6. Gets the page0 status
* 7. Compare the wakeup and sleep page0 status
* 8. Displays the messages based on step 7
*
* =============================================================================
*
* <b> Procedure to run the example </b>
* @verbatim
* 1. Configure the CCS setup to work with the emulator being used
* 2. Please refer CCS manual for setup configuration and loading
* proper GEL file
* 3. Launch CCS window
* 4. Open project Pwrdwn_example.pjt
* 5. Build the project and load the .out file of the project.
*
* @endverbatim
*
*/
/* =============================================================================
* Revision History
* ===============
* 28-Jul-2005 PSK File Created
* 16-Dec-2005 ds Updated documentation
* =============================================================================
*/
#include <csl_pwrdwn.h>
#include <soc.h>
#include <stdio.h>
void pwrdwn_example(void);
Uint32 demoFail = 0;
/*
* =============================================================================
* @func main
*
* @desc
* This is the main routine for the file.
*
* @expected result
* If the example passes, it displays the message "PASSED"
* If the example fails, it displays the messae "FAILED"
*
* =============================================================================
*/
void main(void)
{
printf("PWRDWN EXAMPLE DEMO\n");
/* Invoke example */
pwrdwn_example();
if (demoFail > 0) {
printf("\nPWRDWN: example Demo... FAILED.\n");
}
else {
printf("\nPWRDWN: example Demo... PASSED\n");
}
return;
}
/*
* =============================================================================
* @func pwrdwn_example
*
* @desc
* This function invokes example that prove functionalites of power down
* controller. This example puts a page on a specific port into sleep
* and verifies the status for that page by calling the CSL API to
* retrieve the status parameters.
*
* @arg
* None
*
* @eg
* pwrdwn_example();
* =============================================================================
*/
void pwrdwn_example (void)
{
CSL_PwrdwnContext pContext;
CSL_PwrdwnObj pwrdwnObj;
CSL_PwrdwnHandle hPwrdwn;
CSL_Status status;
CSL_PwrdwnHwSetup hwSetup;
CSL_PwrdwnPortData pageSleep, response, response1;
CSL_PwrdwnL2Manual manualPwrdwn;
manualPwrdwn.port0PageWake = 0x0;
manualPwrdwn.port1PageWake = 0x0;
manualPwrdwn.port0PageSleep = 0x0;
manualPwrdwn.port1PageSleep = 0x0;
hwSetup.idlePwrdwn = (Bool)0x0;
hwSetup.manualPwrdwn = &manualPwrdwn;
/* Initialize the module */
if (CSL_pwrdwnInit(&pContext) != CSL_SOK) {
printf("PWRDWN: Initialization... FAILED\n");
demoFail++;
}
/* Clear the local data structures */
memset(&pwrdwnObj, 0, sizeof(CSL_PwrdwnObj));
/* Open the module */
hPwrdwn = CSL_pwrdwnOpen (&pwrdwnObj, (CSL_InstNum)CSL_PWRDWN, NULL,
&status);
if ((hPwrdwn == NULL) || (status != CSL_SOK)) {
printf("PWRDWN: Error in opening the instance ...\n");
demoFail++;
}
/* Do hardware setup */
if (CSL_pwrdwnHwSetup(hPwrdwn, &hwSetup) != CSL_SOK) {
printf("PWRDWN: CSL_pwrdwnHwSetup ... FAILED\n");
demoFail++;
}
/* select port number and page which should be put into sleep */
pageSleep.portNum = (Bool)0x1;
pageSleep.data = 0x1;
/* Put the selected page into sleep */
if (CSL_pwrdwnHwControl(hPwrdwn, CSL_PWRDWN_CMD_PAGE0_SLEEP, &pageSleep) \
!= CSL_SOK) {
printf("PWRDWN: CSL_pwrdwnHwControl ... FAILED\n");
demoFail++;
}
response.portNum = (Bool)1;
/* Get the status of the page */
if (CSL_pwrdwnGetHwStatus (hPwrdwn, CSL_PWRDWN_QUERY_PAGE0_STATUS,
&response) != CSL_SOK) {
printf ("PWRDWN: CSL_pwrdwnGetHwStatus ... FAILED\n");
demoFail++;
}
/* Check for the correct status of the page */
if ((response.data & 0x1) == 0x1) {
printf("Status example PASSED\n");
}
/* Wake up the page */
if (CSL_pwrdwnHwControl(hPwrdwn, CSL_PWRDWN_CMD_PAGE0_WAKE, &pageSleep)\
!= CSL_SOK) {
printf("PWRDWN: CSL_pwrdwnHwControlCmd ... FAILED\n");
demoFail++;
}
if (CSL_pwrdwnGetHwStatus (hPwrdwn, CSL_PWRDWN_QUERY_PAGE0_STATUS,\
&response1) != CSL_SOK) {
printf ("PWRDWN: CSL_pwrdwnGetHwStatus ... FAILED\n");
demoFail++;
}
if (response.data != response1.data) {
printf("PWRDWN: functionality example PASSED");
}
else {
printf("PWRDWN: functionality example FAILED");
demoFail++;
}
return;
}
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/TI-Header/csl_c6455_src/src/srio/csl_srioClose.c | <gh_stars>0
/* ============================================================================
* Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005
*
* Use of this software is controlled by the terms and conditions found in the
* license agreement under which this software has been supplied.
* ============================================================================
*/
/** ===========================================================================
* @file csl_srioClose.c
*
* @brief File for functional layer of CSL API CSL_srioClose()
*
* @path $(CSLPATH)\srio\src
*
* @desc The CSL_srioClose() function definition and it's associated functions
* ============================================================================
*/
/* ============================================================================
* Revision History
* ===============
* 25-Aug-2005 PSK File Created.
* ============================================================================
*/
#include <csl_srio.h>
/** ===========================================================================
* @n@b csl_srioClose.c
*
* @b Description
* @n This function closes the specified instance of SRIO.
*
* @b Arguments
* @verbatim
hSrio handle to the SRIO
@endverbatim
*
* <b> Return Value </b> CSL_Status
* @li CSL_SOK - SRIO is closed
* successfully
*
* @li CSL_ESYS_BADHANDLE - The handle passed is invalid
*
* <b> Pre Condition </b>
* @n None
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
* CSL_SrioHandle hSrio;
* CSL_Status status;
* ...
* status = CSL_srioClose(hSrio);
@endverbatim
* ============================================================================
*/
#pragma CODE_SECTION (CSL_srioClose, ".text:csl_section:srio");
CSL_Status CSL_srioClose (
CSL_SrioHandle hSrio
)
{
CSL_Status status = CSL_SOK;
if (hSrio != NULL) {
hSrio->regs = (CSL_SrioRegsOvly)NULL;
hSrio->perNum = (CSL_InstNum)-1;
}
else {
status = CSL_ESYS_BADHANDLE;
}
return (status);
}
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/TI-Header/csl_c6455_src/src/mcbsp/csl_mcbspGetHwSetup.c | <filename>DSP/TI-Header/csl_c6455_src/src/mcbsp/csl_mcbspGetHwSetup.c<gh_stars>0
/* ============================================================================
* Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005
*
* Use of this software is controlled by the terms and conditions found in the
* license agreement under which this software has been supplied.
* ===========================================================================
*/
/** ============================================================================
* @file csl_mcbspGetHwSetup.c
*
* @path $(CSLPATH)\src\mcbsp
*
* @desc File for functional layer of CSL API CSL_mcbspGetHwSetup()
*
*/
/* ============================================================================
* Revision History
* ================
* July 04, 2005 ds - Removed support for getting DX Mode.
* - Removed support for getting enhanced sample
* clock mode
* Feb 02 , 2006 ds - Supported the Transmit & Receive Int Mode
* ============================================================================
*/
#include <csl_mcbsp.h>
/** ============================================================================
* @n@b CSL_mcbspGetHwSetup
*
* @b Description
* @n Gets the status of some or all of the setup-parameters of MCBSP.
* To get the status of complete MCBSP h/w setup, all the sub-structure
* pointers inside the main HwSetup structure, should be non-NULL.
*
* @b Arguments
* @verbatim
hMcbsp MCBSP handle returned by successful 'open'
myHwSetup Pointer to CSL_McbspHwSetup structure
@endverbatim
*
* <b> Return Value </b> CSL_Status
* @li CSL_SOK - Get hwsetup successful
* @li CSL_ESYS_INVPARAMS - The param passed is invalid
* @li CSL_ESYS_BADHANDLE - The handle passed is invalid
*
* <b> Pre Condition </b>
* @n CSL_mcbspInit() and CSL_mcbspOpen() must be called successfully
* in that order before CSL_mcbspGetHwSetup() can be called.
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_McbspHandle hMcbsp;
CSL_Status status;
CSL_McbspGlobalSetup gblSetup;
CSL_McbspClkSetup clkSetup;
CSL_McbspEmu emuMode;
CSL_McbspHwSetup readSetup = {
&gblSetup,
NULL, // RX Data-setup structure if not required
NULL, // TX Data-setup structure if not required
&clkSetup,
NULL, // Multichannel-setup structure if not required
emuMode
};
...
status = CSL_mcbspGetHwSetup(hMcbsp, &readSetup);
...
@endverbatim
* =============================================================================
*/
#pragma CODE_SECTION (CSL_mcbspGetHwSetup, ".text:csl_section:mcbsp");
CSL_Status CSL_mcbspGetHwSetup (
CSL_McbspHandle hMcbsp,
CSL_McbspHwSetup *myHwSetup
)
{
Uint16 tempValue;
CSL_Status status = CSL_SOK;
CSL_McbspRegsOvly mcbspRegs = hMcbsp->regs;
if (hMcbsp == NULL) {
status = CSL_ESYS_BADHANDLE;
}
else if (myHwSetup == NULL) {
status = CSL_ESYS_INVPARAMS;
}
else {
if (myHwSetup->global != NULL) {
CSL_McbspGlobalSetup *gbl = myHwSetup->global;
gbl->dlbMode =
(CSL_McbspDlbMode) CSL_FEXT(mcbspRegs->SPCR,MCBSP_SPCR_DLB);
gbl->clkStopMode =
(CSL_McbspClkStp) CSL_FEXT(mcbspRegs->SPCR, MCBSP_SPCR_CLKSTP);
gbl->ioEnableMode =
(CSL_McbspIOMode) (CSL_FEXT(mcbspRegs->PCR,MCBSP_PCR_RIOEN)
|(CSL_FEXT(mcbspRegs->PCR,MCBSP_PCR_XIOEN) << 1));
}
if (myHwSetup->rxdataset != NULL) {
CSL_McbspDataSetup *data = myHwSetup->rxdataset;
data->numPhases =
(CSL_McbspPhase) CSL_FEXT(mcbspRegs->RCR, MCBSP_RCR_RPHASE);
data->wordLength1 =
(CSL_McbspWordLen) CSL_FEXT(mcbspRegs->RCR, MCBSP_RCR_RWDLEN1);
data->wordLength2 =
(CSL_McbspWordLen) CSL_FEXT(mcbspRegs->RCR, MCBSP_RCR_RWDLEN2);
data->frmLength1 = CSL_FEXT(mcbspRegs->RCR, MCBSP_RCR_RFRLEN1) + 1;
data->frmLength2 = CSL_FEXT(mcbspRegs->RCR, MCBSP_RCR_RFRLEN2) + 1;
data->frmSyncIgn =
(CSL_McbspFrmSync) CSL_FEXT(mcbspRegs->RCR, MCBSP_RCR_RFIG);
data->compand =
(CSL_McbspCompand) CSL_FEXT(mcbspRegs->RCR, MCBSP_RCR_RCOMPAND);
data->dataDelay =
(CSL_McbspDataDelay) CSL_FEXT(mcbspRegs->RCR, MCBSP_RCR_RDATDLY);
data->rjust_dxenable =
(CSL_McbspRjustDxena) CSL_FEXT(mcbspRegs->SPCR, MCBSP_SPCR_RJUST);
data->intEvent = (CSL_McbspIntMode) CSL_FEXT(mcbspRegs->SPCR,
MCBSP_SPCR_RINTM);
data->wordReverse =
(CSL_McbspBitReversal)CSL_FEXT (mcbspRegs->RCR, MCBSP_RCR_RWDREVRS);
}
if (myHwSetup->txdataset != NULL) {
CSL_McbspDataSetup *data = myHwSetup->txdataset;
data->numPhases =
(CSL_McbspPhase) CSL_FEXT(mcbspRegs->XCR, MCBSP_XCR_XPHASE);
data->wordLength1 =
(CSL_McbspWordLen) CSL_FEXT(mcbspRegs->XCR, MCBSP_XCR_XWDLEN1);
data->wordLength2 =
(CSL_McbspWordLen) CSL_FEXT(mcbspRegs->XCR, MCBSP_XCR_XWDLEN2);
data->frmLength1 = CSL_FEXT(mcbspRegs->XCR, MCBSP_XCR_XFRLEN1) + 1;
data->frmLength2 = CSL_FEXT(mcbspRegs->XCR, MCBSP_XCR_XFRLEN2) + 1;
data->frmSyncIgn =
(CSL_McbspFrmSync) CSL_FEXT(mcbspRegs->XCR, MCBSP_XCR_XFIG);
data->compand =
(CSL_McbspCompand) CSL_FEXT(mcbspRegs->XCR, MCBSP_XCR_XCOMPAND);
data->dataDelay =
(CSL_McbspDataDelay) CSL_FEXT(mcbspRegs->XCR, MCBSP_XCR_XDATDLY);
data->rjust_dxenable =
(CSL_McbspRjustDxena) CSL_FEXT(mcbspRegs->SPCR,MCBSP_SPCR_DXENA);
data->intEvent = (CSL_McbspIntMode) CSL_FEXT(mcbspRegs->SPCR,
MCBSP_SPCR_XINTM);
data->wordReverse =
(CSL_McbspBitReversal)CSL_FEXT (mcbspRegs->XCR, MCBSP_XCR_XWDREVRS);
}
if (myHwSetup->clkset != NULL) {
CSL_McbspClkSetup *clk = myHwSetup->clkset;
clk->frmSyncRxMode =
(CSL_McbspFsClkMode) CSL_FEXT(mcbspRegs->PCR, MCBSP_PCR_FSRM);
clk->frmSyncTxMode =
(CSL_McbspFsClkMode) CSL_FEXT(mcbspRegs->PCR, MCBSP_PCR_FSXM);
clk->frmSyncRxPolarity =
(CSL_McbspFsPol) CSL_FEXT(mcbspRegs->PCR, MCBSP_PCR_FSRP);
clk->frmSyncTxPolarity =
(CSL_McbspFsPol) CSL_FEXT(mcbspRegs->PCR, MCBSP_PCR_FSXP);
clk->clkRxMode =
(CSL_McbspTxRxClkMode) CSL_FEXT(mcbspRegs->PCR, MCBSP_PCR_CLKRM);
clk->clkTxMode =
(CSL_McbspTxRxClkMode) CSL_FEXT(mcbspRegs->PCR, MCBSP_PCR_CLKXM);
clk->clkRxPolarity =
(CSL_McbspClkPol) CSL_FEXT(mcbspRegs->PCR, MCBSP_PCR_CLKRP);
clk->clkTxPolarity =
(CSL_McbspClkPol) CSL_FEXT(mcbspRegs->PCR, MCBSP_PCR_CLKXP);
clk->srgFrmPulseWidth = CSL_FEXT(mcbspRegs->SRGR, MCBSP_SRGR_FWID);
clk->srgFrmPeriod = CSL_FEXT(mcbspRegs->SRGR, MCBSP_SRGR_FPER);
clk->srgClkDivide = CSL_FEXT(mcbspRegs->SRGR, MCBSP_SRGR_CLKGDV);
clk->srgClkSync =
(CSL_McbspClkgSyncMode) CSL_FEXT(mcbspRegs->SRGR, MCBSP_SRGR_GSYNC);
clk->srgInputClkMode =
(CSL_McbspSrgClk) CSL_FEXT(mcbspRegs->SRGR, MCBSP_SRGR_CLKSM);
clk->srgClkPolarity =
(CSL_McbspClkPol) CSL_FEXT(mcbspRegs->SRGR, MCBSP_SRGR_CLKSP);
clk->srgTxFrmSyncMode =
(CSL_McbspTxFsMode) CSL_FEXT(mcbspRegs->SRGR, MCBSP_SRGR_FSGM);
}
if (myHwSetup->mulCh != NULL) {
CSL_McbspMulChSetup *mulch = myHwSetup->mulCh;
mulch->rxMulChSel = CSL_FEXT(mcbspRegs->MCR, MCBSP_MCR_RMCM);
mulch->txMulChSel = CSL_FEXT(mcbspRegs->MCR, MCBSP_MCR_XMCM);
mulch->rxPartition =
(CSL_McbspPartMode) CSL_FEXT(mcbspRegs->MCR, MCBSP_MCR_RMCME);
mulch->rxPartABlk =
(CSL_McbspPABlk) CSL_FEXT(mcbspRegs->MCR, MCBSP_MCR_RPABLK);
mulch->rxPartBBlk =
(CSL_McbspPBBlk) CSL_FEXT(mcbspRegs->MCR, MCBSP_MCR_RPBBLK);
mulch->txPartition =
(CSL_McbspPartMode) CSL_FEXT(mcbspRegs->MCR, MCBSP_MCR_XMCME);
mulch->txPartABlk =
(CSL_McbspPABlk) CSL_FEXT(mcbspRegs->MCR, MCBSP_MCR_XPABLK);
mulch->txPartBBlk =
(CSL_McbspPBBlk) CSL_FEXT(mcbspRegs->MCR, MCBSP_MCR_XPBBLK);
}
tempValue = CSL_FEXT( mcbspRegs->SPCR, MCBSP_SPCR_SOFT)
|(CSL_FEXT( mcbspRegs->SPCR, MCBSP_SPCR_FREE) << 1);
if (tempValue == 3)
tempValue = 2;
myHwSetup->emumode = (CSL_McbspEmu) tempValue;
/* Extra parameters, for future use */
myHwSetup->extendSetup = NULL;
}
return(status);
}
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/TI-Header/csl_c6455_src/inc/csl_i2cAux.h | <reponame>adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback
/* ===========================================================================
* Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005
*
* Use of this software is controlled by the terms and conditions found in the
* license agreement under which this software has been supplied.
* ===========================================================================
*/
/** ============================================================================
* @file csl_i2cAux.h
*
* @brief Header file for functional layer of CSL
*
* @path $(CSLPATH)\inc
*
* Description
* - The defines inline function definitions for control commands & status
* queris
* ===========================================================================
*/
/* =============================================================================
* Revision History
* ===============
* 31-Aug-2004 Hs File Created from CSL_i2cHwControl.c.
* 01-Sep-2004 Hs Added inline functions for query commands also.
* 11-oct-2004 Hs updated according to code review comments.
* 28-jul-2005 sv removed gpio support
* 06-Feb-2006 ds Updated according to TCI6482/C6455 User Guide
* ===========================================================================
*/
#ifndef _CSL_I2CAUX_H_
#define _CSL_I2CAUX_H_
#include <csl_i2c.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Control Functions of i2c. */
/** ============================================================================
* @n@b CSL_i2cEnable
*
* @b Description
* @n This function enables the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cEnable(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cEnable (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_IRS, FALSE);
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_IRS, TRUE);
}
/** ============================================================================
* @n@b CSL_i2cReset
*
* @b Description
* @n This function resets the I2C module. provides software reset
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cReset(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cReset (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_IRS, FALSE);
}
/** ============================================================================
* @n@b CSL_i2cOutOfReset
*
* @b Description
* @n This function pulls the I2C out of reset.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cOutOfReset(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cOutOfReset (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_IRS, TRUE);
}
/** ============================================================================
* @n@b CSL_i2cClearStatus
*
* @b Description
* @n This function clears the status register of I2C.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cClearStatus(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cClearStatus (
CSL_I2cHandle hI2c
)
{
Uint32 temp_stat = 0x0;
Uint32 temp_stat_old = 0x0;
/* Multiple status bits can be cleared. */
temp_stat_old = hI2c->regs->ICSTR & 0x3F;
if (temp_stat_old & CSL_I2C_CLEAR_AL) {
temp_stat = CSL_FMK(I2C_ICSTR_AL, 1); /* Writing 1 clears bit*/
}
if (temp_stat_old & CSL_I2C_CLEAR_NACK) {
temp_stat = CSL_FMK(I2C_ICSTR_NACK, 1); /* Writing 1 clears bit*/
}
if (temp_stat_old & CSL_I2C_CLEAR_ARDY) {
temp_stat = CSL_FMK(I2C_ICSTR_ARDY, 1) ; /* Writing 1 clears bit*/
}
if (temp_stat_old & CSL_I2C_CLEAR_RRDY) {
temp_stat = CSL_FMK(I2C_ICSTR_ICRRDY, 1) ; /* Writing 1 clears bit*/
}
if (temp_stat_old & CSL_I2C_CLEAR_XRDY) {
temp_stat = CSL_FMK(I2C_ICSTR_ICXRDY, 1) ; /* Writing 1 clears bit*/
}
if (temp_stat_old & CSL_I2C_CLEAR_SCD) {
temp_stat = CSL_FMK(I2C_ICSTR_SCD, 1) ; /* Writing 1 clears bit*/
}
hI2c->regs->ICSTR = hI2c->regs->ICSTR | (temp_stat & 0x3F);
}
/** ============================================================================
* @n@b CSL_i2cSetSlaveAddr
*
* @b Description
* @n This function sets the slave address of I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
arg pointer to hold the slave address
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cSetSlaveAddr(hI2c, &arg);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cSetSlaveAddr (
CSL_I2cHandle hI2c,
void *arg
)
{
hI2c->regs->ICSAR = ((*(Uint32 *)arg) & 0x3FF);
}
/** ============================================================================
* @n@b CSL_i2cSetOwnAddr
*
* @b Description
* @n This function sets its own address.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
arg pointer to hold the own address
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(), CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cSetOwnAddr(hI2c, &arg);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cSetOwnAddr (
CSL_I2cHandle hI2c,
void *arg
)
{
hI2c->regs->ICOAR = (*(Uint32 *)arg);
}
/** ============================================================================
* @n@b CSL_i2cEnableIntr
*
* @b Description
* @n This function enables selected interrupts of I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
arg OR-ed value of interrupts
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cEnableIntr(hI2c, arg);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cEnableIntr (
CSL_I2cHandle hI2c,
Uint32 arg
)
{
hI2c->regs->ICIMR = (hI2c->regs->ICIMR | (arg));
}
/** ============================================================================
* @n@b CSL_i2cDisableIntr
*
* @b Description
* @n This function disables selected interrupts of I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
arg OR-ed value of interrupts
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cDisableIntr(hI2c, arg);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cDisableIntr (
CSL_I2cHandle hI2c,
Uint32 arg
)
{
hI2c->regs->ICIMR = (hI2c->regs->ICIMR & ~(arg));
}
/** ============================================================================
* @n@b CSL_i2cSetDataCount
*
* @b Description
* @n This function sets the data count of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
arg pointer to hold the data count
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cSetDataCount(hI2c, &arg);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cSetDataCount (
CSL_I2cHandle hI2c,
void *arg
)
{
hI2c->regs->ICCNT = (*(Uint32 *)arg) & 0xFFFF;
}
/** ============================================================================
* @n@b CSL_i2cSetClock
*
* @b Description
* @n This function sets the I2C Clock.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
arg address of ClkSetup structure.
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cSetClockSetup(hI2c, &arg);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cSetClock (
CSL_I2cHandle hI2c,
CSL_I2cClkSetup *arg
)
{
CSL_FINS(hI2c->regs->ICPSC, I2C_ICPSC_IPSC, arg->prescalar);
CSL_FINS(hI2c->regs->ICCLKL, I2C_ICCLKL_ICCL, arg->clklowdiv);
CSL_FINS(hI2c->regs->ICCLKH, I2C_ICCLKH_ICCH, arg->clkhighdiv);
}
/** ============================================================================
* @n@b CSL_i2cStart
*
* @b Description
* @n This function writes the start command to the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cStart(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cStart (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_STT, TRUE);
}
/** ============================================================================
* @n@b CSL_i2cStop
*
* @b Description
* @n This function writes the stop command to the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cStop(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cStop (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_STP, TRUE);
}
/** ============================================================================
* @n@b CSL_i2cDirTransmit
*
* @b Description
* @n This function sets the direction of data as transmit of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cDirTransmit(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cDirTransmit (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_TRX, TRUE);
}
/** ============================================================================
* @n@b CSL_i2cDirReceive
*
* @b Description
* @n This function sets the direction of data as receive of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cDirReceive(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cDirReceive (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_TRX, FALSE);
}
/** ============================================================================
* @n@b CSL_i2RmEnable
*
* @b Description
* @n This function enables the repeat mode of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2RmEnable(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cRmEnable (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_RM, TRUE);
}
/** ============================================================================
* @n@b CSL_i2cRmDisable
*
* @b Description
* @n This function disables the repeat mode of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cRmDisable(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cRmDisable (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_RM, FALSE);
}
/** ============================================================================
* @n@b CSL_i2cDlbEnable
*
* @b Description
* @n This function enables the data loop back of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cDlbEnable(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cDlbEnable (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_DLB, TRUE);
}
/** ============================================================================
* @n@b CSL_i2cDlbDisable
*
* @b Description
* @n This function disables the data loop back of I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cDlbDisable(hI2c);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cDlbDisable (
CSL_I2cHandle hI2c
)
{
CSL_FINS(hI2c->regs->ICMDR, I2C_ICMDR_DLB, FALSE);
}
/**
* Status Functions of i2c.
*/
/** ============================================================================
* @n@b CSL_i2cGetClockSetup
*
* @b Description
* @n This function gets the clock setup of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return clock high,clock low and prescale value.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetClockSetup(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetClockSetup (
CSL_I2cHandle hI2c,
void *response
)
{
((CSL_I2cClkSetup *)response)->prescalar
= CSL_FEXT(hI2c->regs->ICPSC, I2C_ICPSC_IPSC);
((CSL_I2cClkSetup *)response)->clklowdiv
= CSL_FEXT(hI2c->regs->ICCLKL, I2C_ICCLKL_ICCL);
((CSL_I2cClkSetup *)response)->clkhighdiv
= CSL_FEXT(hI2c->regs->ICCLKH, I2C_ICCLKH_ICCH);
}
/** ============================================================================
* @n@b CSL_i2cGetBusBusy
*
* @b Description
* @n This function gets the bus busy status of I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return bus busy status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetBusBusy(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetBusBusy (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_BB);
}
/** ============================================================================
* @n@b CSL_i2cGetRxRdy
*
* @b Description
* @n This function gets the receive ready status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return receive ready status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetRxRdy(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetRxRdy (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_ICRRDY);
}
/** ============================================================================
* @n@b CSL_i2cGetTxRdy
*
* @b Description
* @n This function gets the transmit ready status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return Transmit ready status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetTxRdy(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetTxRdy (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_ICXRDY);
}
/** ============================================================================
* @n@b CSL_i2cGetAcsRdy
*
* @b Description
* @n This function gets the ACS ready status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return Register-access-ready status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetAcsRdy(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetAcsRdy (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_ARDY);
}
/** ============================================================================
* @n@b CSL_i2cGetScd
*
* @b Description
* @n This function gets the SCD status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return stop condition detection status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetScd(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetScd (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_SCD);
}
/** ============================================================================
* @n@b CSL_i2cGetAd0
*
* @b Description
* @n This function gets the AD0 status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return Address Zero Status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetAd0(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetAd0 (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_AD0);
}
/** ============================================================================
* @n@b CSL_i2cGetAas
*
* @b Description
* @n This function gets the AAS status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return address as slave status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetAas(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetAas (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_AAS);
}
/** ============================================================================
* @n@b CSL_i2cGetRsFull
*
* @b Description
* @n This function gets the RS Full status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return receive full status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetRsFull(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetRsFull (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_RSFULL);
}
/** ============================================================================
* @n@b CSL_i2cGetXsmt
*
* @b Description
* @n This function gets the transmit status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return transmit status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetXsmt(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetXsmt (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_XSMT);
}
/** ============================================================================
* @n@b CSL_i2cGetAl
*
* @b Description
* @n This function gets the AL status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return Arbitration-Lost status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetAl(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetAl (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_AL);
}
/** ============================================================================
* @n@b CSL_i2cGetSdir
*
* @b Description
* @n This function gets the SDIR status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return Slave Direction status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetSdir(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetSdir (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_SDIR);
}
/** ============================================================================
* @n@b CSL_i2cGetNacksnt
*
* @b Description
* @n This function gets the No Ack Sent status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return No Acknowledge status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetNacksnt(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetNacksnt (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICSTR, I2C_ICSTR_NACKSNT);
}
/** ============================================================================
* @n@b CSL_i2cGetRdone
*
* @b Description
* @n This function gets the Reset Done status of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return receive done status.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetRdone(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetRdone (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICMDR, I2C_ICMDR_IRS);
}
/** ============================================================================
* @n@b CSL_i2cGetBitcount
*
* @b Description
* @n This function gets the bit count number of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> Return bit count value.
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetBitcount(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetBitcount (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICMDR, I2C_ICMDR_BC);
}
/** ============================================================================
* @n@b CSL_i2cGetIntcode
*
* @b Description
* @n This function gets the interrupt code of the I2C module.
*
* @b Arguments
* @verbatim
hI2c Handle to I2C instance
response Placeholder to return status.
@endverbatim
*
* <b> Return Value </b> None
*
* <b> Pre Condition </b>
* @n CSL_i2cInit(),CSL_i2cOpen()has to be called successfully before calling
* this function
*
* <b> Post Condition </b>
* @n None
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_i2cGetIntcode(hI2c, &response);
@endverbatim
* ============================================================================
*/
static inline
void CSL_i2cGetIntcode (
CSL_I2cHandle hI2c,
void *response
)
{
*(Uint32 *)response = CSL_FEXT(hI2c->regs->ICIVR, I2C_ICIVR_INTCODE);
}
#ifdef __cplusplus
}
#endif
#endif /* CSL_I2CAUX_H_ */
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/FB_W2100_SCU_MEA256/Stimulation.h | <reponame>adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback
/*
* Stimulation.h
*
* Created on: 14.05.2018
* Author: jesinger
*/
#ifndef STIMULATION_H_
#define STIMULATION_H_
#define REGISTER_OFFSET 1
#define MEMPOINT_OFFSET (8 * REGISTER_OFFSET)
#define TIGGER_PER_HS 18
#define ELECTRODES_PER_REGISTER 32
#define TRIGGER_CTRL_HS1 0x0100
#define TRIGGER_SET_EVENT_HS1 0x0110
#define TRIGGER_ID_HS1 0x0140
#define STG_ELECTRODE_MODE 0x9c70 // 0x9120 on MEA2100
#define STG_ELECTRODE_ENABLE 0x9ca0 // 0x9158 on MEA2100
#define STG_ELECTRODE_MUX 0x9cd0 // 0x9160 on MEA2100
#define STG_TRIGGER_CONFIG 0x9600
#define STG_TRIGGER_REPEAT 0x9700 // 0x9190 on MEA2100
#define STG_MEMPOINT_CC_BASE 0x9200
#define STG_MEMPOINT_WP_BASE 0x9203 // write to this address clears the stg data
#define STG_DATA_MEMORY 0x9f80
void UploadBiphaseRect(int channel, int segment, int amplitude, int duration, int repeats);
void UploadSine(int channel, int segment, int amplitude, int period, int repeats, int threshold);
void SetSegment(int channel, int segment);
void ClearChannel(int channel, int segment);
void SetupTrigger();
void AddLoop(int channel, int vectors, int repeats);
int AddDataPoint(int channel, int duration, int value);
#endif /* STIMULATION_H_ */
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/FB_W2100_SCU_MEA256/Common/MCS_USB_def.h | <reponame>adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback
// public
//---------------------------------------------------------------------------
//
// Project: MCS_USB_LIB
// Copyright (c) 2007 Multi Channel Systems. All rights reserved
//
// $Header: /MCS_USB_Lib/DLL/MCS_USB_def.h 94 13.07.12 13:18 Jesinger $
// $Modtime: 13.07.12 8:37 $
//
//---------------------------------------------------------------------------
/*! \file
\brief Constants needed by MCS_USB_lib.dll
*/
#ifndef _MCS_USB_DEF_H_
#define _MCS_USB_DEF_H_
/***************************************************************
*
* Include File to be shared between embedded devices and Windows
*
***************************************************************/
/* Firmware destinations */
#define MCSUSB_DEST_UNKNOWN -1
#define MCSUSB_DEST_DSP 0x00
#define MCSUSB_DEST_USB 0x01
#define MCSUSB_DEST_MCU1 0x02
#define MCSUSB_DEST_USB_RAM 0x03
#define MCSUSB_DEST_BOOTSTRAP 0x10
#define MCSUSB_DEST_BOOTSTAP_OTHER_CYPRESS 0x11
#define MCSUSB_DEST_ALTERA 0x40
#define MCSUSB_DEST_FPGA2 0x41
#define MCSUSB_DEST_FPGA3 0x42
#define MCSUSB_DEST_FPGA4 0x43
#define MCSUSB_DEST_FPGA5 0x44
#define MCSUSB_DEST_FPGA6 0x45
#define MCSUSB_DEST_FPGA7 0x46
#define MCSUSB_DEST_FPGA8 0x47
#define MCSUSB_DEST_FPGA9 0x48
#define MCSUSB_DEST_FPGA10 0x49
#define MCSUSB_DEST_FPGA11 0x4A
#define MCSUSB_DEST_FPGA12 0x4B
#define MCSUSB_DEST_FPGA13 0x4C
#define MCSUSB_DEST_FPGA14 0x4D
#define MCSUSB_DEST_FPGA15 0x4E
#define MCSUSB_DEST_FPGA16 0x4F
#define MCSUSB_DEST_MCSBUS1 0x60
#define MCSUSB_DEST_MCSBUS2 0x61
#define MCSUSB_DEST_MCSBUS3 0x62
#define MCSUSB_DEST_MCSBUS4 0x63
#define MCSUSB_DEST_MCSBUS5 0x64
#define MCSUSB_DEST_MCSBUS6 0x65
#define MCSUSB_DEST_MCSBUS7 0x66
#define MCSUSB_DEST_MCSBUS8 0x67
#define MCSUSB_DEST_MCSBUS9 0x68
#define MCSUSB_DEST_MCSBUS10 0x69
#define MCSUSB_DEST_MCSBUS11 0x6A
#define MCSUSB_DEST_MCSBUS12 0x6B
#define MCSUSB_DEST_MCSBUS13 0x6C
#define MCSUSB_DEST_MCSBUS14 0x6D
#define MCSUSB_DEST_MCSBUS15 0x6E
#define MCSUSB_DEST_MCSBUS0 0x6F
#define MCSUSB_DEST_PIC 0x82
#define MCSUSB_DEST_PIC2 0x83
#define MCSUSB_DEST_PIC3 0x84
#define MCSUSB_DEST_PIC4 0x85
#define MCSUSB_DEST_PIC5 0x86
#define MCSUSB_DEST_PIC6 0x87
#define MCSUSB_DEST_PIC7 0x88
#define MCSUSB_DEST_PIC8 0x89
#define MCSUSB_DEST_CHANNELPIC 0x88
// 0x89 reserved
// 0x8A reserved
// 0x8B reserved
// 0x8C reserved
// 0x8D reserved
// 0x8E reserved
// 0x8F reserved
#define MCSUSB_DEST_CHANNELSEC 0x90
// 0x91 reserved
// 0x92 reserved
// 0x93 reserved
// 0x94 reserved
// 0x95 reserved
// 0x96 reserved
// 0x97 reserved
#define MCSUSB_DEST_TIMESLOT0 0x000
#define MCSUSB_DEST_BUSNUMBER0 0x000
#define MCSUSB_DEST_BUS0_MCSBUS1 (MCSUSB_DEST_MCSBUS1 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS2 (MCSUSB_DEST_MCSBUS2 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS3 (MCSUSB_DEST_MCSBUS3 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS4 (MCSUSB_DEST_MCSBUS4 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS5 (MCSUSB_DEST_MCSBUS5 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS6 (MCSUSB_DEST_MCSBUS6 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS7 (MCSUSB_DEST_MCSBUS7 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS8 (MCSUSB_DEST_MCSBUS8 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS9 (MCSUSB_DEST_MCSBUS9 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS10 (MCSUSB_DEST_MCSBUS10 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS11 (MCSUSB_DEST_MCSBUS11 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS12 (MCSUSB_DEST_MCSBUS12 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS13 (MCSUSB_DEST_MCSBUS13 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS14 (MCSUSB_DEST_MCSBUS14 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS15 (MCSUSB_DEST_MCSBUS15 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_BUS0_MCSBUS0 (MCSUSB_DEST_MCSBUS0 | MCSUSB_DEST_BUSNUMBER0)
#define MCSUSB_DEST_TIMESLOT1 0x100
#define XILINX_DEST_GOLDEN 0x100
#define MCSUSB_DEST_BUSNUMBER1 0x100
#define MCSUSB_DEST_BUS1_MCSBUS1 (MCSUSB_DEST_MCSBUS1 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS2 (MCSUSB_DEST_MCSBUS2 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS3 (MCSUSB_DEST_MCSBUS3 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS4 (MCSUSB_DEST_MCSBUS4 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS5 (MCSUSB_DEST_MCSBUS5 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS6 (MCSUSB_DEST_MCSBUS6 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS7 (MCSUSB_DEST_MCSBUS7 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS8 (MCSUSB_DEST_MCSBUS8 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS9 (MCSUSB_DEST_MCSBUS9 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS10 (MCSUSB_DEST_MCSBUS10 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS11 (MCSUSB_DEST_MCSBUS11 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS12 (MCSUSB_DEST_MCSBUS12 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS13 (MCSUSB_DEST_MCSBUS13 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS14 (MCSUSB_DEST_MCSBUS14 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS15 (MCSUSB_DEST_MCSBUS15 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_BUS1_MCSBUS0 (MCSUSB_DEST_MCSBUS0 | MCSUSB_DEST_BUSNUMBER1)
#define MCSUSB_DEST_TIMESLOT2 0x200
#define XILINX_DEST_BASEIMAGE 0x200
#define MCSUSB_DEST_BUSNUMBER2 0x200
#define MCSUSB_DEST_BUS2_MCSBUS1 (MCSUSB_DEST_MCSBUS1 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS2 (MCSUSB_DEST_MCSBUS2 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS3 (MCSUSB_DEST_MCSBUS3 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS4 (MCSUSB_DEST_MCSBUS4 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS5 (MCSUSB_DEST_MCSBUS5 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS6 (MCSUSB_DEST_MCSBUS6 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS7 (MCSUSB_DEST_MCSBUS7 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS8 (MCSUSB_DEST_MCSBUS8 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS9 (MCSUSB_DEST_MCSBUS9 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS10 (MCSUSB_DEST_MCSBUS10 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS11 (MCSUSB_DEST_MCSBUS11 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS12 (MCSUSB_DEST_MCSBUS12 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS13 (MCSUSB_DEST_MCSBUS13 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS14 (MCSUSB_DEST_MCSBUS14 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS15 (MCSUSB_DEST_MCSBUS15 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_BUS2_MCSBUS0 (MCSUSB_DEST_MCSBUS0 | MCSUSB_DEST_BUSNUMBER2)
#define MCSUSB_DEST_TIMESLOT3 0x300
#define XILINX_DEST_BOOTSTRAP 0x300
#define MCSUSB_DEST_BUSNUMBER3 0x300
#define MCSUSB_DEST_BUS3_MCSBUS1 (MCSUSB_DEST_MCSBUS1 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS2 (MCSUSB_DEST_MCSBUS2 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS3 (MCSUSB_DEST_MCSBUS3 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS4 (MCSUSB_DEST_MCSBUS4 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS5 (MCSUSB_DEST_MCSBUS5 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS6 (MCSUSB_DEST_MCSBUS6 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS7 (MCSUSB_DEST_MCSBUS7 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS8 (MCSUSB_DEST_MCSBUS8 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS9 (MCSUSB_DEST_MCSBUS9 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS10 (MCSUSB_DEST_MCSBUS10 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS11 (MCSUSB_DEST_MCSBUS11 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS12 (MCSUSB_DEST_MCSBUS12 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS13 (MCSUSB_DEST_MCSBUS13 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS14 (MCSUSB_DEST_MCSBUS14 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS15 (MCSUSB_DEST_MCSBUS15 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUS3_MCSBUS0 (MCSUSB_DEST_MCSBUS0 | MCSUSB_DEST_BUSNUMBER3)
#define MCSUSB_DEST_BUSNUMBER4 0x400
#define MCSUSB_DEST_BUS4_MCSBUS1 (MCSUSB_DEST_MCSBUS1 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS2 (MCSUSB_DEST_MCSBUS2 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS3 (MCSUSB_DEST_MCSBUS3 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS4 (MCSUSB_DEST_MCSBUS4 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS5 (MCSUSB_DEST_MCSBUS5 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS6 (MCSUSB_DEST_MCSBUS6 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS7 (MCSUSB_DEST_MCSBUS7 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS8 (MCSUSB_DEST_MCSBUS8 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS9 (MCSUSB_DEST_MCSBUS9 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS10 (MCSUSB_DEST_MCSBUS10 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS11 (MCSUSB_DEST_MCSBUS11 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS12 (MCSUSB_DEST_MCSBUS12 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS13 (MCSUSB_DEST_MCSBUS13 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS14 (MCSUSB_DEST_MCSBUS14 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS15 (MCSUSB_DEST_MCSBUS15 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUS4_MCSBUS0 (MCSUSB_DEST_MCSBUS0 | MCSUSB_DEST_BUSNUMBER4)
#define MCSUSB_DEST_BUSNUMBER5 0x500
#define MCSUSB_DEST_BUS5_MCSBUS1 (MCSUSB_DEST_MCSBUS1 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS2 (MCSUSB_DEST_MCSBUS2 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS3 (MCSUSB_DEST_MCSBUS3 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS4 (MCSUSB_DEST_MCSBUS4 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS5 (MCSUSB_DEST_MCSBUS5 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS6 (MCSUSB_DEST_MCSBUS6 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS7 (MCSUSB_DEST_MCSBUS7 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS8 (MCSUSB_DEST_MCSBUS8 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS9 (MCSUSB_DEST_MCSBUS9 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS10 (MCSUSB_DEST_MCSBUS10 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS11 (MCSUSB_DEST_MCSBUS11 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS12 (MCSUSB_DEST_MCSBUS12 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS13 (MCSUSB_DEST_MCSBUS13 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS14 (MCSUSB_DEST_MCSBUS14 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS15 (MCSUSB_DEST_MCSBUS15 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUS5_MCSBUS0 (MCSUSB_DEST_MCSBUS0 | MCSUSB_DEST_BUSNUMBER5)
#define MCSUSB_DEST_BUSNUMBER6 0x600
#define MCSUSB_DEST_BUS6_MCSBUS1 (MCSUSB_DEST_MCSBUS1 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS2 (MCSUSB_DEST_MCSBUS2 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS3 (MCSUSB_DEST_MCSBUS3 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS4 (MCSUSB_DEST_MCSBUS4 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS5 (MCSUSB_DEST_MCSBUS5 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS6 (MCSUSB_DEST_MCSBUS6 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS7 (MCSUSB_DEST_MCSBUS7 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS8 (MCSUSB_DEST_MCSBUS8 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS9 (MCSUSB_DEST_MCSBUS9 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS10 (MCSUSB_DEST_MCSBUS10 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS11 (MCSUSB_DEST_MCSBUS11 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS12 (MCSUSB_DEST_MCSBUS12 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS13 (MCSUSB_DEST_MCSBUS13 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS14 (MCSUSB_DEST_MCSBUS14 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS15 (MCSUSB_DEST_MCSBUS15 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUS6_MCSBUS0 (MCSUSB_DEST_MCSBUS0 | MCSUSB_DEST_BUSNUMBER6)
#define MCSUSB_DEST_BUSNUMBER7 0x700
#define MCSUSB_DEST_BUS7_MCSBUS1 (MCSUSB_DEST_MCSBUS1 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS2 (MCSUSB_DEST_MCSBUS2 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS3 (MCSUSB_DEST_MCSBUS3 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS4 (MCSUSB_DEST_MCSBUS4 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS5 (MCSUSB_DEST_MCSBUS5 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS6 (MCSUSB_DEST_MCSBUS6 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS7 (MCSUSB_DEST_MCSBUS7 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS8 (MCSUSB_DEST_MCSBUS8 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS9 (MCSUSB_DEST_MCSBUS9 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS10 (MCSUSB_DEST_MCSBUS10 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS11 (MCSUSB_DEST_MCSBUS11 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS12 (MCSUSB_DEST_MCSBUS12 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS13 (MCSUSB_DEST_MCSBUS13 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS14 (MCSUSB_DEST_MCSBUS14 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS15 (MCSUSB_DEST_MCSBUS15 | MCSUSB_DEST_BUSNUMBER7)
#define MCSUSB_DEST_BUS7_MCSBUS0 (MCSUSB_DEST_MCSBUS0 | MCSUSB_DEST_BUSNUMBER7)
#define FPGA_DEST_TARGET_MASK 0xf000
#define FX3_DEST_TARGET_MASK 0xff00
#define FLASH_DEST_TARGET1 0x1000
#define FLASH_DEST_TARGET2 0x2000
#define FLASH_DEST_TARGET3 0x3000
// the following are only used for the firmware list in IFB-Multiboot
#define FLASH_DEST_TARGET4 0x4000
#define FLASH_DEST_TARGET5 0x5000
#define FLASH_DEST_TARGET6 0x6000
#define FLASH_DEST_TARGET7 0x7000
#define FLASH_DEST_TARGET8 0x8000
#define FLASH_DEST_TARGET9 0x9000
#define FLASH_DEST_TARGET10 0xA000
#define FLASH_DEST_TARGET11 0xB000
#define FLASH_DEST_TARGET12 0xC000
#define FLASH_DEST_TARGET13 0xD000
#define FLASH_DEST_TARGET14 0xE000
#define FLASH_DEST_TARGET15 0xF000
#define MCSUSB_NAME_DSP "DSP"
#define MCSUSB_NAME_USB "USB"
#define MCSUSB_NAME_MCU1 "MCU1"
#define MCSUSB_NAME_BOOTSTRAP "Bootstrap"
#define MCSUSB_NAME_BOOTSTRAP_OTHER_CYPRESS "Bootstrap Other Usb"
#define MCSUSB_NAME_ALTERA "Altera"
#define MCSUSB_NAME_FPGA2 "FPGA2"
#define MCSUSB_NAME_FPGA3 "FPGA3"
#define MCSUSB_NAME_FPGA4 "FPGA4"
#define MCSUSB_NAME_FPGA5 "FPGA5"
#define MCSUSB_NAME_FPGA6 "FPGA6"
#define MCSUSB_NAME_FPGA7 "FPGA7"
#define MCSUSB_NAME_FPGA8 "FPGA8"
#define MCSUSB_NAME_FPGA9 "FPGA9"
#define MCSUSB_NAME_FPGA10 "FPGA10"
#define MCSUSB_NAME_FPGA11 "FPGA11"
#define MCSUSB_NAME_FPGA12 "FPGA12"
#define MCSUSB_NAME_FPGA13 "FPGA13"
#define MCSUSB_NAME_FPGA14 "FPGA14"
#define MCSUSB_NAME_FPGA15 "FPGA15"
#define MCSUSB_NAME_FPGA16 "FPGA17"
#define MCSUSB_NAME_MCSBUS1 "McsBus1"
#define MCSUSB_NAME_MCSBUS2 "McsBus2"
#define MCSUSB_NAME_MCSBUS3 "McsBus3"
#define MCSUSB_NAME_MCSBUS4 "McsBus4"
#define MCSUSB_NAME_MCSBUS5 "McsBus5"
#define MCSUSB_NAME_MCSBUS6 "McsBus6"
#define MCSUSB_NAME_MCSBUS7 "McsBus7"
#define MCSUSB_NAME_MCSBUS8 "McsBus8"
#define MCSUSB_NAME_MCSBUS9 "McsBus9"
#define MCSUSB_NAME_MCSBUS10 "McsBus10"
#define MCSUSB_NAME_MCSBUS11 "McsBus11"
#define MCSUSB_NAME_MCSBUS12 "McsBus12"
#define MCSUSB_NAME_MCSBUS13 "McsBus13"
#define MCSUSB_NAME_MCSBUS14 "McsBus14"
#define MCSUSB_NAME_MCSBUS15 "McsBus15"
#define MCSUSB_NAME_MCSBUS0 "McsBus0"
#define MCSUSB_NAME_PIC "PIC"
#define MCSUSB_NAME_PIC2 "PIC2"
#define MCSUSB_NAME_PIC3 "PIC3"
#define MCSUSB_NAME_PIC4 "PIC4"
#define MCSUSB_NAME_PIC5 "PIC5"
#define MCSUSB_NAME_PIC6 "PIC6"
#define MCSUSB_NAME_PIC7 "PIC7"
#define MCSUSB_NAME_PIC8 "PIC8"
#define MCSUSB_NAME_SCU_HS "SCU_HS_0x.."
#define MCSUSB_NAME_BUS1_MCSBUS1 "Bus1McsBus1"
#define MCSUSB_NAME_BUS1_MCSBUS2 "Bus1McsBus2"
#define MCSUSB_NAME_BUS1_MCSBUS3 "Bus1McsBus3"
#define MCSUSB_NAME_BUS1_MCSBUS4 "Bus1McsBus4"
#define MCSUSB_NAME_BUS1_MCSBUS5 "Bus1McsBus5"
#define MCSUSB_NAME_BUS1_MCSBUS6 "Bus1McsBus6"
#define MCSUSB_NAME_BUS1_MCSBUS7 "Bus1McsBus7"
#define MCSUSB_NAME_BUS1_MCSBUS8 "Bus1McsBus8"
#define MCSUSB_NAME_BUS1_MCSBUS9 "Bus1McsBus9"
#define MCSUSB_NAME_BUS1_MCSBUS10 "Bus1McsBus10"
#define MCSUSB_NAME_BUS1_MCSBUS11 "Bus1McsBus11"
#define MCSUSB_NAME_BUS1_MCSBUS12 "Bus1McsBus12"
#define MCSUSB_NAME_BUS1_MCSBUS13 "Bus1McsBus13"
#define MCSUSB_NAME_BUS1_MCSBUS14 "Bus1McsBus14"
#define MCSUSB_NAME_BUS1_MCSBUS15 "Bus1McsBus15"
#define MCSUSB_NAME_BUS1_MCSBUS0 "Bus1McsBus0"
#define MCSUSB_NAME_BUS2_MCSBUS1 "Bus2McsBus1"
#define MCSUSB_NAME_BUS2_MCSBUS2 "Bus2McsBus2"
#define MCSUSB_NAME_BUS2_MCSBUS3 "Bus2McsBus3"
#define MCSUSB_NAME_BUS2_MCSBUS4 "Bus2McsBus4"
#define MCSUSB_NAME_BUS2_MCSBUS5 "Bus2McsBus5"
#define MCSUSB_NAME_BUS2_MCSBUS6 "Bus2McsBus6"
#define MCSUSB_NAME_BUS2_MCSBUS7 "Bus2McsBus7"
#define MCSUSB_NAME_BUS2_MCSBUS8 "Bus2McsBus8"
#define MCSUSB_NAME_BUS2_MCSBUS9 "Bus2McsBus9"
#define MCSUSB_NAME_BUS2_MCSBUS10 "Bus2McsBus10"
#define MCSUSB_NAME_BUS2_MCSBUS11 "Bus2McsBus11"
#define MCSUSB_NAME_BUS2_MCSBUS12 "Bus2McsBus12"
#define MCSUSB_NAME_BUS2_MCSBUS13 "Bus2McsBus13"
#define MCSUSB_NAME_BUS2_MCSBUS14 "Bus2McsBus14"
#define MCSUSB_NAME_BUS2_MCSBUS15 "Bus2McsBus15"
#define MCSUSB_NAME_BUS2_MCSBUS0 "Bus2McsBus0"
#define MCSUSB_NAME_BUS3_MCSBUS1 "Bus3McsBus1"
#define MCSUSB_NAME_BUS3_MCSBUS2 "Bus3McsBus2"
#define MCSUSB_NAME_BUS3_MCSBUS3 "Bus3McsBus3"
#define MCSUSB_NAME_BUS3_MCSBUS4 "Bus3McsBus4"
#define MCSUSB_NAME_BUS3_MCSBUS5 "Bus3McsBus5"
#define MCSUSB_NAME_BUS3_MCSBUS6 "Bus3McsBus6"
#define MCSUSB_NAME_BUS3_MCSBUS7 "Bus3McsBus7"
#define MCSUSB_NAME_BUS3_MCSBUS8 "Bus3McsBus8"
#define MCSUSB_NAME_BUS3_MCSBUS9 "Bus3McsBus9"
#define MCSUSB_NAME_BUS3_MCSBUS10 "Bus3McsBus10"
#define MCSUSB_NAME_BUS3_MCSBUS11 "Bus3McsBus11"
#define MCSUSB_NAME_BUS3_MCSBUS12 "Bus3McsBus12"
#define MCSUSB_NAME_BUS3_MCSBUS13 "Bus3McsBus13"
#define MCSUSB_NAME_BUS3_MCSBUS14 "Bus3McsBus14"
#define MCSUSB_NAME_BUS3_MCSBUS15 "Bus3McsBus15"
#define MCSUSB_NAME_BUS3_MCSBUS0 "Bus3McsBus0"
#define MCSUSB_NAME_BUS4_MCSBUS1 "Bus4McsBus1"
#define MCSUSB_NAME_BUS4_MCSBUS2 "Bus4McsBus2"
#define MCSUSB_NAME_BUS4_MCSBUS3 "Bus4McsBus3"
#define MCSUSB_NAME_BUS4_MCSBUS4 "Bus4McsBus4"
#define MCSUSB_NAME_BUS4_MCSBUS5 "Bus4McsBus5"
#define MCSUSB_NAME_BUS4_MCSBUS6 "Bus4McsBus6"
#define MCSUSB_NAME_BUS4_MCSBUS7 "Bus4McsBus7"
#define MCSUSB_NAME_BUS4_MCSBUS8 "Bus4McsBus8"
#define MCSUSB_NAME_BUS4_MCSBUS9 "Bus4McsBus9"
#define MCSUSB_NAME_BUS4_MCSBUS10 "Bus4McsBus10"
#define MCSUSB_NAME_BUS4_MCSBUS11 "Bus4McsBus11"
#define MCSUSB_NAME_BUS4_MCSBUS12 "Bus4McsBus12"
#define MCSUSB_NAME_BUS4_MCSBUS13 "Bus4McsBus13"
#define MCSUSB_NAME_BUS4_MCSBUS14 "Bus4McsBus14"
#define MCSUSB_NAME_BUS4_MCSBUS15 "Bus4McsBus15"
#define MCSUSB_NAME_BUS4_MCSBUS0 "Bus4McsBus0"
#define MCSUSB_NAME_BUS5_MCSBUS1 "Bus5McsBus1"
#define MCSUSB_NAME_BUS5_MCSBUS2 "Bus5McsBus2"
#define MCSUSB_NAME_BUS5_MCSBUS3 "Bus5McsBus3"
#define MCSUSB_NAME_BUS5_MCSBUS4 "Bus5McsBus4"
#define MCSUSB_NAME_BUS5_MCSBUS5 "Bus5McsBus5"
#define MCSUSB_NAME_BUS5_MCSBUS6 "Bus5McsBus6"
#define MCSUSB_NAME_BUS5_MCSBUS7 "Bus5McsBus7"
#define MCSUSB_NAME_BUS5_MCSBUS8 "Bus5McsBus8"
#define MCSUSB_NAME_BUS5_MCSBUS9 "Bus5McsBus9"
#define MCSUSB_NAME_BUS5_MCSBUS10 "Bus5McsBus10"
#define MCSUSB_NAME_BUS5_MCSBUS11 "Bus5McsBus11"
#define MCSUSB_NAME_BUS5_MCSBUS12 "Bus5McsBus12"
#define MCSUSB_NAME_BUS5_MCSBUS13 "Bus5McsBus13"
#define MCSUSB_NAME_BUS5_MCSBUS14 "Bus5McsBus14"
#define MCSUSB_NAME_BUS5_MCSBUS15 "Bus5McsBus15"
#define MCSUSB_NAME_BUS5_MCSBUS0 "Bus5McsBus0"
#define MCSUSB_NAME_BUS6_MCSBUS1 "Bus6McsBus1"
#define MCSUSB_NAME_BUS6_MCSBUS2 "Bus6McsBus2"
#define MCSUSB_NAME_BUS6_MCSBUS3 "Bus6McsBus3"
#define MCSUSB_NAME_BUS6_MCSBUS4 "Bus6McsBus4"
#define MCSUSB_NAME_BUS6_MCSBUS5 "Bus6McsBus5"
#define MCSUSB_NAME_BUS6_MCSBUS6 "Bus6McsBus6"
#define MCSUSB_NAME_BUS6_MCSBUS7 "Bus6McsBus7"
#define MCSUSB_NAME_BUS6_MCSBUS8 "Bus6McsBus8"
#define MCSUSB_NAME_BUS6_MCSBUS9 "Bus6McsBus9"
#define MCSUSB_NAME_BUS6_MCSBUS10 "Bus6McsBus10"
#define MCSUSB_NAME_BUS6_MCSBUS11 "Bus6McsBus11"
#define MCSUSB_NAME_BUS6_MCSBUS12 "Bus6McsBus12"
#define MCSUSB_NAME_BUS6_MCSBUS13 "Bus6McsBus13"
#define MCSUSB_NAME_BUS6_MCSBUS14 "Bus6McsBus14"
#define MCSUSB_NAME_BUS6_MCSBUS15 "Bus6McsBus15"
#define MCSUSB_NAME_BUS6_MCSBUS0 "Bus6McsBus0"
#define MCSUSB_NAME_BUS7_MCSBUS1 "Bus7McsBus1"
#define MCSUSB_NAME_BUS7_MCSBUS2 "Bus7McsBus2"
#define MCSUSB_NAME_BUS7_MCSBUS3 "Bus7McsBus3"
#define MCSUSB_NAME_BUS7_MCSBUS4 "Bus7McsBus4"
#define MCSUSB_NAME_BUS7_MCSBUS5 "Bus7McsBus5"
#define MCSUSB_NAME_BUS7_MCSBUS6 "Bus7McsBus6"
#define MCSUSB_NAME_BUS7_MCSBUS7 "Bus7McsBus7"
#define MCSUSB_NAME_BUS7_MCSBUS8 "Bus7McsBus8"
#define MCSUSB_NAME_BUS7_MCSBUS9 "Bus7McsBus9"
#define MCSUSB_NAME_BUS7_MCSBUS10 "Bus7McsBus10"
#define MCSUSB_NAME_BUS7_MCSBUS11 "Bus7McsBus11"
#define MCSUSB_NAME_BUS7_MCSBUS12 "Bus7McsBus12"
#define MCSUSB_NAME_BUS7_MCSBUS13 "Bus7McsBus13"
#define MCSUSB_NAME_BUS7_MCSBUS14 "Bus7McsBus14"
#define MCSUSB_NAME_BUS7_MCSBUS15 "Bus7McsBus15"
#define MCSUSB_NAME_BUS7_MCSBUS0 "Bus7McsBus0"
/************************************************************
*
* common for all devices
*
************************************************************/
#define MCS_USB_IDENT_LENGTH 100
#define MCS_USB_UL_BLOCKSIZE 256
#define MCS_USB_VERSION_LENGTH 32
#define MCS_USB_SERIAL_LENGTH 10
/*! \cond stg200x */
/***********************************************************************
*
* defines for the STG200x
*
***********************************************************************/
//#define STG200x_BULK_OUT_EP 2
#define STG_MAX_NUM_CHANNELS 8
#define STG_MAX_NUM_SYNC_OUT 8
#define STG_MAX_NUM_TRIGGER 8
#define STG_EXTENDED_MAX_NUM_TRIGGER 32
//! max. number of stimulus channels
#define STG200x_NUM_CHANNELS 8
//! max. number of sync output channels
#define STG200x_NUM_SYNC_OUT 4
//! max. number of triggers
#define STG200x_NUM_TRIGGER 4
#define STG200x_MAX_SEGMENTS 100 // for STG200x
#define STG200x_MAX_SAMPLERATE 50000
#define STG_STREAM_MAGIC_NUMBER_START 0x7612
#define STG_STREAM_MAGIC_NUMBER_END 0xca7d
#define STG_STREAM_MAGIC_NUMBER_FEEDBACK 0x6a31de9a
#define STG_STREAM_BYTES_PER_SAMPLE_HIGHSPEED 32
#define STG_STREAM_BYTES_PER_SAMPLE_FULLSPEED (2*STG200x_NUM_CHANNELS)
#define STG200x_PROGINFO_LENGTH 512 // this is also the longest answer packet used so far
#define STG200x_DATA_BLOCKSIZE 2000
#define ADAPTER_TYPE_UNKOWN 9998
#define ADAPTER_TYPE_ENUM_NOT_APPLICABLE 9999
enum enSTG_ExtendedInterruptPipe {
STG_ExIntPipe_None, // reserved
STG_ExIntPipe_ListIndex,
MW_ExIntPipe_CurrentTemp,
MW_ExIntPipe_PlateState,
MW_ExIntPipe_SwitchState,
STG_ExIntPipe_AdditionalTrigger,
MCS_DeviceStatePush
};
#define MEA21_MAX_LISTMODE_ENTRIES 9
/*! \endcond */
#define FPGA_ID_NOT_CONNECTED 0x00000000
#define FPGA_ID_MEA2100_IF 0x00000001
#define FPGA_ID_MEA2100_HS 0x00000002
#define FPGA_ID_MEA2100_STG 0x00000003
#define FPGA_ID_HS_MULTIWELL 0x00000004
#define FPGA_ID_IF_MULTIWELL 0x00000005
#define FPGA_ID_TBSI_DACQ_IF 0x00000006
#define FPGA_ID_TBSI_DACQ_HS 0x00000007
#define FPGA_ID_CMOS_MEA_IF 0x00000008
#define FPGA_ID_CMOS_MEA_HS 0x00000009
#define FPGA_ID_MEA2100_MW_IFB2 0x0000000A
#define FPGA_ID_ME2100_IFB 0x0000000B
#define FPGA_ID_ME2100_InvivoSCU 0x0000000C
#define FPGA_ID_ME2100_32_XILINX_HS 0x0000000D
#define FPGA_ID_MEA2100_256_IF 0x0000000E
#define FPGA_ID_MEA2100_256_HS 0x0000000F
#define FPGA_ID_W2100_IF 0x00000010
#define FPGA_ID_W2100_REC 0x00000011
#define FPGA_ID_W2100_REC_ANALOG 0x00000012
#define FPGA_ID_MEA2100MINI60_PIC_ICE40_HS 0x00000013
#define FPGA_ID_MEA2100BETASCREEN_HS 0x00000014
#define FPGA_ID_ME2100UPA32_HS 0x00000015
#define FPGA_ID_MULTIWELL_MINI_HS 0x00000016
#define FPGA_ID_MEA2100MINI120_HS 0x00000017
#define FPGA_ID_MEA2100MINI60_ECP5_HS 0x00000018
#define FPGA_ID_ECUBE_HS 0x00000019
#define FPGA_ID_ME2100_InvitroSCU 0x0000001C
#define FPGA_ID_ME2100_32_PIC_ICE40_HS 0x0000001D
#define FPGA_ID_ME2100_GRAPHENE_16_32_HS 0x0000001E
#define FPGA_ID_GRAPHENE_FLAGSHIP_CORE_2_HS 0x0000001F
#define FPGA_ID_WHOLE_CELL_PATCH_HS 0x00000020
#define FPGA_ID_INTERFACEBOARD2 0x00000021
#define FPGA_ID_W2100_IFB2 0x00000022
#define FPGA_ID_CMOS_MEA_IFB2 0x00000023
#define FPGA_ID_LIH30_USB_IF 0x00000041
#define FPGA_ID_LIH30_ADC_CTRL 0x00000042
#define FPGA_ID_USSING_RAIL 0x00000050
#define FPGA_ID_USSING_CHAMBER 0x00000051
#define FPGA_ID_IFB2_GOLDEN 0x000000FD
#define FPGA_ID_IFB30_GOLDEN 0x000000FE
#define FPGA_ID_HAS_NO_HS 0x00001000
//#ifdef __cplusplus
//class AnalogSource
//{
//public:
//#endif
// enum AnalogSourceEnum {
// AnalogSource_HS1,
// AnalogSource_HS2,
// AnalogSource_IF
// };
//#ifdef __cplusplus
//};
//#endif
// define how a trigger is handles while the STG is running
#define STG200x_RETRIGGER_STOP 0
#define STG200x_RETRIGGER_RESTART 1
#define STG200x_RETRIGGER_IGNORE 2
#define STG200x_RETRIGGER_GATEMODE 3
#define STG200x_RETRIGGER_SINGLE 4
// flags for segmentated mode used in the STG400x:
// transfered in req_index, and not used by the STG200x
#define SEGMENTFLAGS_UPDATETRIGGER 1 // assign all channels to the triggernum which corresponds to its segment
#define SEGMENTFLAGS_DOWNLOADONLY 2 // for STG200x_SegmentSelect: switch the segment used for next download while keeping the device with the selected segment running
#define SEGMENTFLAGS_TRIGGERONLY 4 // switch the segment used for next trigger while keeping the segment for download
#define SEGMENTFLAGS_SYNCSTART 8 // switch segment used for trigger and start segment after next sweep
#define STG200x_NUM_DIGOUTMODES 10
#define STG200x_DIGOUTMODE_MONITOR 0
#define STG200x_DIGOUTMODE_MANUAL 1
#define STG200x_DIGOUTMODE_SYNCOUT1 2
#define STG200x_DIGOUTMODE_SYNCOUT2 3
#define STG200x_DIGOUTMODE_SYNCOUT3 4
#define STG200x_DIGOUTMODE_SYNCOUT4 5
#define STG200x_DIGOUTMODE_SYNCOUT5 6
#define STG200x_DIGOUTMODE_SYNCOUT6 7
#define STG200x_DIGOUTMODE_SYNCOUT7 8
#define STG200x_DIGOUTMODE_SYNCOUT8 9
// error handling analog the motusb library, see motstatus.h
#define IS_MCSUSB_STATUS(Status) ( ((Status) & 0xF0000000) == 0xA0000000 )
#define MCSUSB_EP0_MAX_IN_LENGTH STG200x_PROGINFO_LENGTH
/***********************************************************************
*
* defines for the MEA_USB
*
***********************************************************************/
/*! \cond meausb */
#define ME16_USB_CHANNELS 16
#define MEA_USB_CHANNELS 64
//#define MEA_USB_AMPLIFICATION 1000 removed this line, because this is not a global setting for all devices
#define MeaUSB_MAX_SAMPLERATE 50000
/*! \endcond */
/***********************************************************************
*
* defines for the OctoPot
*
***********************************************************************/
/*! \cond octopot */
#define NANOBIO_CHANNELS 8
#define NANOBIO_PATTERNS 50
#define DOTRIA_CHANNELS 32
#define DOTRIA_DACS 4
/*! \endcond */
/***********************************************************************
*
* defines for the TerSens
*
***********************************************************************/
/*! \cond tersens */
#define TER_CHANNELS 12
/*! \endcond */
/* Channel group defines */
#define INTERFACEANALOGCHANNELSGROUP 0x10
#define DSPDATACHANNELSGROUP 0x20
#define WIRELESSHEADSTAGEANALOGGROUPBASE 0x40
#define INTERFACEDIGITALCHANNELSGROUP 0x80
#define AUDIOTESTCHANNELGROUP 0xF8
#define PACKETFRAMECONTEXTGROUP 0xFF
#define ANALOG_GROUP 0x01
#define DIGITAL_GROUP 0x02
#define FRAME_CONTEXT_GROUP 0x03
/***********************************************************************/
#define WVC_VALVE_MODE_MANUAL 0
#define WVC_VALVE_MODE_DIGITAL 1
#define WVC_VALVE_MODE_ANALOG 2
#define WVC_VALVE_MODE_TABLE 3
#define WVC_DISPLAY_MODE_WORK 0
#define WVC_DISPLAY_MODE_PC 1
#define WVC_DISPLAY_MODE_SETTINGS 2
#define WVC_DISPLAY_MODE_TOUCH_TEST 3
/***********************************************************************/
#define USB_ERROR_I2C_NAK 0xfe
// Pic Robo Error Codes
#define ROBOERROR_BASE (0xA0110000L)
//#define PIC_ROBOERROR_UNKNOWNCOMMAND 0x0000 // If a Stall PID is send without setting of UsbLastError, this is used
#define PIC_ROBOERROR_TIMEOUT 0x0001
#define PIC_ROBOERROR_PRESSURE 0x0002
#define PIC_ROBOERROR_RANGE_EXCEEDED 0x0003
#define PIC_ROBOERROR_COMMUNICATIONTIMEOUT 0x0004
#define PIC_ROBOERROR_ANOTHER_MASTER 0x0005
#define PIC_ROBOERROR_FINDREFERENCEMETHOD 0x0006
#define PIC_ROBOERROR_NOSPEEDORACCELERATION 0x0007
#define PIC_ROBOERROR_NOENDSWITCH 0x0008
#define PIC_ROBOERROR_CANNOTESCAPEENDWITCH 0x0009
#define PIC_ROBOERROR_COMMANDALREADYINPROGRESS 0x000A
#define PIC_ROBOERROR_NOREFERENCE 0x000B
#define PIC_ROBOERROR_OVERPRESSURE 0x000C
#define PIC_ROBOERROR_PHASE0OUTOFRANGE 0x000D
#define PIC_ROBOERROR_PERISTALTIC_TIMEOUT 0x000E
#define PIC_ROBOERROR_GILSON_TIMEOUT 0x000F
#define PIC_ROBOERROR_GILSON_WRONG_ID 0x0010
#define PIC_ROBOERROR_GILSON_COMMAND_PENDING 0x0011
#define PIC_ROBOERROR_PARAMETER_NOT_ALLOWED 0x0012
#define PIC_ROBOERROR_STATECHANGENOTPOSSIBLE 0x0013
#define PIC_ROBOERROR_COMMANDNOTPOSSIBLE 0x0014
#define PIC_ROBOERROR_DACQ_NOT_READY 0x0015
#define PIC_ROBOERROR_NO_MORE_DATA 0x0016
// Robo current modes
#define ROBO_CURRENT_OFFMODE 0
#define ROBO_CURRENT_BREAKMODE 1
#define ROBO_CURRENT_STANDBYMODE 2
#define ROBO_CURRENT_REFERENCEMODE 3
#define ROBO_CURRENT_MOVEMENTMODE 4
//
#define WPA8_ERROR_BASE (0xA0220000L)
#define PIC_WPA8_ERR_UNKNOWN_COMMAND 0x0001
#define PIC_WPA8_ERR_HEADSTAGE_SLEEPS 0x0030
#define PIC_WPA8_ERR_HEADSTAGE_TIMEOUT 0x0031
#define PIC_WPA8_ERR_BUSTIMEOUT 0x0032
#define PIC_WPA8_ERR_COMMANDTIMEOUT 0x0033
#define PIC_WPA8_ERR_ALREADYSTARTED 0x0034
#define PIC_WPA8_ERR_ILLEGAL_COMMAND_WHEN_SAMPLING 0x0035
#define PIC_WPA8_ERR_SCANNING_IS_PENDING 0x0036
// 0x0037
#define PIC_WPA8_ERR_ENABLE_CHECKSUM_RESULT 0x0038
// 0x0039 reserved
// 0x003A reserved
// 0x003B reserved
#define PIC_WPA8_ERR_ANSWER_PENDING 0x0099
#endif
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/TI-Header/csl_c64xplus_intc_src/inc/_csl_intc.h | /* ============================================================================
* Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005
*
* Use of this software is controlled by the terms and conditions found in the
* license agreement under which this software has been supplied.
* ===========================================================================
*/
/*
* @file _csl_int.h
*
* @brief File for functional layer of INTC CSL
*
* PATH $(CSLPATH)\inc
*/
/* =============================================================================
* Revision History
* ===============
* 12-Jun-2004 <NAME> File Created
*
* =============================================================================
*/
#ifndef __CSL_INTC_H_
#define __CSL_INTC_H_
#include <csl_intc.h>
void _CSL_intcNmiDummy();
typedef struct CSL_IntcVect {
Uint32 currentVectId;
void (*resv0)();
void (*nmiIsr)();
void (*resv2)();
void (*resv3)();
void (*isr4)();
void (*isr5)();
void (*isr6)();
void (*isr7)();
void (*isr8)();
void (*isr9)();
void (*isr10)();
void (*isr11)();
void (*isr12)();
void (*isr13)();
void (*isr14)();
void (*isr15)();
} CSL_IntcVect;
extern CSL_IntcVect _CSL_intcCpuIntrTable;
/* These declarations are meant for computing the ISR jump location. */
void _CSL_intcIvpSet();
interrupt void _CSL_intcDispatcher (void);
interrupt void _CSL_intcEvent0Dispatcher (void);
interrupt void _CSL_intcEvent1Dispatcher (void);
interrupt void _CSL_intcEvent2Dispatcher (void);
interrupt void _CSL_intcEvent3Dispatcher (void);
#endif /* __CSL_INTC_H_ */
|
adildahlan/BE-thesis-Repo-McsDspRealtimeFeedback | DSP/TI-Header/csl_c6455_src/src/edma/csl_edma3GetHwSetup.c | /* ============================================================================
* Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005
*
* Use of this software is controlled by the terms and conditions found in the
* license agreement under which this software has been supplied.
* ===========================================================================
*/
/** ============================================================================
* @file csl_edma3GetHwSetup.c
*
* @path $(CSLPATH)\src\edma
*
* @desc EDMA3 CSL Implementation on DSP side
*
*/
/* =============================================================================
* Revision History
* ===============
* 29-May-2004 <NAME> File Created.
*
* =============================================================================
*/
#include <csl_edma3.h>
#include <csl_edma3Aux.h>
/** ============================================================================
* @n@b CSL_edma3GetHwSetup
*
* @b Description
* @n It gets setup of the all dma/qdma channels
*
* @b Arguments
* @verbatim
hMod Edma Handle
setup pointer to the setup structure
@endverbatim
*
* <b> Return Value </b> CSL_Status
* @li CSL_SOK - Get Module Setup
* @li CSL_ESYS_BADHANDLE - The handle is passed is
* invalid
* @li CSL_ESYS_INVPARAMS - Invalid Parameter entry
*
* <b> Pre Condition </b>
* @n Functions CSL_edma3Init(), CSL_edma3Open() must be called successfully
* in that order before CSL_edma3GetHwSetup() can be called.
*
* <b> Post Condition </b>
* @n The hardware setup structure is populated with the hardware setup
* parameters
*
* @b Modifies
* @n None
*
* @b Example
* @verbatim
CSL_Edma3Handle hModule;
CSL_Edma3HwSetup hwSetup,gethwSetup;
CSL_Edma3Obj edmaObj;
CSL_Edma3ChannelObj ChObj;
CSL_Edma3ChannelAttr chAttr;
CSL_Edma3HwDmaChannelSetup dmahwSetup[CSL_EDMA3_NUM_DMACH] =
CSL_EDMA3_DMACHANNELSETUP_DEFAULT;
CSL_Edma3HwDmaChannelSetup getdmahwSetup[CSL_EDMA3_NUM_DMACH];
CSL_Status status;
Uint32 i, passStatus = 1;
// Module Initialization
CSL_edma3Init(NULL);
// Module Level Open
hModule = CSL_edma3Open(&edmaObj,CSL_EDMA3,NULL,&status);
// Module Setup
hwSetup.dmaChaSetup = &dmahwSetup[0];
hwSetup.qdmaChaSetup = NULL;
CSL_edma3HwSetup(hModule,&hwSetup);
// Get Module Setup
gethwSetup.dmaChaSetup = &getdmahwSetup[0];
gethwSetup.qdmaChaSetup = NULL;
CSL_edma3GetHwSetup(hModule,&gethwSetup);
@endverbatim
* =============================================================================
*/
#pragma CODE_SECTION (CSL_edma3GetHwSetup, ".text:csl_section:edma3");
CSL_Status CSL_edma3GetHwSetup (
CSL_Edma3Handle hMod,
CSL_Edma3HwSetup *setup
)
{
Uint32 numCha;
Uint32 tempQnum = 0;
Uint32 tempChmap = 0;
Uint32 ii;
CSL_Status status = CSL_SOK;
if (hMod == NULL) {
status = CSL_ESYS_BADHANDLE;
}
else if (setup == NULL) {
status = CSL_ESYS_INVPARAMS;
}
else {
if (setup->dmaChaSetup != NULL) {
for (numCha = 0 ; numCha < CSL_EDMA3_NUM_DMACH; numCha++) {
#ifdef CSL_EDMA3_CHMAPEXIST
setup->dmaChaSetup[numCha].paramNum = \
CSL_FEXT(hMod->regs->DCHMAP[numCha], EDMA3CC_DCHMAP_PAENTRY);
#endif
if (((ii) % 8) == 0)
tempQnum = hMod->regs->DMAQNUM[numCha/8];
ii = numCha % 8;
setup->dmaChaSetup[numCha].que = \
(CSL_Edma3Que) CSL_FEXTR(tempQnum, (ii * 4) + 2, (ii * 4));
}
}
if (setup->qdmaChaSetup != NULL) {
tempQnum = hMod->regs->QDMAQNUM;
for (numCha = 0 ; numCha < CSL_EDMA3_NUM_QDMACH; numCha++) {
tempChmap = hMod->regs->QCHMAP[numCha];
setup->qdmaChaSetup[numCha].paramNum = \
CSL_FEXT(tempChmap,EDMA3CC_QCHMAP_PAENTRY);
setup->qdmaChaSetup[numCha].triggerWord = \
CSL_FEXT(tempChmap,EDMA3CC_QCHMAP_TRWORD);
setup->qdmaChaSetup[numCha].que = \
(CSL_Edma3Que)CSL_FEXTR(tempQnum, (numCha * 4) + 2, numCha* 4);
}
}
}
return (status);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.