text stringlengths 1 2.12k | source dict |
|---|---|
c++, ai, sfml, connect-four
return;
} else if (selectedNodeTerminalStatus == 2) {
nodes[selectedNodeIndex].wins += 1.0;
nodes[selectedNodeIndex].simulations += 1.0;
return;
} else if (selectedNodeTerminalStatus == 3) {
nodes[selectedNodeIndex].simulations += 1.0;
return;
}
std::vector<int> selectedNodeChildNodesIndices = selectedNode.childNodesIndices;
for (auto selectedNodeChildNodeIndex : selectedNodeChildNodesIndices) {
node childNode = nodes[selectedNodeChildNodeIndex];
uint64_t currentNodeRedBoard = childNode.redBoard;
uint64_t currentNodeYellowBoard = childNode.yellowBoard;
uint64_t currentNodeBothBoards = childNode.bothBoards;
int currentNodeSideToPlay = childNode.sideToPlay;
while (true) {
if (currentNodeBothBoards == 4398046511103ULL) {
nodes[selectedNodeChildNodeIndex].wins += 0.5;
nodes[selectedNodeChildNodeIndex].simulations += 1.0;
break;
} else if (currentNodeSideToPlay == 0) {
if (isWinning(currentNodeYellowBoard)) {
nodes[selectedNodeChildNodeIndex].simulations += 1.0;
break;
}
} else {
if (isWinning(currentNodeRedBoard)) {
nodes[selectedNodeChildNodeIndex].wins += 1.0;
nodes[selectedNodeChildNodeIndex].simulations += 1.0;
break;
}
}
std::vector<int> currentNodeMoves = moves(currentNodeBothBoards);
int currentNodeMove = currentNodeMoves[rand() % currentNodeMoves.size()];
uint64_t currentNodeMoveBit = bits[moveTargetSquare(currentNodeMove, currentNodeBothBoards)];
if (currentNodeSideToPlay == 0) {
currentNodeRedBoard |= currentNodeMoveBit;
} else {
currentNodeYellowBoard |= currentNodeMoveBit;
}
currentNodeBothBoards |= currentNodeMoveBit;
currentNodeSideToPlay ^= 1;
}
}
}
void ComputerPlayer::propogate() {
node selectedNode = nodes[selectedNodeIndex];
int selectedNodeTerminalStatus = selectedNode.terminalStatus; | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
int selectedNodeTerminalStatus = selectedNode.terminalStatus;
double terminalWinToAdd;
bool isTerminalNode = false;
if (selectedNodeTerminalStatus == 1) {
terminalWinToAdd = 0.5;
isTerminalNode = true;
} else if (selectedNodeTerminalStatus == 2) {
terminalWinToAdd = 1.0;
isTerminalNode = true;
} else if (selectedNodeTerminalStatus == 3) {
terminalWinToAdd = 0.0;
isTerminalNode = true;
}
if (isTerminalNode) {
int currentNodeIndex = selectedNodeIndex;
while (true) {
int currentNodeParentNodeIndex = nodes[currentNodeIndex].parentNodeIndex;
if (currentNodeParentNodeIndex == -1) {
break;
}
nodes[currentNodeParentNodeIndex].wins += terminalWinToAdd;
nodes[currentNodeParentNodeIndex].simulations += 1.0;
currentNodeIndex = currentNodeParentNodeIndex;
}
return;
}
std::vector<int> selectedNodeChildNodesIndices = selectedNode.childNodesIndices;
for (auto selectedNodeChildNodeIndex : selectedNodeChildNodesIndices) {
double winToAdd = nodes[selectedNodeChildNodeIndex].wins;
int currentNodeIndex = selectedNodeChildNodeIndex;
while (true) {
int currentNodeParentNodeIndex = nodes[currentNodeIndex].parentNodeIndex;
if (currentNodeParentNodeIndex == -1) {
break;
}
nodes[currentNodeParentNodeIndex].wins += winToAdd;
nodes[currentNodeParentNodeIndex].simulations += 1.0;
currentNodeIndex = currentNodeParentNodeIndex;
}
}
}
void ComputerPlayer::select() {
int currentNodeIndex = 0;
while (true) {
node currentNode = nodes[currentNodeIndex];
std::vector<int> currentNodeChildNodesIndices = currentNode.childNodesIndices;
if (currentNodeChildNodesIndices.size() == 0) {
selectedNodeIndex = currentNodeIndex;
break;
}
double currentNodeSimulations = currentNode.simulations;
int currentNodeSideToPlay = currentNode.sideToPlay;
int bestChildNodeIndex;
double bestUcb = 0.0; | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
int bestChildNodeIndex;
double bestUcb = 0.0;
for (auto currentNodeChildNodeIndex : currentNodeChildNodesIndices) {
node childNode = nodes[currentNodeChildNodeIndex];
double childNodeWins = childNode.wins;
double childNodeSimulations = childNode.simulations;
double exploitation = childNodeWins / childNodeSimulations;
// Account for perspective when selecting nodes.
if (currentNodeSideToPlay == 1) {
exploitation = 1.0 - exploitation;
}
double ucb = exploitation + sqrt(2.0 * log(currentNodeSimulations) / childNodeSimulations);
if (ucb > bestUcb) {
bestChildNodeIndex = currentNodeChildNodeIndex;
bestUcb = ucb;
}
}
currentNodeIndex = bestChildNodeIndex;
}
} | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
computerPlayer.h
#pragma once
#include "node.h"
class ComputerPlayer {
private:
std::vector<node> nodes;
int selectedNodeIndex;
void expand();
void simulate();
void propogate();
void select();
public:
int bestMove(uint64_t redBoard, uint64_t yellowBoard, uint64_t bothBoards, int sideToPlay);
};
game.cpp (handles logic for generating moves, validating moves, executing moves)
#include "common.h"
#include <cstdint>
#include <vector>
int popcount(uint64_t n) {
int count = 0;
while (n) {
if ((n & 1ULL) == 1ULL) {
count++;
}
n >>= 1ULL;
}
return count;
}
std::vector<int> moves(uint64_t bothBoards) {
uint64_t topRow = (bothBoards & 4363686772736ULL) >> 35ULL;
std::vector<int> moves;
for (int i = 0; i < 7; i++) {
if ((topRow & 1ULL) == 0ULL) {
moves.push_back(6 - i);
}
topRow >>= 1ULL;
}
return moves;
}
int moveTargetSquare(int move, uint64_t bothBoards) {
return 7 * (5 - popcount(bothBoards & columns[move])) + move;
}
bool isWinning(uint64_t ourBoard) {
for (int i = 0; i < 69; i++) {
uint64_t combination = combinations[i];
if ((ourBoard & combination) == combination) {
return true;
}
}
return false;
}
bool verifyMove(int move, uint64_t bothBoards) {
if (popcount(bothBoards & columns[move]) == 6) {
return false;
}
return true;
}
game.h
#pragma once
std::vector<int> moves(uint64_t bothBoards);
int moveTargetSquare(int move, uint64_t bothBoards);
bool isWinning(uint64_t ourBoard);
bool verifyMove(int move, uint64_t bothBoards); | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
main.cpp (the main game loop, graphics, and initialisation for global variables)
#include <math.h>
#include <unistd.h>
#include <SFML/Graphics.hpp>
#include "common.h"
#include "game.h"
#include "computerPlayer.h"
uint64_t bits[42];
uint64_t columns[7];
uint64_t combinations[69];
uint64_t redBoard = 0ULL;
uint64_t yellowBoard = 0ULL;
uint64_t bothBoards = 0ULL;
int humanPlayer;
int aiPlayer;
int gameState = 0;
sf::Color gray = sf::Color(128, 128, 128, 255);
sf::Color cyan = sf::Color(0, 255, 255, 255);
sf::RenderWindow window(sf::VideoMode(639, 553), "Connect Four", sf::Style::Close | sf::Style::Titlebar);
sf::Texture boardTexture;
sf::Sprite boardSprite;
sf::Font comicSans;
sf::Text rematch("Rematch?", comicSans);
void initializeGlobals() {
uint64_t bit = 2199023255552ULL;
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 7; x++) {
int index = 7 * y + x;
bits[index] = bit;
bit >>= 1ULL;
}
}
uint64_t column = 2216338399296ULL;
for (int x = 0; x < 7; x++) {
columns[x] = column;
column >>= 1ULL;
}
int combinationIndex = 0;
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 7; x++) {
int index = 7 * y + x;
if (x <= 3) {
uint64_t combination = 0ULL;
combination |= bits[index];
combination |= bits[index + 1];
combination |= bits[index + 2];
combination |= bits[index + 3];
combinations[combinationIndex] = combination;
combinationIndex++;
}
if (y <= 2) {
uint64_t combination = 0ULL;
combination |= bits[index];
combination |= bits[index + 7];
combination |= bits[index + 14];
combination |= bits[index + 21];
combinations[combinationIndex] = combination;
combinationIndex++;
}
if (x <= 3 && y <= 2) {
uint64_t combination = 0ULL;
combination |= bits[index];
combination |= bits[index + 8];
combination |= bits[index + 16]; | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
combination |= bits[index + 8];
combination |= bits[index + 16];
combination |= bits[index + 24];
combinations[combinationIndex] = combination;
combinationIndex++;
}
if (x <= 3 && y >= 3) {
uint64_t combination = 0ULL;
combination |= bits[index];
combination |= bits[index - 6];
combination |= bits[index - 12];
combination |= bits[index - 18];
combinations[combinationIndex] = combination;
combinationIndex++;
}
}
}
}
void renderBoard() {
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 7; x++) {
int index = 7 * y + x;
uint64_t bit = bits[index];
float xPosition = 29 + x * 87;
float yPosition = 29 + y * 87;
if ((redBoard & bit) == bit) {
sf::CircleShape redCell;
redCell.setRadius(29);
redCell.setFillColor(sf::Color::Red);
redCell.setPosition(xPosition, yPosition);
window.draw(redCell);
} else if ((yellowBoard & bit) == bit) {
sf::CircleShape yellowCell;
yellowCell.setRadius(29);
yellowCell.setFillColor(sf::Color::Yellow);
yellowCell.setPosition(xPosition, yPosition);
window.draw(yellowCell);
}
}
}
}
bool makeMoveAndReturnIfTerminal(int move, int side) {
int pieceCenterX = 29 + move * 87;
int pieceCenterY = -29;
int targetSquare = moveTargetSquare(move, bothBoards);
int targetRow = (targetSquare - move) / 7;
int pieceTargetY = 29 + targetRow * 87;
sf::CircleShape gameCell;
gameCell.setRadius(29);
if (side == 0) {
gameCell.setFillColor(sf::Color::Red);
} else {
gameCell.setFillColor(sf::Color::Yellow);
}
while (pieceCenterY < pieceTargetY) {
gameCell.setPosition(pieceCenterX, pieceCenterY);
window.clear(gray);
window.draw(gameCell);
renderBoard();
window.draw(boardSprite);
window.display();
pieceCenterY++;
usleep(1000000 / 553);
} | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
window.display();
pieceCenterY++;
usleep(1000000 / 553);
}
uint64_t bit = bits[targetSquare];
if (side == 0) {
redBoard |= bit;
} else {
yellowBoard |= bit;
}
bothBoards |= bit;
bool isTerminal = false;
int terminalState;
if (bothBoards == 4398046511103ULL) {
terminalState = 0;
isTerminal = true;
} else if (side == 0) {
if (isWinning(redBoard)) {
if (humanPlayer == 0) {
terminalState = 1;
} else {
terminalState = 2;
}
isTerminal = true;
}
} else if (side == 1) {
if (isWinning(yellowBoard)) {
if (humanPlayer == 1) {
terminalState = 1;
} else {
terminalState = 2;
}
isTerminal = true;
}
}
window.clear(gray);
renderBoard();
window.draw(boardSprite);
if (isTerminal) {
sf::Text verdict;
if (terminalState == 0) {
verdict.setString("Draw!");
} else if (terminalState == 1) {
verdict.setString("You win!");
} else if (terminalState == 2) {
verdict.setString("Computer wins!");
}
verdict.setFont(comicSans);
verdict.setCharacterSize(40);
verdict.setFillColor(cyan);
verdict.setOutlineColor(sf::Color::Black);
verdict.setOutlineThickness(2.0);
sf::FloatRect verdictRectangle = verdict.getLocalBounds();
verdict.setOrigin(verdictRectangle.width / 2.0f,
verdictRectangle.height / 2.0f);
verdict.setPosition(sf::Vector2f(319.5f, 232.0f));
window.draw(verdict);
window.draw(rematch);
}
window.display();
return isTerminal;
}
int main() {
initializeGlobals();
boardTexture.loadFromFile("connectFourBoard.png");
boardSprite.setTexture(boardTexture);
comicSans.loadFromFile("COMIC.TTF"); | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
sf::Text heading("C++ Connect-4", comicSans);
heading.setCharacterSize(40);
heading.setFillColor(cyan);
heading.setOutlineColor(sf::Color::Black);
heading.setOutlineThickness(2.0);
sf::FloatRect headingRectangle = heading.getLocalBounds();
heading.setOrigin(headingRectangle.width / 2.0f,
headingRectangle.height / 2.0f);
heading.setPosition(sf::Vector2f(319.5f, 232.0f));
sf::Text prompt("Choose a Color!", comicSans);
prompt.setCharacterSize(26);
prompt.setFillColor(cyan);
prompt.setOutlineColor(sf::Color::Black);
prompt.setOutlineThickness(2.0);
sf::FloatRect promptRectangle = prompt.getLocalBounds();
prompt.setOrigin(promptRectangle.width / 2.0f,
promptRectangle.height / 2.0f);
prompt.setPosition(sf::Vector2f(319.5f, 283.0f));
sf::Text red("Red", comicSans);
red.setCharacterSize(26);
red.setFillColor(sf::Color::Red);
red.setOutlineColor(sf::Color::Black);
red.setOutlineThickness(2.0);
sf::FloatRect redRectangle = red.getLocalBounds();
red.setOrigin(redRectangle.width / 2.0f,
redRectangle.height / 2.0f);
red.setPosition(sf::Vector2f(319.5f - redRectangle.width / 2.0f - 5.5f, 320.0f));
float redLeft = 319.5f - redRectangle.width - 5.5f;
float redRight = redLeft + redRectangle.width;
float redTop = 320.0f - redRectangle.height / 2.0f;
float redBottom = redTop + redRectangle.height;
sf::Text yellow("Yellow", comicSans);
yellow.setCharacterSize(26);
yellow.setFillColor(sf::Color::Yellow);
yellow.setOutlineColor(sf::Color::Black);
yellow.setOutlineThickness(2.0);
sf::FloatRect yellowRectangle = yellow.getLocalBounds();
yellow.setOrigin(yellowRectangle.width / 2.0f,
yellowRectangle.height / 2.0f);
yellow.setPosition(sf::Vector2f(319.5f + yellowRectangle.width / 2.0f + 5.5f, 320.0f)); | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
float yellowLeft = 325.0f;
float yellowRight = yellowLeft + yellowRectangle.width;
float yellowTop = 320.0f - yellowRectangle.height / 2.0f;
float yellowBottom = yellowTop + yellowRectangle.height;
rematch.setCharacterSize(26);
rematch.setFillColor(cyan);
rematch.setOutlineColor(sf::Color::Black);
rematch.setOutlineThickness(2.0);
sf::FloatRect rematchRectangle = rematch.getLocalBounds();
rematch.setOrigin(rematchRectangle.width / 2.0f,
rematchRectangle.height / 2.0f);
rematch.setPosition(sf::Vector2f(319.5f, 283.0f));
float rematchLeft = 319.5f - rematchRectangle.width / 2.0f;
float rematchRight = rematchLeft + rematchRectangle.width;
float rematchTop = 283.0f - rematchRectangle.height / 2.0f;
float rematchBottom = rematchTop + rematchRectangle.height;
ComputerPlayer computerPlayer;
window.clear(gray);
window.draw(boardSprite);
window.draw(heading);
window.draw(prompt);
window.draw(red);
window.draw(yellow);
window.display(); | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
while (window.isOpen()) {
sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
int move = (int)floor(7.0 * (double)mousePosition.x / 639.0);
sf::Event sfmlEvent;
while (window.pollEvent(sfmlEvent)) {
if (sfmlEvent.type == sf::Event::Closed) {
window.close();
} else if (sfmlEvent.type == sf::Event::MouseButtonReleased) {
if (gameState == 0) {
if (
mousePosition.x > (int)redLeft &&
mousePosition.x < (int)redRight &&
mousePosition.y > (int)redTop &&
mousePosition.y < (int)redBottom
) {
gameState = 1;
humanPlayer = 0;
aiPlayer = 1;
window.clear(gray);
window.draw(boardSprite);
window.display();
} else if (
mousePosition.x > (int)yellowLeft &&
mousePosition.x < (int)yellowRight &&
mousePosition.y > (int)yellowTop &&
mousePosition.y < (int)yellowBottom
) {
gameState = 1;
humanPlayer = 1;
aiPlayer = 0;
window.clear(gray);
window.draw(boardSprite);
window.display();
int computerMove = computerPlayer.bestMove(redBoard, yellowBoard, bothBoards, aiPlayer);
bool isComputerMoveTerminal = makeMoveAndReturnIfTerminal(computerMove, aiPlayer);
if (isComputerMoveTerminal) {
gameState = 2;
}
}
} else if (gameState == 1) {
if (verifyMove(move, bothBoards)) {
bool isHumanMoveTerminal = makeMoveAndReturnIfTerminal(move, humanPlayer);
if (isHumanMoveTerminal) {
gameState = 2;
} else {
int computerMove = computerPlayer.bestMove(redBoard, yellowBoard, bothBoards, aiPlayer);
bool isComputerMoveTerminal = makeMoveAndReturnIfTerminal(computerMove, aiPlayer); | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
bool isComputerMoveTerminal = makeMoveAndReturnIfTerminal(computerMove, aiPlayer);
if (isComputerMoveTerminal) {
gameState = 2;
}
}
}
} else if (gameState == 2) {
if (
mousePosition.x > (int)rematchLeft &&
mousePosition.x < (int)rematchRight &&
mousePosition.y > (int)rematchTop &&
mousePosition.y < (int)rematchBottom
) {
redBoard = 0ULL;
yellowBoard = 0ULL;
bothBoards = 0ULL;
window.clear(gray);
window.draw(boardSprite);
window.draw(heading);
window.draw(prompt);
window.draw(red);
window.draw(yellow);
window.display();
gameState = 0;
}
}
}
}
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
node.h (the node data structure for the Monte Carlo Tree Search algorithm)
#pragma once
#include <cstdint>
#include <vector>
struct node {
uint64_t redBoard;
uint64_t yellowBoard;
uint64_t bothBoards;
double wins;
double simulations;
int sideToPlay;
// 0 if normal, 1 if draw, 2 if red won, 3 if yellow won.
int terminalStatus;
std::vector<int> childNodesIndices;
int parentNodeIndex;
};
I feel that especially my game loop is unclear, as thanks to my javascript experience I am used to having used event listeners. But in c++, it seems I have put all of the logic into one loop. So I would like some advice on how gameloops are managed in C++.
Also the computerPlayer seems to run quite slow (similar to the javascript version of this game I wrote a year ago). So I would like some optimisation tips in C++, as I am unfamiliar with them as of yet.
Answer: First we have to get this out of the way:
I decided to try learning a low level language for once, so I did C++. | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
I decided to try learning a low level language for once, so I did C++.
C++ is definitely a high-level language. If you want a low-level language, you should write your code in assembly. The main difference between the languages you mentioned is that C++ is a compiled language, whereas Python and JavaScript are interpreted languages.
Add more structure to your code
The overall impression I get from your code is that functions are too long and that you have way too many global variables. You have made a class ComputerPlayer and an associated struct node for its tree search algorithm, but the rest of the code is mainly in free functions. I strongly recommend you add more structure by grouping relevant data into classes, and try to split more functionality into their own (member) functions.
At the very least, I would expect a class Board that represents a Connect 4 board, with member functions that allow you to query and change the state of the board. A class Game for the game itself, that not only contains the board but also keeps track of who is playing, and allows you to query who is winning, and so on. A class UI could be added that has everything related to the user interface.
Names like Board, Game, node and UI are very generic, so I would put everything except the main() function inside a namespace Connect4.
Avoid magic numbers
I see a lot of magic numbers in your code, like 4363686772736ULL. It's hard for someone reading your code to understand what that number means. Create constants for these numbers, so they have a name that explains what they mean. Also, since these are bit masks, it helps to write them in hexadecimal instead:
static constexpr uint64_t topRowMask = 0x3f800000000;
static constexpr uint64_t topRowOffset = 35;
...
uint64_t topRow = (bothBoards & topRowMask) >> topRowOffset; | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
Similarly, what does gameState == 1 mean? In this case, create an enum class to give all the states a name. Instead of a sequence of if-else statements, use switch (gameState). In combination with an enum, the compiler will then be able to warn you if you forgot to handle one of the possible states.
Consider using std::bitset
If you want to manipulate sets of bits, the standard library comes with std::bitset. It has several nice features, such as being able to exactly specify how many bits there are in a set, and allowing you to construct a bit set from a string of zeroes and ones, so for example you can write:
static const std::bitset<42> topRowMask("1111111"
"0000000"
"0000000"
"0000000"
"0000000"
"0000000");
Don't bother with bits[] and rows[]
You are pre-computing these arrays, but in fact the combination of a multiplication, add and shift operation is so cheap on today's hardware that it is probably not worth making them. Instead, I would create functions:
static constexpr uint64_t bit(int x, int y) {
static constexpr uint64_t firstBit = 0x20000000000;
return firstBit >> (7 * y + x);
}
static constexpr uint64_t column(int x) {
static constexpr uint64_t firstColumn = 0x20408102040;
return firstColumn >> x;
}
Similarly, is it really necessary to have a separate bothBoards? If it's always just meant to be the combination of redBoard and yellowBoard, then just writing this when you need it:
uint64_t bothBoards = redBoard | yellowBoard; | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
Is faster than passing it around as a parameter.
Avoid using obsolete and platform-specific functions
You call usleep() in your code, but that is an obsolete POSIX function, and doesn't work on non-POSIX operating systems, like Windows. Either use the proper standard C++ function, like std::this_thread::sleep_for(), or use SFML's platform-independent functions, like sf::sleep(). | {
"domain": "codereview.stackexchange",
"id": 43537,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, ai, sfml, connect-four",
"url": null
} |
c++, algorithm, image, pathfinding, dijkstra
Title: Finding the cheapest path between two points using Dijkstra
Question: I am trying to use Dijkstra to find the cheapest path between two pixels in an image.
Implementation:
#include <vector>
#include <queue>
#include <map>
#include <cmath>
#include <numbers>
#include <array>
#include <algorithm>
using vec2i_t [[gnu::vector_size(16)]] = int64_t;
using vec2f_t [[gnu::vector_size(16)]] = double;
template<class T, auto tag>
struct tagged_value
{
public:
tagged_value() = default;
explicit tagged_value(T value):m_value{value}{}
T value() const { return m_value; }
private:
T m_value;
};
template<class T>
using from = tagged_value<T, 0>;
template<class T>
using to = tagged_value<T, 1>;
template<class T, auto tag>
inline tagged_value<T, tag> operator+(tagged_value<T, tag> a, T b)
{
return tagged_value<T, tag>{a.value() + b};
}
template< auto tag>
inline tagged_value<int64_t, tag> operator*(int64_t b, tagged_value<vec2i_t, tag> a)
{
return tagged_value<int64_t, tag>{b*a.value()};
}
struct pending_route_node
{
to<vec2i_t> loc;
double total_cost;
};
bool is_cheaper(pending_route_node const& a, pending_route_node const& b)
{
return a.total_cost < b.total_cost;
}
struct route_node
{
from<vec2i_t> loc;
double total_cost = std::numeric_limits<double>::infinity();
};
constexpr auto scale_factor = 1;
template<auto tag>
constexpr auto scale_by_factor(tagged_value<vec2i_t, tag> val)
{
auto const x = val.value();
return tagged_value<vec2f_t, tag>
{vec2f_t{static_cast<double>(x[0]), static_cast<double>(x[1])}/ static_cast<double>(scale_factor)};
} | {
"domain": "codereview.stackexchange",
"id": 43538,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, image, pathfinding, dijkstra",
"url": null
} |
c++, algorithm, image, pathfinding, dijkstra
constexpr auto gen_neigbour_offset_table()
{
std::array<vec2i_t, 8> ret{};
constexpr auto r = static_cast<double>(scale_factor);
for(size_t k = 0; k != std::size(ret); ++k)
{
auto const theta = k*2.0*std::numbers::pi/std::size(ret);
ret[k] = vec2i_t{static_cast<int64_t>(std::round(r*std::cos(theta))),
static_cast<int64_t>(std::round(r*std::sin(theta)))};
}
return ret;
}
constexpr auto neigbour_offsets = gen_neigbour_offset_table();
template<class CostFunction>
auto search(from<vec2i_t> origin, CostFunction&& f)
{
auto cmp = [](pending_route_node const& a, pending_route_node const& b)
{ return is_cheaper(b, a); };
std::priority_queue<pending_route_node, std::vector<pending_route_node>, decltype(cmp)> nodes_to_visit;
nodes_to_visit.push(pending_route_node{to<vec2i_t>{scale_factor*origin.value()}, 0.0});
auto loc_cmp=[](to<vec2i_t> p1, to<vec2i_t> p2) {
auto const a = p1.value();
auto const b = p2.value();
return (a[0] == b[0]) ? a[1] < b[1] : a[0] < b[0];
};
std::map<to<vec2i_t>, std::pair<route_node, bool>, decltype(loc_cmp)> cost_table;
while(!nodes_to_visit.empty())
{
auto current = nodes_to_visit.top();
nodes_to_visit.pop();
auto& cost_item = cost_table[current.loc];
cost_item.second = true;
for(auto item : neigbour_offsets)
{
auto const next_loc = current.loc + item;
auto const cost_increment = f(scale_by_factor(from{current.loc.value()}), scale_by_factor(next_loc));
static_assert(std::is_same_v<std::decay_t<decltype(cost_increment)>, double>);
if(cost_increment == std::numeric_limits<double>::infinity())
{ break; } | {
"domain": "codereview.stackexchange",
"id": 43538,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, image, pathfinding, dijkstra",
"url": null
} |
c++, algorithm, image, pathfinding, dijkstra
auto& new_cost_item = cost_table[next_loc];
if(new_cost_item.second)
{ break; }
auto const new_cost = current.total_cost + cost_increment;
if(new_cost < new_cost_item.first.total_cost)
{
new_cost_item.first.total_cost = new_cost;
new_cost_item.first.loc = from<vec2i_t>{current.loc.value()};
nodes_to_visit.push(pending_route_node{next_loc, new_cost});
}
}
}
return cost_table;
}
Example usage:
auto result = search(cheapest_route::from{cheapest_route::vec2i_t{0, 0}},
[](cheapest_route::from<cheapest_route::vec2f_t> a, cheapest_route::to<cheapest_route::vec2f_t> b) {
auto const v1 = a.value();
auto const v2 = b.value();
constexpr auto size = 4.0;
if((v2[0] < -size || v2[0] > size) || (v2[1] < -size || v2[1] > size))
{ return std::numeric_limits<double>::infinity(); }
// Use Euclidian distance as a simple test case
auto delta = v1 - v2;
auto d2 = delta*delta;
return d2[0] + d2[1];
});
std::ranges::for_each(result, [](auto const& item) {
auto [to, node_info] = item;
printf("to = (%ld, %ld), from = (%ld, %ld). total_cost = %.8g\n",
to.value()[0], to.value()[1],
node_info.first.loc.value()[0], node_info.first.loc.value()[1],
node_info.first.total_cost);
}); | {
"domain": "codereview.stackexchange",
"id": 43538,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, image, pathfinding, dijkstra",
"url": null
} |
c++, algorithm, image, pathfinding, dijkstra
Output:
... to = (-1, -1), from = (0, 0). total_cost = 2
... to = (-1, 0), from = (0, 0). total_cost = 1
... to = (-1, 1), from = (0, 0). total_cost = 2
... to = (-1, 2), from = (0, 1). total_cost = 3
... to = (-1, 3), from = (0, 2). total_cost = 4
... to = (-1, 4), from = (0, 3). total_cost = 5
... to = (0, -1), from = (0, 0). total_cost = 1
... to = (0, 0), from = (0, 0). total_cost = inf
... to = (0, 1), from = (0, 0). total_cost = 1
... to = (0, 2), from = (0, 1). total_cost = 2
... to = (0, 3), from = (0, 2). total_cost = 3
... to = (0, 4), from = (0, 3). total_cost = 4
... to = (1, -1), from = (0, 0). total_cost = 2
... to = (1, 0), from = (0, 0). total_cost = 1
... to = (1, 1), from = (0, 0). total_cost = 2
... to = (1, 2), from = (0, 1). total_cost = 3
... to = (1, 3), from = (0, 2). total_cost = 4
... to = (1, 4), from = (0, 3). total_cost = 5
... to = (2, -1), from = (1, -1). total_cost = 3
... to = (2, 0), from = (1, 0). total_cost = 2
... to = (2, 1), from = (1, 0). total_cost = 3
... to = (2, 2), from = (1, 1). total_cost = 4
... to = (2, 3), from = (1, 2). total_cost = 5
... to = (2, 4), from = (1, 3). total_cost = 6
... to = (3, -1), from = (2, -1). total_cost = 4
... to = (3, 0), from = (2, 0). total_cost = 3
... to = (3, 1), from = (2, 0). total_cost = 4
... to = (3, 2), from = (2, 1). total_cost = 5
... to = (3, 3), from = (2, 2). total_cost = 6
... to = (3, 4), from = (2, 3). total_cost = 7
... to = (4, -1), from = (3, -1). total_cost = 5
... to = (4, 0), from = (3, 0). total_cost = 4
... to = (4, 1), from = (3, 0). total_cost = 5
... to = (4, 2), from = (3, 1). total_cost = 6
... to = (4, 3), from = (3, 2). total_cost = 7
... to = (4, 4), from = (3, 3). total_cost = 8
I think the output is correct, but if I increase the domain size beyond anything but a very small value, the algorithm starts to consume tons of RAM, and I cannot run it to completion, because I would run out of RAM. | {
"domain": "codereview.stackexchange",
"id": 43538,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, image, pathfinding, dijkstra",
"url": null
} |
c++, algorithm, image, pathfinding, dijkstra
Is it expected to take that much system resources, or is there something that I have missed?
I do not need the cost between start point and any other point. How can I terminate early?
Answer: Don't use compiler-specific vector extensions unnecessarily
Using [[gnu::vector_size(16)]] makes your code unportable. I don't think there is any great benefit for your code to force coordinates to be in vector registers. Instead I would just write:
struct vec2i {
uint64_t x;
uint64_t y;
};
Or consider using an external library that provides you with vector types (like GLM, but there are many others), so that you don't have to worry about portability.
Where is your graph?
Normally, I would expect an implementation of Dijkstra's to take as input a pre-existing graph (usually stored as either a set of edges or as an adjacency list) and a starting vertex, and then it will iterate over the graph. However, your graph is not explicitly stored in memory. Instead, the cost function will implicitly generate a graph for you. And I think that is where your main problem is: even for a relatively small value of size, this can generate infinitely many paths that are within the square defined by size. Sure, you prune paths you know for sure will be too long, but the larger size gets, the bigger the chance is that a huge amount of paths will be visited by your code. And in turn that means nodes_to_visit and cost_table will grow larger and larger.
I suggest you first generate an explicit graph, then have your algorithm work on that.
Avoid C functions
I would avoid using C functions where possible, and use equivalent C++ functionality. Sure, shifting things into std::cout isn't as nice as printf(), but since C++17 you can use std::format, or if you cannot use that function yet, you can use the {fmt} library. | {
"domain": "codereview.stackexchange",
"id": 43538,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, image, pathfinding, dijkstra",
"url": null
} |
linux, c++14, windows, networking, framework
Title: Simple networking framework in C++
Question: Question: What do you think about this design and the implementation? This is a simple networking framework for IPv4, IPv6 TCP client and TCP server for Linux and MS-Windows in C++14. It uses a single-thread solution around the system call select(), that is IO-multiplexing. Connect and network read are asynchronous, network write is synchronous. The iomux.hpp file implements the framework as a header only library and chatpp.cpp implements a chat application as example.
On http://www.andreadrian.de/non-blocking_connect/index.html is a lot of information about an older version of this source code.
/* chatpp.cpp
* chat application, example for simple networking framework in C++
*
* Copyright 2022 Andre Adrian
* License for this source code: 3-Clause BSD License
*
* 28jun2022 adr: 3rd published version
*/
#include <libgen.h> // basename()
#include "iomux.hpp"
/* ******************************************************** */
// Business logic
enum {
BUFMAX = 1460, // Ethernet packet size minus IPv4 TCP header size
};
class Chat_Client : public Client {
public:
virtual int cb_read(SOCKET fd) override;
static Conn* make() { return make_impl<Chat_Client>(); }
};
// callback client network read available
int Chat_Client::cb_read(SOCKET fdrecv) {
assert(fdrecv >= 0 && fdrecv < FDMAX);
char buf[BUFMAX];
int readbytes = recv(fdrecv, buf, sizeof buf, 0);
if (readbytes > 0 && readbytes != SOCKET_ERROR) {
// Write all data out
int writebytes = fwrite(buf, 1, readbytes, stdout);
assert(writebytes == readbytes && "fwrite");
}
return readbytes;
}
class Chat_Server : public Server {
public:
virtual int cb_read(SOCKET fd) override;
static Conn* make() { return make_impl<Chat_Server>(); }
}; | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
// callback server network read available
int Chat_Server::cb_read(SOCKET fdrecv) {
assert(fdrecv >= 0 && fdrecv < FDMAX);
char buf[BUFMAX]; // buffer for client data
int readbytes = recv(fdrecv, buf, sizeof buf, 0);
if (readbytes > 0 && readbytes != SOCKET_ERROR) {
// we got some data from a client
for (SOCKET fd = 0; fd < FDMAX; ++fd) {
// send to everyone!
if (FD_ISSET(fd, &fds)) {
// except the listener and ourselves
if (fd != sockfd && fd != fdrecv) {
int writebytes = send(fd, buf, readbytes, 0);
if (writebytes != readbytes) {
perror("WW send");
}
}
}
}
}
return readbytes;
}
// callback keyboard polling
void cb_keyboard_poll(Conn* obj) {
assert(obj != nullptr);
if (_kbhit()) { // very MS-DOS
char buf[BUFMAX];
char* rv = fgets(buf, sizeof buf, stdin);
if (rv != nullptr) {
send(Conn::get_sockfd(obj), buf, strlen(buf), 0);
}
}
Timer::after(TIMEOUT, reinterpret_cast<cb_timer_t>(cb_keyboard_poll), obj);
}
int main(int argc, char* argv[]) {
iomux_begin();
if (argc < 4) {
char* name = basename(argv[0]);
fprintf(stderr,"usage server: %s s hostname port\n", name);
fprintf(stderr,"usage client: %s c hostname port\n", name);
fprintf(stderr,"example server IPv4: %s s 127.0.0.1 60000\n", name);
fprintf(stderr,"example client IPv4: %s c 127.0.0.1 60000\n", name);
fprintf(stderr,"example server IPv6: %s s ::1 60000\n", name);
fprintf(stderr,"example client IPv6: %s c ::1 60000\n", name);
exit(EXIT_FAILURE);
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
switch(argv[1][0]) {
case 'c': {
Conn* obj = Chat_Client::make();
obj->connectRetry = 1;
obj->open(argv[2], argv[3]);
Timer::after(TIMEOUT, reinterpret_cast<cb_timer_t>(cb_keyboard_poll), obj);
}
break;
case 's': {
Conn* obj = Chat_Server::make();
obj->open(argv[2], argv[3]);
}
break;
default:
fprintf(stderr,"EE %s: unexpected argument %s\n", FUNCTION, argv[1]);
exit(EXIT_FAILURE);
}
Conn::event_loop(); // start inversion of control
iomux_end();
return 0;
}
The header file iomux.hpp is very simple. The real work is done in the operating system specific header files liomux.hpp and wiomux.hpp.
/* iomux.hpp
*/
#ifndef IOMUX_HPP_
#define IOMUX_HPP_
#ifdef _WIN32
#include "wiomux.hpp"
#else
#include "liomux.hpp"
#endif
#endif // IOMUX_HPP_
The framework offers a "Timer class" and a "Connection class". The Connection class sub-classes into a "server class" and into a "client class". The business logic are sub-classes of "server class" and "client class". We have a little class hierarchy.
/* liomux.hpp
* Simple networking framework in C++
* Linux version
* I/O Multiplexing (select) IPv4, IPv6, TCP Server, TCP client
*
* Copyright 2022 Andre Adrian
* License for this source code: 3-Clause BSD License
*
* 28jun2022 adr: 4th published version
*/
#ifndef LIOMUX_HPP_
#define LIOMUX_HPP_
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <libgen.h> // basename()
#include <time.h>
#include <memory> // make_unique, unique_ptr
#include <cstdint>
#include <climits>
// Linux
#include <errno.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <arpa/inet.h>
#define FUNCTION __PRETTY_FUNCTION__ | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
#define FUNCTION __PRETTY_FUNCTION__
enum {
CONNMAX = 10, // maximum number of Connection objects
FDMAX = 64, // maximum number of open file descriptors
TIMEOUT = 40, // select() timeout in milli seconds
STRMAX = 80, // maximum length of C-String
TIMERMAX = 10, // maximum number of Timer objects
SOCKET_ERROR = INT_MAX, // for MS-Windows compability
INVALID_SOCKET = INT_MAX-1, // for MS-Windows compability
};
typedef int SOCKET; // for MS-Windows compability
// Copies a string with security enhancements
void strcpy_s(char* dest, size_t n, const char* src) {
strncpy(dest, src, n-1);
dest[n - 1] = '\0';
}
/** @brief Checks the console for keyboard input
* @retval >0 keyboard input
* @retval =0 no keyboard input
*/
int _kbhit(void) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
struct timeval tv = {0, 0};
return select(STDIN_FILENO + 1, &fds, nullptr, nullptr, &tv);
}
/* ******************************************************** */
// Timer object
using cb_timer_t = void (*)(void* obj);
class Timer {
cb_timer_t cb_timer; // cb_timer and obj are a closure
void* obj;
struct timespec ts; // expire time
public:
static int after(int interval, cb_timer_t cb_timer, void* obj);
static void walk();
};
static Timer timers[TIMERMAX]; // Timer objects array
int Timer::after(int interval, cb_timer_t cb_timer, void* obj) {
assert(interval >= 0);
assert(cb_timer != nullptr);
// no assert obj
int id;
for (id = 0; id < TIMERMAX; ++id) {
if (nullptr == timers[id].cb_timer) {
break; // found a free entry
}
}
assert (id < TIMERMAX && "timer array full"); | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
// convert interval in milliseconds to timespec
struct timespec dts;
dts.tv_nsec = (interval % 1000) * 1000000;
dts.tv_sec = interval / 1000;
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
timers[id].cb_timer = cb_timer;
timers[id].obj = obj;
timers[id].ts.tv_nsec = (now.tv_nsec + dts.tv_nsec) % 1000000000;
timers[id].ts.tv_sec = (now.tv_nsec + dts.tv_nsec) / 1000000000;
timers[id].ts.tv_sec += (now.tv_sec + dts.tv_sec);
/*
printf("II %s now=%ld,%ld dt=%ld,%ld ts=%ld,%ld\n", FUNCTION,
now.tv_sec, now.tv_nsec, dts.tv_sec, dts.tv_nsec,
timers[i].ts.tv_sec, timers[i].ts.tv_nsec);
*/
return id;
}
void Timer::walk() {
// looking for expired timers
for (int i = 0; i < TIMERMAX; ++i) {
if (timers[i].cb_timer != nullptr) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
if ((ts.tv_sec > timers[i].ts.tv_sec) || (ts.tv_sec == timers[i].ts.tv_sec
&& ts.tv_nsec >= timers[i].ts.tv_nsec)) {
Timer tmp = timers[i];
// erase array entry because called function can overwrite this entry
memset(&timers[i], 0, sizeof timers[i]);
assert(tmp.cb_timer != nullptr);
(*tmp.cb_timer)(tmp.obj);
}
}
}
}
/* ******************************************************** */
// Connection object
class Conn {
virtual void handle(SOCKET fd) = 0;
virtual void connected() = 0;
protected:
fd_set fds; // read file descriptor set
SOCKET sockfd; // network port for client, listen port for server
char hostname[STRMAX];
char port[STRMAX];
uint8_t isConnecting; // non-blocking connect started, but no finished
public:
uint8_t acceptOne; // behavior modifier for server
uint8_t connectRetry; // behavior modifier for client | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
Conn() : sockfd(-1), isConnecting(0), acceptOne(0), connectRetry(0) {
FD_ZERO(&fds);
};
virtual void open(const char* hostname, const char* port) = 0;
virtual int cb_read(SOCKET fd) = 0;
virtual void open1() = 0;
virtual ~Conn() { };
static SOCKET get_sockfd(Conn* obj);
static const fd_set* get_fds(Conn* obj);
static void event_loop();
};
static std::unique_ptr<Conn> conns[CONNMAX]; // Connection objects pointers array
SOCKET Conn::get_sockfd(Conn* obj) {
assert(obj != nullptr);
return obj->sockfd;
}
const fd_set* Conn::get_fds(Conn* obj) {
assert(obj != nullptr);
return &(obj->fds);
}
class Client : public Conn {
virtual void handle(SOCKET fd) override;
virtual void connected() override;
void reopen();
public:
virtual void open(const char* hostname, const char* port) override;
virtual int cb_read(SOCKET fd) override = 0;
static void open1_(Conn* obj); // from C to C++ helper
virtual void open1() override;
};
void Client::open(const char* hostname_, const char* port_) {
assert(port_ != nullptr);
assert(hostname_ != nullptr);
printf("II %s: port=%s hostname=%s\n", FUNCTION, port_, hostname_);
FD_ZERO(&fds);
strcpy_s(port, sizeof port, port_);
strcpy_s(hostname, sizeof hostname, hostname_);
open1();
}
void Client::open1() {
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo* res;
int rv = getaddrinfo(hostname, port, &hints, &res);
if (rv != 0) {
fprintf(stderr, "EE %s getaddrinfo: %s\n", FUNCTION, gai_strerror(rv));
exit(EXIT_FAILURE);
}
// loop through all the results and connect to the first we can
struct addrinfo* p;
for (p = res; p != nullptr; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (-1 == sockfd) {
perror("WW socket");
continue;
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
// UNPv2 ch. 15.4, 16.2 non-blocking connect
int val = 1;
rv = ioctl(sockfd, FIONBIO, &val);
if (rv != 0) {
perror("WW ioctl FIONBIO ON");
close(sockfd);
continue;
}
rv = connect(sockfd, p->ai_addr, p->ai_addrlen);
if (rv != 0) {
if (EINPROGRESS == errno) {
isConnecting = 1;
} else {
perror("WW connect");
close(sockfd);
continue;
}
}
break; // exit loop after socket and connect were successful
}
assert(p != nullptr && "connect try");
char dst[NI_MAXHOST];
rv = getnameinfo(p->ai_addr, p->ai_addrlen, dst, sizeof dst, nullptr, 0, 0);
assert(0 == rv && "getnameinfo");
freeaddrinfo(res);
// don't add sockfd to the fd_set, client_connect() will do
printf("II %s: connect try to %s (%s) port %s socket %d\n", FUNCTION,
hostname, dst, port, sockfd);
}
void Client::open1_(Conn* obj) {
assert(obj != nullptr);
obj->open1();
}
void Client::reopen() {
close(sockfd);
FD_CLR(sockfd, &fds); // remove network fd
sockfd = -1;
if (connectRetry) {
Timer::after(5000, reinterpret_cast<cb_timer_t>(Client::open1_), this);
// ugly bug with after(0, ...
} else {
exit(EXIT_SUCCESS);
}
}
void Client::handle(SOCKET fdrecv) {
assert(fdrecv >= 0 && fdrecv < FDMAX);
int rv = cb_read(fdrecv);
if (rv < 1) {
int optval = 0;
socklen_t optlen = sizeof optval;
int rv = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen);
assert(0 == rv && "getsockopt SOL_SOCKET SO_ERROR");
fprintf(stderr, "WW %s: connect fail to %s port %s socket %d rv %d: %s\n",
FUNCTION, hostname, port, sockfd, rv, strerror(optval));
reopen();
}
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
void Client::connected() {
isConnecting = 0;
int optval = 0;
socklen_t optlen = sizeof optval;
int rv = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen);
assert(0 == rv && "getsockopt SOL_SOCKET SO_ERROR");
if (0 == optval) {
FD_SET(sockfd, &fds);
printf("II %s: connect success to %s port %s socket %d\n", FUNCTION,
hostname, port, sockfd);
} else {
fprintf(stderr, "WW %s: connect fail to %s port %s socket %d: %s\n", FUNCTION,
hostname, port, sockfd, strerror(optval));
reopen();
}
}
class Server : public Conn {
virtual void handle(SOCKET fdrecv) override;
virtual void connected() override { }; // dummy method
public:
virtual void open(const char* hostname, const char* port) override;
virtual int cb_read(SOCKET fdrecv) override = 0;
virtual void open1() override { }; // dummy method
};
void Server::open(const char* hostname, const char* port) {
assert(port != nullptr);
// no assert hostname
printf("II %s: port=%s hostname=%s\n", FUNCTION, port, hostname);
FD_ZERO(&fds);
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
struct addrinfo* res;
int rv = getaddrinfo(hostname, port, &hints, &res);
if (rv != 0) {
fprintf(stderr, "EE %s getaddrinfo: %s\n", FUNCTION, gai_strerror(rv));
exit(EXIT_FAILURE);
}
struct addrinfo* p;
for(p = res; p != nullptr; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (-1 == sockfd) {
perror("WW socket");
continue;
}
int yes = 1;
rv = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if (rv != 0) {
perror("WW setsockopt SO_REUSEADDR");
close(sockfd);
continue;
}
rv = bind(sockfd, p->ai_addr, p->ai_addrlen);
if (rv != 0) {
perror("WW bind");
close(sockfd);
continue;
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
break; // exit loop after socket and bind were successful
}
freeaddrinfo(res);
assert(p != nullptr && "bind");
rv = listen(sockfd, 10);
assert(0 == rv && "listen");
// add the listener to the master set
FD_SET(sockfd, &fds);
printf("II %s: listen on socket %d\n", FUNCTION, sockfd);
}
void Server::handle(SOCKET fdrecv) {
assert(fdrecv >= 0 && fdrecv < FDMAX);
if (fdrecv == sockfd) {
// handle new connections
struct sockaddr_storage remoteaddr; // client address
socklen_t addrlen = sizeof remoteaddr;
if (acceptOne) {
// close old connections
for (SOCKET fd = 0; fd < FDMAX; ++fd) {
if (FD_ISSET(fd, &fds) && fd != sockfd) {
close(fd);
FD_CLR(fd, &fds);
}
}
}
// newly accept()ed socket descriptor
SOCKET newfd = accept(sockfd, reinterpret_cast<struct sockaddr*>(&remoteaddr),
&addrlen);
if (-1 == newfd) {
perror("WW accept");
} else {
FD_SET(newfd, &fds); // add to master set
char dst[NI_MAXHOST];
int rv = getnameinfo(reinterpret_cast<struct sockaddr*>(&remoteaddr),
sizeof remoteaddr, dst, sizeof dst, nullptr, 0, 0);
assert(0 == rv && "getnameinfo");
printf("II %s: new connection %s on socket %d\n", FUNCTION, dst, newfd);
}
} else {
int rv = cb_read(fdrecv);
if (rv < 1) {
printf("II %s: connection closed on socket %d\n", FUNCTION, fdrecv);
close(fdrecv);
FD_CLR(fdrecv, &fds); // remove from fd_set
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
void Conn::event_loop() {
for(;;) {
// virtualization pattern: join all read fds into one
fd_set read_fds;
FD_ZERO(&read_fds);
for (int i = 0; i < CONNMAX; ++i) {
if (conns[i]) {
for (SOCKET fd = 0; fd < FDMAX; ++fd) {
if (FD_ISSET(fd, &conns[i]->fds)) {
FD_SET(fd, &read_fds);
}
}
}
}
// virtualization pattern: join all connect pending into one
fd_set write_fds;
FD_ZERO(&write_fds);
for (int i = 0; i < CONNMAX; ++i) {
if (conns[i] && conns[i]->isConnecting) {
FD_SET(conns[i]->sockfd, &write_fds);
}
}
struct timeval tv = {0, TIMEOUT * 1000};
int rv = select(FDMAX, &read_fds, &write_fds, nullptr, &tv);
if (-1 == rv && EINTR != errno) {
perror("EE select");
exit(EXIT_FAILURE);
}
if (rv > 0) {
// looking for data to read available
for (SOCKET fd = 0; fd < FDMAX; ++fd) {
if (FD_ISSET(fd, &read_fds)) {
for (int i = 0; i < CONNMAX; ++i) {
if (conns[i] && FD_ISSET(fd, &conns[i]->fds)) {
conns[i]->handle(fd); // vtable "switch"
}
}
}
}
// looking for connect pending success or fail
for (int i = 0; i < CONNMAX; ++i) {
if (conns[i] && FD_ISSET(conns[i]->sockfd, &write_fds)) {
conns[i]->connected();
}
}
}
Timer::walk();
}
}
template <class T>
Conn* make_impl() {
for (int i = 0; i < CONNMAX; ++i) {
if (nullptr == conns[i]) {
conns[i] = std::make_unique<T>();
return conns[i].get();
}
}
assert(0 && "conns array full");
return nullptr;
}
void iomux_begin() {
// do nothing
}
void iomux_end() {
// do nothing
}
#endif // LIOMUX_HPP_ | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
void iomux_begin() {
// do nothing
}
void iomux_end() {
// do nothing
}
#endif // LIOMUX_HPP_
The MS-Windows implemenation is different in the area of asynchrounous connect. The Linux select() uses write fd_set to signal the "connecting success/failed" event, but MS-Windows select() uses exception fd_set for this event. There are some more differences. Linux can use file descriptors for check for console input, read from/write to the file system and read from/write to the network. MS-Windows uses the MS-DOS leftover _kbhit() for the first, stream IO for the second and SOCKET descriptors for the third. Worst of all, SOCKET descriptors are unsigned 64 bit integers. Somebody at Microsoft was thinking big.
/* wiomux.hpp
* Simple networking framework in C++
* MS-Windows version
* I/O Multiplexing (select) IPv4, IPv6, TCP Server, TCP client
*
* Copyright 2022 Andre Adrian
* License for this source code: 3-Clause BSD License
*
* 28jun2022 adr: 4th published version
*/
#ifndef WIOMUX_HPP_
#define WIOMUX_HPP_
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <libgen.h> // basename()
#include <time.h>
#include <memory> // make_unique, unique_ptr
#include <cstdint>
// MS-Windows
#include <conio.h> // _kbhit()
#include <winsock2.h>
#include <ws2tcpip.h> // getaddrinfo()
#define FUNCTION __PRETTY_FUNCTION__
enum {
CONNMAX = 10, // maximum number of Connection objects
FDMAX = 256, // maximum number of open file descriptors
TIMEOUT = 40, // select() timeout in milli seconds
STRMAX = 80, // maximum length of C-String
TIMERMAX = 10, // maximum number of Timer objects
};
// get sockaddr, IPv4 or IPv6:
void* get_in_addr(struct sockaddr* sa) {
assert(sa != nullptr);
if (AF_INET == sa->sa_family) {
return &(reinterpret_cast<struct sockaddr_in*>(sa)->sin_addr);
} else {
return &(reinterpret_cast<struct sockaddr_in6*>(sa)->sin6_addr);
}
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
/* ******************************************************** */
// Timer object
using cb_timer_t = void (*)(void* obj);
class Timer {
cb_timer_t cb_timer; // cb_timer and obj are a closure
void* obj;
struct timespec ts; // expire time
public:
static int after(int interval, cb_timer_t cb_timer, void* obj);
static void walk();
};
static Timer timers[TIMERMAX]; // Timer objects array
int Timer::after(int interval, cb_timer_t cb_timer, void* obj) {
assert(interval >= 0);
assert(cb_timer != nullptr);
// no assert obj
int id;
for (id = 0; id < TIMERMAX; ++id) {
if (nullptr == timers[id].cb_timer) {
break; // found a free entry
}
}
assert (id < TIMERMAX && "timer array full");
// convert interval in milliseconds to timespec
struct timespec dts;
dts.tv_nsec = (interval % 1000) * 1000000;
dts.tv_sec = interval / 1000;
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
timers[id].cb_timer = cb_timer;
timers[id].obj = obj;
timers[id].ts.tv_nsec = (now.tv_nsec + dts.tv_nsec) % 1000000000;
timers[id].ts.tv_sec = (now.tv_nsec + dts.tv_nsec) / 1000000000;
timers[id].ts.tv_sec += (now.tv_sec + dts.tv_sec);
/*
printf("II %s now=%ld,%ld dt=%ld,%ld ts=%ld,%ld\n", FUNCTION,
now.tv_sec, now.tv_nsec, dts.tv_sec, dts.tv_nsec,
timers[i].ts.tv_sec, timers[i].ts.tv_nsec);
*/
return id;
}
void Timer::walk() {
// looking for expired timers
for (int i = 0; i < TIMERMAX; ++i) {
if (timers[i].cb_timer != nullptr) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
if ((ts.tv_sec > timers[i].ts.tv_sec) || (ts.tv_sec == timers[i].ts.tv_sec
&& ts.tv_nsec >= timers[i].ts.tv_nsec)) {
Timer tmp = timers[i];
// erase array entry because called function can overwrite this entry
memset(&timers[i], 0, sizeof timers[i]);
assert(tmp.cb_timer != nullptr);
(*tmp.cb_timer)(tmp.obj);
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
/* ******************************************************** */
// Connection object
class Conn {
virtual void handle(SOCKET fd) = 0;
virtual void connected() = 0;
protected:
fd_set fds; // read file descriptor set
SOCKET sockfd; // network port for client, listen port for server
char hostname[STRMAX];
char port[STRMAX];
uint8_t isConnecting; // non-blocking connect started, but no finished
public:
uint8_t acceptOne; // behavior modifier for server
uint8_t connectRetry; // behavior modifier for client
Conn() : sockfd(-1), isConnecting(0), acceptOne(0), connectRetry(0) {
FD_ZERO(&fds);
};
virtual void open(const char* hostname, const char* port) = 0;
virtual int cb_read(SOCKET fd) = 0;
virtual ~Conn() { };
static SOCKET get_sockfd(Conn* obj);
static const fd_set* get_fds(Conn* obj);
static void event_loop();
};
static std::unique_ptr<Conn> conns[CONNMAX]; // Connection objects pointers array
SOCKET Conn::get_sockfd(Conn* obj) {
assert(obj != nullptr);
return obj->sockfd;
}
const fd_set* Conn::get_fds(Conn* obj) {
assert(obj != nullptr);
return &(obj->fds);
}
class Client : public Conn {
virtual void handle(SOCKET fd) override;
virtual void connected() override;
void open1();
public:
virtual void open(const char* hostname, const char* port) override;
virtual int cb_read(SOCKET fd) override = 0;
};
void Client::open(const char* hostname_, const char* port_) {
assert(port_ != nullptr);
assert(hostname_ != nullptr);
printf("II %s: port=%s hostname=%s\n", FUNCTION, port_, hostname_);
FD_ZERO(&fds);
strcpy_s(port, sizeof port, port_);
strcpy_s(hostname, sizeof hostname, hostname_);
open1();
}
void Client::open1() {
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM; | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
struct addrinfo* res;
int rv = getaddrinfo(hostname, port, &hints, &res);
if (rv != 0) {
fprintf(stderr, "EE %s getaddrinfo: %d\n", FUNCTION, rv);
exit(EXIT_FAILURE);
}
// loop through all the results and connect to the first we can
struct addrinfo* p;
for (p = res; p != nullptr; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (INVALID_SOCKET == sockfd) {
perror("WW socket");
continue;
}
// UNPv2 ch. 15.4, 16.2 non-blocking connect
unsigned long val = 1;
rv = ioctlsocket(sockfd, FIONBIO, &val);
if (rv != 0) {
perror("WW ioctlsocket FIONBIO ON");
closesocket(sockfd);
continue;
}
rv = connect(sockfd, p->ai_addr, p->ai_addrlen);
if (rv != 0) {
if (WSAEWOULDBLOCK == WSAGetLastError()) {
isConnecting = 1;
} else {
perror("WW connect");
closesocket(sockfd);
continue;
}
}
break; // exit loop after socket and connect were successful
}
assert(p != nullptr && "connect try");
void* src = get_in_addr(reinterpret_cast<struct sockaddr*>(p->ai_addr));
char dst[INET6_ADDRSTRLEN];
inet_ntop(p->ai_family, src, dst, sizeof dst);
freeaddrinfo(res);
FD_SET(sockfd, &fds);
printf("II %s: connect try to %s (%s) port %s socket %llu\n", FUNCTION,
hostname, dst, port, sockfd);
}
void Client::connected() {
closesocket(sockfd);
FD_CLR(sockfd, &fds); // remove network fd
sockfd = -1;
if (connectRetry) {
open1();
} else {
exit(EXIT_SUCCESS);
}
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
void Client::handle(SOCKET fdrecv) {
assert(fdrecv < FDMAX);
int rv = cb_read(fdrecv);
if (rv < 1 || SOCKET_ERROR == rv) {
// documentation conflict between
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-getsockopt
// https://docs.microsoft.com/en-us/windows/win32/winsock/sol-socket-socket-options
unsigned long optval;
int optlen = sizeof optval;
int rv = getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char*>(&optval), &optlen);
assert(0 == rv && "getsockopt SOL_SOCKET SO_ERROR");
fprintf(stderr, "WW %s: connect fail to %s port %s socket %llu rv %d: %s\n",
FUNCTION, hostname, port, sockfd, rv, strerror(optval));
connected();
} else {
isConnecting = 0; // hack: connect successful after first good read()
}
}
class Server : public Conn {
virtual void handle(SOCKET fdrecv) override;
virtual void connected() override { }; // dummy method
public:
virtual void open(const char* hostname, const char* port) override;
virtual int cb_read(SOCKET fdrecv) override = 0;
};
void Server::open(const char* hostname, const char* port) {
assert(port != nullptr);
assert(hostname != nullptr);
printf("II %s: port=%s hostname=%s\n", FUNCTION, port, hostname);
FD_ZERO(&fds);
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
struct addrinfo* res;
int rv = getaddrinfo(hostname, port, &hints, &res);
if (rv != 0) {
fprintf(stderr, "EE %s getaddrinfo: %d\n", FUNCTION, rv);
exit(EXIT_FAILURE);
}
struct addrinfo* p;
for(p = res; p != nullptr; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (INVALID_SOCKET == sockfd) {
perror("WW socket");
continue;
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
// documentation conflict between
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-setsockopt
// https://docs.microsoft.com/en-us/windows/win32/winsock/sol-socket-socket-options
const unsigned long yes = 1;
rv = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<const char*>(&yes), sizeof(yes));
if (rv != 0) {
perror("WW setsockopt SO_REUSEADDR");
closesocket(sockfd);
continue;
}
rv = bind(sockfd, p->ai_addr, p->ai_addrlen);
if (rv != 0) {
perror("WW bind");
closesocket(sockfd);
continue;
}
break; // exit loop after socket and bind were successful
}
freeaddrinfo(res);
assert(p != nullptr && "bind");
rv = listen(sockfd, 10);
assert(0 == rv && "listen");
// add the listener to the master set
FD_SET(sockfd, &fds);
printf("II %s: listen on socket %llu\n", FUNCTION, sockfd);
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
printf("II %s: listen on socket %llu\n", FUNCTION, sockfd);
}
void Server::handle(SOCKET fdrecv) {
assert(fdrecv < FDMAX);
if (fdrecv == sockfd) {
// handle new connections
struct sockaddr_storage remoteaddr; // client address
socklen_t addrlen = sizeof remoteaddr;
if (acceptOne) {
// close old connections
for (SOCKET fd = 0; fd < FDMAX; ++fd) {
if (FD_ISSET(fd, &fds) && fd != sockfd) {
closesocket(fd);
FD_CLR(fd, &fds);
}
}
}
// newly accept()ed socket descriptor
SOCKET newfd = accept(sockfd, reinterpret_cast<struct sockaddr*>(&remoteaddr),
&addrlen);
if (INVALID_SOCKET == newfd) {
perror("WW accept");
} else {
FD_SET(newfd, &fds); // add to master set
void* src = get_in_addr(reinterpret_cast<struct sockaddr*>(&remoteaddr));
char dst[INET6_ADDRSTRLEN];
inet_ntop(remoteaddr.ss_family, src, dst, sizeof dst);
printf("II %s: new connection %s on socket %llu\n", FUNCTION, dst, newfd);
}
} else {
int rv = cb_read(fdrecv);
if (rv < 1 || SOCKET_ERROR == rv) {
printf("II %s: connection closed on socket %llu\n", FUNCTION, fdrecv);
closesocket(fdrecv);
FD_CLR(fdrecv, &fds); // remove from fd_set
}
}
}
void Conn::event_loop() {
for(;;) {
// virtualization pattern: join all read fds into one
fd_set read_fds;
FD_ZERO(&read_fds);
for (int i = 0; i < CONNMAX; ++i) {
if (conns[i]) {
for (SOCKET fd = 0; fd < FDMAX; ++fd) {
if (FD_ISSET(fd, &conns[i]->fds)) {
FD_SET(fd, &read_fds);
}
}
}
}
// virtualization pattern: join all connect pending into one
fd_set except_fds;
FD_ZERO(&except_fds);
for (int i = 0; i < CONNMAX; ++i) {
if (conns[i] && conns[i]->isConnecting) {
FD_SET(conns[i]->sockfd, &except_fds);
}
} | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
struct timeval tv = {0, TIMEOUT * 1000};
int rv = select(FDMAX, &read_fds, nullptr, &except_fds, &tv);
if (SOCKET_ERROR == rv && WSAGetLastError() != WSAEINTR) {
perror("EE select");
exit(EXIT_FAILURE);
}
if (rv > 0) {
// looking for data to read available
for (SOCKET fd = 0; fd < FDMAX; ++fd) {
if (FD_ISSET(fd, &read_fds)) {
for (int i = 0; i < CONNMAX; ++i) {
if (conns[i] && FD_ISSET(fd, &conns[i]->fds)) {
conns[i]->handle(fd); // vtable "switch"
}
}
}
}
// looking for connect pending fail
for (int i = 0; i < CONNMAX; ++i) {
if (conns[i] && FD_ISSET(conns[i]->sockfd, &except_fds)) {
conns[i]->connected();
}
}
}
Timer::walk();
}
}
template <class T>
Conn* make_impl() {
for (int i = 0; i < CONNMAX; ++i) {
if (nullptr == conns[i]) {
conns[i] = std::make_unique<T>();
return conns[i].get();
}
}
assert(0 && "conns array full");
return nullptr;
}
void iomux_begin() {
static WSADATA wsaData;
int rv = WSAStartup(MAKEWORD(2, 2), &wsaData);
assert(0 == rv && "WSAStartup");
}
void iomux_end() {
WSACleanup();
}
#endif // WIOMUX_HPP_
The line count (wc -l) of this source code is: 116 for chatpp.c, 481 for liomux.hpp and 448 for wiomux.hpp. I think, this is really a simple networking framework. The constant CONNMAX defines the maximum number of "TCP servers" and "TCP clients" in the application. TIMERMAX defines the maximum number of Timers and FDMAX defines the maximum number of open SOCKET descriptors.
There is a simple networking framework in C from me, see Simple networking framework in C | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
Answer: Make much more use of C++
Of course you will need to use POSIX functions to open sockets and read from and write to them, but a lot of your code is still using C functions where it could use C++ functions.
Instead of printf(), use std::cout and std::cerr, possibly in combination with std::format().
Instead of using arrays of char to store strings, use std::string, so you no longer need to use the unsafe strcpy() or the non-standard strcpy_s().
Error handling in C++ can be done in several ways. An easy one is to throw exceptions. Create your own exception type that derives from one of the existing ones, like std::runtime_error, so that you can do something like throw network_error("getaddrinfo() failed"). This will allow the caller to catch it if they want, and if they don't it will cause the program to be terminated.
C++ also comes with time handling functions, has lots of containers types and algorithms. Using these can greatly simplify your code. There is much more to C++ than just slapping a few classes here and there onto C code.
Timers the C++ way
As an example of how to make things more C++, let's look at the timers.
First, instead of having a function pointer that takes a void*, and having a void* obj that you pass to it, in effect forming a closure as you wrote in the comments, use std::function to store closures.
Second, instead of struct timespec, use the appropriate std::chrono type to store a timestamp. To avoid having to write long type names everywhere, you can create an alias.
Finally, since you want to be able to check which timers have expired, it would be nice to keep them somehow sorted. The first thing to make that happen is to make timers comparable based on their expiry time. You can overload operator< to do this.
Throw in a proper constructor and member functions read the expiry time and to trigger the callback, the result is:
using clock = std::chrono::steady_clock; // the equivalent of CLOCK_MONOTONIC | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
linux, c++14, windows, networking, framework
class Timer {
clock::timestamp expire_time;
std::function<void()> callback;
public:
Timer(clock::timestamp expire_time, std::function<void()> callback):
expire_time(expire_time), callback(callback) {}
clock::timestamp get_expire_time() const {
return expire_time;
}
void expire() {
callback();
}
bool operator<(const Timer& other) {
return expire_time > other.expire_time;
}
};
Instead of having a fixed-length array, you can now store those timers in a std::priority_queue, and because of the operator< overload, it will sort the queue based in the expiry time. Note that because you can only access the largest element in a std::priority_queue, but we want the earliest expiry time, we had to invert the comparison inside operator<. Now you can do:
std::priority_queue<Timer> timers;
void after(clock::duration interval, std::function<void()> callback) {
timers.emplace(clock::now() + interval, callback);
}
void walk_timers() {
auto now = clock::now();
while (!timers.empty() && timers.top().get_expire_time() < now) {
timers.top().expire();
timers.pop();
}
}
And to use it, you would write something like:
static constexpr std::chrono::milliseconds TIMEOUT = 40;
...
case 'c': {
Conn* obj = Chat_Client::make();
obj->connectRetry = 1;
obj->open(argv[2], argv[3]);
after(TIMEOUT, [obj]{ cb_keyboard_poll(obj); });
}
A lambda expression is used here to capture obj and to call cb_keyboard_poll(obj) after the timeout expired. No casts were necessary. Also note how it is now clear from the code that TIMEOUT is in milliseconds, no need to comment this anywhere. No arbitrary limit on the number of timers that can be pending. Most importantly, much less code! | {
"domain": "codereview.stackexchange",
"id": 43539,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, c++14, windows, networking, framework",
"url": null
} |
java, multithreading, concurrency
Title: Task executor thread pool
Question: Despite my experience with Java, I am not well-versed with concurrency. I wrote this thread pool that has a queue of tasks. Please ignore any signature choices, such as overuse of final. Thank you for your feedback!
public final class ThreadPool {
// Logging
//--------------------------------------------------
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPool.class);
// Constructors
//--------------------------------------------------
public ThreadPool(final int size, final boolean lazy) {
super();
this.size = size;
this.workers = new Worker[this.size];
this.queue = new LinkedBlockingQueue<>();
if(!lazy) createAndStartWorkers();
}
// Fields
//--------------------------------------------------
private volatile boolean initialized = false;
private final int size;
private final Worker[] workers;
private final BlockingQueue<Runnable> queue;
// Methods
//--------------------------------------------------
public final void schedule(final Runnable task) {
if(!initialized) createAndStartWorkers();
synchronized(queue) {
queue.add(task);
queue.notify();
}
}
public final void shutdown() {
for(int i = 0; i < size; i++) {
workers[i] = null;
}
}
public final int getSize() {
return size;
}
private void createAndStartWorkers() {
for(int i = 0; i < size; i++) {
workers[i] = new Worker();
workers[i].start();
}
initialized = true;
}
// Nested
//--------------------------------------------------
/**
* Worker thread.
*
* @author Oliver Yasuna
* @since 2.0.0
*/
private final class Worker extends Thread {
// Constructors
//--------------------------------------------------
private Worker() {
super();
}
// Overrides
//--------------------------------------------------
// Runnable
// | {
"domain": "codereview.stackexchange",
"id": 43540,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, multithreading, concurrency",
"url": null
} |
java, multithreading, concurrency
// Overrides
//--------------------------------------------------
// Runnable
//
@Override
public final void run() {
Runnable task;
while(true) {
synchronized(queue) {
while(queue.isEmpty()) {
try {
queue.wait();
} catch(final InterruptedException e) {
LOGGER.warn("An error occurred while waiting for the queue.", e);
}
}
task = queue.poll();
}
try {
task.run();
} catch(final RuntimeException e) {
LOGGER.warn("Thread pool was interrupted due to an exception.", e);
}
}
}
}
}
Answer: I am assuming this is not intended for serious use, as there’s no good reason not to use the tools already provided by Java for pooling threads made available in Executors. As I am not an expert in concurrent programming in Java, I’m sure I’ve missed at least one important thing. Strongly consider picking up the excellent Java Concurrency in Practice. It is somewhat dated, but the core of the concurrency library was written before the book. You can also look at the implementation of ThreadPoolExecutor, which will show you all the things the API writers felt were necessary.
All of the comments which are used to visually separate “sections” are noise, and make it harder to actually read the code.
In idiomatic java
instance variables are declared before constructors, not after.
There is whitespace between control flow operators (for, while,if, catch) and open parens. This visually distinguishes them from method calls, where the paren is adjacent. | {
"domain": "codereview.stackexchange",
"id": 43540,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, multithreading, concurrency",
"url": null
} |
java, multithreading, concurrency
queue can and should be assigned when it is declared.
size does not need to be tracked separately, as it can always be determined from the length of the workers array.
super() in the constructor is noise. The no-argument constructor of Object does nothing.
Validation should be added for size in the constructor. A size of zero will create a thread pool which accepts tasks but never executes them.
I do not see any value in waiting to start the workers. Sleeping threads do not typically consume significant resources. The code complexity is almost certainly not worth the marginal system resource gain.
Even when optional, curly braces should always be used. They improve readability and eliminate a common class of programming error.
Synchronizing on queue is not leveraging a primary feature of LinkedBlockingQueue. The take() method will block until an item is available. Each worker thread should call take() instead of waiting to be notified.
Shutdown doesn’t. Making the pointers to the worker threads null doesn’t affect the threads themselves at all. They will happily continue running and acquiring tasks from the queue. The threads need to be interrupted. The queue needs to be drained so the threads don’t grab any new tasks. The schedule method needs to check if the thread pool is running and disallow adding new tasks.
Javadoc that merely says “Worker Thread” is meaningless and can be removed. If documentation doesn’t provide value, it’s just making it harder to read the important bits.
Worker should not extends Thread. You have not created a new, generally-usable type of Thread. You have a specific block of code you want a thread to run. Worker should implements Runnable.
Your personal preferences aside, the constructor is noise and should be removed.
As mentioned above, using take() in run() removes a lot of noise from the method. | {
"domain": "codereview.stackexchange",
"id": 43540,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, multithreading, concurrency",
"url": null
} |
java, multithreading, concurrency
As mentioned above, using take() in run() removes a lot of noise from the method.
An InterruptedException is not “An error occurred”. It’s “Somebody asked me to stop what I’m doing”. The worker should stop running when it sees an InterruptedException. It is most likely an info(), not a warn().
A RuntimeException is not “Thread pool was interrupted”. It’s “The current task threw an exception”. It should be an error(), not a warn().
If you made all these changes, your code might look more like:
public final class ThreadPool { | {
"domain": "codereview.stackexchange",
"id": 43540,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, multithreading, concurrency",
"url": null
} |
java, multithreading, concurrency
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPool.class);
private final Thread[] workers;
private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
private volatile boolean running = true;
public ThreadPool(final int size) {
this.workers = new Thread[size];
for (int i = 0; i < workers.length; i++) {
workers[i] = new Thread(new Worker());
workers[i].start();
}
}
public final void schedule(final Runnable task) {
if (running) {
queue.add(task);
} else {
// TODO: handle this case. Log, throw, etc.
}
}
public final void shutdown() {
running = false;
queue.clear();
for (int i = 0; i < workers.length; i++) {
workers[i].interrupt();
}
}
public final int getSize() {
return workers.length;
}
/**
* @author Oliver Yasuna
* @since 2.0.0
*/
private final class Worker implements Runnable {
@Override
public final void run() {
while (true) {
try {
queue.take().run();
} catch (final InterruptedException ie) {
LOGGER.info("Thread " + Thread.currentThread().getName() + " interrupted.", ie);
break;
} catch (final RuntimeException e) {
LOGGER.error("Worker task failed due to an exception.", e);
}
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43540,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, multithreading, concurrency",
"url": null
} |
c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type
Title: Implementation of std::any
Question: Today, I decided to implement std::any using the cppreference page. I've never actually used std::any before and after seeing the implementation first hand... I don't think I'll start now! I'm not entirely sure what this class is actually meant for. I'm not even sure why I implemented this in the first place...
Anyway, here's the code:
#include <memory>
#include <utility>
#include <typeinfo>
namespace mystd {
template <typename T>
struct is_in_place_type : std::false_type {};
template <typename T>
struct is_in_place_type<std::in_place_type_t<T>> : std::true_type {};
class any {
template <typename ValueType>
friend const ValueType *any_cast(const any *) noexcept;
template <typename ValueType>
friend ValueType *any_cast(any *) noexcept;
public:
// constructors
constexpr any() noexcept = default;
any(const any &other) {
if (other.instance) {
instance = other.instance->clone();
}
}
any(any &&other) noexcept
: instance(std::move(other.instance)) {}
template <typename ValueType, typename = std::enable_if_t<
!std::is_same_v<std::decay_t<ValueType>, any> &&
!is_in_place_type<std::decay_t<ValueType>>::value &&
std::is_copy_constructible_v<std::decay_t<ValueType>>
>>
any(ValueType &&value) {
static_assert(std::is_copy_constructible_v<std::decay_t<ValueType>>, "program is ill-formed");
emplace<std::decay_t<ValueType>>(std::forward<ValueType>(value));
}
template <typename ValueType, typename... Args, typename = std::enable_if_t<
std::is_constructible_v<std::decay_t<ValueType>, Args...> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>
>>
explicit any(std::in_place_type_t<ValueType>, Args &&... args) {
emplace<std::decay_t<ValueType>>(std::forward<Args>(args)...);
} | {
"domain": "codereview.stackexchange",
"id": 43541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type",
"url": null
} |
c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type
template <typename ValueType, typename List, typename... Args, typename = std::enable_if_t<
std::is_constructible_v<std::decay_t<ValueType>, std::initializer_list<List> &, Args...> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>
>>
explicit any(std::in_place_type_t<ValueType>, std::initializer_list<List> list, Args &&... args) {
emplace<std::decay_t<ValueType>>(list, std::forward<Args>(args)...);
}
// assignment operators
any &operator=(const any &rhs) {
any(rhs).swap(*this);
return *this;
}
any &operator=(any &&rhs) noexcept {
any(std::move(rhs)).swap(*this);
return *this;
}
template <typename ValueType>
std::enable_if_t<
!std::is_same_v<std::decay_t<ValueType>, any> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>,
any &
>
operator=(ValueType &&rhs) {
any(std::forward<ValueType>(rhs)).swap(*this);
return *this;
}
// modifiers
template <typename ValueType, typename... Args>
std::enable_if_t<
std::is_constructible_v<std::decay_t<ValueType>, Args...> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>,
std::decay_t<ValueType> &
>
emplace(Args &&... args) {
auto new_inst = std::make_unique<storage_impl<std::decay_t<ValueType>>>(std::forward<Args>(args)...);
std::decay_t<ValueType> &value = new_inst->value;
instance = std::move(new_inst);
return value;
}
template <typename ValueType, typename List, typename... Args>
std::enable_if_t<
std::is_constructible_v<std::decay_t<ValueType>, std::initializer_list<List> &, Args...> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>,
std::decay_t<ValueType> &
>
emplace(std::initializer_list<List> list, Args &&... args) {
auto new_inst = std::make_unique<storage_impl<std::decay_t<ValueType>>>(list, std::forward<Args>(args)...);
std::decay_t<ValueType> &value = new_inst->value;
instance = std::move(new_inst);
return value;
} | {
"domain": "codereview.stackexchange",
"id": 43541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type",
"url": null
} |
c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type
void reset() noexcept {
instance.reset();
}
void swap(any &other) noexcept {
std::swap(instance, other.instance);
}
// observers
bool has_value() const noexcept {
return static_cast<bool>(instance);
}
const std::type_info &type() const noexcept {
return instance ? instance->type() : typeid(void);
}
private:
struct storage_base;
std::unique_ptr<storage_base> instance;
struct storage_base {
virtual ~storage_base() = default;
virtual const std::type_info &type() const noexcept = 0;
virtual std::unique_ptr<storage_base> clone() const = 0;
};
template <typename ValueType>
struct storage_impl final : public storage_base {
template <typename... Args>
storage_impl(Args &&... args)
: value(std::forward<Args>(args)...) {}
const std::type_info &type() const noexcept override {
return typeid(ValueType);
}
std::unique_ptr<storage_base> clone() const override {
return std::make_unique<storage_impl<ValueType>>(value);
}
ValueType value;
};
};
} // mystd
template <>
void std::swap(mystd::any &lhs, mystd::any &rhs) noexcept {
lhs.swap(rhs);
}
namespace mystd {
class bad_any_cast : public std::exception {
public:
const char *what() const noexcept {
return "bad any cast";
}
};
// C++20
template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
// any_cast
template <typename ValueType>
ValueType any_cast(const any &anything) {
using value_type_cvref = remove_cvref_t<ValueType>;
static_assert(std::is_constructible_v<ValueType, const value_type_cvref &>, "program is ill-formed");
if (auto *value = any_cast<value_type_cvref>(&anything)) {
return static_cast<ValueType>(*value);
} else {
throw bad_any_cast();
}
} | {
"domain": "codereview.stackexchange",
"id": 43541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type",
"url": null
} |
c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type
template <typename ValueType>
ValueType any_cast(any &anything) {
using value_type_cvref = remove_cvref_t<ValueType>;
static_assert(std::is_constructible_v<ValueType, value_type_cvref &>, "program is ill-formed");
if (auto *value = any_cast<value_type_cvref>(&anything)) {
return static_cast<ValueType>(*value);
} else {
throw bad_any_cast();
}
}
template <typename ValueType>
ValueType any_cast(any &&anything) {
using value_type_cvref = remove_cvref_t<ValueType>;
static_assert(std::is_constructible_v<ValueType, value_type_cvref>, "program is ill-formed");
if (auto *value = any_cast<value_type_cvref>(&anything)) {
return static_cast<ValueType>(std::move(*value));
} else {
throw bad_any_cast();
}
}
template <typename ValueType>
const ValueType *any_cast(const any *anything) noexcept {
if (!anything) return nullptr;
auto *storage = dynamic_cast<any::storage_impl<ValueType> *>(anything->instance.get());
if (!storage) return nullptr;
return &storage->value;
}
template <typename ValueType>
ValueType *any_cast(any *anything) noexcept {
return const_cast<ValueType *>(any_cast<ValueType>(static_cast<const any *>(anything)));
}
// make_any
template <typename ValueType, typename... Args>
any make_any(Args &&... args) {
return any(std::in_place_type<ValueType>, std::forward<Args>(args)...);
}
template <typename ValueType, typename List, typename... Args>
any make_any(std::initializer_list<List> list, Args &&... args) {
return any(std::in_place_type<ValueType>, list, std::forward<Args>(args)...);
}
} // mystd
I'm thinking about doing this in C++11 without rigorously adhering to the standard and without RTTI. Maybe another day... | {
"domain": "codereview.stackexchange",
"id": 43541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type",
"url": null
} |
c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type
Answer: Your implementation is excellent! I can hardly find any problems. I was amazed how simple a conforming implementation of any can be. And I wholeheartedly agree with @papagaga's comment.
Here's my two cents. I use the N4659, the C++17 final draft, as a reference.
Non-conformance (priority: high)
Thou Shalt Not Specialize std::swap. Instead, you should overload swap to be found by ADL. See How to overload std::swap() on Stack Overflow.
class any {
public:
// ...
friend void swap(any& lhs, any& rhs)
{
lhs.swap(rhs);
}
};
[any.bad_any_cast]/2 specifies that bad_any_cast should derive from std::bad_cast. Your implementation fails to do this.
Other suggestions (priority: low)
[any.class]/3 says:
Implementations should avoid the use of dynamically allocated memory
for a small contained value. [ Example: where the object constructed
is holding only an int. — end example ]
Such small-object optimization shall only be applied to types T for
which is_nothrow_move_constructible_v<T> is true.
Clearly, you did not implement this optimization.
Initially I thought, "where is your destructor?" Then I realized that the synthesized destructor is equivalent to reset(). I recommend you explicitly default this to reduce confusion since you implemented the rest of the Big Five.
~any() = default;
The following static_assert on line 40 is unnecessary:
static_assert(std::is_copy_constructible_v<std::decay_t<ValueType>>, "program is ill-formed");
because this constructor does not participate in overload resolution unless std::is_copy_constructible_v<std::decay_t<ValueType>>. | {
"domain": "codereview.stackexchange",
"id": 43541,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, reinventing-the-wheel, template-meta-programming, c++17, variant-type",
"url": null
} |
python, performance, strings, mathematics
Title: Applying a cost function to a string based on a pattern string | {
"domain": "codereview.stackexchange",
"id": 43542,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, strings, mathematics",
"url": null
} |
python, performance, strings, mathematics
Question: I have a cost function Cost_Func(pt,STRING) that calculates value in a specific way based on the given pattern string pt and main string STRING.
A mathematical expression ( y := y-11*int(STRING[i-length]))/6+ int(STRING[i])*pow(11,length), this is the main calculation ) is used,
and the intuition is, it will be faster than KMP string matching (to compare I present here the function KMPSearch(pt,STRING)),
but to my surprise, it is not.
I thought KMP function would have to use a lot of value-comparison, while the expression y runs through the loop once.
In the hope of better performance, I used assignment expressions in list comprehension (Python 3.8), but the function is still slower than the KMP matching function. I need to be faster than KMP function, otherwise the cost function will not be accepted.
txt = "010110101010101010100000000000111111111111111111111111111111111110000"
pat = "01000000000001"
import time
def Cost_Func(pt,STRING):
x=y=0
h,length,cnst=[],len(pt),3
[(x := x+pow(11*int(pt[i]),(i+1)),y := y+pow(11*int(STRING[i]),(i+1))) for i in range(length)]
h=[((i-length+1)) for i in range(length,len(STRING)) if (y := (y-11*int(STRING[i-length]))/6+ int(STRING[i])*pow(11,length))>x/cnst]
return h
def KMPSearch(pt, tt):
k=[]
M = len(pat)
N = len(txt)
lps = [0]*M
j = 0
computeLPSArray(pat, M, lps)
i = 0
while i < N:
if pat[j] == txt[i]:
i += 1
j += 1
if j == M:
k.append(i-j)
j = lps[j-1]
elif i < N and pat[j] != txt[i]:
if j != 0: | {
"domain": "codereview.stackexchange",
"id": 43542,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, strings, mathematics",
"url": null
} |
python, performance, strings, mathematics
if j != 0:
j = lps[j-1]
else:
i += 1
return k
def computeLPSArray(pat, M, lps):
len = 0
lps[0]
i = 1
while i < M:
if pat[i]== pat[len]:
len += 1
lps[i] = len
i += 1
else:
if len != 0:
len = lps[len-1]
else:
lps[i] = 0
i += 1 | {
"domain": "codereview.stackexchange",
"id": 43542,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, strings, mathematics",
"url": null
} |
python, performance, strings, mathematics
k=200
t0 = time.time()
for i in range(1,k):
Cost_Func(pat,txt)
t1 = time.time()
for i in range(1,k):
KMPSearch(pat, txt)
t2 = time.time()
print("Cost_func:",(t1-t0)/k*10000,"KMP:",(t2-t1)/k*10000,k)
Is there a faster way to complete the Cost_Func(pt,STRING)?
For example, would library like NumPy help? Is there any other technique?
The source of the code of KMP function is taken from here.
Answer: Without saying this lightly, this code is a proper nightmare. Here is a list of things that do not make your code faster:
Combining variable assignments on one line
Writing a list comprehension used for its side-effects and then throwing away the result of the comprehension
Removing all whitespace from comprehensions
Hyper-abbreviating variable names
So don't do any of those. Add type hints, follow PEP8 for your variable and function names and whitespace, add a __main__ guard, add unit tests, expand your first comprehension to a plain loop, replace pow() with the ** operator, loop more pythonically via zip, make compute_lps_array() return instead of mutate, and you get what I consider to be a bare-minimum first refactor:
from typing import Literal, Sequence
PatternT = Sequence[Literal['0', '1']]
def cost_func(pattern: PatternT, string: PatternT) -> list[int]:
x = y = 0
length = len(pattern)
const = 3
for i, (p, s) in enumerate(zip(pattern, string), start=1):
x += (11 * int(p)) ** i
y += (11 * int(s)) ** i
h = [
(i - length + 1)
for i in range(length, len(string))
if (
y := (y - 11 * int(string[i - length])) / 6 + int(string[i]) * 11**length
) > x / const
]
return h
def kmp_search(pattern: PatternT, text: PatternT) -> list[int]:
i = j = 0
k = []
M = len(pattern)
N = len(text)
lps = compute_lps_array(pattern, M) | {
"domain": "codereview.stackexchange",
"id": 43542,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, strings, mathematics",
"url": null
} |
python, performance, strings, mathematics
while i < N:
if pattern[j] == text[i]:
i += 1
j += 1
if j == M:
k.append(i - j)
j = lps[j - 1]
elif i < N and pattern[j] != text[i]:
if j != 0:
j = lps[j - 1]
else:
i += 1
return k
def compute_lps_array(pattern: PatternT, M: int) -> list[int]:
lps = [0] * M
len = 0
i = 1
while i < M:
if pattern[i] == pattern[len]:
len += 1
lps[i] = len
i += 1
elif len != 0:
len = lps[len - 1]
else:
lps[i] = 0
i += 1
return lps
def test() -> None:
text = "010110101010101010100000000000111111111111111111111111111111111110000"
pattern = "01000000000001"
assert cost_func(pattern, text) == [
1, 3, 5, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51
]
assert kmp_search(pattern, text) == [17]
if __name__ == '__main__':
test()
The KMP search doesn't lend itself well to Numpy vectorisation. If you really need this to be faster, don't use Python. If you want it to be Python-compatible, write it in C with an FFI to Python. It's probable that someone has already done this for you..
On the contrary, cost_func is definitely vectorisable. Recognise that your predicate y := ... > x/const is a recurrence relation, and one that has a pretty easy solution. In my very limited testing, this is equivalent:
def cost_func(pattern: np.ndarray, string: np.ndarray) -> np.ndarray:
x = (11. ** (np.nonzero(pattern)[0] + 1)).sum()
y0 = (11. ** (np.nonzero(string[:pattern.size])[0] + 1)).sum()
addends = (
string[pattern.size:] * 11**pattern.size -
11/6 * string[:-pattern.size]
) | {
"domain": "codereview.stackexchange",
"id": 43542,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, strings, mathematics",
"url": null
} |
python, performance, strings, mathematics
# Inspired by linear recurrence relation solution at
# https://stackoverflow.com/a/30069366/313768
pot = 6.**np.arange(string.size - pattern.size + 1)
revpot = pot[-2::-1]
ycomp = np.cumsum(addends/revpot)*revpot + y0/pot[1:]
const = 3
indices, = (ycomp > x/const).nonzero()
return indices + 1
def string_to_array(string: Sequence[Literal['0', '1']]) -> np.ndarray:
return np.array([
int(c) for c in string
])
def test() -> None:
pattern = string_to_array("01000000000001")
text = string_to_array("010110101010101010100000000000111111111111111111111111111111111110000")
assert np.all(
cost_func(pattern, text) == [
1, 3, 5, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51
]
)
if __name__ == '__main__':
test()
In the recurrence question I linked, there is another, simpler solution to express the recurrence relation with a single function call, scipy.signal.lfilter. I have not tested its performance, but I somewhat trust its numerical stability to be better and the results are the same:
def cost_func(pattern: np.ndarray, string: np.ndarray) -> np.ndarray:
x = (11. ** (np.nonzero(pattern)[0] + 1)).sum()
y0 = (11. ** (np.nonzero(string[:pattern.size])[0] + 1)).sum()
addends = (
string[pattern.size:] * 11**pattern.size -
11/6 * string[:-pattern.size]
)
# Inspired by linear recurrence relation solution at
# https://stackoverflow.com/a/53705423/313768
ycomp, _ = scipy.signal.lfilter(
b=[1, 0], a=[1, -1/6], x=addends, zi=[y0/6],
)
const = 3
indices, = (ycomp > x/const).nonzero()
return indices + 1
Also on numerical stability: your quantities are enormous, even in this small example going past 4e14. Strongly consider operating in log-domain math instead. | {
"domain": "codereview.stackexchange",
"id": 43542,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, strings, mathematics",
"url": null
} |
c#, classes, wrapper
Title: Common interface for fixed-length and variable-length lists in C#
Question: I am working on library project in which I am reading and writing binary files that have own file format structure. In that structure there are variable-length and fixed-length elements. My approach is to parse byte stream of such files, create corresponding objects, and then get current byte stream and write it back to file. So I need to have byte stream <-> object binding. The problem is very complicated file format (AFP) in which some structures are variable length and some are not. I got stuck on choosing best "list" class for storing byte streams that may be fixed-length or variable-length. My idea is to wrap such byte stream "list" in another class (composition) and allow different external objects to be passed into that class (C# array or List).
namespace TEST
{
public class ByteStreamList : IList<byte>, IEnumerable<byte>
{
protected IList<byte> bytes = null;
public byte this[int index] {
get {
return bytes[index];
}
set {
bytes[index] = value;
}
}
public int Count {
get {
return bytes.Count;
}
}
public bool IsReadOnly {
get {
return bytes.IsReadOnly;
}
}
public ByteStreamList(IList<byte> bytes)
{
this.bytes = bytes;
}
public void Add(byte item)
{
if (!(bytes is IReadOnlyList<byte>)) {
bytes.Add(item);
}
}
public void Clear()
{
if (!(bytes is IReadOnlyList<byte>)) {
bytes.Clear();
}
}
public bool Contains(byte item)
{
if (!(bytes is IReadOnlyList<byte>)) {
return bytes.Contains(item);
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43543,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, classes, wrapper",
"url": null
} |
c#, classes, wrapper
return false;
}
// ... rest of IList<byte> and IEnumerable<byte> interface ///
}
namespace Test_CA
{
public class Program
{
public static void Main(string[] args)
{
ByteStreamList fixedLengthByteList = new ByteStreamList(new byte[] { 0xAA, 0xBB, 0xCC });
ByteStreamList variableLengthByteList = new ByteStreamList(new List<byte>() { 0xDD, 0xEE, 0xFF });
}
}
}
With that approach (using IList<> class) I would need to provide some access to byte stream via IList<> methods. So I could let my wrapper class implement IList<>. That approach forces me to check if underlying "list" class is IReadOnlyList or not. If not, methods like Add() Clear() would be allowed. I know it is very bad approach to use List<> because if something will require that type I will not pass any other list/container except List<> .
Is it good approach with checking everytime if "list" is readonly? | {
"domain": "codereview.stackexchange",
"id": 43543,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, classes, wrapper",
"url": null
} |
c#, classes, wrapper
Answer: I would think you would rather use the IList.IsFixedSize property concerning Add, Clear, Remove, or RemoveAt actions.
Your indexer logic seems lacking. Granted you could make a custom exception for an out-of-range index, but it will be thrown anyway. More to my point and to align with your stated objective, the indexer setter is where you would want to check IsReadOnly.
I would also encourage you to add more constructors, specifically at least one for IEnumerable<byte> as an input parameter, but you may want the constructor to include bool parameters for IsReadOnly and IsFixedSize. As you have it know accepting only another IList as input, you retain the properties of that input. If you were to accomodate IEnumerable<byte> as input, you may want to allow the caller to the constructor to declare the intentions for IsReadOnly and IsFixedSize.
Consider this possible signature:
public ByteStreamList(IEnumerable<byte> bytes, bool isReadOnly, bool isFixedSize)
This poses a challenge of what if someone calls this with an IList with different properties than what is passed in the constructor? What if they pass in a fixed-size, read-only IList with:
var sbl = new ByteStreamList(fixedSizeReadOnlyIList, false, false);
The constructor would have to compose the underlying bytes accordingly and not just simply assign fixedSizeReadOnlyIList to bytes. Could be a fun challenge. | {
"domain": "codereview.stackexchange",
"id": 43543,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, classes, wrapper",
"url": null
} |
javascript, linked-list
Title: Doubly Linked List with forward and reverse iterators (javascript)
Question: A doubly linked list contains elements that include pointers to the previous and next element along with a value. Being able to search and iterate through the list in both directions is an important feature.
This is my improvement over the previous version. I implemented it with classes, added a forward and reverse iterator, added a reverse search, and made reading at an index faster by starting at the end if the index is after the middle of the list.
I am looking for any advice on how this can be improved, both from a style and from a data structure perspective. If there are mistakes, or any redundant code, please tell me about it.
class ListElement {
constructor(value, prev, next) {
this.value = value;
this.prev = prev;
this.next = next;
}
}
class DoublyLinkedList {
#size;
#head;
#tail;
constructor() {
this.#size = 0;
this.#head = undefined;
this.#tail = undefined;
}
#getListElement(index) {
if (index < 0 || index >= this.#size) return undefined;
let currentElement;
if (index < Math.floor(this.#size / 2)) {
currentElement = this.#head;
for (let step = 0; step < index; ++step) {
currentElement = currentElement.next;
}
} else {
currentElement = this.#tail;
for (let step = this.#size - 1; step > index; --step) {
currentElement = currentElement.prev;
}
}
return currentElement;
}
#insertBefore(element, value) {
const newListElement = new ListElement(value, element.prev, element);
if (element.prev) element.prev.next = newListElement;
else this.#head = newListElement;
element.prev = newListElement;
++this.#size;
}
#insertAfter(element, value) {
const newListElement = new ListElement(value, element, element.next);
if (element.next) element.next.prev = newListElement;
else this.#tail = newListElement; | {
"domain": "codereview.stackexchange",
"id": 43544,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, linked-list",
"url": null
} |
javascript, linked-list
if (element.next) element.next.prev = newListElement;
else this.#tail = newListElement;
element.next = newListElement;
++this.#size;
}
size() {
return this.#size;
}
empty() {
let currentElement = this.#head;
for (let step = 0; step < this.#size; ++step) {
if (currentElement.prev) currentElement.prev.next = undefined;
currentElement.value = currentElement.prev = undefined;
currentElement = currentElement.next;
}
this.#head = this.#tail = undefined;
this.#size = 0;
}
append(value) {
if (this.#size === 0) {
this.#head = this.#tail = new ListElement(value, undefined, undefined);
this.#size = 1;
return;
}
this.#insertAfter(this.#tail, value);
}
prepend(value) {
if (this.#size === 0) return this.append(value);
this.#insertBefore(this.#head, value);
}
headFind(value) {
let currentElement = this.#head;
for (let step = 0; step < this.#size; ++step) {
if (currentElement.value === value) return step;
currentElement = currentElement.next;
}
return -1;
}
tailFind(value) {
let currentElement = this.#tail;
for (let step = this.#size - 1; step >= 0; --step) {
if (currentElement.value === value) return step;
currentElement = currentElement.prev;
}
return -1;
}
read(index) {
return this.#getListElement(index)?.value;
}
insert(index, value) {
if (index < 0 || index > this.#size) return false;
if (index === this.#size) {
this.append(value);
return true;
}
this.#insertBefore(this.#getListElement(index), value);
return true;
}
remove(index) {
const element = this.#getListElement(index);
if (!element) return undefined;
if (element.prev) element.prev.next = element.next;
else {
this.#head = element.next;
this.#head.prev = undefined;
} | {
"domain": "codereview.stackexchange",
"id": 43544,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, linked-list",
"url": null
} |
javascript, linked-list
if (element.next) element.next.prev = element.prev;
else {
this.#tail = element.prev;
this.#tail.next = undefined;
}
--this.#size;
return element.v;
}
[Symbol.iterator]() {
let currentElement = this.#head;
return {
next: () => {
if (currentElement) {
const currentValue = currentElement.value;
currentElement = currentElement.next;
return { value: currentValue, done: false };
} else {
return { done: true };
}
},
};
}
reverse() {
return {
[Symbol.iterator]: () => {
let currentElement = this.#tail;
return {
next: () => {
if (currentElement) {
const currentValue = currentElement.value;
currentElement = currentElement.prev;
return { value: currentValue, done: false };
} else {
return { done: true };
}
},
};
},
};
}
}
Some test code to see it in action:
const list = new DoublyLinkedList();
list.append(20);
list.append(30);
list.append(40);
list.append(50);
list.insert(1, 5);
list.insert(3, 6);
list.insert(6, 7);
list.prepend(10);
for (let element of list) {
console.log(element);
}
console.log();
list.remove(list.size() - 1);
list.remove(list.size() - 2);
list.remove(0);
for (let element of list) {
console.log(element);
}
console.log();
console.log(list.tailFind(7));
console.log(list.headFind(5));
console.log(list.read(1));
console.log(list.read(list.size() - 2));
Answer: Very nice! A couple things:
Linked lists don't only optimize removing a single element, they are equally efficient at removing spans of elements by only detaching them at the ends. Thus, empty() can be greatly simplified to:
empty() {
this.#head = this.#tail = undefined;
this.#size = 0;
} | {
"domain": "codereview.stackexchange",
"id": 43544,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, linked-list",
"url": null
} |
javascript, linked-list
Though I wonder if your current implementation might be easier on the garbage collector... Not worth thinking about.
Since you have iterators now, you can use them to minorly simplify your other code:
headFind(value) {
let step = 0;
for (const e of this) {
if (e === value) return step;
++step;
}
return -1;
}
tailFind(value) {
let step = this.#size - 1;
for (const e of this.reverse()) {
if (e === value) return step;
--step;
}
return -1;
}
Writing iterators manually is a pain. That's one reason why the schmucks at JavaScript HQ gave us generator functions! They let you write iterators like normal code; When .next() is called, the generator code will run until it reaches a yield statement, at which point .next() will return whatever you gave to the statement. But when .next() is called again, the generator code will continue right where it left off!
// The asterisk * before the function makes it a generator function:
*[Symbol.iterator]() {
for (let current = this.#head; current; current = current.next) {
yield current.value; // Generator will pause until the next call to next()
}
}
*reverse() {
for (let current = this.#tail; current; current = current.prev) {
yield current.value;
}
}
Your iterators are relatively simple, but manual iterators get gross quickly if you need to do something advanced.
Besides that, here're a couple neutral notes: | {
"domain": "codereview.stackexchange",
"id": 43544,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, linked-list",
"url": null
} |
javascript, linked-list
My original suggestion for remove() worked properly, but your version's redundant assignments to undefined might in fact make the code more readable. Wicked!
I want to confirm that you understand the difference between size() and get size(). Ultimately, it's up to you if you want to use a method instead of a getter for your API.
Your test code at the end doesn't cover all your functions, nor does it test edge cases. This isn't really important since you're just mucking around, but this is a good place to practice unit tests. Things like "does prepend()/append() work when the list is empty?", "can I insert() into an empty list properly?" and so on. | {
"domain": "codereview.stackexchange",
"id": 43544,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, linked-list",
"url": null
} |
c, parsing, functional-programming
Title: Commented Parser Combinators in Lisp-style C
Question: I've attempted to remedy the issues outlined in the answer to my previous question. I've added several hundred blank lines to better illustrate the grouping of functions and generally make things look less dense. I've trimmed all the lines to 80 columns except for one 83 character line in ppnarg.h which was inside the original author's comment, so I chose not to alter that. I've added forward declarations for all the static functions inside the .c files so all the static "helper functions" can be placed below the non-static function that uses them, so the implementation can be presented in a more top down fashion overall. I've added a description of every API function next to its declaration in the .h file, and comments in the .c files explaining design decisions that are important for understanding the implementation.
github
README.md
omitted for size
Makefile
CFLAGS= -std=c99 -g -Wall -Wpedantic -Wextra -Wno-unused-function -Wno-unused-parameter -Wno-switch -Wno-return-type -Wunused-variable
CFLAGS+= $(cflags)
test : pc11test
./$<
pc11test : pc11object.o pc11parser.o pc11io.o pc11test.o
$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
pc11object.o : pc11object.[ch]
pc11parser.o : pc11parser.[ch] pc11object.h
pc11io.o : pc11io.[ch] pc11object.h pc11parser.h
pc11test.o : pc11test.[ch] pc11object.h pc11parser.h pc11io.h
clean :
rm *.o pc11test.exe
count :
wc -l -c -L pc11*[ch] ppnarg.h
cloc pc11*[ch] ppnarg.h
ppnarg.h
omitted for size
pc11object.h
#define PC11OBJECT_H
#include <stdlib.h>
#include <stdio.h>
#if ! PPNARG_H
#include "ppnarg.h"
#endif
/* Variant subtypes of object,
and signatures for function object functions */
#define IS_THE_TARGET_OF_THE_HIDDEN_POINTER_ *
typedef union object IS_THE_TARGET_OF_THE_HIDDEN_POINTER_ object;
typedef object integer;
typedef object list;
typedef object symbol;
typedef object string;
typedef object boolean; | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
typedef object suspension;
typedef object parser;
typedef object operator;
typedef operator predicate;
typedef operator binoperator;
typedef object fSuspension( object env );
typedef object fParser( object env, list input );
typedef object fOperator( object env, object input );
typedef boolean fPredicate( object env, object input );
typedef object fBinOperator( object left, object right );
typedef enum {
INVALID,
INT,
LIST,
SYMBOL,
STRING,
VOID,
SUSPENSION,
PARSER,
OPERATOR,
END_TAGS
} tag;
enum object_symbol_codes {
T,
END_OBJECT_SYMBOLS
};
struct integer {
tag t;
int i;
};
struct list {
tag t;
object first, rest;
};
struct symbol {
tag t;
int code;
const char *printname;
object data;
};
struct string {
tag t;
char *str;
int disposable;
};
struct void_ {
tag t;
void *pointer;
};
struct suspension {
tag t;
object env;
fSuspension *f;
const char *printname;
};
struct parser {
tag t;
object env;
fParser *f;
const char *printname;
};
struct operator {
tag t;
object env;
fOperator *f;
const char *printname;
};
struct header {
int mark;
object next;
int forward;
};
union object {
tag t;
struct integer Int;
struct list List;
struct symbol Symbol;
struct string String;
struct void_ Void;
struct suspension Suspension;
struct parser Parser;
struct operator Operator;
struct header Header;
};
/* Global true/false objects. */
extern object NIL_; /* .t == INVALID */
extern symbol T_;
/* Determine if object is non-NULL and non-NIL.
Will also convert a boolean T_ or NIL_ to an integer 1 or 0.
*/
static int
valid( object it ){
return it
&& it->t < END_TAGS
&& it->t != INVALID;
}
/* Constructors */
integer Int( int i );
boolean Boolean( int b );
string String( char *str, int disposable );
object Void( void *pointer );
/* List of one element */
list one( object it ); | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
object Void( void *pointer );
/* List of one element */
list one( object it );
/* Join two elements togther. If rest is a list or NIL_, result is a list. */
list cons( object first, object rest );
/* Join N elements together in a list */
#define LIST(...) \
reduce( cons, PP_NARG(__VA_ARGS__), (object[]){ __VA_ARGS__ } )
/* Macros capture printnames automatically for these constructors */
#define Symbol( n ) \
Symbol_( n, #n, NIL_ )
symbol Symbol_( int code, const char *printname, object data );
#define Suspension( env, f ) \
Suspension_( env, f, __func__ )
suspension Suspension_( object env, fSuspension *f, const char *printname );
#define Parser( env, f ) \
Parser_( env, f, __func__ )
parser Parser_( object env, fParser *f, const char *printname );
#define Operator( env, f ) \
Operator_( env, f, #f )
operator Operator_( object env, fOperator *f, const char *printname );
/* Printing */
/* Print list with dot notation or any object */
void print( object a );
/* Print list with list notation or any object */
void print_list( object a );
/* Functions over lists */
/* car */
object first( list it );
/* cdr */
list rest( list it );
/* Length of list */
int length( list ls );
/* Force n elements from the front of (lazy?) list */
list take( int n,
list it );
/* Skip ahead n elements in (lazy?) list */
list drop( int n,
list it );
/* Index a (lazy?) list */
object nth( int n,
list it );
/* Apply operator to (lazy?) object */
object apply( operator op,
object it );
/* Produce lazy lists */
list infinite( object mother );
list chars_from_str( char *str );
list chars_from_file( FILE *file );
/* Lazy list adapters */
list ucs4_from_utf8( list o );
list utf8_from_ucs4( list o );
/* Maps and folds */
/* Transform each element of list with operator; yield new list. */ | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
/* Maps and folds */
/* Transform each element of list with operator; yield new list. */
list map( operator op,
list it );
/* Fold right-to-left over list with f */
object collapse( fBinOperator *f,
list it );
/* Fold right-to-left over array of objects with f */
object reduce( fBinOperator *f,
int n,
object *po );
/* Comparisons and Association Lists (Environments) */
/* Compare for equality. For symbols, just compare codes. */
boolean eq( object a,
object b );
/* Call eq, but avoid the need to allocate a Symbol object */
boolean eq_symbol( int code,
object b );
/* Return copy of start sharing end */
list append( list start,
list end );
/* Prepend n (key . value) pairs to tail */
list env( list tail,
int n, ... );
/* Return value associated with key */
object assoc( object key,
list env );
/* Call assoc, but avoid the need to allocate a Symbol object */
object assoc_symbol( int code,
list env );
/* Conversions */
/* Copy integers and strings into *str. modifies caller supplied pointer */
void fill_string( char **str,
list it );
/* Convert integers and strings from list into a string */
string to_string( list ls );
/* Dynamically create a symbol object corresponding to printname s.
Scans the list of allocations linearly to find a matching printname.
Failing that, it allocates a new symbol code from the space [-2,-inf). */
symbol symbol_from_string( string s );
/* That one lone function without a category to group it in. */
/* Report (an analogue of) memory usage.
By current measure, an allocation is 64 bytes,
ie. 2x 32 byte union objects. */
int count_allocations( void );
pc11object.c
#define _BSD_SOURCE
#include "pc11object.h"
#include <stdarg.h>
#include <string.h>
static void print_listn( object a );
static int leading_ones( object byte );
static int mask_off( object byte, int m ); | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static fSuspension force_first;
static fSuspension force_rest;
static fSuspension force_apply;
fSuspension infinite;
static fSuspension force_chars_from_string;
static fSuspension force_chars_from_file;
static fSuspension force_ucs4_from_utf8;
static fSuspension force_utf8_from_ucs4;
fBinOperator map;
fBinOperator eq;
fBinOperator append;
fBinOperator assoc;
/* Helper macro for constructor functions. */
#define OBJECT(...) new_( (union object[]){{ __VA_ARGS__ }} )
/* Flags controlling print(). */
static int print_innards = 1;
static int print_chars = 1;
static int print_codes = 0;
/* Define simple objects T_ and NIL_, the components of our boolean type. */
static union object nil_object = { .t=INVALID };
object NIL_ = & nil_object;
object T_ = 1 + (union object[]){ {.Header={1}},
{.Symbol={SYMBOL, T, "T", & nil_object}} };
/* Allocation function is defined at the end of this file with
its file scoped data protected from the vast majority of
other functions here. */
static object new_( object prototype );
integer
Int( int i ){
return OBJECT( .Int = { INT, i } );
}
boolean
Boolean( int b ){
return b ? T_ : NIL_;
}
string
String( char *str, int disposable ){
return OBJECT( .String = { STRING, str, disposable } );
}
object
Void( void *pointer ){
return OBJECT( .Void = { VOID, pointer } );
}
list
one( object it ){
return cons( it, NIL_ );
}
list
cons( object first, object rest ){
return OBJECT( .List = { LIST, first, rest } );
}
symbol
Symbol_( int code, const char *printname, object data ){
return OBJECT( .Symbol = { SYMBOL, code, printname, data } );
}
suspension
Suspension_( object env, fSuspension *f, const char *printname ){
return OBJECT( .Suspension = { SUSPENSION, env, f, printname } );
}
parser
Parser_( object env, fParser *f, const char *printname ){
return OBJECT( .Parser = { PARSER, env, f, printname } );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
operator
Operator_( object env, fOperator *f, const char *printname ){
return OBJECT( .Operator = { OPERATOR, env, f, printname } );
}
void
print( object a ){
switch( a ? a->t : 0 ){
default: printf( "() " ); break;
case INT: printf( print_chars ? "'%c' " : "%d ", a->Int.i ); break;
case LIST: printf( "(" ), print( a->List.first ), printf( "." ),
print( a->List.rest ), printf( ")" ); break;
case SUSPENSION: printf( "...(%s) ", a->Suspension.printname ); break;
case PARSER: printf( "Parser(%s", a->Parser.printname ),
(print_innards & ! a[-1].Header.forward) &&
(printf( ", " ), print( a->Parser.env ),0),
printf( ") " ); break;
case OPERATOR: printf( "Oper(%s", a->Operator.printname ),
printf( ", " ), print( a->Operator.env ),
printf( ") " ); break;
case STRING: printf( "\"%s\" ", a->String.str ); break;
case SYMBOL: if( print_codes )
printf( "%d:%s ", a->Symbol.code, a->Symbol.printname );
else
printf( "%s ", a->Symbol.printname );
break;
case VOID: printf( "VOID " ); break;
}
}
void
print_list( object a ){
switch( a ? a->t : 0 ){
default: print( a ); break;
case LIST: printf( "(" ), print_list( first( a ) ),
print_listn( rest( a ) ), printf( ") " ); break;
}
}
static void
print_listn( object a ){
if( ! valid( a ) ) return;
switch( a->t ){
default: print( a ); break;
case LIST: print_list( first( a ) ),
print_listn( rest( a ) ); break;
}
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
/* force_() executes a suspension function to instantiate and yield
a value. It may unwrap many layers of suspended operations to shake
off any laziness at the front of a list or resolve a lazy calculation
down to its result.
In order to simulate the feature of lazy evaluation that a lazy
list will manifest its elements "in place", the resulting object
from force_() must be overwritten over the representation of the
suspension object to provide the illusion that the list magically
manifests for all handles to that part of the list.
Consequently, force_() is declared static to this file and it is
exclusively used in the stereotyped form:
*it = *force_( it );
Functions outside of this module requiring the forced execution
of a potential suspension must use side effect of take() or drop().
Eg. drop( 1, it ) will transform a suspended calculation into its
actual resulting value. If it is a lazy list, this will manifest
the list node with a new suspension as the rest().
*/
static object
force_( object it ){
if( it->t != SUSPENSION ) return it;
return force_( it->Suspension.f( it->Suspension.env ) );
}
object first( list it ){
if( it->t == SUSPENSION ) return Suspension( it, force_first );
if( it->t != LIST ) return NIL_;
return it->List.first;
}
static object force_first ( object it ){
*it = *force_( it );
return first( it );
}
object rest( list it ){
if( it->t == SUSPENSION ) return Suspension( it, force_rest );
if( it->t != LIST ) return NIL_;
return it->List.rest;
}
static object force_rest ( object it ){
*it = *force_( it );
return rest( it );
}
int
length( list ls ){
return valid( ls ) ? valid( first( ls ) ) + length( rest( ls ) ) : 0;
}
list
take( int n, list it ){
if( n == 0 ) return NIL_;
*it = *force_( it );
if( ! valid( it ) ) return NIL_;
return cons( first( it ), take( n-1, rest( it ) ) );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
list
drop( int n, list it ){
if( n == 0 ) return it;
*it = *force_( it );
if( ! valid( it ) ) return NIL_;
return drop( n-1, rest( it ) );
}
object nth( int n, list it ){
return first( take( 1, drop( n-1, it ) ) );
}
object
apply( operator op, object it ){
if( it->t == SUSPENSION )
return Suspension( cons( op, it ), force_apply );
return op->Operator.f( op->Operator.env, it );
}
static object
force_apply( list env ){
operator op = first( env );
object it = rest( env );
*it = *force_( it );
return apply( op, it );
}
list
infinite( object mother ){
return cons( mother, Suspension( mother, infinite ) );
}
list
chars_from_str( char *str ){
if( ! str ) return NIL_;
return Suspension( String( str, 0 ), force_chars_from_string );
}
static list
force_chars_from_string( string s ){
char *str = s->String.str;
if( ! *str ) return one( Symbol( EOF ) );
return cons( Int( *str ),
Suspension( String( str+1, 0 ), force_chars_from_string ) );
}
list
chars_from_file( FILE *file ){
if( ! file ) return NIL_;
return Suspension( Void( file ), force_chars_from_file );
}
static list
force_chars_from_file( object file ){
FILE *f = file->Void.pointer;
int c = fgetc( f );
if( c == EOF ) return one( Symbol( EOF ) );
return cons( Int( c ), Suspension( file, force_chars_from_file ) );
}
/* UCS4 <=> UTF8 */
list
ucs4_from_utf8( list input ){
if( ! input ) return NIL_;
return Suspension( input, force_ucs4_from_utf8 );
}
list
utf8_from_ucs4( list input ){
if( ! input ) return NIL_;
return Suspension( input, force_utf8_from_ucs4 );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static list
force_ucs4_from_utf8( list input ){
*input = *force_( input );
object byte;
byte = first( input ), input = rest( input );
if( !valid(byte) ) return NIL_;
if( eq_symbol( EOF, byte ) ) return input;
int ones = leading_ones( byte );
int bits = mask_off( byte, ones );
int n = ones;
while( n-- > 1 ){
*input = *force_( input );
byte = first( input ), input = rest( input );
if( eq_symbol( EOF, byte ) ) return input;
bits = ( bits << 6 ) | ( byte->Int.i & 0x3f );
}
if( bits < ((int[]){0,0,0x80,0x800,0x10000,0x110000,0x4000000})[ ones ] )
fprintf( stderr, "Overlength encoding in utf8 char.\n" );
return cons( Int( bits ), Suspension( input, force_ucs4_from_utf8 ) );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static list
force_utf8_from_ucs4( list input ){
*input = *force_( input );
object code = first( input );
if( eq_symbol( EOF, code ) ) return input;
int x = code->Int.i;
object next = Suspension( drop( 1, input ), force_utf8_from_ucs4 );
if( x <= 0x7f )
return cons( code, next );
if( x <= 0x7ff )
return LIST( Int( (x >> 6) | 0xc0 ),
Int( (x & 0x3f) | 0x80 ), next );
if( x <= 0xffff )
return LIST( Int( (x >> 12) | 0xe0 ),
Int( ( (x >> 6) & 0x3f ) | 0x80 ),
Int( ( x & 0x3f ) | 0x80 ), next );
if( x <= 0x10ffff )
return LIST( Int( (x >> 18) | 0xf0 ),
Int( ( (x >> 12) & 0x3f ) | 0x80 ),
Int( ( (x >> 6) & 0x3f ) | 0x80 ),
Int( ( x & 0x3f ) | 0x80 ), next );
if( x <= 0x3ffffff )
return LIST( Int( (x >> 24) | 0xf8 ),
Int( ( (x >> 18) & 0x3f ) | 0x80 ),
Int( ( (x >> 12) & 0x3f ) | 0x80 ),
Int( ( (x >> 6) & 0x3f ) | 0x80 ),
Int( ( x & 0x3f ) | 0x80 ), next );
if( x <= 0x3fffffff )
return LIST( Int( (x >> 30) | 0xfc ),
Int( ( (x >> 24) & 0x3f ) | 0x80 ),
Int( ( (x >> 18) & 0x3f ) | 0x80 ),
Int( ( (x >> 12) & 0x3f ) | 0x80 ),
Int( ( (x >> 6) & 0x3f ) | 0x80 ),
Int( ( x & 0x3f ) | 0x80 ), next );
fprintf( stderr, "Invalid unicode code point in ucs4 char.\n" );
return next;
}
static int
leading_ones( object byte ){
if( byte->t != INT ) return 0;
int x = byte->Int.i;
return x&0200 ? x&0100 ? x&040 ? x&020 ? x&010 ? x&4 ? 6
: 5
: 4
: 3
: 2
: 1
: 0;
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static int
mask_off( object byte, int m ){
if( byte->t != INT ) return 0;
int x = byte->Int.i;
return x & (m ? (1<<(8-m))-1 : -1);
}
list
map( operator op, list it ){
if( ! valid( it ) ) return it;
return cons( apply( op, first( it ) ),
map( op, rest( it ) ) );
}
object
collapse( fBinOperator *f, list it ){
if( !valid( it ) ) return it;
object right = collapse( f, rest( it ) );
if( !valid( right ) ) return first( it );
return f( first( it ), right );
}
object
reduce( fBinOperator *f, int n, object *po ){
return n==1 ? *po : f( *po, reduce( f, n-1, po+1 ) );
}
boolean
eq( object a, object b ){
return Boolean(
!valid( a ) && !valid( b ) ? 1 :
!valid( a ) || !valid( b ) ? 0 :
a->t != b->t ? 0 :
a->t == SYMBOL ? a->Symbol.code == b->Symbol.code :
!memcmp( a, b, sizeof *a ) ? 1 : 0
);
}
boolean
eq_symbol( int code, object b ){
return eq( (union object[]){ {.Symbol = {SYMBOL, code, "", 0} } }, b );
}
list
append( list start, list end ){
if( ! valid( start ) ) return end;
return cons( first( start ), append( rest( start ), end ) );
}
list
env( list tail, int n, ... ){
va_list v;
va_start( v, n );
list r = tail;
while( n-- ){
object a = va_arg( v, object );
object b = va_arg( v, object );
r = cons( cons( a, b ), r );
}
va_end( v );
return r;
}
object
assoc( object key, list b ){
if( !valid( b ) ) return NIL_;
object pair = first( b );
if( valid( eq( key, first( pair ) ) ) )
return rest( pair );
else
return assoc( key, rest( b ) );
}
object
assoc_symbol( int code, list b ){
return assoc( (union object[]){ {.Symbol = {SYMBOL, code, "", 0}} }, b );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static int
string_length( object it ){
switch( it ? it->t : 0 ){
default: return 0;
case INT: return 1;
case STRING: return strlen( it->String.str );
case LIST: return string_length( first( it ) )
+ string_length( rest( it ) );
}
}
void
fill_string( char **str, list it ){
switch( it ? it->t : 0 ){
default: return;
case INT:
*(*str)++ = it->Int.i;
return;
case STRING:
strcpy( *str, it->String.str );
*str += strlen( it->String.str );
return;
case LIST:
fill_string( str, first( it ) );
fill_string( str, rest( it ) );
return;
}
}
string
to_string( list ls ){
char *str = calloc( 1 + string_length( ls ), 1 );
string s = OBJECT( .String = { STRING, str, 1 } );
fill_string( &str, ls );
return s;
}
/* The following functions are isolated to the bottom of this file
so that their static variables are protected from all other
functions in this file.
*/
/* Allocation of objects */
static list allocation_list = NULL;
static object
new_( object prototype ){
object record = calloc( 2, sizeof *record );
if( record ){
record[0] = (union object){ .Header = { 0, allocation_list } };
allocation_list = record;
record[1] = *prototype;
}
return record + 1;
}
/* Construction of dynamic symbols */
static int next_symbol_code = -2;
symbol
symbol_from_string( string s ){
list ls = allocation_list;
while( ls != NULL && valid( ls + 1 ) ){
if( ls[1].t == SYMBOL
&& strcmp( ls[1].Symbol.printname, s->String.str ) == 0 ){
return ls + 1;
}
ls = ls[0].Header.next;
}
return Symbol_( next_symbol_code--, strdup( s->String.str ), NIL_ );
}
int
count_allocations( void ){
list ls = allocation_list;
int n = 0;
while( ls != NULL && valid( ls + 1 ) ){
++n;
ls = ls->Header.next;
}
return n;
}
pc11parser.h
#define PC11PARSER_H
#if ! PC11OBJECT_H
#include "pc11object.h"
#endif | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
pc11parser.h
#define PC11PARSER_H
#if ! PC11OBJECT_H
#include "pc11object.h"
#endif
enum parser_symbol_codes {
VALUE = END_OBJECT_SYMBOLS,
OK,
FAIL,
SATISFY_PRED,
EITHER_P,
EITHER_Q,
SEQUENCE_P,
SEQUENCE_Q,
SEQUENCE_OP,
BIND_P,
BIND_OP,
INTO_P,
INTO_ID,
INTO_Q,
REGEX_ATOM,
PROBE_P,
PROBE_MODE,
EBNF_SEQ,
EBNF_ANY,
EBNF_EPSILON,
EBNF_MAYBE,
EBNF_MANY,
END_PARSER_SYMBOLS
};
/* Parse the input using parser p. */
list parse( parser p,
list input );
/* Check result from parse(). */
int is_ok( list result );
int not_ok( list result );
/* Return OK or FAIL result. */
parser succeeds( list result );
parser fails( list errormsg );
/* Emit debugging output from p.
Print on ok iff mode&1; print not ok iff mode&2. */
parser probe( parser p,
int mode );
/* The basic (leaf) parser. */
parser satisfy( predicate pred );
/* Simple parsers built with satisfy(). */
parser alpha( void );
parser upper( void );
parser lower( void );
parser digit( void );
parser literal( object example );
parser chr( int c );
parser str( char *s );
parser anyof( char *s );
parser noneof( char *s );
/* Accept any single element off the input list. */
parser item( void );
/* Choice ("OR" branches) */
/* Combine 2 parsers into a choice. */
parser either( parser p,
parser q );
/* Combine N parsers into a choice. */
#define ANY(...) \
reduce( either, \
PP_NARG(__VA_ARGS__), \
(object[]){ __VA_ARGS__ } )
/* Sequence ("AND" branches) */
/* Combine 2 parsers into a sequence,
using op to merge the value portions of results. */
parser sequence( parser p,
parser q,
binoperator op );
/* Sequence 2 parsers but drop result from first. */
parser xthen( parser x,
parser q );
/* Sequence 2 parsers but drop result from second. */
parser thenx( parser p,
parser x ); | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
/* Sequence 2 parsers but drop result from second. */
parser thenx( parser p,
parser x );
/* Sequence 2 parsers and concatenate results. */
parser then( parser p,
parser q );
/* Sequence N parsers and concatenate results. */
#define SEQ(...) \
reduce( then, \
PP_NARG(__VA_ARGS__), \
(object[]){ __VA_ARGS__ } )
/* Sequence 2 parsers, but pass result from first as a
(id.value) pair in second's env. */
parser into( parser p,
object id,
parser q );
/* Repetitions */
/* Accept 0 or 1 successful results from p. */
parser maybe( parser p );
/* Accept 0 or more successful results from p. */
parser many( parser p );
/* Accept 1 or more successful results from p. */
parser some( parser p );
/* Transform of values */
/* Process succesful result from p
by transforming the value portion with op. */
parser bind( parser p,
operator op );
/* Building recursive parsers */
/* Create an empty parser, useful for building loops.
A forward declaration of a parser. */
parser forward( void );
/* Compilers */
/* Compile a regular expression into a parser. */
// E->T ('|' T)*
// T->F*
// F->A ('*' | '+' | '?')?
// A->'.' | '('E')' | C
// C->S|L|P
// S->'\' ('.' | '|' | '(' | ')' | '[' | ']' | '/' )
// L->'[' '^'? ']'? [^]]* ']'
// P->Plain char
parser regex( char *re );
/* Compile a block of EBNF definitions into a list of
(symbol.parser) pairs. */
// D->N '=' E ';'
// N->name
// E->T ('|' T)*
// T->F*
// F->R | N | '[' E ']' | '{' E '}' | '(' E ')' | '/' regex '/'
// R->'"' [^"]* '"' | "'" [^']* "'"
list ebnf( char *productions,
list supplements,
list handlers );
pc11parser.c
#include "pc11parser.h"
#include <ctype.h>
#include <string.h>
static fParser success;
static fParser fail; | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static fParser success;
static fParser fail;
static fParser parse_satisfy;
static fPredicate is_upper;
static fPredicate is_alpha;
static fPredicate is_lower;
static fPredicate is_digit;
static fPredicate is_literal;
static fPredicate is_range;
static fPredicate is_anyof;
static fPredicate is_noneof;
static fPredicate always_true;
static fParser parse_either;
fBinOperator either;
static fParser parse_sequence;
static fBinOperator concat;
fBinOperator then;
static fBinOperator left;
static fBinOperator right;
fBinOperator xthen;
fBinOperator thenx;
static fParser parse_bind;
static fParser parse_into;
static fParser parse_probe;
static fOperator apply_meta;
static fOperator on_dot;
static fOperator on_chr;
static fOperator on_meta;
static fOperator on_class;
static fOperator on_term;
static fOperator on_expr;
static fOperator stringify;
static fOperator symbolize;
static fOperator encapsulate;
static fOperator make_matcher;
static fOperator make_sequence;
static fOperator make_any;
static fOperator make_maybe;
static fOperator make_many;
static fOperator define_forward;
static fOperator compile_bnf;
static fOperator compile_rhs;
static fOperator define_parser;
static fOperator wrap_handler;
/* Execute a parser upon an input stream by invoking its function,
supplying its env. */
list
parse( parser p, list input ){
if( !valid( p ) || !valid( input ) || p->t != PARSER )
return cons( Symbol(FAIL),
cons( String("parse() validity check failed",0),
input ) );
return p->Parser.f( p->Parser.env, input );
}
/*
The result structure from a parser is either
( OK . ( <value> . <remaining input ) )
or
( FAIL . ( <error message> . <remaining input> ) )
*/
static object
success( object result, list input ){
return cons( Symbol(OK),
cons( result,
input ) );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static object
fail( object errormsg, list input ){
return cons( Symbol(FAIL),
cons( errormsg,
input ) );
}
int
is_ok( list result ){
return valid( eq_symbol( OK, first( result ) ) );
}
int
not_ok( list result ){
return ! is_ok( result );
}
parser
succeeds( list result ){
return Parser( result, success );
}
parser
fails( list errormsg ){
return Parser( errormsg, fail );
}
/* For all of the parsers after this point, the associated parse_*()
function should be considered the "lambda" or "closure" function for
the constructed parser object.
C, of course, doesn't have lambdas. Hence these closely associated
functions are close by and have related names.
These parse_* functions receive an association list of (symbol.value)
pairs in their env parameter, and they extract their needed values
using assoc_symbol().
*/
/* The satisfy(pred) parser is the basis for all "leaf" parsers.
Importantly, it forces the first element off of the (lazy?) input
list. Therefore, all other functions that operate upon this result
of this parser need not fuss with suspensions at all. */
parser
satisfy( predicate pred ){
return Parser( env( NIL_, 1, Symbol(SATISFY_PRED), pred ), parse_satisfy );
}
static list
parse_satisfy( object env, list input ){
predicate pred = assoc_symbol( SATISFY_PRED, env );
drop( 1, input );
object item = first( input );
if( ! valid( item ) ) return fail( String( "empty input", 0 ),
input );
return valid( apply( pred, item ) )
? success( item,
rest( input ) )
: fail( LIST( String( "predicate not satisfied", 0 ), pred, NIL_ ),
input );
}
parser item( void ){
return satisfy( Operator( NIL_, always_true ) );
}
boolean
always_true( object v, object it ){
return T_;
}
parser
alpha( void ){
return satisfy( Operator( NIL_, is_alpha ) );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
parser
alpha( void ){
return satisfy( Operator( NIL_, is_alpha ) );
}
static boolean
is_alpha( object v, object it ){
return Boolean( it->t == INT && isalpha( it->Int.i ) );
}
parser
upper( void ){
return satisfy( Operator( NIL_, is_upper ) );
}
static boolean
is_upper( object v, object it ){
return Boolean( it->t == INT && isupper( it->Int.i ) );
}
parser
lower( void ){
return satisfy( Operator( NIL_, is_lower ) );
}
static boolean
is_lower( object v, object it ){
return Boolean( it->t == INT && islower( it->Int.i ) );
}
parser
digit( void ){
return satisfy( Operator( NIL_, is_digit ) );
}
static boolean
is_digit( object v, object it ){
return Boolean( it->t == INT && isdigit( it->Int.i ) );
}
parser
literal( object example ){
return satisfy( Operator( example, is_literal ) );
}
static boolean
is_literal( object example, object it ){
return eq( example, it );
}
parser
chr( int c ){
return literal( Int( c ) );
}
parser
str( char *s ){
return !*s ? succeeds( NIL_ )
: !s[1] ? chr( *s )
: then( chr( *s ), str( s+1 ) );
}
parser
range( int lo, int hi ){
return satisfy( Operator( cons( Int( lo ), Int( hi ) ), is_range ) );
}
static boolean
is_range( object bounds, object it ){
int lo = first( bounds )->Int.i,
hi = rest( bounds )->Int.i;
return Boolean( it->t == INT && lo <= it->Int.i && it->Int.i <= hi );
}
parser
anyof( char *s ){
return satisfy( Operator( String( s, 0 ), is_anyof ) );
}
static boolean
is_anyof( object set, object it ){
return Boolean( it->t == INT && strchr( set->String.str, it->Int.i ) );
}
parser
noneof( char *s ){
return satisfy( Operator( String( s, 0 ), is_noneof ) );
}
static boolean
is_noneof( object set, object it ){
return Boolean( it->t == INT && ! strchr( set->String.str, it->Int.i ) );
}
/* The choice combinator. Result is success if either p or q succeed.
Short circuits q if p was successful. Not lazy. */ | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
parser
either( parser p, parser q ){
return Parser( env( NIL_, 2,
Symbol(EITHER_Q), q,
Symbol(EITHER_P), p ),
parse_either );
}
static object
parse_either( object env, list input ){
parser p = assoc_symbol( EITHER_P, env );
object result = parse( p, input );
if( is_ok( result ) ) return result;
parser q = assoc_symbol( EITHER_Q, env );
return parse( q, input );
}
/* Sequence 2 parsers and join the 2 results using a binary operator.
By parameterizing this "joining" operator, this parser supports
then(), thenx() and xthen() while being completely agnostic as to
how joining might or might not be done.
*/
parser
sequence( parser p, parser q, binoperator op ){
return Parser( env( NIL_, 3,
Symbol(SEQUENCE_OP), op,
Symbol(SEQUENCE_Q), q,
Symbol(SEQUENCE_P), p ),
parse_sequence );
}
static object
parse_sequence( object env, list input ){
parser p = assoc_symbol( SEQUENCE_P, env );
object p_result = parse( p, input );
if( not_ok( p_result ) ) return p_result;
parser q = assoc_symbol( SEQUENCE_Q, env );
list remainder = rest( rest( p_result ) );
object q_result = parse( q, remainder );
if( not_ok( q_result ) ){
object q_error = first( rest( q_result ) );
object q_remainder = rest( rest( q_result ) );
return fail( LIST( q_error, String( "after", 0),
first( rest( p_result ) ), NIL_ ),
q_remainder );
}
binoperator op = assoc_symbol( SEQUENCE_OP, env );
return success( op->Operator.f( first( rest( p_result ) ),
first( rest( q_result ) ) ),
rest( rest( q_result ) ) );
}
parser
then( parser p, parser q ){
return sequence( p, q, Operator( NIL_, concat ) );
}
parser
xthen( parser x, parser q ){
return sequence( x, q, Operator( NIL_, right ) );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
parser
xthen( parser x, parser q ){
return sequence( x, q, Operator( NIL_, right ) );
}
parser
thenx( parser p, parser x ){
return sequence( p, x, Operator( NIL_, left ) );
}
/* Some hacking and heuristics to massage 2 objects together into a list,
taking care if either is already a list */
static object
concat( object l, object r ){
if( ! valid( l ) ) return r;
if( r->t == LIST
&& valid( eq_symbol( VALUE, first( first( r ) ) ) )
&& ! valid( rest( r ) )
&& ! valid( rest( first( r ) ) ) )
return l;
switch( l->t ){
case LIST: return cons( first( l ), concat( rest( l ), r ) );
default: return cons( l, r );
}
}
static object
right( object l, object r ){
return r;
}
static object
left( object l, object r ){
return l;
}
/* Sequence parsers p and q, but define the value portion of the result of p
(if successful) as (id.value) in the env of q.
*/
parser
into( parser p, object id, parser q ){
return Parser( env( NIL_, 3,
Symbol(INTO_P), p,
Symbol(INTO_ID), id,
Symbol(INTO_Q), q ),
parse_into );
}
static object
parse_into( object v, list input ){
parser p = assoc_symbol( INTO_P, v );
object p_result = parse( p, input );
if( not_ok( p_result ) ) return p_result;
object id = assoc_symbol( INTO_ID, v );
parser q = assoc_symbol( INTO_Q, v );
object q_result = q->Parser.f( env( q->Parser.env, 1,
id, first( rest( p_result ) ) ),
rest( rest( p_result ) ) );
if( not_ok( q_result ) ){
object q_error = first( rest( q_result ) );
object q_remainder = rest( rest( q_result ) );
return fail( LIST( q_error, String( "after", 0),
first( rest( p_result ) ), NIL_ ),
q_remainder );
}
return q_result;
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
/* If the parser p succeeds, great! return its result.
If not, who cares?! call it a success, but give a nothing value.
If this parser is composed using then(), the merging of values will
simply ignore this nothing value. It just disappears.
If you bind() this parser to an operator, the operator can test
if valid( input ) to tell whether p succeeded (and yielded a value)
or not (which yielded NIL).
*/
parser
maybe( parser p ){
return either( p, succeeds( NIL_ ) );
}
/* Uses a forward() to build an infinite sequence of maybe(p). */
parser
many( parser p ){
parser q = forward();
*q = *maybe( then( p, q ) );
return q;
}
parser
some( parser p ){
return then( p, many( p ) );
}
/* Bind transforms a succesful result from the child parser
through the operator. The operator's environment is supplemented
with the environment passed to bind itself.
*/
parser
bind( parser p, operator op ){
return Parser( env( NIL_, 2,
Symbol(BIND_P), p,
Symbol(BIND_OP), op ),
parse_bind );
}
static object
parse_bind( object env, list input ){
parser p = assoc_symbol( BIND_P, env );
operator op = assoc_symbol( BIND_OP, env );
object result = parse( p, input );
if( not_ok( result ) ) return result;
object payload = rest( result ),
value = first( payload ),
remainder = rest( payload );
return success( apply( (union object[]){{.Operator={
OPERATOR,
append(op->Operator.env, env),
op->Operator.f,
op->Operator.printname
}}}, value ), remainder );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
/* Construct a forwarding parser to aid building of loops.
This parser can be composed with other parsers.
Later, the higher level composed parser can be copied over this object
to create the point of recursion in the parser graph.
Remembers the fact that it was created as a forward
by storing a flag in the hidden allocation record for the parser.
This flag is not altered by overwriting the parser's normal union object.
*/
parser
forward( void ){
parser p = Parser( 0, 0 );
p[-1].Header.forward = 1;
return p;
}
parser
probe( parser p, int mode ){
return Parser( env( NIL_, 2,
Symbol(PROBE_MODE), Int( mode ),
Symbol(PROBE_P), p ),
parse_probe );
}
static object
parse_probe( object env, object input ){
parser p = assoc_symbol( PROBE_P, env );
int mode = assoc_symbol( PROBE_MODE, env )->Int.i;
object result = parse( p, input );
if( is_ok( result ) && mode&1 )
print( result ), puts("");
else if( not_ok( result ) && mode&2 )
print_list( result ), puts("");
return result;
}
/* Regex compiler */
static parser regex_grammar( void );
static parser regex_parser;
parser
regex( char *re ){
if( !regex_parser ) regex_parser = regex_grammar();
object result = parse( regex_parser, chars_from_str( re ) );
if( not_ok( result ) ) return result;
return first( rest( result ) );
}
#define META "*+?"
#define SPECIAL META ".|()[]/" | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
#define META "*+?"
#define SPECIAL META ".|()[]/"
static parser
regex_grammar( void ){
parser dot = bind( chr('.'), Operator( NIL_, on_dot ) );
parser meta = anyof( META );
parser escape = xthen( chr('\\'), anyof( SPECIAL "\\" ) );
parser class = xthen( chr('['),
thenx( SEQ( maybe( chr('^') ),
maybe( chr(']') ),
many( noneof( "]" ) ) ),
chr(']') ) );
parser character = ANY( bind( escape, Operator( NIL_, on_chr ) ),
bind( class, Operator( NIL_, on_class ) ),
bind( noneof( SPECIAL ), Operator( NIL_, on_chr ) ) );
parser expr = forward();
{
parser atom = ANY( dot,
xthen( chr('('), thenx( expr, chr(')') ) ),
character );
parser factor = into( atom, Symbol(REGEX_ATOM),
bind( maybe( meta ),
Operator( NIL_, on_meta ) ) );
parser term = bind( many( factor ),
Operator( NIL_, on_term ) );
*expr = *bind( then( term, many( xthen( chr('|'), term ) ) ),
Operator( NIL_, on_expr ) );
}
return expr;
}
/* syntax directed compilation to parser */
static parser
apply_meta( parser a, object it ){
switch( it->Int.i ){
default: return a;
case '*': return many( a );
case '+': return some( a );
case '?': return maybe( a );
}
}
static parser
on_dot( object v, object it ){
return item();
}
static parser
on_chr( object v, object it ){
return literal( it );
}
static parser
on_meta( object v, object it ){
parser atom = assoc_symbol( REGEX_ATOM, v );
if( it->t == LIST
&& valid( eq_symbol( VALUE, first( first( it ) ) ) )
&& ! valid( rest( it ) )
&& ! valid( rest( rest( it ) ) ) )
return atom;
return apply_meta( atom, it );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static parser
on_class( object v, object it ){
if( first( it )->Int.i == '^' )
return satisfy( Operator( to_string( rest( it ) ), is_noneof ) );
return satisfy( Operator( to_string( it ), is_anyof ) );
}
static parser
on_term( object v, object it ){
if( ! valid( it ) ) return NIL_;
if( it->t == LIST && ! valid( rest( it ) ) ) it = first( it );
if( it->t == PARSER ) return it;
return collapse( then, it );
}
static parser
on_expr( object v, object it ){
if( it->t == LIST && ! valid( rest( it ) ) ) it = first( it );
if( it->t == PARSER ) return it;
return collapse( either, it );
}
/* EBNF compiler */
static parser ebnf_grammar( void );
/* Compile a block of EBNF definitions into an association list
of (symbol.parser) pairs.
Accepts an association list of supplemental parsers for any syntactic
constructs that are easier to build outside of the EBNF syntax.
Accepts an association list of operators to bind the results of any
named parser from the EBNF block or the supplements.
*/
list
ebnf( char *productions, list supplements, list handlers ){
static parser ebnf_parser;
if( !ebnf_parser ) ebnf_parser = ebnf_grammar();
object result = parse( ebnf_parser, chars_from_str( productions ) );
if( not_ok( result ) ) return result;
object payload = first( rest( result ) );
list defs = append( payload,
env( supplements, 1,
Symbol(EBNF_EPSILON), succeeds(NIL_) ) );
list forwards = map( Operator( NIL_, define_forward ), defs );
list parsers = map( Operator( forwards, compile_rhs ), defs );
list final = map( Operator( forwards, define_parser ), parsers );
map( Operator( forwards, wrap_handler ), handlers );
return final;
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static parser
ebnf_grammar( void ){
if( !regex_parser ) regex_parser = regex_grammar();
parser spaces = many( anyof( " \t\n" ) );
parser defining_symbol = thenx( chr( '=' ), spaces );
parser choice_symbol = thenx( chr( '|' ), spaces );
parser terminating_symbol = thenx( chr( ';' ), spaces );
parser name = some( either( anyof( "-_" ), alpha() ) );
parser identifier = thenx( name, spaces );
parser terminal =
bind(
thenx( either( thenx( xthen( chr( '"'), many( noneof("\"") ) ),
chr( '"') ),
thenx( xthen( chr('\''), many( noneof( "'") ) ),
chr('\'') ) ),
spaces ),
Operator( NIL_, make_matcher ) );
parser symb = bind( identifier, Operator( NIL_, symbolize ) );
parser nonterminal = symb;
parser expr = forward();
{
parser factor = ANY( terminal,
nonterminal,
bind( xthen( then( chr( '[' ), spaces ),
thenx( expr,
then( chr( ']' ), spaces ) ) ),
Operator( NIL_, make_maybe ) ),
bind( xthen( then( chr( '{' ), spaces ),
thenx( expr,
then( chr( '}' ), spaces ) ) ),
Operator( NIL_, make_many ) ),
bind( xthen( then( chr( '(' ), spaces ),
thenx( expr,
then( chr( ')' ), spaces ) ) ),
Operator( NIL_, encapsulate ) ),
bind( xthen( chr( '/' ),
thenx( regex_parser, chr( '/' ) ) ),
Operator( NIL_, encapsulate ) ) );
parser term = bind( many( factor ), Operator( NIL_, make_sequence ) );
*expr = *bind( then( term, many( xthen( choice_symbol, term ) ) ),
Operator( NIL_, make_any ) );
};
parser definition = bind( then( symb,
xthen( defining_symbol, | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
};
parser definition = bind( then( symb,
xthen( defining_symbol,
thenx( expr, terminating_symbol ) ) ),
Operator( NIL_, encapsulate) );
return some( definition );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
/* helpers */
static string
stringify( object env, object input ){
return to_string( input );
}
static symbol
symbolize( object env, object input ){
return symbol_from_string( to_string( input ) );
}
static list
encapsulate( object env, object input ){
return one( input );
}
/* syntax directed translation to list form */
static parser
make_matcher( object env, object input ){
return str( to_string( input )->String.str );
}
static list
make_sequence( object env, object input ){
if( length( input ) == 0 ) return Symbol(EBNF_EPSILON);
if( length( input ) < 2 ) return input;
return one( cons( Symbol(EBNF_SEQ), input ) );
}
static list
make_any( object env, object input ){
if( length( input ) < 2 ) return input;
return one( cons( Symbol(EBNF_ANY), input ) );
}
static list
make_maybe( object env, object input ){
return one( cons( Symbol(EBNF_MAYBE), input ) );
}
static list
make_many( object env, object input ){
return one( cons( Symbol(EBNF_MANY), input ) );
}
/* stages of constructing the parsers from list form */
static list
define_forward( object env, object it ){
if( rest( it )->t == PARSER ) return it;
return cons( first( it ), forward() );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static parser
compile_bnf( object env, object it ){
operator self = (union object[]){{.Operator={OPERATOR,env,compile_bnf}}};
switch( it->t ){
default:
return it;
case SYMBOL: {
object ob = assoc( it, env );
return valid( ob ) ? ob : it;
}
case LIST: {
object f = first( it );
if( valid( eq_symbol( EBNF_SEQ, f ) ) )
return collapse( then,
map( self, rest( it ) ) );
if( valid( eq_symbol( EBNF_ANY, f ) ) )
return collapse( either,
map( self, rest( it ) ) );
if( valid( eq_symbol( EBNF_MANY, f ) ) )
return many( map( self, rest( it ) ) );
if( valid( eq_symbol( EBNF_MAYBE, f ) ) )
return maybe( map( self, rest( it ) ) );
if( length( it ) == 1 )
return compile_bnf( env, f );
return map( self, it );
}
}
}
static list
compile_rhs( object env, object it ){
if( rest( it )->t == PARSER ) return it;
object result = cons( first( it ),
map( (union object[]){{.Operator={OPERATOR,env,compile_bnf}}},
rest( it ) ) );
return result;
}
static list
define_parser( object env, object it ){
object lhs = assoc( first( it ), env );
if( valid( lhs ) && lhs->t == PARSER && lhs->Parser.f == NULL ){
object rhs = rest( it );
if( rhs->t == LIST ) rhs = first( rhs );
*lhs = *rhs;
}
return it;
}
static list
wrap_handler( object env, object it ){
object lhs = assoc( first( it ), env );
if( valid( lhs ) && lhs->t == PARSER ){
object op = rest( it );
parser copy = Parser( 0, 0 );
*copy = *lhs;
*lhs = *bind( copy, op );
}
return it;
}
pc11io.h
#define PC11IO_H
#if ! PC11PARSER_H
#include "pc11parser.h"
#endif
enum io_symbol_codes {
ARGS = END_PARSER_SYMBOLS,
END_IO_SYMBOLS
};
int pprintf( char const *fmt, ... );
int pscanf( char const *fmt, ... );
pc11io.c
code omitted for size
pc11test.h
#define PC11TEST_H
#if ! PC11IO_H
#include "pc11io.h"
#endif
int main( void ); | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
pc11test.h
#define PC11TEST_H
#if ! PC11IO_H
#include "pc11io.h"
#endif
int main( void );
pc11test.c
#include <ctype.h>
#include "pc11test.h"
enum test_symbol_codes {
TEST = END_IO_SYMBOLS,
DIGIT,
UPPER,
NAME,
NUMBER,
EOL,
SP,
postal_address,
name_part,
street_address,
street_name,
zip_part,
END_TEST_SYMBOLS
};
static int test_basics();
static int test_parsers();
static int test_regex();
static int test_ebnf();
static int test_io();
int main( void ){
return 0
|| test_basics()
|| test_parsers()
|| test_regex()
|| test_ebnf()
|| test_io()
;
}
static fOperator to_upper;
static integer
to_upper( object env, integer it ){
return Int( toupper( it->Int.i ) );
}
static int
test_basics(){
puts( __func__ );
list ch = chars_from_str( "abcdef" );
print( ch ), puts("");
print_list( ch ), puts("");
integer a = apply( Operator( NIL_, to_upper ), first( ch ) );
print( a ), puts("");
drop( 1, a );
print( a ), puts("");
drop( 6, ch );
print( ch ), puts("");
print_list( ch ), puts("");
drop( 7, ch );
print( ch ), puts("");
print_list( ch ), puts("");
puts("");
list xs = infinite( Int('x') );
print_list( xs ), puts("");
drop( 3, xs );
print_list( xs ), puts("");
puts("");
return 0;
}
static int
test_parsers(){
puts( __func__ );
list ch = chars_from_str( "a b c d 1 2 3 4" );
parser p = succeeds( Int('*') );
print_list( parse( p, ch ) ), puts("");
parser q = fails( String("Do you want a cookie?",0) );
print_list( parse( q, ch ) ), puts("");
parser r = item();
print_list( parse( r, ch ) ), puts("");
parser s = either( alpha(), item() );
print_list( parse( s, ch ) ), puts("");
parser t = literal( Int('a') );
print_list( parse( t, ch ) ), puts("");
puts("");
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static int
test_regex(){
puts( __func__ );
parser a = regex( "." );
print_list( a ), puts("");
print_list( parse( a, chars_from_str( "a" ) ) ), puts("");
print_list( parse( a, chars_from_str( "." ) ) ), puts("");
print_list( parse( a, chars_from_str( "\\." ) ) ), puts("");
puts("");
parser b = regex( "\\." );
print_list( b ), puts("");
print_list( parse( b, chars_from_str( "a" ) ) ), puts("");
print_list( parse( b, chars_from_str( "." ) ) ), puts("");
print_list( parse( b, chars_from_str( "\\." ) ) ), puts("");
puts("");
parser c = regex( "\\\\." );
print_list( c ), puts("");
print_list( parse( c, chars_from_str( "a" ) ) ), puts("");
print_list( parse( c, chars_from_str( "." ) ) ), puts("");
print_list( parse( c, chars_from_str( "\\." ) ) ), puts("");
print_list( parse( c, chars_from_str( "\\a" ) ) ), puts("");
puts("");
parser d = regex( "\\\\\\." );
print_list( d ), puts("");
print_list( parse( d, chars_from_str( "a" ) ) ), puts("");
print_list( parse( d, chars_from_str( "." ) ) ), puts("");
print_list( parse( d, chars_from_str( "\\." ) ) ), puts("");
print_list( parse( d, chars_from_str( "\\a" ) ) ), puts("");
puts("");
parser e = regex( "\\\\|a" );
print_list( e ), puts("");
print_list( parse( e, chars_from_str( "a" ) ) ), puts("");
print_list( parse( e, chars_from_str( "." ) ) ), puts("");
print_list( parse( e, chars_from_str( "\\." ) ) ), puts("");
print_list( parse( e, chars_from_str( "\\a" ) ) ), puts("");
puts("");
parser f = regex( "[abcd]" );
print_list( f ), puts("");
print_list( parse( f, chars_from_str( "a" ) ) ), puts("");
print_list( parse( f, chars_from_str( "." ) ) ), puts("");
puts("");
return 0;
}
static fOperator stringify;
static string
stringify( object env, list it ){
return to_string( it );
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static string
stringify( object env, list it ){
return to_string( it );
}
static int
test_ebnf(){
puts( __func__ );
Symbol(postal_address);
Symbol(name_part);
Symbol(street_address);
Symbol(street_name);
Symbol(zip_part);
list parsers = ebnf(
"postal_address = name_part street_address zip_part ;\n"
"name_part = personal_part SP last_name SP opt_suffix_part EOL\n"
" | personal_part SP name_part ;\n"
"personal_part = initial '.' | first_name ;\n"
"street_address = house_num SP street_name opt_apt_num EOL ;\n"
"zip_part = town_name ',' SP state_code SP zip_code EOL ;\n"
"opt_suffix_part = 'Sr.' | 'Jr.' | roman_numeral | ;\n"
"opt_apt_num = [ apt_num ] ;\n"
"apt_num = NUMBER ;\n"
"town_name = NAME ;\n"
"state_code = UPPER UPPER ;\n"
"zip_code = DIGIT DIGIT DIGIT DIGIT DIGIT ;\n"
"initial = 'Mrs' | 'Mr' | 'Ms' | 'M' ;\n"
"roman_numeral = 'I' [ 'V' | 'X' ] { 'I' } ;\n"
"first_name = NAME ;\n"
"last_name = NAME ;\n"
"house_num = NUMBER ;\n"
"street_name = NAME ;\n",
env( NIL_, 6,
Symbol(EOL), chr('\n'),
Symbol(DIGIT), digit(),
Symbol(UPPER), upper(),
Symbol(NUMBER), some( digit() ),
Symbol(NAME), some( alpha() ),
Symbol(SP), many( anyof( " \t\n" ) ) ),
env( NIL_, 2,
Symbol(name_part), Operator( NIL_, stringify ),
Symbol(street_name), Operator( NIL_, stringify ) )
);
parser start = assoc_symbol( postal_address, parsers );
if( valid( start ) && start->t == LIST )
start = first( start );
print_list( start ), puts("\n");
print_list( parse( start,
chars_from_str( "Mr. luser droog I\n"
"2357 Streetname\n"
"Anytown, ST 00700\n" ) ) ),
puts("");
printf( "%d objects\n", count_allocations() );
return 0;
}
static int
test_io(){
pprintf( "%s:%c-%c\n", "does it work?", '*', '@' );
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
static int
test_io(){
pprintf( "%s:%c-%c\n", "does it work?", '*', '@' );
return 0;
}
Size:
$ make count
wc -l -c -L pc11*[ch] ppnarg.h
180 4442 78 pc11io.c
13 218 36 pc11io.h
549 13731 77 pc11object.c
361 5955 77 pc11object.h
818 20944 80 pc11parser.c
214 3601 63 pc11parser.h
202 5453 69 pc11test.c
6 82 21 pc11test.h
29 1018 83 ppnarg.h
2372 55444 83 total
cloc pc11*[ch] ppnarg.h
9 text files.
9 unique files.
0 files ignored.
github.com/AlDanial/cloc v 1.93 T=0.05 s (194.9 files/s, 51356.5 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
C 4 316 98 1335
C/C++ Header 5 241 99 283
-------------------------------------------------------------------------------
SUM: 9 557 197 1618
-------------------------------------------------------------------------------
Any improvements to make to the interface, implementation, or documentation?
Answer: Makefile improvements
At first glance, the makefile looks OK, but a few improvements can be made. First, you always override CFLAGS, although you allow to add things to be added to it via the environment variable $cflags. However, that lower case form is very non-standard, and it's more common to expect CFLAGS=... make to work. The usual solution is this:
CFLAGS ?= -g -Wall -Wpedantic -Wextra -Wno-unused-function -Wno-unused-parameter -Wno-switch -Wno-return-type -Wunused-variable
CFLAGS += -std=c99 | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
Where in the first line, we only add those options if no CFLAGS were provided via the environment, and in the second line we unconditionally add any required flags for the build to work.
Second, targets that don't build anything but just run commands should be marked as .PHONY, so if you accidentily created a file test that has a timestamp newer than pc11test, it wouldn't prevent make test from working as expect. So add:
.PHONY: test clean count
About forward declarations
I've added forward declarations for all the static functions inside the .c files so all the static "helper functions" can be placed below the non-static function that uses them, so the implementation can be presented in a more top down fashion overall. | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
Personally I don't think that is very helpful. Now you have both the forward declaration and the actual definition to keep in sync. The files are long enough that you are going to use search functionality anyway to jump to functions.
Documentation
It is great that you are documenting all the functions and also having them grouped in a sensible way. However, I recommend that you write these documentation comments in Doxygen format. Doxygen is a widely used standard for documenting C and C++ code, and the Doxygen tools can then do all kinds of nice stuff for you: apart from generating documentation in navigatable PDF and HTML formats, it can also warn you when you forgot to document functions and/or function parameters.
Naming things
Especially in pc11object.h, I am a bit surprised by some of the function names, in particular when the comments above them describe those in terms that don't match the function name itself.
For example, drop() has as documentation "Skip ahead n elements". Why not call the function skip() then, or alternatively, write "Drop the first n elements" in the comments. There are more examples of this, like map() "Transform", collapse()/reduce() "Fold", env() "Prepend", and so on.
Some comments don't make sense at all to a C programmer, like first() being documented as "car". If you don't know LISP, you might think "what does this have to do with automobiles?".
Some comments are needlessly complicated, like append() being documented as "return copy of start sharing end". But it also raises questions: does this append one list to another like the function name implies, or does it create a new list that is the concatenation of two lists like the comments hint at? | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, parsing, functional-programming
Make sure the function name, while concise, conveys clearly what is is going to do, and make sure the documentation matches. I would go over all the function names and make changes where appropriate. For example, instead of having to remember whether collapse() is for lists and reduce() is for arrays of objects, why not make them fold_list() and fold_objects()? | {
"domain": "codereview.stackexchange",
"id": 43545,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, functional-programming",
"url": null
} |
c, strings
Title: Function that get 3 word for strings, than combine them to 1 string and finally print the string in reverse
Question: I'm learning C and I got a task to make 3 function.
The first get 3 addresses of string, get 3 words from the user, and enter into the addresses.
The second get the 3 addresses of string and combine them to a new large string.
The last should get the new address and print in reverse the string.
I wrote this and will happy to hear of problems or things to improve.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
void swap(char *x, char *y) {
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void initWords(char* w1, char* w2, char* w3) {
printf("Please enter a word\n");
scanf("%s", w1);
printf("Please enter another word\n");
scanf("%s", w2);
printf("Please enter one last word\n");
scanf("%9s", w3);
}
char* concatWords(char* w1, char* w2, char* w3) {
char* new_w = malloc(strlen(w1)+strlen(w2)+strlen(w3));
strcat(new_w, w1);
strcat(new_w, w2);
strcat(new_w, w3);
return new_w;
free(new_w);
}
void printReversedWord(char* word) {
int i;
int number = strlen(word);
for (i=0; i<=(number/2); i++) {
swap(&word[i], &word[number-1-i]);
}
printf("%s", word);
}
int main() {
char w1 [N + 1];
char w2 [N + 1];
char w3 [N + 1];
initWords(w1, w2, w3);
char* new_w = concatWords(w1, w2, w3);
printReversedWord(new_w);
return 0;
}
thanks a lot!
Answer:
free(new_w) has no effect. It is unreachable. And unnecessary (and dangerous if placed before return).
malloc(strlen(w1)+strlen(w2)+strlen(w3)) allocates one character less than necessary. There is no room for a zero terminator.
scanfs make the code prone to the buffer overflow. Prefer fgets. | {
"domain": "codereview.stackexchange",
"id": 43546,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
c, strings
scanfs make the code prone to the buffer overflow. Prefer fgets.
I understand it is not a part of assignment, but think of separation of responsibilities. A function that just reverses the word is better than a function which reverses and prints it.
number is not the greatest name. new_word_length perhaps? | {
"domain": "codereview.stackexchange",
"id": 43546,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.