text
stringlengths
1
2.12k
source
dict
c, reinventing-the-wheel, formatting, io // if the zeroes are already stripped out or it is the last element, // store it in output s2 if (!isZero || s[i-2] == '.'){ s2[i-1] = s[i-1]; } } // print the output str printf("%s",s2); }else if (cch2 == '.'){ // if its like $.2f or something explicit like $.2d for double char cch3 = fmt[i+1]; // check if the next number is not a number [ we want it to be a number] if (cch3>'9' || cch3<'0'){ printf("%c.",IO_INPUT_TOK); }else{ // if it is a number check that the last one is a 'f' or a 'd' char cch4 = fmt[i+2]; i+=2; if (cch4 == 'f') { // preparation string for float char mk[] = "%. f"; // since the number is in cch3 [ the explicitly point printing num ] // assign it so it becomes like %.nf where n is the number mk[2] = cch3; // use the preparation string to print what's in the argument printf(mk,va_arg(va,double)); }else if (cch4 == 'd'){ // preparation string for double char mk[] = "%. lf"; // since the number is in cch3 [ the explicitly point printing num ] // assign it so it becomes like %.nlf where n is the number mk[2] = cch3;
{ "domain": "codereview.stackexchange", "id": 43507, "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, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io // use the preparation string to print what's in the argument printf(mk,va_arg(va,double)); }else{ i-=1; printf("%c.%c%c",IO_OUTPUT_TOK,cch3,cch4); } } // just check and print it }else if (cch2 == 'u' || cch2 == 'U'){ printf("%u",va_arg(va,unsigned int)); }else if (cch2 == 'p' || cch2 == 'P'){ printf("%p",va_arg(va,void*)); }else if (cch2 == 'x' || cch2 == 'X'){ printf("%x",va_arg(va,int)); }else if (cch2 == 's' || cch2 == 'S'){ printf("%s",va_arg(va,char*)); }else if (cch2 == 'l' || cch2 == 'L'){ // if it is in long type char cch3 = fmt[i]; i+=2; if (cch3 == 'i' || cch3 == 'I'){ printf("%li",va_arg(va,long int)); }else if (cch3 == 'l'){ printf("%lli",va_arg(va,long long int)); }else if (cch3 == 'L'){ printf("%llu",va_arg(va,long long unsigned int)); }else if (cch3 == 'u'){ printf("%lu",va_arg(va,long unsigned int)); }else{ i-=1; printf("%c%c%c",IO_OUTPUT_TOK,cch2,cch3); } }else if (cch2 == IO_OUTPUT_TOK){ printf("%c",IO_OUTPUT_TOK); }else{ i-=1; printf("%c",IO_OUTPUT_TOK); } // if its not input token or if the mode states its not input mode, // print the charachter whatever it may be }else if (cch!=IO_INPUT_TOK||mode){ printf("%c",cch); } } }
{ "domain": "codereview.stackexchange", "id": 43507, "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, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io // full wrapper for vio void io(const char* fmt, ...) { va_list va; va_start(va,fmt); vio(fmt,0,va); va_end(va); } // print "only" wrapper for vio void print(const char* fmt, ...) { va_list va; va_start(va,fmt); vio(fmt,1,va); va_end(va); } file: exampleUsage.c // format specifiers to be customized before including io.h // #define IO_INPUT_TOK '%' // uncomment and change the '%' to your own token // #define IO_OUTPUT_TOK '$' // uncomment and change the '$' to your own token #include "io.h" /* ---- Format Specifiers ---- [ default ] change the '$' if you have customized it! == == For Output == == - $i : integer - $c : charachter - $f : float - $d : double - $.nf : prints n number of points after main value [ float ] ( n needs to be 0-9 ) - $.nd : prints n number of points after main value [ double ] ( n needs to be 0-9 ) - $u : unsigned integer - $p : pointers - $x : hexadecimal conversion from int - $li : long - $lu : long unsigned - $ll : long long - $LL : long long unsigned - $s : string change the '%' if you have customized it! == == For input == == - %i : integer - %c : charachter - %f : float - %d : double - %u : unsigned integer - %li : long int - %lu : long unsigned [int] - %ll : long long [int] - %lL : long long unsigned [int] - %s : string */ int main() { double a, b; // $i maps to -> 1, %d maps to -> &a, $i maps to -> 2, %d maps to -> &b io("Num $i: %dNum $i: %d", 1, &a, 2, &b); // $d maps to -> a+b io("Sum is: $d\n",a+b); //or print("Sum is : $d\n",a+b); return 0; } I would be happy to receive suggestions, feedback, improvements, and bugs of my code. I have used it and it works with no errors or warnings gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0 using flags -Wall -Wextra -Werror
{ "domain": "codereview.stackexchange", "id": 43507, "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, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io Answer: So here we go. As usual, be prepared that the feedback here is quite detailed. The first thing I did was to load your code into my IDE and run gcc -O2 -Wall -Wextra -Werror on it. The -O2 is needed because without this optimization level, some consistency checks are skipped. There were no warnings indeed, just as you promised. The next step was to check your code into version control, so that I could do any changes without losing the original code. After setting up the backup, I was ready to format your code to my likings. This changed a+b to a + b and if(cond){ to if (cond) {, as I'm more used to that standard layout of C code. Now to the API from io.h: The idea of having input and output intermixed in a single function call is appealing for interactive programs that follow this input-output style that originated in the 1970, when line printers were a common thing. I don't think that style of input-output is common nowadays, except for some introductory programming courses that just take their material from wherever they can get it, without questioning whether it still applies to reality. Using varargs for input/output is dangerous, as the compiler will not tell you about accidental typos. The code in GCC that validates format strings is 5000 lines long. To make your API similarly safe to use, you would have to write this much support code for the common compilers, or for a separate iolint tool. I don't see why anyone would need the flexibility of configuring the input and output characters. Environments that support <stdio.h> usually can handle the '$' character. Now to the implementation in io.c:
{ "domain": "codereview.stackexchange", "id": 43507, "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, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io Now to the implementation in io.c: Putting the detailed documentation at the beginning of the file is great. It could use a little more formatting, to align the columns of the (invisible) tables vertically, but aside from that, the documentation covers the basic API usage. Talking about API usage, the documentation should probably go into the header file, not the implementation file. There's a typo in the word for 'character', says my IDE. The output specifiers are not sorted in any meaningful way. The usual way would be integers first (from small to big), then floating point, then everything else. Why are the decimal places of floating points limited to 0-9? The IEEE 754-1985 64-bit floating point type has 17 significant decimal places, and I want to be able to read and write all of them. The input section differs unnecessarily from the output section: $li means long, %li means long int. Either use long or long int, don't mix them arbitrarily. $LL means long long unsigned. This type is usually spelled unsigned long long. There is no clue in $LL that this means unsigned. The printf family of functions did this better by using %llu, which has a 1:1 correspondence to unsigned long long. Why do you use uppercase letters at all, instead of repeating the lowercase l? Regarding the function vio:
{ "domain": "codereview.stackexchange", "id": 43507, "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, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io Is the parameter mode intended to either be IO_OUTPUT_TOK or IO_INPUT_TOK? If so, the name of the parameter should match the names of the constants. I don't see how TOK relates to mode. Either way, the documentation for this parameter is missing. Instead of #define, it is easier to define an enum, which gives you a bit more type safety, depending on the compiler and the compiler options. It definitely helps humans to understand the code. Since mode has type char, don't use boolean operators on it. Instead of !mode, write mode == '\0', which makes the comment above that line partly redundant. My IDE yells at me that each call to scanf is missing the error handling, and indeed, when I ran your example program and entered three for the first number, your program said: Num 2: Sum is: 0.0, which is nonsense. Your example program should demonstrate how to use your code in a robust way. Why do you handle uppercase and lowercase format specifiers in the same way? The documentation says nothing about that, and it makes the code harder to read. Just using lowercase characters is enough. Why is u only allowed in lowercase? That's inconsistent. I didn't thoroughly check all the branches of that huge loop, that's the job of your test suite. Speaking of which, you didn't provide one. This means that you cannot be sure that after tweaking your code, all the basic use cases still work as intended. Your code produces buffer overflows when reading a string. It is as bad as the function gets that was banned from the C standard library because it is impossible to be used in a safe way. For int isZero = 1;, you are using the wrong data type. If that variable is supposed to be a boolean variable, make its type bool instead of int. The comment above that declaration is useless, as it only states the obvious.
{ "domain": "codereview.stackexchange", "id": 43507, "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, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io The code for printing float and double is so large that you should extract it to a separate function. Maybe you don't even need the same code twice; the two cases for float and double look quite similar after all.
{ "domain": "codereview.stackexchange", "id": 43507, "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, formatting, io", "url": null }
c, reinventing-the-wheel, formatting, io Regarding your example usage program: The program is too short. It doesn't cover 10% of your actual code. Regarding your automated tests: They are missing. Summary: I wouldn't use your code, and if I would find it in a larger project, I would throw it away and migrate the code to using the C standard library. While the C standard library has its own problems in terms of robustness, error handling and buffer overflows, these are well-known and the most obvious bugs are caught by compilers or linters. The scanf family of functions has built-in error handling, your code ignores all errors and doesn't provide any way to let the caller deal with them. This makes your code only suitable for unreliable programs.
{ "domain": "codereview.stackexchange", "id": 43507, "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, formatting, io", "url": null }
java, interview-questions Title: Implement simplified liquibase Question: I attended job interview and on live codeing session was asked to implement code based on some requirements. There are quite long text description but idea that we have to accept some file system path and run some files if they satisfy some name pattern and depends on pattern SqlRunner should call different methos. I am free to create interfaces or can use any existing java API. I've created following code: class MigrationProcessor { private static final String[] STOP_FOLDER_NAMES = new String[]{"tmp", "system"}; private SqlRunner sqlRunner; private FileSystemReader fileSystemReader; public void process(Path path) { for (FileSystemSObject fileSystemSObject : fileSystemReader.getAllObjects(path)) { if (fileSystemSObject.isFile()) { processFile(fileSystemSObject); } else if (fileSystemSObject.isFolder()) { processFolder(fileSystemSObject); } } } private void processFolder(FileSystemSObject fileSystemSObject) { if (Arrays.asList(STOP_FOLDER_NAMES).contains(fileSystemSObject.getName())) { System.out.println("skipped processing of folder " + fileSystemSObject.getName()); } else { process(fileSystemSObject.getPath()); } }
{ "domain": "codereview.stackexchange", "id": 43508, "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, interview-questions", "url": null }
java, interview-questions private void processFile(FileSystemSObject fileSystemSObject) { String fileName = fileSystemSObject.getName(); ScriptType scriptType = ScriptType.getTypeByName(fileName); if (scriptType == null) { System.out.println("Ignore file " + fileSystemSObject.getName()); } else { switch (scriptType) { case SQL: sqlRunner.runSql(fileName); break; case CREATE_INDEX: sqlRunner.createIndex(fileName); break; case RUN_STORED_PROCEDURE: sqlRunner.runStoredProcedure(fileName); break; } } } } interface SqlRunner { void runSql(String fileName); void createIndex(String fileName); void runStoredProcedure(String fileName); } interface FileSystemReader { Iterable<FileSystemSObject> getAllObjects(Path path); } interface FileSystemSObject { boolean isFolder(); boolean isFile(); String getName(); Path getPath(); } enum ScriptType { SQL, CREATE_INDEX, RUN_STORED_PROCEDURE; public static ScriptType getTypeByName(String name) { if (name.startsWith("create_index_") && name.endsWith(".sql")) { return CREATE_INDEX; } else if (name.startsWith("run_procedure_") && name.endsWith(".sql")) { return RUN_STORED_PROCEDURE; } else if (name.endsWith(".sql")) { return SQL; } return null; } } please review
{ "domain": "codereview.stackexchange", "id": 43508, "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, interview-questions", "url": null }
java, interview-questions please review Answer: Some thoughts: STOP_FOLDER_NAMES should be a Set for O(1) lookups. It should definitely not get converted from an array into a list every time processFolder runs. STOP_FOLDER_NAMES might be better named “FOLDERS_TO_IGNORE”. As I’m old school, I also prefer the term “directory”, but that’s probably just me. It’s not clear how one starts MigrationProcessor off. If you start from a directory which is below one of the folder names to ignore, the code should ignore all of them but will instead process all of them. What does the S in FileSystemSObject` stand for? Script? The extra characters are free and add to readability. FileSystemScriptObject appears to be a subset of the functionality available in File. Since you’re already using Path, is there a reason you don’t also use File? processFile would be cleaner if the unknown ScriptType was handled in a default case, rather than checking it earlier. How can processFile’s sqlRunner locate the file with only the filename? Isn’t the full path required? Writing to System.out is suboptimal. Use a logger. At the very least, errors should go to System.err. It’s unclear how large the file system is, but you could theoretically run into issues if you have to recurse too deeply. Hopefully you asked the interviewer about that. It would be nice if there was javadoc on FileSystemScriptObject explaining the difference between “name” and “path”. Is “name” just a simple name, or does it have the whole directory structure in String form? ScriptType.getTypeByName() might read better as ScriptType.forFilename() getTypeByName may wish to accept a FileSystemSObject or a path instead of a filename. It seems reasonable that script type detection may rely on the contents of a file. There’s no allowance for failure when SqlRunner executes. A big advantage of Liquibase is being able to roll back files. This application doesn’t support that. Unclear if that was part of the problem statement.
{ "domain": "codereview.stackexchange", "id": 43508, "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, interview-questions", "url": null }
javascript, array, hash-map Title: Shortest way possible to generate javascript string from a large array of values to A, B, C and n others Question: I have an array of values containing names, e.g. let members = [{id: 1, name: 'Tyler'}, {id: 2, name: 'John'}, {id: 3, name: 'Dayo'}, ..., {id: 7, name: 'George'] There's multiple ways I can generate a string that looks like: Tyler, John, Dayo and 4 Others Here's one way I'm doing this: let memberString = members.length <= 3 ? members.map(member => member.name).join(', ') : members.slice(0,3).map(member => member.name).join(', ') + ' and ' + (members.length-3) + ' others' Using map is the most common way. I've been trying to search similar question on stack overflow and other sites to see what's the smartest way possible to achieve this but couldn't find any. Looking for experts to leave their ways to achieve this.
{ "domain": "codereview.stackexchange", "id": 43509, "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, array, hash-map", "url": null }
javascript, array, hash-map Answer: There are of course many ways to achieve this, but the shortest possible expression is not necessarily going survive any sort of refactoring to cope with edge cases. It's generally better for code to be expressive. The first step to that is to encapsulate the functionality into a suitably named function. This allows the calling code to clearly state what it expects to happen. How verbose you need to be depends on the application complexity. Your quoted example code does the same .map().join() in two places, which is a bit redundant (and is likely why you desire to shorten/simplify it). Given that we only need the name from the object, we can do the map first. reduce() is then perhaps a better choice for converting the array elements to the components of the string. This is arguably a bit inefficient because it's going to iterate over additional members of the array because we can't tell reduce to bail out. Finally we can join all the elements with the comma, which also gives us an Oxford comma. Note that this is not going to be correct for edge cases such as 0 or 1 names, different counts. And that's why the shortest possible expression is probably not what you need. let members = [{id: 1, name: 'Tyler'}, {id: 2, name: 'John'}, {id: 3, name: 'Dayo'}, {id: 7, name: 'George'}] function stringifyMembers(members, count = members.length) { return members.map(member => member.name).reduce((acc, name, index) => { return index < count ? [ ...acc, name ] : index === count && members.length > count ? [ ...acc, `and ${members.length - count} others` ] : acc }, []).join(', ') } console.log(stringifyMembers(members, 3))
{ "domain": "codereview.stackexchange", "id": 43509, "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, array, hash-map", "url": null }
c, c++17, library, dynamic-loading Title: Load and execute shared library Question: This is my attempt to load shared library on linux (and may be mac - did not test yet) I am interested if I am implementing everything correctly and if I can really use my function in a loop like that. I deliberately use iostream, because it is part of the C++ library and it wont work unless library is linked (-lstdc++) Thanks in advance. base.h #ifndef BASE_H__ #define BASE_H__ struct Base{ virtual int do_something() = 0; virtual ~Base(){ } }; #endif main.cpp #include "base.h" #include <dlfcn.h> #include <iostream> #include <memory> #include <optional> template<typename T, typename... Args> std::optional<T> dl_exec(const char *filename, const char *symbol, Args... args){ constexpr bool show_errors = true; auto err = [show_errors](const char *msg){ if constexpr(show_errors){ std::cerr << "Error Message: " << msg << '\n'; std::cerr << "Error System: " << dlerror() << '\n'; } return std::optional<T>{}; }; void *handle = dlopen(filename, RTLD_LAZY); if (!handle) return err("Bad filename"); void *fp = dlsym(handle, symbol); if (!fp) return err("Bad symbol name"); auto f = ( T (*)(Args...) ) fp; return f(args...); } int main(int argc, char **argv){ for(int i = 0; i < 10; ++i){ auto o = dl_exec<Base *, int>(argv[1], "create_class", i); if (!o){ std::cerr << "Error detected" << '\n'; return 1; } std::unique_ptr<Base> b{ *o }; std::cout << "result " << b->do_something() << '\n'; } } dynamic1.cpp #include "base.h" #include <iostream> struct Dynamic : public Base{ int do_something() final{ std::cout << "It works!!!" << '\n'; return 42; } }; extern "C" { Base *create_class(int){ return new Dynamic(); } } // g++ -fPIC -shared dynamic1.cc -o dynamic1.so dynamic2.cpp #include "base.h"
{ "domain": "codereview.stackexchange", "id": 43510, "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, c++17, library, dynamic-loading", "url": null }
c, c++17, library, dynamic-loading // g++ -fPIC -shared dynamic1.cc -o dynamic1.so dynamic2.cpp #include "base.h" #include <iostream> struct Dynamic : public Base{ Dynamic(int a) : a(a){ } int do_something() final{ std::cout << "It works 100%!!!" << '\n'; return 100 + a; } int a; }; extern "C" { Base *create_class(int a){ return new Dynamic(a); } } // g++ -fPIC -shared dynamic2.cc -o dynamic2.so Example usage [nmmm@zenbook DL]$ gcc main.cpp -lstdc++ [nmmm@zenbook DL]$ g++ -fPIC -shared dynamic1.cpp -o dynamic1.so [nmmm@zenbook DL]$ g++ -fPIC -shared dynamic2.cpp -o dynamic2.so [nmmm@zenbook DL]$ ./a.out ./dynamic1.so result It works!!! 42 result It works!!! 42 result It works!!! 42 result It works!!! 42 result It works!!! 42 result It works!!! 42 result It works!!! 42 result It works!!! 42 result It works!!! 42 result It works!!! 42 [nmmm@zenbook DL]$ ./a.out ./dynamic2.so result It works 100%!!! 100 result It works 100%!!! 101 result It works 100%!!! 102 result It works 100%!!! 103 result It works 100%!!! 104 result It works 100%!!! 105 result It works 100%!!! 106 result It works 100%!!! 107 result It works 100%!!! 108 result It works 100%!!! 109
{ "domain": "codereview.stackexchange", "id": 43510, "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, c++17, library, dynamic-loading", "url": null }
c, c++17, library, dynamic-loading Answer: Prefer = default over {} Prefer using = default instead of using an empty function body for the special member functions. While it doesn't really matter for the code you wrote, there is a slight difference between = default and {}. In particular, defining a function with an empty body {} causes it to be treated as a user-provided function, which means the class would no longer be trivial, which could impact performance and/or the ability to freely copy it around in memory. However, since your class is already virtual, it can't be trivial to begin with. Another potential issue with virtual classes is that if the base class has its destructor deleted, then you cannot create a destructor in the derived class. But as explained in this post, if you use = default in the derived class, it would be legal and it would cause the destructor in the derived class to also be deleted. Basically, it would work without you having to know anything about the destructor of the base class. So in general, write = default instead of {} for the special member functions, as it will almost always be better. Resource leak You call dlopen() but you never call dlclose(). While this is not as bad as forgetting to close a file or freeing memory, as it won't actually load in the shared object twice, this is bad practice. Always make sure resources are freed after you have used them. However, calling dlclose() inside dl_exec() is actually very inefficient, which brings me to: Create a class that wraps a shared object handle
{ "domain": "codereview.stackexchange", "id": 43510, "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, c++17, library, dynamic-loading", "url": null }
c, c++17, library, dynamic-loading Create a class that wraps a shared object handle Calling dlopen() and dlclose() every time you want to execute a function is inefficient, as it then might unload and reload the whole shared object each time. It would be much better to load it once and reuse the handle you got back from dlopen() multiple times. The same actually goes for the function you want to execute: calling dlsym() every time can be slow. You could create a class that wraps the handle returned by dlopen(), and instead of a function that executes a given function in the shared object, just add a function that returns the function pointer. class SharedObject { void *handle;
{ "domain": "codereview.stackexchange", "id": 43510, "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, c++17, library, dynamic-loading", "url": null }
c, c++17, library, dynamic-loading public: SharedObject(const char *filename) { handle = dlopen(filename, RTLD_LAZY); if (!handle) throw std::runtime_error("Could not load shared object"); } ~SharedObject() { dlclose(handle); } template<typename T> T* get_function(const char *symbol) { return reinterpret_cast<T*>(dlsym(handle, symbol)); } }; Then you can use it like so: int main(int argc, char *argv[]) { SharedObject so(argv[1]); auto create_class = so.get_function<Base *(int)>("create_class"); if (!create_class) { std::cerr << "Function not found!\n"; return EXIT_FAILURE; } for (int i = 0; i < 10; ++i) { std::unique_ptr<Base> b{create_class(i)}; std::cout << "result " << b->do_something() << '\n'; } } Simplify template parameters Instead of passing the types of the return value and all the parameters to dl_exec(), consider just passing the type of the function you want it to return. That way there is only one template parameter to deal with. I've shown an example of that in the code above. Avoid C-style casts Always prefer to use a C++-style cast, as they are typically a bit safer than C-style casts. In this case, you need to use reinterpret_cast<>() to cast the handle you got from dlsym() to the function pointer type you want. Consider having create_class() return a std::unique_ptr<Base *> Instead of the caller having to create a std::unique_ptr, consider doing that already inside create_class. The earlier you do this, the less chance of any code forgetting this and causing a potential memory leak.
{ "domain": "codereview.stackexchange", "id": 43510, "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, c++17, library, dynamic-loading", "url": null }
algorithm, php, strings Title: Count each word within a string Question: I am looking for a solution with fewer lines of code. This is code that is working perfectly, but I think I typed too much for this algorithm. If I did something wrong, feel free to tell me the error. Code <?php function Clearstring(string $string) { $string = strtolower($string); $string = preg_replace('/[,.!;?]/',"",$string); return $string; } function CountString($string){ $textsplit = preg_split("/\s/",$string); $wordsArray = []; $array= []; $counter = 0; foreach($textsplit as $word){ try{ $word = Clearstring($word); if(in_array($word,$array)) { if(in_array($wordsArray[$word],$wordsArray)) { $wordsArray[$word] +=1; } } else{ array_push($array,$word); $counter =0; $wordsArray[$word] = $counter; if(in_array($wordsArray[$word],$wordsArray)) { $wordsArray[$word] +=1; } } }catch(Exception $ex){ echo "It has occurred the next error ".$ex; } } print_r($wordsArray); } CountString('Hello, I don`t know who I am but I know who you are, but I don`t know where I am'); ?> Output Array ( [hello] => 1 [i] => 5 [don`t] => 2 [know] => 3 [who] => 2 [am] => 2 [but] => 2 [you] => 1 [are] => 1 [where] => 1 )
{ "domain": "codereview.stackexchange", "id": 43511, "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": "algorithm, php, strings", "url": null }
algorithm, php, strings Answer: You can competely avoid rolling your own code for this task. PHP offers a solution via just two native function calls. Ask str_word_count() to return all words found using 1 as the second parameter AND nominate the backtick as an acceptable character within words. Then call array_count_values() to group the encountered words and find their total occurrences. ...How considerate of PHP to offer these tools for you! Code: (Demo) $string = 'Hello, I don`t know who I "am" but I know who you are, but I don`t know where I am'; var_export(array_count_values(str_word_count($string, 1, '`'))); Output: array ( 'Hello' => 1, 'I' => 5, 'don`t' => 2, 'know' => 3, 'who' => 2, 'am' => 2, 'but' => 2, 'you' => 1, 'are' => 1, 'where' => 1, ) If you used standard apostrophes instead of backticks, you don't need to declare the 3rd parameter in str_word_count(). Demo $string = "Hello, I don't know who I \"am\" but I know who you are, but I don't know where I am"; var_export(array_count_values(str_word_count($string, 1))); p.s. I see that I overlooked the strtolower() part. Just call that inside str_word_count().
{ "domain": "codereview.stackexchange", "id": 43511, "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": "algorithm, php, strings", "url": null }
javascript, node.js, async-await, promise, mongodb Title: Basic node login routes for authentication system Question: I am building a basic authentication system with a node backend and wonder whether I am using the try-catch block excessively. I have this example controller: export const getUser = async (req: Request, res: Response) => { try { const user = await User.findById(req.body.id); if (!user) { return res.status(404).send('No user found'); } res.send(user); } catch (err: any) { return res.status(400).send(err.message); } }; And this findById User class method: static async findById(id: string): Promise<any> { // try { const collection = getCollection(USERS_COLLECTION_NAME); const user = await collection.findOne({ _id: new mongodb.ObjectId(id) }); return user; // } catch (err) { // throw err; // } } The controller already uses a try-catch block, so is having another try-catch block in the class method necessary? It still works after commenting out the try-catch block. How far should its usage be taken? To give some more context, here is the User class: import { USERS_COLLECTION_NAME } from '../utils/db'; import { getCollection } from '../utils/helpers'; import jwt from 'jsonwebtoken'; const mongodb = require('mongodb'); // do not convert to import (otherwise undefined) // does anywhere here NOT need try catch? export class User { email: string; hashedPassword: any; dateCreated: Date; constructor(email: string, hashedPassword: any) { this.email = email.toLowerCase(); this.hashedPassword = hashedPassword; this.dateCreated = new Date(); } signToken(): string { try { // { ...this } overcomes error `Expected "payload" to be a plain object` const token = jwt.sign({ ...this }, this.email, { expiresIn: 60 * 24, }); return token; } catch (err) { throw err; } }
{ "domain": "codereview.stackexchange", "id": 43512, "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, node.js, async-await, promise, mongodb", "url": null }
javascript, node.js, async-await, promise, mongodb async saveToDb(): Promise<any> { try { const collection = getCollection(USERS_COLLECTION_NAME); const saveResult = await collection.insertOne(this); return saveResult; } catch (err) { throw err; } } static async delete(id: string): Promise<any> { try { const collection = getCollection(USERS_COLLECTION_NAME); const user = await User.findById(id); if (!user) throw new Error('404 - User not found'); const deleteResult = await collection.deleteOne(user); if (!deleteResult) throw new Error('500 - Could not delete user'); return deleteResult; } catch (err) { throw err; } } static async fetchAll(): Promise<any> { try { const collection = getCollection(USERS_COLLECTION_NAME); const users = await collection.find().toArray(); // @todo: may need to optimise as it gets ALL users - what if a million users existed? return users; } catch (err) { throw err; } } static async findByEmail(email: string): Promise<any> { try { const collection = getCollection(USERS_COLLECTION_NAME); const user = await collection.findOne({ email }); return user; } catch (err) { throw err; } } static async findById(id: string): Promise<any> { // try { const collection = getCollection(USERS_COLLECTION_NAME); const user = await collection.findOne({ _id: new mongodb.ObjectId(id) }); return user; // } catch (err) { // throw err; // } } } And the controllers: import { Request, Response } from 'express'; import { User } from '../models/auth'; import bcrypt from 'bcrypt'; import { USERS_COLLECTION_NAME } from '../utils/db'; import { getCollection } from '../utils/helpers'; const mongodb = require('mongodb'); // do not convert to import (otherwise undefined)
{ "domain": "codereview.stackexchange", "id": 43512, "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, node.js, async-await, promise, mongodb", "url": null }
javascript, node.js, async-await, promise, mongodb export const createUser = async (req: Request, res: Response) => { const { email, password } = req.body; const existingUser = await User.findByEmail(email); if (existingUser) { return res.status(409).send('User already exists. Please log in.'); } const hashedPassword = await bcrypt.hash(password, 10); const newUser = new User(email, hashedPassword); const saveToDb = await newUser.saveToDb(); if (!saveToDb) { return res.status(500).send('Could not insert user into the database.'); } const token = newUser.signToken(); res.status(201).json({ token, id: saveToDb.insertedId }); }; // only updates email for now... export const updateUser = async (req: Request, res: Response) => { const collection = getCollection(USERS_COLLECTION_NAME); try { const updateResult = await collection.updateOne( { _id: new mongodb.ObjectId(req.body.id), // new mongodb.ObjectId needed, otherwide null; converts to BSON }, { $set: { email: req.body.email, }, } ); if (!updateResult.modifiedCount) { return res.status(500).send('Could not update user.'); } res.send({ updateResult }); } catch (err: any) { return res.status(400).send(err.message); } }; export const deleteUser = async (req: Request, res: Response) => { const { id } = req.body; try { const deleteUserResult = await User.delete(id); res.send({ deleteUserResult }); } catch (err: any) { return res.status(500).send(err.message); // would prefer to set status code from err as it's not always 500! e.g. the delete class method can throw a 404 or 500 error } }; export const getUser = async (req: Request, res: Response) => { try { const user = await User.findById(req.body.id); if (!user) { return res.status(404).send('No user found'); } res.send(user); } catch (err: any) { return res.status(400).send(err.message); } };
{ "domain": "codereview.stackexchange", "id": 43512, "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, node.js, async-await, promise, mongodb", "url": null }
javascript, node.js, async-await, promise, mongodb res.send(user); } catch (err: any) { return res.status(400).send(err.message); } }; export const getUsers = async (req: Request, res: Response) => { const users = await User.fetchAll(); if (!users) { return res.status(404).send('No users found'); } res.send(users); }; export const logUserIn = async (req: Request, res: Response) => { const { email, password } = req.body; const user = await User.findByEmail(email); if (!user) { return res.status(404).send('User not found. Please create an account.'); } const correctPassword = await bcrypt.compare(password, user.hashedPassword); if (!correctPassword) { return res.status(403).send('Wrong password for this account.'); } // assign object methods to the user instance as objects retrieved from db don't have methods Object.setPrototypeOf(user, User.prototype); const token = user.signToken(); return res.json({ token, id: user._id }); }; Any other tips or suggestions would also be greatly appreciated, thank you! Answer: Short answer is -- yes, you're using try/catch excessively. When working with errors in general, you'll want to determine which type of error you're throwing. Did the user make a mistake? (400) Is the user accessing a resource they're not allowed to see? (403) Did an unexpected error occur? ⚠️ (5XX) ...etc You want to be able to differentiate between these different types, because sometimes there are errors you want the user to know about and some others you'd rather not want to expose. For example, if a malicious user is trying to gain access to your system and they're able to trigger an error (5XX) and you're generous eough to provide them with what exactly went wrong.. they're in heaven. Usually the standard is to Create custom HTTP errors Have a single try/catch block to forward the error with next. Have a middleware to handle errors
{ "domain": "codereview.stackexchange", "id": 43512, "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, node.js, async-await, promise, mongodb", "url": null }
javascript, node.js, async-await, promise, mongodb Here is an example, suppose you create a few http errors. class AppError extends Error { constructor(message, status, code) { super(message); this.status = status; this.code = code; } } class BadRequestError extends AppError { constructor(message, code) { super(message, 400, code); } } class NotFoundError extends AppError { constructor(message, code) { super(message, 404, code); } } class InternalServerError extends AppError { constructor(message, code) { super(message, 500, code); } } You create and register an error handling middleware. app.use(function(err, req, res, next) { if(err instanceof InternalServerError) { console.error(err); // Do not expose the internal server error to the client res.status(err.status).send('Internal Server Error'); return; } if(err instanceof AppError && err.status >= 400 && err.status < 500) { res.status(err.status).send(err.message); return; } // If nothing matched up till now then you're dealing with // an error that you did not expect console.error(err); res.status(500).send('Unexpected Internal Server Error'); return; }); ℹ️ Consider using winston library for logging stuff. Then in your controller forward the error. export const getUser = async (req: Request, res: Response) => { try { const user = await User.findById(req.body.id); if (!user) { throw new NotFoundError('No user found'); } res.send(user); } catch (err: any) { next(err); } }; Then in your code when you're throwing an error static async delete(id: string): Promise<any> { const collection = getCollection(USERS_COLLECTION_NAME); const user = await User.findById(id); if (!user) throw new NotFoundError('User not found'); const deleteResult = await collection.deleteOne(user); if (!deleteResult) throw new InternalServerError('Could not delete user'); return deleteResult; }
{ "domain": "codereview.stackexchange", "id": 43512, "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, node.js, async-await, promise, mongodb", "url": null }
python, authentication, tkinter, canvas, user-interface Title: Python Tkinter UI Pattern Password Code Question: This post is less of a question and more of a hope for people to see my code which I know is far from great and give me some direction or simple tips on improving the quality of it. Normal Stud: Active Stud: The program is a small simple class which inherits tkinter's Canvas object and uses it to create a 'for purpose' Touchscreen Pattern Password. It uses Images which have been attached and need to be placed in the same folder as the code which are for the pattern studs and then uses a series of bind events to know where the touch presses happen. Have a play around if you wish and let me know any structure / coding improvement I could make. FYI this program was coded with python3.6 on windows operating system :) Code: import tkinter as tk class PatternPassword(tk.Canvas): def __init__(self, show_pattern=False, show_numbers=False, max_length=9): super().__init__() if 1 < max_length > 9: #print('[*] Not aloud more than 9 as max_length') raise Exception('[*] Max length must be between 1 and 9') self.config(bg='grey', width=300, height=300) self.bind_all("<B1-Motion>", self.ShowInfo) self.bind_all("<ButtonPress-1>", self.ShowInfo) self.show_pattern = show_pattern self.show_numbers = show_numbers self.max_length = max_length self.pattern = tk.StringVar() self.pattern.set('Pattern Password: ') self.current_widget = None self.activeStub = tk.PhotoImage(file='stubActive.png') self.click_num = 0 self.x1, self.y1, self.x2, self.y2 = None, None, None, None self.lines = [] self.points = [] self.SetupStubs() def AddLine(self, event): self.delete(self.lines[0]) del self.lines[0] line = self.create_line(self.points, fill="white", arrow=tk.LAST, width=3) self.lines.append(line)
{ "domain": "codereview.stackexchange", "id": 43513, "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, authentication, tkinter, canvas, user-interface", "url": null }
python, authentication, tkinter, canvas, user-interface def DrawLine(self, event, middleBounds): if self.click_num==0: self.x1=middleBounds[0] self.y1=middleBounds[1] self.click_num=1 self.points.append(self.x1) self.points.append(self.y1) else: self.x2=middleBounds[0] self.y2=middleBounds[1] self.points.append(self.x2) self.points.append(self.y2) if len(self.lines) == 1: self.AddLine(event) return line = self.create_line(self.x1,self.y1,self.x2,self.y2, fill="white", width=3, arrow=tk.LAST, smooth=1, splinesteps=12) self.lines.append(line) def AddToPattern(self, number): self.pattern.set(f'Pattern Password: {self.pattern.get()[18:]}{str(number)}') def ActivateStub(self, number): self.itemconfig(self.stubs[number-1], image=self.activeStub) def ShowInfo(self, event): for stubNumber in list(self.stubs.values()): bound = self.bbox(stubNumber) x = [bound[0], bound[2]] y = [bound[1], bound[3]] middleBoundX = sum(x) / len(x) middleBoundY = sum(y) / len(y) middleBounds = [middleBoundX, middleBoundY] if bound[0] < event.x < bound[2] and bound[1] < event.y < bound[3]: widget = stubNumber if self.current_widget != widget: self.current_widget = widget if len(self.pattern.get()) < (18+self.max_length) and str(self.current_widget) not in self.pattern.get()[18:]: self.AddToPattern(self.current_widget) self.ActivateStub(self.current_widget) if self.show_pattern: self.DrawLine(event, middleBounds) def SetupStubs(self): x=20 y=20
{ "domain": "codereview.stackexchange", "id": 43513, "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, authentication, tkinter, canvas, user-interface", "url": null }
python, authentication, tkinter, canvas, user-interface x=20 y=20 self.stub = tk.PhotoImage(file='stub.png') self.stubs = {} for stubNum in range(9): stubButtonID = self.create_image(x,y,anchor=tk.NW,image=self.stub) x += 100 if x == 320: y += 100 x = 20 self.stubs.update({stubNum: stubButtonID}) if self.show_numbers: x=20 y=20 for stubNum in range(9): self.create_text(x+34, y+34, text=stubNum+1, fill="white", font=('Helvetica 15 bold')) x += 100 if x == 320: y += 100 x = 20 def ClearPattern(self): self.pattern.set('Pattern Password: ') for stub in list(self.stubs.values()): #stub.config(image=self.stub) self.itemconfig(stub, image=self.stub) for line in self.lines: self.delete(line) self.click_num = 0 self.points = [] if __name__ == '__main__': main = tk.Tk() main.geometry('500x500') main.config(bg='grey') title = tk.Label(main, text='Pattern Password', bg=main['bg'], fg='white', font=('Verdana Pro Light', 32, 'underline')) title.pack(fill=tk.X, pady=20) pattern = PatternPassword(show_pattern=True, show_numbers=False, max_length=9) pattern.pack() controlFrame = tk.Frame(main, bg='grey') controlFrame.pack_propagate(False) controlFrame.pack(padx=(50,0), pady=20, ipady=40, fill=tk.X, expand=1) passLabel = tk.Label(controlFrame, textvariable=pattern.pattern, font=('Verdana Pro Light', 18), bg='grey', fg='white') passLabel.pack(side=tk.LEFT) clearPattern = tk.Button(controlFrame, text='Clear', font=('Arial', 20), bg='grey', activebackground='grey', fg='white', activeforeground='white', bd=0, highlightthickness=0, command=pattern.ClearPattern) clearPattern.pack(side=tk.LEFT, padx=(20,0), ipadx=20, ipady=3)
{ "domain": "codereview.stackexchange", "id": 43513, "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, authentication, tkinter, canvas, user-interface", "url": null }
python, authentication, tkinter, canvas, user-interface main.mainloop() Answer: Welcome to CodeReview! Your code is quite readable, but there are still ways to improve it: Remove "magic" numbers Whenever you write a number that is not 0 or 1 in your program think to yourself: what does this number represent? self.config(bg='grey', width=300, height=300) x += 100 if x == 320: y += 100 x = 20 self.create_text(x+34, y+34, text=stubNum+1, fill="white", font=('Helvetica 15 bold')) controlFrame.pack(padx=(50,0), pady=20, ipady=40, fill=tk.X, expand=1) What are 300, 100, 320, 20, 34, 50 and so on? They are probably dimensions of your user interface but I am not sure exactly what they represent by glancing at the code. If I change just one of the 20s into 30 does the code still work, does the UI look weird? At the start of your class you should do: self.X_STEP = 20 self.WIDTH = 300 self.TEXT_OFFSET = 34 or better yet, pass these parameters to the __init__ method of your class to give the user a better costumization. Function doing one thing only def AddLine(self, event): self.delete(self.lines[0]) del self.lines[0] line = self.create_line(self.points, fill="white", arrow=tk.LAST, width=3) self.lines.append(line) Why does a function named AddLine also delete a line? At the very least you should add a comment saying why that needs to be deleted, but better yet, the function should do only what it says in the name. Remove repetition x=20 y=20 self.stub = tk.PhotoImage(file='stub.png') self.stubs = {} for stubNum in range(9): stubButtonID = self.create_image(x,y,anchor=tk.NW,image=self.stub) x += 100 if x == 320: y += 100 x = 20 self.stubs.update({stubNum: stubButtonID}) if self.show_numbers: x=20 y=20 for stubNum in range(9): self.create_text(x+34, y+34, text=stubNum+1, fill="white", font=('Helvetica 15 bold')) x += 100
{ "domain": "codereview.stackexchange", "id": 43513, "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, authentication, tkinter, canvas, user-interface", "url": null }
python, authentication, tkinter, canvas, user-interface if x == 320: y += 100 x = 20 The code calculating the x,y position is duplicated here, the positions should be calculated once at the start and saved in a list to be reused. Simplification I am not 100% sure, but in the DrawLine function: def DrawLine(self, event, middleBounds): You should be able to just draw the line without saving the points in a list to simplify the code.
{ "domain": "codereview.stackexchange", "id": 43513, "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, authentication, tkinter, canvas, user-interface", "url": null }
c, parsing, functional-programming Title: Parser Combinators in C redux Question: A few more rewrites down the line from my previous question, this is the C version 11 based on the PostScript prototype version 12. The PostScript version is shorter, but it's some crazy ass PostScript gibberish that's like my own private dialect, so translating to C makes it easier to share with the world. I showed off a little in comp.lang.c during the final round of debugging. According to Greenspun's 10th rule: Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.
{ "domain": "codereview.stackexchange", "id": 43514, "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 I've attempted to break this rule by explicitly adopting and crafting a much more modest fraction of Common Lisp. Just a tiny fraction. More like a Scheme, or a Lisp 1, with no (eval). There are lists of things which could be an integer or a string or a symbol or a parser or an operator or a list. There's just enough lazy evaluation to support lazy streams but then I got too lazy to carry it all the way through. So there's a careful handling of suspensions in the *object.[ch] module, but in the *parser.[ch] module it just forces the first item off of the input list in parse_satisfy() and all other parsers build upon that as their base. So, satisfy() parsers comprise the leaf nodes of the parser graph. Building a recursive loop in a graph of parsers requires allocating a "forwarding parser", ie. an empty parser which can be composed in a graph with other parsers and then filled in later. Both the regex_grammar() and ebnf_grammar() functions use this technique to create parser graphs with loops in them. The print() and print_list() functions, when trying to print a parser will in some configurations print its saved environment. For many parser graphs, this will print out the whole graph in an awkward but informative format. But the printing functions take care not to dive into the saved environment of a parser that was constructed as a forward(), because it's very likely to lead to an infinite loop. To simplify the usage code, many of the constructors -- Parser(), Operator(), Suspension() -- which take a function pointer to build a "function object", each try to capture a print name for the function at the same time. This is done by interfacing the constructor functions with macros that can make a copy of the function pointer argument and use the preprocessor's # stringify operation.
{ "domain": "codereview.stackexchange", "id": 43514, "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 Another consequence of simplification is the use of environments. Parsers and Suspensions and Operator objects all contain a pointer to an environment -- ie. the saved, closed or curried values that accompany the function pointer. But in many cases I've seemed to "get away with" not actually using the environment pointer to hold an association list. For simple things like predicate operators the code just stores the values directly in the environment slot or a simple cons structure to hold a few values in a little tree. This approach seemed to help keep simple things simple. Parser objects for the most part use the environment to hold association lists. And the into() and bind() parsers take some care to propagate environment information to their child functions. This is essential for the behavior of parser into( parser p, symbol id, parser q ) combinator. The parser resulting from this function must pass the result from executing the parser p into the parser q by defining it with the symbol id. The parser q in this case should be the result of parser bind( parser p, operator op ) so that the op can receive this value in its environment. For my own uses this feels like a safe restriction, but possibly it could limit the applicability of this code for certain applications that might need environment data to propagate around more, I guess. As much as possible, I've tried to make the code read like pseudocode. So if you just look at the nouns and verbs in a line of code, that ought to give you some sense of what it's trying to do. The punctuation might get a little heavy in places, however.
{ "domain": "codereview.stackexchange", "id": 43514, "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 The symbol type builds upon an enum for compile time symbols. So compile time symbols use the "code space" from 0 going up. That leaves EOF to resolve naturally to -1. And any dynamic symbols created by symbol symbol_from_string( string s ), if there are no previously allocated compile time symbols with the same printname, then a new dynamic symbol code is allocated in the code space from -2 going down. The effect of this can be seen in the test_ebnf() function. Any dynamically created symbols that arise from the productions string, in order to refer to them elsewhere in the code and have the symbol codes actually match, must be previously allocated. In the test_ebnf() function, in order to call assoc_symbol() on the result from the ebnf parser and actually get the start parser out of the association list, there must be a previous call to Symbol() with that enum name. So, if you were to comment out the call to Symbol(postal_address) from the beginning of the function it would fail at the end. Any improvements to be made, to the interface or the implementation? I'd like to use this code to build compilers and interpreters for languages described by EBNF grammars. One notable missing feature is the ability to factor out left recursion from EBNF productions or parser graphs. github $ make count wc pc11*[ch] 437 1879 11141 pc11object.c 101 517 3607 pc11object.h 639 2496 16281 pc11parser.c 81 322 1918 pc11parser.h 169 685 4904 pc11test.c 1427 5899 37851 total
{ "domain": "codereview.stackexchange", "id": 43514, "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 Makefile CFLAGS= -std=c99 -g -Wall -Wpedantic -Wextra -Wno-unused-function -Wno-unused-parameter -Wno-switch -Wno-return-type -Wunused-variable CFLAGS+= $(cflags) test : pc11 ./$< pc11 : pc11object.o pc11parser.o pc11test.o $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS) pc11object.o : pc11object.[ch] pc11parser.o : pc11parser.[ch] pc11object.h pc11test.o : pc11test.c pc11parser.h pc11object.h clean : rm *.o count : wc pc11*[ch] ppnarg_h /* * The PP_NARG macro evaluates to the number of arguments that have been * passed to it. * * Laurent Deniau, "__VA_NARG__," 17 January 2006, <comp.std.c> (29 November 2007). */ #define PP_NARG(...) PP_NARG_(__VA_ARGS__,PP_RSEQ_N()) #define PP_NARG_(...) PP_ARG_N(__VA_ARGS__) #define PP_ARG_N( \ _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \ _11,_12,_13,_14,_15,_16,_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,_52,_53,_54,_55,_56,_57,_58,_59,_60, \ _61,_62,_63,_64,_65,_66,_67,_68,_69,_70, \ _71,N,...) N #define PP_RSEQ_N() \ 71,70, \ 69,68,67,66,65,64,63,62,61,60, \ 59,58,57,56,55,54,53,52,51,50, \ 49,48,47,46,45,44,43,42,41,40, \ 39,38,37,36,35,34,33,32,31,30, \ 29,28,27,26,25,24,23,22,21,20, \ 19,18,17,16,15,14,13,12,11,10, \ 9,8,7,6,5,4,3,2,1,0 pc11object.h #define PC11OBJECT_H #include <stdlib.h> #include <stdio.h> #include "ppnarg.h"
{ "domain": "codereview.stackexchange", "id": 43514, "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 pc11object.h #define PC11OBJECT_H #include <stdlib.h> #include <stdio.h> #include "ppnarg.h" #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 suspension; typedef object parser; typedef object operator; typedef operator binoperator; typedef operator predicate; typedef object symbol; typedef object string; typedef object boolean; 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 ); enum object_symbol_codes { T, END_OBJECT_SYMBOLS }; typedef enum { INVALID, INT, LIST, SUSPENSION, PARSER, OPERATOR, SYMBOL, STRING, VOID } tag; union object { tag t; struct { tag t; int i; } Int; struct { tag t; object first, rest; } List; struct { tag t; object env; fSuspension *f; const char *printname; } Suspension; struct { tag t; object env; fParser *f; const char *printname; } Parser; struct { tag t; object env; fOperator *f; const char *printname; } Operator; struct { tag t; int code; const char *printname; object data; } Symbol; struct { tag t; char *str; int disposable; } String; struct { tag t; object next; int forward; } Header; struct { tag t; void *pointer; } Void; }; extern object T_ /* = (union object[]){ {.t=1}, {.Symbol={SYMBOL, T, "T"}} } + 1 */, NIL_ /* = (union object[]){ {.t=INVALID} } */; static int valid( object it ){ // valid will also convert a boolean T_ or NIL_ to an integer 1 or 0 return it && it->t <= VOID && it->t != INVALID; }
{ "domain": "codereview.stackexchange", "id": 43514, "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 integer Int( int i ); boolean Boolean( int b ); list one( object it ); list cons( object first, object rest ); suspension Suspension_( object env, fSuspension *f, const char *printname ); #define Suspension(env,f) Suspension_( env, f, __func__ ) parser Parser_( object env, fParser *f, const char *printname ); #define Parser(env,f) Parser_( env, f, __func__ ) operator Operator_( object env, fOperator *f, const char *printname ); #define Operator(env,f) Operator_( env, f, #f ) string String( char *str, int disposable ); symbol Symbol_( int code, const char *printname, object data ); #define Symbol(n) Symbol_( n, #n, NIL_ ) object Void( void *pointer ); int length( list ls ); string to_string( list ls ); void print( object a ); void print_list( object a ); object first( list it ); list rest( list it ); list take( int n, list it ); list drop( int n, list it ); object apply( operator op, object it ); list chars_from_str( char *str ); list chars_from_file( FILE *file ); list ucs4_from_utf8( list o ); list utf8_from_ucs4( list o ); list map( operator op, list it ); object collapse( fBinOperator *f, list it ); object reduce( fBinOperator *f, int n, object *po ); #define LIST(...) \ reduce( cons, PP_NARG(__VA_ARGS__), (object[]){ __VA_ARGS__ } ) boolean eq( object a, object b ); boolean eq_symbol( int code, object b ); list append( list start, list end ); list env( list tail, int n, ... ); object assoc( object key, list env ); object assoc_symbol( int code, list env ); symbol symbol_from_string( string s ); pc11object.c #define _BSD_SOURCE #include "pc11object.h" #include <stdarg.h> #include <string.h> #define OBJECT(...) new_( (union object[]){{ __VA_ARGS__ }} ) object T_ = (union object[]){ {.t=1}, {.Symbol={SYMBOL, T, "T"}} } + 1, NIL_ = (union object[]){ {.t=INVALID} }; static object new_( object prototype );
{ "domain": "codereview.stackexchange", "id": 43514, "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 new_( object prototype ); integer Int( int i ){ return OBJECT( .Int = { INT, i } ); } boolean Boolean( int b ){ return b ? T_ : NIL_; } list one( object it ){ return cons( it, NIL_ ); } list cons( object first, object rest ){ return OBJECT( .List = { LIST, first, rest } ); } 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 } ); } operator Operator_( object env, fOperator *f, const char *printname ){ return OBJECT( .Operator = { OPERATOR, env, f, printname } ); } string String( char *str, int disposable ){ return OBJECT( .String = { STRING, str, disposable } ); } symbol Symbol_( int code, const char *printname, object data ){ return OBJECT( .Symbol = { SYMBOL, code, printname, data } ); } object Void( void *pointer ){ return OBJECT( .Void = { VOID, pointer } ); } int length( list ls ){ return valid( ls ) ? valid( first( ls ) ) + length( rest( ls ) ) : 0; } 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; }
{ "domain": "codereview.stackexchange", "id": 43514, "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 print_innards = 1; static int print_chars = 1; static int print_codes = 0; 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; } } 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; } } 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; } } object force_( object it ){ if( it->t != SUSPENSION ) return it; return force_( it->Suspension.f( it->Suspension.env ) ); } static object force_first ( object it ){ \ *it = *force_( it ); \ return first( it ); \ } \ object first( list it ){ \ if( it->t == SUSPENSION ) return Suspension( it, force_first ); if( it->t != LIST ) return NIL_; return it->List.first; }
{ "domain": "codereview.stackexchange", "id": 43514, "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 force_rest ( object it ){ \ *it = *force_( it ); \ return rest( it ); \ } \ object rest( list it ){ \ if( it->t == SUSPENSION ) return Suspension( it, force_rest ); if( it->t != LIST ) return NIL_; return it->List.rest; } 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 ) ) ); } 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 ) ); } static object force_apply( list env ){ operator op = first( env ); object it = rest( env ); *it = *force_( it ); return apply( op, 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 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_str( char *str ){ if( ! str ) return NIL_; return Suspension( String( str, 0 ), force_chars_from_string ); } 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 ) ); } list chars_from_file( FILE *file ){ if( ! file ) return NIL_; return Suspension( Void( file ), force_chars_from_file ); }
{ "domain": "codereview.stackexchange", "id": 43514, "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 leading_ones( object byte ){ if( byte->t != INT ) return 0; int x = byte->Int.i; return x&0x80 ? x&0x40 ? x&0x20 ? x&0x10 ? x&8 ? x&4 ? 6 : 5 : 4 : 3 : 2 : 1 : 0; } 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); } 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 ) ); } list ucs4_from_utf8( list input ){ if( ! input ) return NIL_; return Suspension( input, force_ucs4_from_utf8 ); }
{ "domain": "codereview.stackexchange", "id": 43514, "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; } list utf8_from_ucs4( list input ){ if( ! input ) return NIL_; return Suspension( input, force_utf8_from_ucs4 ); } list map( operator op, list it ){ if( ! valid( it ) ) return it; return cons( apply( op, first( it ) ), map( op, rest( it ) ) ); }
{ "domain": "codereview.stackexchange", "id": 43514, "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 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 ); } 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; } static int next_symbol_code = -2;
{ "domain": "codereview.stackexchange", "id": 43514, "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 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_ ); } 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, ATOM, PROBE_P, PROBE_MODE, SEQ, ANY, EPSILON, MAYBE, MANY, END_PARSER_SYMBOLS }; list parse( parser p, list input ); int is_ok( list result ); int not_ok( list result ); parser succeeds( list result ); parser fails( list errormsg ); parser satisfy( predicate pred ); 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 ); parser either( parser p, parser q ); #define ANY(...) reduce( either, PP_NARG(__VA_ARGS__), (object[]){ __VA_ARGS__ } ) parser sequence( parser p, parser q, binoperator op ); parser xthen( parser p, parser q ); parser thenx( parser p, parser q ); parser then( parser p, parser q ); #define SEQ(...) reduce( then, PP_NARG(__VA_ARGS__), (object[]){ __VA_ARGS__ } ) parser forward( void ); parser maybe( parser p ); parser many( parser p ); parser some( parser p ); parser item( void ); parser probe( parser p, int mode ); //print on ok iff mode&1, print not ok iff mode&2 parser bind( parser p, operator op ); parser into( parser p, object id, parser q );
{ "domain": "codereview.stackexchange", "id": 43514, "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 bind( parser p, operator op ); parser into( parser p, object id, parser q ); // E->T ('|' T)* // T->F* // F->A ('*' | '+' | '?')? // A->'.' | '('E')' | C // C->S|L|P // S->'\' ('.' | '|' | '(' | ')' | '[' | ']' | '/' ) // L->'[' '^'? ']'? [^]]* ']' // P->Plain char parser regex( char *re ); // 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> list parse( parser p, list input ){ if( !valid( p ) || !valid( input ) || p->t != PARSER ) return LIST( Symbol( FAIL ), String("parse() validity check failed",0), input ); return p->Parser.f( p->Parser.env, input ); } static object success( object v, list input ){ return cons( Symbol( OK ), cons( v, input ) ); } static object fail( object v, list input ){ return cons( Symbol( FAIL ), cons( v, 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 ); } 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 satisfy( predicate pred ){ return Parser( env( NIL_, 1, Symbol(SATISFY_PRED), pred ), parse_satisfy ); } boolean always_true( object v, object it ){ return T_; } parser item( void ){ return satisfy( Operator( NIL_, always_true ) ); }
{ "domain": "codereview.stackexchange", "id": 43514, "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 item( void ){ return satisfy( Operator( NIL_, always_true ) ); } static boolean is_alpha( object v, object it ){ return Boolean( it->t == INT && isalpha( it->Int.i ) ); } parser alpha( void ){ return satisfy( Operator( NIL_, is_alpha ) ); } static boolean is_upper( object v, object it ){ return Boolean( it->t == INT && isupper( it->Int.i ) ); } parser upper( void ){ return satisfy( Operator( NIL_, is_upper ) ); } static boolean is_lower( object v, object it ){ return Boolean( it->t == INT && islower( it->Int.i ) ); } parser lower( void ){ return satisfy( Operator( NIL_, is_lower ) ); } static boolean is_digit( object v, object it ){ return Boolean( it->t == INT && isdigit( it->Int.i ) ); } parser digit( void ){ return satisfy( Operator( NIL_, is_digit ) ); } static boolean is_literal( object example, object it ){ return eq( example, it ); } parser literal( object example ){ return satisfy( Operator( example, is_literal ) ); } parser chr( int c ){ return literal( Int( c ) ); } parser str( char *s ){ return !*s ? succeeds( NIL_ ) : s[1] ? then( chr( *s ), str( s+1 ) ) : chr( *s ); } 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 range( int lo, int hi ){ return satisfy( Operator( cons( Int( lo ), Int( hi ) ), is_range ) ); } static boolean is_anyof( object set, object it ){ return Boolean( it->t == INT && strchr( set->String.str, it->Int.i ) != NULL ); } parser anyof( char *s ){ return satisfy( Operator( String( s, 0 ), is_anyof ) ); } static boolean is_noneof( object set, object it ){ return Boolean( it->t == INT && strchr( set->String.str, it->Int.i ) == NULL ); } parser noneof( char *s ){ return satisfy( Operator( String( s, 0 ), is_noneof ) ); }
{ "domain": "codereview.stackexchange", "id": 43514, "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 noneof( char *s ){ return satisfy( Operator( String( s, 0 ), is_noneof ) ); } 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 ); } parser either( parser p, parser q ){ return Parser( env( NIL_, 2, Symbol(EITHER_Q), q, Symbol(EITHER_P), p ), parse_either ); } 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 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 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 ); } }
{ "domain": "codereview.stackexchange", "id": 43514, "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 then( parser p, parser q ){ return sequence( p, q, Operator( NIL_, concat ) ); } static object left( object l, object r ){ return l; } static object right( object l, object r ){ return r; } parser xthen( parser p, parser q ){ return sequence( p, q, Operator( NIL_, right ) ); } parser thenx( parser p, parser q ){ return sequence( p, q, Operator( NIL_, left ) ); } parser forward( void ){ parser p = Parser( 0, 0 ); p[-1].Header.forward = 1; return p; } parser maybe( parser p ){ return either( p, succeeds( NIL_ ) ); } parser many( parser p ){ parser q = forward(); *q = *maybe( then( p, q ) ); return q; } parser some( parser p ){ return then( p, many( p ) ); } 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 ); } parser bind( parser p, operator op ){ return Parser( env( NIL_, 2, Symbol(BIND_P), p, Symbol(BIND_OP), op ), parse_bind ); }
{ "domain": "codereview.stackexchange", "id": 43514, "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 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; } 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 ); } 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; } parser probe( parser p, int mode ){ return Parser( env( NIL_, 2, Symbol(PROBE_MODE), Int( mode ), Symbol(PROBE_P), p ), parse_probe ); } 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 ); }
{ "domain": "codereview.stackexchange", "id": 43514, "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_chr( object v, object it ){ return literal( it ); } static parser on_meta( object v, object it ){ parser atom = assoc_symbol( 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 ); } 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 ); } #define META "*+?" #define SPECIAL META ".|()[]/"
{ "domain": "codereview.stackexchange", "id": 43514, "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(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; } 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 ) ); } 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 ); } static parser make_matcher( object env, object input ){ return str( to_string( input )->String.str ); }
{ "domain": "codereview.stackexchange", "id": 43514, "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 make_sequence( object env, object input ){ if( length( input ) == 0 ) return Symbol( EPSILON ); if( length( input ) < 2 ) return input; return one( cons( Symbol( SEQ ), input ) ); } static list make_any( object env, object input ){ if( length( input ) < 2 ) return input; return one( cons( Symbol( ANY ), input ) ); } static list make_maybe( object env, object input ){ return one( cons( Symbol( MAYBE ), input ) ); } static list make_many( object env, object input ){ return one( cons( Symbol( MANY ), input ) ); }
{ "domain": "codereview.stackexchange", "id": 43514, "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": 43514, "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": 43514, "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 define_forward( object env, object it ){ if( rest( it )->t == PARSER ) return it; return cons( first( it ), forward() ); } static parser compile_bnf( object env, object it ){ 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( SEQ, f ) ) ) return collapse( then, map( (union object[]){{.Operator={OPERATOR,env,compile_bnf}}}, rest( it ) ) ); if( valid( eq_symbol( ANY, f ) ) ) return collapse( either, map( (union object[]){{.Operator={OPERATOR,env,compile_bnf}}}, rest( it ) ) ); if( valid( eq_symbol( MANY, f ) ) ) return many( map( (union object[]){{.Operator={OPERATOR,env,compile_bnf}}}, rest( it ) ) ); if( valid( eq_symbol( MAYBE, f ) ) ) return maybe( map( (union object[]){{.Operator={OPERATOR,env,compile_bnf}}}, rest( it ) ) ); return map( (union object[]){{.Operator={OPERATOR,env,compile_bnf}}}, 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; }
{ "domain": "codereview.stackexchange", "id": 43514, "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 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(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; } pc11test.c #include "pc11parser.h" enum test_symbol_codes { TEST = END_PARSER_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(); int main( void ){ return test_basics() || test_parsers() || test_regex() || test_ebnf(); } static int test_basics(){ puts( __func__ ); list ch = chars_from_str( "abcdef" ); print( ch ), puts(""); // print with dot notation print_list( ch ), puts(""); // print with list notation drop( 6, ch ); // force first 6 elements of stream print( ch ), puts(""); print_list( ch ), puts(""); drop( 7, ch ); print( ch ), puts(""); print_list( ch ), puts(""); puts(""); return 0; }
{ "domain": "codereview.stackexchange", "id": 43514, "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_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; } 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("");
{ "domain": "codereview.stackexchange", "id": 43514, "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 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 object stringify( object env, object 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);
{ "domain": "codereview.stackexchange", "id": 43514, "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 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 ) ) ); print_list( parsers ), puts("\n"); // long output when showing innards parser start = first( assoc_symbol( postal_address, parsers ) ); print_list( start ), puts("\n"); print_list( parse( start, chars_from_str( "Mr. luser droog I\n2357 Streetname\nAnytown, ST 00700\n" ) ) ), puts(""); return 0; }
{ "domain": "codereview.stackexchange", "id": 43514, "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 return 0; } Output from the testing code: $ make clean test rm *.o cc -std=c99 -g -Wall -Wpedantic -Wextra -Wno-unused-function -Wno-unused-parameter -Wno-switch -Wno-return-type -Wunused-variable -c -o pc11object.o pc11object.c cc -std=c99 -g -Wall -Wpedantic -Wextra -Wno-unused-function -Wno-unused-parameter -Wno-switch -Wno-return-type -Wunused-variable -c -o pc11parser.o pc11parser.c cc -std=c99 -g -Wall -Wpedantic -Wextra -Wno-unused-function -Wno-unused-parameter -Wno-switch -Wno-return-type -Wunused-variable -c -o pc11test.o pc11test.c cc -std=c99 -g -Wall -Wpedantic -Wextra -Wno-unused-function -Wno-unused-parameter -Wno-switch -Wno-return-type -Wunused-variable -o pc11 pc11object.o pc11parser.o pc11test.o ./pc11 test_basics ...(chars_from_str) ...(chars_from_str) ('a' .('b' .('c' .('d' .('e' .('f' ....(force_chars_from_string) )))))) ('a' 'b' 'c' 'd' 'e' 'f' ...(force_chars_from_string) ) ('a' .('b' .('c' .('d' .('e' .('f' .(EOF .() ))))))) ('a' 'b' 'c' 'd' 'e' 'f' EOF ) test_parsers (OK '*' ...(chars_from_str) ) (FAIL "Do you want a cookie?" ...(chars_from_str) ) (OK 'a' ...(force_chars_from_string) ) (OK 'a' ...(force_chars_from_string) ) (OK 'a' ...(force_chars_from_string) ) test_regex Parser(satisfy, ((SATISFY_PRED .Oper(always_true, () ) ).() )) (OK 'a' ...(force_chars_from_string) ) (OK '.' ...(force_chars_from_string) ) (OK '\' ...(force_chars_from_string) ) Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '.' ) ).() )) (FAIL ("predicate not satisfied" Oper(is_literal, '.' ) ) 'a' ...(force_chars_from_string) ) (OK '.' ...(force_chars_from_string) ) (FAIL ("predicate not satisfied" Oper(is_literal, '.' ) ) '\' ...(force_chars_from_string) )
{ "domain": "codereview.stackexchange", "id": 43514, "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(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '\' ) ).() )) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(always_true, () ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) (FAIL ("predicate not satisfied" Oper(is_literal, '\' ) ) 'a' ...(force_chars_from_string) ) (FAIL ("predicate not satisfied" Oper(is_literal, '\' ) ) '.' ...(force_chars_from_string) ) (OK ('\' '.' ) ...(force_chars_from_string) ) (OK ('\' 'a' ) ...(force_chars_from_string) ) Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '\' ) ).() )) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '.' ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) (FAIL ("predicate not satisfied" Oper(is_literal, '\' ) ) 'a' ...(force_chars_from_string) ) (FAIL ("predicate not satisfied" Oper(is_literal, '\' ) ) '.' ...(force_chars_from_string) ) (OK ('\' '.' ) ...(force_chars_from_string) ) (FAIL (("predicate not satisfied" Oper(is_literal, '.' ) ) "after" '\' ) 'a' ...(force_chars_from_string) ) Parser(either, ((EITHER_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '\' ) ).() )) ).((EITHER_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'a' ) ).() )) ).() ))) (OK 'a' ...(force_chars_from_string) ) (FAIL ("predicate not satisfied" Oper(is_literal, 'a' ) ) '.' ...(force_chars_from_string) ) (OK '\' ...(force_chars_from_string) ) (OK '\' ...(force_chars_from_string) ) Parser(satisfy, ((SATISFY_PRED .Oper(is_anyof, "abcd" ) ).() )) (OK 'a' ...(force_chars_from_string) ) (FAIL ("predicate not satisfied" Oper(is_anyof, "abcd" ) ) '.' ...(force_chars_from_string) )
{ "domain": "codereview.stackexchange", "id": 43514, "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 test_ebnf ((postal_address Parser(sequence, ((SEQUENCE_P .Parser(bind) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(sequence) ).((SEQUENCE_Q .Parser(sequence) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (name_part Parser(either, ((EITHER_P .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(sequence) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, ' ' ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((EITHER_Q .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(bind) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).() ))) ) (personal_part Parser(either, ((EITHER_P .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '.' ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((EITHER_Q .Parser(sequence) ).() ))) ) (street_address Parser(sequence, ((SEQUENCE_P .Parser(sequence) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(bind) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '
{ "domain": "codereview.stackexchange", "id": 43514, "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_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (zip_part Parser(sequence, ((SEQUENCE_P .Parser(sequence) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, ',' ) ).() )) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(sequence) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(either) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(sequence) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '
{ "domain": "codereview.stackexchange", "id": 43514, "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_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (opt_suffix_part Parser(either, ((EITHER_P .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'S' ) ).() )) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'r' ) ).() )) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '.' ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((EITHER_Q .Parser(either, ((EITHER_P .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'J' ) ).() )) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'r' ) ).() )) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '.' ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((EITHER_Q .Parser(either, ((EITHER_P .Parser(sequence) ).((EITHER_Q .Parser(succeeds, () ) ).() ))) ).() ))) ).() ))) ) (opt_apt_num Parser(either, ((EITHER_P .(Parser(sequence) .() )).((EITHER_Q .Parser(succeeds, () ) ).() ))) ) (apt_num Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_digit, () ) ).() )) ).((SEQUENCE_Q .Parser(either) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (town_name Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_alpha, () ) ).() )) ).((SEQUENCE_Q .Parser(either) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (state_code Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_upper, () ) ).() )) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_upper, () ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (zip_code Parser(sequence, ((SEQUENCE_P .Parser(satisfy,
{ "domain": "codereview.stackexchange", "id": 43514, "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 .Oper(concat, () ) ).() )))) ) (zip_code Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_digit, () ) ).() )) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_digit, () ) ).() )) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_digit, () ) ).() )) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_digit, () ) ).() )) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_digit, () ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (initial Parser(either, ((EITHER_P .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'M' ) ).() )) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'r' ) ).() )) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 's' ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((EITHER_Q .Parser(either, ((EITHER_P .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'M' ) ).() )) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'r' ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((EITHER_Q .Parser(either, ((EITHER_P .Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'M' ) ).() )) ).((SEQUENCE_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 's' ) ).() )) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((EITHER_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'M' ) ).() )) ).() ))) ).() ))) ).() ))) ) (roman_numeral Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'I' ) ).() )) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(either, ((EITHER_P .(Parser(either, ((EITHER_P .Parser(satisfy, ((SATISFY_PRED
{ "domain": "codereview.stackexchange", "id": 43514, "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_P .Parser(either, ((EITHER_P .(Parser(either, ((EITHER_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'V' ) ).() )) ).((EITHER_Q .Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, 'X' ) ).() )) ).() ))) .() )).((EITHER_Q .Parser(succeeds, () ) ).() ))) ).((SEQUENCE_Q .Parser(either) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (first_name Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_alpha, () ) ).() )) ).((SEQUENCE_Q .Parser(either) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (last_name Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_alpha, () ) ).() )) ).((SEQUENCE_Q .Parser(either) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (house_num Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_digit, () ) ).() )) ).((SEQUENCE_Q .Parser(either) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (street_name Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_alpha, () ) ).() )) ).((SEQUENCE_Q .Parser(either) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (EPSILON Parser(succeeds, () ) ) (SP Parser(either) ) (NAME Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_alpha, () ) ).() )) ).((SEQUENCE_Q .Parser(either) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (NUMBER Parser(sequence, ((SEQUENCE_P .Parser(satisfy, ((SATISFY_PRED .Oper(is_digit, () ) ).() )) ).((SEQUENCE_Q .Parser(either) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ) (UPPER Parser(satisfy, ((SATISFY_PRED .Oper(is_upper, () ) ).() )) ) (DIGIT Parser(satisfy, ((SATISFY_PRED .Oper(is_digit, () ) ).() )) ) (EOL Parser(satisfy, ((SATISFY_PRED .Oper(is_literal, '
{ "domain": "codereview.stackexchange", "id": 43514, "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 ' ) ).() )) ) )
{ "domain": "codereview.stackexchange", "id": 43514, "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(sequence, ((SEQUENCE_P .Parser(bind) ).((SEQUENCE_Q .Parser(sequence, ((SEQUENCE_P .Parser(sequence) ).((SEQUENCE_Q .Parser(sequence) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) ).((SEQUENCE_OP .Oper(concat, () ) ).() )))) (OK ("Mr. luser droog I " '2' '3' '5' '7' ' ' "Streetname" ' ' 'A' 'n' 'y' 't' 'o' 'w' 'n' ',' ' ' 'S' 'T' ' ' '0' '0' '7' '0' '0' ' ' ) ...(force_chars_from_string) ) Answer: General Observations The code is not maintainable. While the code seems to follow some general software development principles such as the Single Responsibility Principle there is no documentation (comments) within the code. Each file should indicate the purpose of the file and the design decisions within the file. The comments that do exist are not helpful, meaningful: print(ch), puts(""); // print with dot notation print_list(ch), puts(""); // print with list notation drop(6, ch); // force first 6 elements of stream ... print_list(parsers), puts("\n"); // long output when showing innards Enum declarations such as typedef enum { INVALID, INT, LIST, SUSPENSION, PARSER, OPERATOR, SYMBOL, STRING, VOID } tag;
{ "domain": "codereview.stackexchange", "id": 43514, "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 are harder to maintain than enums that are declared vertically. The code contains both so the code is inconsistent in its implementation. The fact that pointers are used is hidden in many places: #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 suspension; typedef object parser; typedef object operator; typedef operator binoperator; typedef operator predicate; typedef object symbol; typedef object string; typedef object boolean; 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); Hiding pointers can lead to all kinds of maintenance issues, and it makes the code harder to write and debug. Most of the declarations above could use some comments, I don't know what parser should actually be doing, nor do I now what suspension is for. The list of typedefs above also needs some vertical spacing, I was originally unable to find list. Missing Include Guards Include guards are necessary to prevent header files from being included multiple times. The code doesn't contain any include guards in the header files. There are 2 ways in C and C++ to implement include guards, for personal preference I use #ifndef INCLUDE_FILENAME_H #define INCLUDE_FILENAME_H Body of include here ... #endif /* INCLUDE_FILENAME_H */
{ "domain": "codereview.stackexchange", "id": 43514, "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 Body of include here ... #endif /* INCLUDE_FILENAME_H */ The alternative is #pragma once In the C and C++ programming languages, pragma once is a non-standard but widely supported preprocessor directive designed to cause the current source file to be included only once in a single compilation. Thus, #pragma once serves the same purpose as include guards, but with several advantages, including: less code, avoidance of name clashes, and sometimes improvement in compilation speed. On the other hand, #pragma once is not necessarily available in all compilers and its implementation is tricky and might not always be reliable.
{ "domain": "codereview.stackexchange", "id": 43514, "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 }
python, python-3.x, pandas Title: Forecast experimental results based on temperature Question: I would really welcome any hints on making this code more concise please. In this example we have some experiment results. For each planned experiment We have predicted results based on 4 temperatures and we have 4 forecasted results, 1 for each of the temperature. For each experiment when the actual experiment is received, we need to find it's predicted results and use the actual result to find between which 2 temperatures did the result fall between and then use the prediction values corresponding to those temperatures. i.e. if the actual result is between the values for Temp_10 and Temp_15 we know we have to use Predicted_Result_10 and Predicted_Result_15. I would welcome any suggestions on how to make this more concise and most labs will have at least 18 temperatures and 18 predicted results and also cater for different labs that have more that 18. I will know for each lab how many they will have ie USA Lab has 25 temperatures and 25 predicted results UK Lab has 20 temperatures and 20 predicted results AUS Lab has 18 temperatures and 18 predicted results Thanks for your time import pandas as pd predicted_data = [['A',35,36,37,37,11.1955,11.8546,12.3809,12.8378], ['B',38,36,38,37,9.2410,9.7486,10.1248,10.4282], ['C',34,35,35,39,9.2686,9.7707,10.1330,10.4166] ] result_data = [['A',11.3], ['B',10.11], ['C',9.53]] predicted_df = pd.DataFrame(predicted_data,columns=['Experiment','Predicted_Result_10','Predicted_Result_15', \ 'Predicted_Result_20','Predicted_Result_30', \ 'Temp_10','Temp_15','Temp_20','Temp_30']) print (predicted_df) result_df = pd.DataFrame(result_data,columns=['Experiment','Result']) print (result_df)
{ "domain": "codereview.stackexchange", "id": 43515, "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, python-3.x, pandas", "url": null }
python, python-3.x, pandas def dummy_function (predicted_result1: float, predicted_result2: float): # actual function is more complex print ('calculation using ', predicted_result1, predicted_result2) return predicted_result1 + predicted_result2 Experiment_A_result = 0 Experiment_B_result = 0 Experiment_C_result = 0 for index,result in result_df.iterrows(): # search predicted results for each experiment # print (predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]) # print ( ' actual result ',result['Result']) # print (type(result['Result'])) # print (predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Temp_10'])
{ "domain": "codereview.stackexchange", "id": 43515, "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, python-3.x, pandas", "url": null }
python, python-3.x, pandas # For an actual result, we want to find which 2 Temp columns from the predicted data does the actual # result fall between. Having found those 2 columns if (predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Temp_10'].iloc[0]) <= result['Result'] \ < predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Temp_15'].iloc[0]: print (' do a calculation using the predicted results 10 and 15 as they match the range') my_result = dummy_function(predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Predicted_Result_10'].iloc[0], predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Predicted_Result_15'].iloc[0]) elif (predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Temp_15'].iloc[0]) <= result['Result'] \ < predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Temp_20'].iloc[0]: print (' do a calculation using the predicted results 15 and 20 as they match the range') my_result = dummy_function( predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Predicted_Result_15'].iloc[0], predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Predicted_Result_20'].iloc[0]) elif (predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Temp_20'].iloc[0]) <= result['Result'] \ < predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Temp_30'].iloc[0]: print (' do a calculation using the predicted results 20 and 30 as they match the range') my_result = dummy_function(predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Predicted_Result_20'].iloc[0], predicted_df.loc[predicted_df['Experiment'] == result['Experiment']]['Predicted_Result_30'].iloc[0]) if result['Experiment'] == 'A':
{ "domain": "codereview.stackexchange", "id": 43515, "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, python-3.x, pandas", "url": null }
python, python-3.x, pandas if result['Experiment'] == 'A': Experiment_A_result = Experiment_A_result + my_result elif result['Experiment'] == 'B': Experiment_B_result = Experiment_B_result + my_result else: Experiment_C_result = Experiment_C_result + my_result
{ "domain": "codereview.stackexchange", "id": 43515, "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, python-3.x, pandas", "url": null }
python, python-3.x, pandas Answer: Your data are misshapen. Rather than having a separate Temp_ column per... what are those (10, 15, etc.)? Temperatures? There should be an index level per experiment and temperature, and your Result column should have 3 * 4 = 12 rows, due to the cartesian product of those index levels. Don't write _data lists, and don't separately define your columns. Just pass a dict into the DataFrame constructor directly whose keys correspond to the columns. Your dummy_function needs to be deleted and replaced with an aggregate .sum(). Don't iterrows except as a last resort. More importantly, and I'm sure this is you refusing to show what your real code is doing, your my_result is mostly meaningless because it overwrites itself on every iteration. I am going to assume that you really only care about the last row, which is what this loop would deliver; and so delete the loop altogether. Your chained if statements don't have good behaviour at the edges: what if the experimental result is outside of the range of the predicted results? Currently, you don't initialise my_result at all. All of those ifs should be replaced by a call to searchsorted. Suggested import pandas as pd predicted_df = pd.DataFrame( { 'Temp': (11.1955, 11.8546, 12.3809, 12.8378, 9.2410, 9.7486, 10.1248, 10.4282, 9.2686, 9.7707, 10.1330, 10.4166), 'Result': (35, 36, 37, 37, 38, 36, 38, 37, 34, 35, 35, 39), }, index=pd.MultiIndex.from_product( names=('Experiment', 'Base_Temp'), iterables=( ('A', 'B', 'C'), (10, 15, 20, 30), ), ), ) result_df = pd.DataFrame( {'Result': (11.30, 10.11, 9.53)}, index=predicted_df.index.unique('Experiment'), ) print(predicted_df) print(result_df)
{ "domain": "codereview.stackexchange", "id": 43515, "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, python-3.x, pandas", "url": null }
python, python-3.x, pandas print(predicted_df) print(result_df) result = result_df.iloc[-1:] experiment = predicted_df.loc[result.index] y, = experiment.Temp.searchsorted(result.Result) if 0 < y < experiment.shape[0]: my_result = experiment.Result.iloc[y-1: y+1].sum() print(my_result) Output Temp Result Experiment Base_Temp A 10 11.1955 35 15 11.8546 36 20 12.3809 37 30 12.8378 37 B 10 9.2410 38 15 9.7486 36 20 10.1248 38 30 10.4282 37 C 10 9.2686 34 15 9.7707 35 20 10.1330 35 30 10.4166 39 Result Experiment A 11.30 B 10.11 C 9.53 69
{ "domain": "codereview.stackexchange", "id": 43515, "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, python-3.x, pandas", "url": null }
c, linux, 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. 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 liomux.h file implements the Linux specific version, the wiomux.h implements the MS-Windows specific version and chat.c 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. /* chat.c * chat application, example for simple networking framework in C * * Copyright 2022 Andre Adrian * License for this source code: 3-Clause BSD License * * 25jun2022 adr: 2nd published version */ #include <libgen.h> // basename() #ifdef _WIN32 #include "wiomux.h" #else #include "liomux.h" #endif /* ******************************************************** */ // Business logic enum { BUFMAX = 1460, // Ethernet packet size minus IPv4 TCP header size }; // callback client read available int cb_chat_client_read(Conn* obj, SOCKET fd) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(fd >= 0 && fd < FDMAX); char buf[BUFMAX]; int readbytes = recv(fd, 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; }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework // callback server read available int cb_chat_server_read(Conn* obj, SOCKET fd) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(fd >= 0 && fd < FDMAX); char buf[BUFMAX]; // buffer for client data int readbytes = recv(fd, buf, sizeof buf, 0); if (readbytes > 0 && readbytes != SOCKET_ERROR) { // we got some data from a client for (SOCKET i = 0; i < FDMAX; ++i) { // send to everyone! if (FD_ISSET(i, &obj->fds)) { // except the listener and ourselves if (i != obj->sockfd && i != fd) { int writebytes = send(i, buf, readbytes, 0); if (writebytes != readbytes) { perror("WW send"); } } } } } return readbytes; } void keyboard_poll(Conn* obj) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); if (_kbhit()) { // very MS-DOS char buf[BUFMAX]; char* rv = fgets(buf, sizeof buf, stdin); assert(rv != NULL); send(obj->sockfd, buf, strlen(buf), 0); } after(TIMEOUT, (cb_timer_t)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": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework switch(argv[1][0]) { case 'c': { Conn* obj = conn_make(); client_open(obj, argv[2], argv[3]); conn_add_cb(obj, cb_chat_client_read); after(TIMEOUT, (cb_timer_t)keyboard_poll, obj); } break; case 's': { Conn* obj = conn_make(); server_open(obj, argv[2], argv[3]); conn_add_cb(obj, cb_chat_server_read); } 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 framework offers a "Timer class" and a "Connection class". The Connection class sub-classes into a "server class" and into a "client class". Because C is not object oriented, these are only design ideas. /* liomux.h * 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 * * 25jun2022 adr: 2nd published version */ #ifndef LIOMUX_H_ #define LIOMUX_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #include <limits.h> // 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 __func__ enum { CONNMAX = 10, // maximum number of Connection objects FDMAX = 64, // maximum number of open file descriptors CONN_SERVER = 1, // TCP server connection object label CONN_CLIENT = 2, // TCP client connection object label 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
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework typedef int SOCKET; // for MS-Windows compability // get sockaddr, IPv4 or IPv6: void* get_in_addr(struct sockaddr* sa) { assert(sa != NULL); if (AF_INET == sa->sa_family) { return &(((struct sockaddr_in*)sa)->sin_addr); } else { return &(((struct sockaddr_in6*)sa)->sin6_addr); } } // 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, NULL, NULL, &tv); } /* ******************************************************** */ // Timer object typedef void (*cb_timer_t)(void* obj); typedef struct { cb_timer_t cb_timer; // cb_timer and obj are a closure void* obj; struct timespec ts; // expire time } Timer; static Timer timers[TIMERMAX]; // Timer objects array int after(int interval, cb_timer_t cb_timer, void* obj) { assert(interval >= 0); assert(cb_timer != NULL); // no assert obj int id; for (id = 0; id < TIMERMAX; ++id) { if (NULL == timers[id].cb_timer) { break; // found a free entry } } assert (id < TIMERMAX && "timer array full");
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, 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(void) { // looking for expired timers for (int i = 0; i < TIMERMAX; ++i) { if (timers[i].cb_timer != NULL) { 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 != NULL); (*tmp.cb_timer)(tmp.obj); } } } } /* ******************************************************** */ // Connection object typedef struct Conn { fd_set fds; // read file descriptor set int sockfd; // network port for client, listen port for server int isConnecting; // non-blocking connect started, but no finished int typ; // tells client or server object char hostname[STRMAX]; char port[STRMAX]; int (*cb_read)(struct Conn* obj, int fd); // Callback Pointer } Conn; typedef int (*cb_read_t)(Conn* obj, int fd); // Callback Pointer type static Conn conns[CONNMAX]; // Connection objects array
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework static Conn conns[CONNMAX]; // Connection objects array Conn* conn_make(void) { for (int i = 0; i < CONNMAX; ++i) { if (0 == conns[i].typ) { return &conns[i]; // found a free entry } } assert(0 && "conn array full"); return NULL; } void client_open(Conn* obj, const char* hostname, const char* port) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(port != NULL); assert(hostname != NULL); printf("II %s: port=%s hostname=%s\n", FUNCTION, port, hostname); FD_ZERO(&obj->fds); obj->typ = CONN_CLIENT; strcpy_s(obj->port, sizeof obj->port, port); strcpy_s(obj->hostname, sizeof obj->hostname, hostname); void client_open1(Conn* obj); client_open1(obj); } void client_open1(Conn* obj) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); struct addrinfo hints; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; struct addrinfo* res; int rv = getaddrinfo(obj->hostname, obj->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 != NULL; p = p->ai_next) { obj->sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (-1 == obj->sockfd) { perror("WW socket"); continue; } // Unix Networking Programming v2 ch. 15.4, 16.2 non-blocking connect int val = 1; rv = ioctl(obj->sockfd, FIONBIO, &val); if (rv != 0) { perror("WW ioctl FIONBIO ON"); close(obj->sockfd); continue; } rv = connect(obj->sockfd, p->ai_addr, p->ai_addrlen); if (rv != 0) { if (EINPROGRESS == errno) { obj->isConnecting = 1; } else { perror("WW connect"); close(obj->sockfd); continue; } } break; // exit loop after socket and connect were successful }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework break; // exit loop after socket and connect were successful } assert(p != NULL && "connect try"); void* src = get_in_addr((struct sockaddr*)p->ai_addr); char dst[INET6_ADDRSTRLEN]; inet_ntop(p->ai_family, src, dst, sizeof dst); 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, obj->hostname, dst, obj->port, obj->sockfd); } void client_reopen(Conn* obj) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); close(obj->sockfd); FD_CLR(obj->sockfd, &obj->fds); // remove network fd obj->sockfd = -1; after(5000, (cb_timer_t)client_open1, obj); // ugly bug with after(0, ... } void client_connect(Conn* obj) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); obj->isConnecting = 0; int optval = 0; socklen_t optlen = sizeof optval; int rv = getsockopt(obj->sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen); assert(0 == rv && "getsockopt SOL_SOCKET SO_ERROR"); if (0 == optval) { FD_SET(obj->sockfd, &obj->fds); printf("II %s: connect success to %s port %s socket %d\n", FUNCTION, obj->hostname, obj->port, obj->sockfd); } else { fprintf(stderr, "WW %s: connect fail to %s port %s socket %d: %s\n", FUNCTION, obj->hostname, obj->port, obj->sockfd, strerror(optval)); client_reopen(obj); } } void client_handle(Conn* obj, int fd) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(fd >= 0 && fd < FDMAX); assert(obj->cb_read != NULL); int rv = (*obj->cb_read)(obj, fd); if (rv < 1) { int optval = 0; socklen_t optlen = sizeof optval; int rv = getsockopt(obj->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, obj->hostname, obj->port, obj->sockfd, rv, strerror(optval)); client_reopen(obj); } }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework void conn_add_cb(Conn* obj, cb_read_t cb_read) { assert(cb_read != NULL); obj->cb_read = cb_read; } void server_open(Conn* obj, const char* hostname, const char* port) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(port != NULL); // no assert hostname printf("II %s: port=%s hostname=%s\n", FUNCTION, port, hostname); FD_ZERO(&obj->fds); obj->typ = CONN_SERVER; 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 != NULL; p = p->ai_next) { obj->sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (-1 == obj->sockfd) { perror("WW socket"); continue; } int yes = 1; rv = setsockopt(obj->sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); if (rv != 0) { perror("WW setsockopt SO_REUSEADDR"); close(obj->sockfd); continue; } rv = bind(obj->sockfd, p->ai_addr, p->ai_addrlen); if (rv != 0) { perror("WW bind"); close(obj->sockfd); continue; } break; // exit loop after socket and bind were successful } freeaddrinfo(res); assert(p != NULL && "bind"); rv = listen(obj->sockfd, 10); assert(0 == rv && "listen"); // add the listener to the master set FD_SET(obj->sockfd, &obj->fds); printf("II %s: listen on socket %d\n", FUNCTION, obj->sockfd); }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework printf("II %s: listen on socket %d\n", FUNCTION, obj->sockfd); } void server_handle(Conn* obj, int fd) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(fd >= 0 && fd < FDMAX); if (fd == obj->sockfd) { // handle new connections struct sockaddr_storage remoteaddr; // client address socklen_t addrlen = sizeof remoteaddr; // newly accept()ed socket descriptor int newfd = accept(obj->sockfd, (struct sockaddr*)&remoteaddr, &addrlen); if (-1 == newfd) { perror("WW accept"); } else { FD_SET(newfd, &obj->fds); void* src = get_in_addr((struct sockaddr*)&remoteaddr); char dst[INET6_ADDRSTRLEN]; inet_ntop(remoteaddr.ss_family, src, dst, sizeof dst); printf("II %s: new connection %s on socket %d\n", FUNCTION, dst, newfd); } } else { assert(obj->cb_read != NULL); int rv = (*obj->cb_read)(obj, fd); if (rv < 1) { printf("II %s: connection closed on socket %d\n", FUNCTION, fd); close(fd); FD_CLR(fd, &obj->fds); // remove from fd_set } } } void conn_event_loop(void) { for(;;) { // virtualization pattern: join all read fds into one fd_set read_fds = conns[0].fds; for (int i = 1; i < CONNMAX; ++i) { for (int 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].isConnecting) { FD_SET(conns[i].sockfd, &write_fds); } } struct timeval tv = {0, TIMEOUT * 1000}; int rv = select(FDMAX, &read_fds, &write_fds, NULL, &tv); if (-1 == rv && EINTR != errno) { perror("EE select"); exit(EXIT_FAILURE); }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework if (rv > 0) { // looking for data to read available for (int fd = 0; fd < FDMAX; ++fd) { if (FD_ISSET(fd, &read_fds)) { for (int i = 0; i < CONNMAX; ++i) { if (FD_ISSET(fd, &conns[i].fds)) { switch (conns[i].typ) { case CONN_CLIENT: client_handle(&conns[i], fd); break; case CONN_SERVER: server_handle(&conns[i], fd); break; } } } } } // looking for connect pending success or fail for (int i = 0; i < CONNMAX; ++i) { if (FD_ISSET(conns[i].sockfd, &write_fds)) { client_connect(&conns[i]); } } } timer_walk(); } } void iomux_begin(void) { // do nothing } void iomux_end(void) { // do nothing } #endif // LIOMUX_H_ The MS-Windows implemenation is differnt 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. /* wiomux.h * 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 * * 25jun2022 adr: 2nd published version */ #ifndef WIOMUX_H_ #define WIOMUX_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> // MS-Windows #include <conio.h> // _kbhit() #include <winsock2.h> #include <ws2tcpip.h> // getaddrinfo() #define FUNCTION __func__
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework #define FUNCTION __func__ enum { CONNMAX = 10, // maximum number of Connection objects FDMAX = 256, // maximum number of open file descriptors CONN_SERVER = 1, // TCP server connection object label CONN_CLIENT = 2, // TCP client connection object label 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 != NULL); if (AF_INET == sa->sa_family) { return &(((struct sockaddr_in*)sa)->sin_addr); } else { return &(((struct sockaddr_in6*)sa)->sin6_addr); } } /* ******************************************************** */ // Timer object typedef void (*cb_timer_t)(void* obj); typedef struct { cb_timer_t cb_timer; // cb_timer and obj are a closure void* obj; struct timespec ts; // expire time } Timer; static Timer timers[TIMERMAX]; // Timer objects array int after(int interval, cb_timer_t cb_timer, void* obj) { assert(interval >= 0); assert(cb_timer != NULL); // no assert obj int id; for (id = 0; id < TIMERMAX; ++id) { if (NULL == 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; }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework void timer_walk(void) { // looking for expired timers for (int i = 0; i < TIMERMAX; ++i) { if (timers[i].cb_timer != NULL) { 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 != NULL); (*tmp.cb_timer)(tmp.obj); } } } } /* ******************************************************** */ // Connection object typedef struct Conn { fd_set fds; // read file descriptor set SOCKET sockfd; // network port for client, listen port for server int isConnecting; // non-blocking connect started, but no finished int typ; // tells client or server object char hostname[STRMAX]; char port[STRMAX]; int (*cb_read)(struct Conn* obj, SOCKET fd); // Callback Pointer } Conn; typedef int (*cb_read_t)(Conn* obj, SOCKET fd); // Callback Pointer type static Conn conns[CONNMAX]; // Connection objects array Conn* conn_make(void) { for (int i = 0; i < CONNMAX; ++i) { if (0 == conns[i].typ) { return &conns[i]; // found a free entry } } assert(0 && "conn array full"); return NULL; } void client_open(Conn* obj, const char* hostname, const char* port) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(port != NULL); assert(hostname != NULL); printf("II %s: port=%s hostname=%s\n", FUNCTION, port, hostname); FD_ZERO(&obj->fds); obj->typ = CONN_CLIENT; strcpy_s(obj->port, sizeof obj->port, port); strcpy_s(obj->hostname, sizeof obj->hostname, hostname); void client_open1(Conn* obj); client_open1(obj); }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework void client_open1(Conn* obj) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); struct addrinfo hints; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; struct addrinfo* res; int rv = getaddrinfo(obj->hostname, obj->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 != NULL; p = p->ai_next) { obj->sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (INVALID_SOCKET == obj->sockfd) { perror("WW socket"); continue; } // Unix Networking Programming v2 ch. 15.4, 16.2 non-blocking connect unsigned long val = 1; rv = ioctlsocket(obj->sockfd, FIONBIO, &val); if (rv != 0) { perror("WW ioctlsocket FIONBIO ON"); closesocket(obj->sockfd); continue; } rv = connect(obj->sockfd, p->ai_addr, p->ai_addrlen); if (rv != 0) { if (WSAEWOULDBLOCK == WSAGetLastError()) { obj->isConnecting = 1; } else { perror("WW connect"); closesocket(obj->sockfd); continue; } } break; // exit loop after socket and connect were successful } assert(p != NULL && "connect try"); void* src = get_in_addr((struct sockaddr*)p->ai_addr); char dst[INET6_ADDRSTRLEN]; inet_ntop(p->ai_family, src, dst, sizeof dst); freeaddrinfo(res); FD_SET(obj->sockfd, &obj->fds); printf("II %s: connect try to %s (%s) port %s socket %llu\n", FUNCTION, obj->hostname, dst, obj->port, obj->sockfd); } void client_reopen(Conn* obj) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); closesocket(obj->sockfd); FD_CLR(obj->sockfd, &obj->fds); // remove network fd obj->sockfd = -1; client_open1(obj); }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework void client_handle(Conn* obj, SOCKET fd) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(fd < FDMAX); assert(obj->cb_read != NULL); int rv = (*obj->cb_read)(obj, fd); if (rv < 1) { // 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(obj->sockfd, SOL_SOCKET, SO_ERROR, (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, obj->hostname, obj->port, obj->sockfd, rv, strerror(optval)); client_reopen(obj); } else { obj->isConnecting = 0; // hack: connect successful after first good read() } } void conn_add_cb(Conn* obj, cb_read_t cb_read) { assert(cb_read != NULL); obj->cb_read = cb_read; } void server_open(Conn* obj, const char* hostname, const char* port) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(port != NULL); assert(hostname != NULL); printf("II %s: port=%s hostname=%s\n", FUNCTION, port, hostname); FD_ZERO(&obj->fds); obj->typ = CONN_SERVER; 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 != NULL; p = p->ai_next) { obj->sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (INVALID_SOCKET == obj->sockfd) { perror("WW socket"); continue; }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, 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(obj->sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof(yes)); if (rv != 0) { perror("WW setsockopt SO_REUSEADDR"); closesocket(obj->sockfd); continue; } rv = bind(obj->sockfd, p->ai_addr, p->ai_addrlen); if (rv != 0) { perror("WW bind"); closesocket(obj->sockfd); continue; } break; // exit loop after socket and bind were successful } freeaddrinfo(res); assert(p != NULL && "bind"); rv = listen(obj->sockfd, 10); assert(0 == rv && "listen"); // add the listener to the master set FD_SET(obj->sockfd, &obj->fds); printf("II %s: listen on socket %llu\n", FUNCTION, obj->sockfd); }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework printf("II %s: listen on socket %llu\n", FUNCTION, obj->sockfd); } void server_handle(Conn* obj, SOCKET fd) { assert(obj >= &conns[0] && obj < &conns[CONNMAX]); assert(fd < FDMAX); if (fd == obj->sockfd) { // handle new connections struct sockaddr_storage remoteaddr; // client address socklen_t addrlen = sizeof remoteaddr; // newly accept()ed socket descriptor SOCKET newfd = accept(obj->sockfd, (struct sockaddr*)&remoteaddr, &addrlen); if (INVALID_SOCKET == newfd) { perror("WW accept"); } else { FD_SET(newfd, &obj->fds); // add to master set void* src = get_in_addr((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 { assert(obj->cb_read != NULL); int rv = (*obj->cb_read)(obj, fd); if (rv < 1 || SOCKET_ERROR == rv) { printf("II %s: connection closed on socket %llu\n", FUNCTION, fd); closesocket(fd); FD_CLR(fd, &obj->fds); // remove from fd_set } } } void conn_event_loop(void) { for(;;) { // virtualization pattern: join all read fds into one fd_set read_fds = conns[0].fds; for (int i = 1; i < CONNMAX; ++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].isConnecting) { FD_SET(conns[i].sockfd, &except_fds); } } struct timeval tv = {0, TIMEOUT * 1000}; int rv = select(FDMAX, &read_fds, NULL, &except_fds, &tv); if (SOCKET_ERROR == rv && WSAGetLastError() != WSAEINTR) { perror("EE select"); exit(EXIT_FAILURE); }
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework 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 (FD_ISSET(fd, &conns[i].fds)) { switch (conns[i].typ) { case CONN_CLIENT: client_handle(&conns[i], fd); break; case CONN_SERVER: server_handle(&conns[i], fd); break; } } } } } // looking for connect pending fail for (int i = 0; i < CONNMAX; ++i) { if (FD_ISSET(conns[i].sockfd, &except_fds)) { client_reopen(&conns[i]); } } } timer_walk(); } } void iomux_begin(void) { static WSADATA wsaData; int rv = WSAStartup(MAKEWORD(2, 2), &wsaData); assert(0 == rv && "WSAStartup"); } void iomux_end(void) { WSACleanup(); } #endif // WIOMUX_H_ The line count (wc -l) of this source code is: 109 for chat.c, 443 for liomux.h and 409 for wiomux.h. 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 file descriptors. There is a simple networking framework in C++ from me, see Simple networking framework in C++ Answer: Create a platform-independent header file Instead of an application having to write code to choose between liomux.h and wiomux.h, create a header file named iomux.h that does this internally. This simplifies the application, and also allows you to add support for other platforms to your framework in the future without having to modify the application code itself. Be consistent I see a great deal of inconsistency in your code. Try to be as consistent as possible in the things you are doing. Here is a list of some of the things that are not consistent:
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework Documentation: some functions look like they have proper Doxygen documentation, others just have a simple comment. Try to document everything using Doxygen. Turn on warnings in Doxygen so it will tell you when you forgot to document certain functions, types and parameters. Typedefs: for example, typedef struct {...} TIMER; versus struct CONN_ {...}; typedef struct CONN_ CONN;. I recommend you declare structs like so: typedef struct FOO {...} FOO;. Note that the struct and its typedef can have exactly the same name. Error handling: I see assert(), perror(), exit(EXIT_FAILURE), and sometimes forgetting to handle errors at all. More on this below. Naming: write_fds (with an underscore separating words) vs remoteaddr vs isConnecting.
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework Improve error handling Make sure you check the return value of all functions that might return an error. That includes things like inet_ntop(), close(), clock_gettime() and so on. Yes it might be very unlikely, but it is important for a framework that you want to be able to blindly rely upon to actually handle all possible issues it can run into. Use assert() only to check for programming bugs. So for example, assert(interval >= 0) in after() is fine; if it is ever called with a negative interval, that's a bug in the calling code. However, never use this for things that are not programming bugs. For example, assert(rv != NULL) in poll_keyboard() is wrong; it is certainly possible that fgets() will return NULL if something is wrong with stdin (for example, the terminal the program is running in is closed). assert() is meant to become a no-op when compiled with the -DNDEBUG flag, which is automatically set in build systems like Meson and CMake when you make release builds. When you do encounter an error, make sure you print an error message to stdout using fprintf() or perror(). However, also make sure you then handle the error in the best possible way, never ignore them. Don't call exit(); this prevents the application from dealing with the error in its own way, instead return a meaningful error code. In server_handle(), you just ignore accept() returning an error. Perhaps it is fine in some cases, like if errno == EAGAIN, but if errno == EBADF, that means there is something wrong with the listening socket, and ignoring it will just cause your program to go into an infinite loop thinking there is a new socket to accept, but it will get the same error over and over. Naming things There are a few things that can be improved when naming functions, variables and so on:
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
c, linux, windows, networking, framework Avoid overly generic names. For example obj. Does that mean it's an object? But what kind of object? It is better to name it connection. It is common to use ALLCAPS names only for macros and constants, but not for structs. In general, function names should be verbs, variable names should be nouns. For example, conn_factory() should be renamed to something like new_connection(). Use the plural for arrays, so instead of conn[], write connections[]. About debug print statements There are several times you print debugging information to stdout, like when accepting a connection you print a message including the address connected to. While that might be nice while developing the framework, this will be very annoying for an application that is linking to your framework. It also adds quite a bit of noise to your code. I suggest that at this point, you remove all those printf("II...") statements from your code, as well as all the code that converts addresses to strings. Learn how to use a proper debugger like GDB if you want to debug your code, it avoids you having to add print() statements everywhere. Use getnameinfo() to convert addresses to strings Instead of using inet_ntop(), prefer to use getnameinfo() to convert addresses to strings. This way, you don't have to deal with the differences between IPv4 and IPv6 addresses. Functions that take no arguments should be (void) I see you write functions like void timer_walk() {...}. That syntax should be avoided, write void timer_walk(void) {...} instead. See this post for an explanation.
{ "domain": "codereview.stackexchange", "id": 43516, "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, linux, windows, networking, framework", "url": null }
python, beginner, python-3.x, file-system Title: Compare files by name in two folders A and B and delete duplicates from folder A Question: I wrote my very first Python program to answer a Super User question. I'm wondering how the application can be rewritten to make it as pythonic as possible. Unit test import unittest import os import shutil from DeleteDuplicateInFolderA import DeleteDuplicateInFolderA class DeleteDuplicateInFolderATest(unittest.TestCase): def __init__(self, *args, **kwargs): super(DeleteDuplicateInFolderATest, self).__init__(*args, **kwargs) self._base_directory = r"c:\temp\test" self._path_A = self._base_directory + r"\A" self._path_B = self._base_directory + r"\B" def create_folder_and_create_some_files(self, path, filename_list): if os.path.exists(path): shutil.rmtree(path) os.makedirs(path) for filename in filename_list: open(os.path.join(path, filename), "w+").close() def setUp(self): # Create folders and files for testing self.create_folder_and_create_some_files(self._path_A, ["1.txt", "2.txt"]) self.create_folder_and_create_some_files(self._path_B, ["2.txt", "3.txt"]) def tearDown(self): for path in [self._path_A, self._path_B, self._base_directory]: if os.path.exists(path): shutil.rmtree(path) def test_duplicate_file_gets_deleted(self): # Arrange app = DeleteDuplicateInFolderA(self._path_A, self._path_B, is_dry_run=False) # Act app.delete_duplicates_in_folder_A() # Assert self.assertFalse(os.path.isfile(self._path_A + r"\2.txt"), "File 2.txt has not been deleted.") def test_duplicate_file_gets_not_deleted_in_mode_dryrun(self): # Arrange app = DeleteDuplicateInFolderA(self._path_A, self._path_B, is_dry_run=True) # Act app.delete_duplicates_in_folder_A()
{ "domain": "codereview.stackexchange", "id": 43517, "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, beginner, python-3.x, file-system", "url": null }
python, beginner, python-3.x, file-system # Act app.delete_duplicates_in_folder_A() # Assert self.assertTrue(os.path.isfile(self._path_A + r"\2.txt"), "File 2.txt should not have been deleted in mode '--dryrun'") def main(): unittest.main() if __name__ == '__main__': main() Application #!/usr/bin/python import sys import os class DeleteDuplicateInFolderA(object): """Given two paths A and B, the application determines which files are in path A which are also in path B and then deletes the duplicates from path A. If the "dry run" flag is set to 'false', files are deleted. Otherwise they are only displayed but not deleted. """ def __init__(self, path_A, path_B, is_dry_run=True): self._path_A = path_A self._path_B = path_B self._is_dry_run = is_dry_run def get_filenames_in_folder(self, folder_path): only_files = [] for (dirpath, dirnames, filenames) in os.walk(folder_path): only_files.extend(filenames) return only_files def print_files(sel, heading, files): print(heading) if len(files) == 0: print(" none") else: for file in files: print(" {}".format(file)) def delete_duplicates_in_folder_A(self): only_files_A = self.get_filenames_in_folder(self._path_A) only_files_B = self.get_filenames_in_folder(self._path_B) files_of_A_that_are_in_B = [file for file in only_files_A if file in only_files_B] self.print_files("Files in {}".format(self._path_A), only_files_A) self.print_files("Files in {}".format(self._path_B), only_files_B)
{ "domain": "codereview.stackexchange", "id": 43517, "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, beginner, python-3.x, file-system", "url": null }
python, beginner, python-3.x, file-system if self._is_dry_run: self.print_files("These files would be deleted: ", [os.path.join(self._path_A, file) for file in files_of_A_that_are_in_B]) else: print("Deleting files:") for filepath in [os.path.join(self._path_A, file) for file in files_of_A_that_are_in_B]: print(" {}".format(filepath)) os.remove(filepath) if __name__ == "__main__": if len(sys.argv) == 4: is_dry_run_argument = sys.argv[3] if not is_dry_run_argument == "--dryrun": print("The 3rd argument must be '--dryrun' or nothing.") else: app = DeleteDuplicateInFolderA(sys.argv[1], sys.argv[2], is_dry_run=True) else: app = DeleteDuplicateInFolderA(sys.argv[1], sys.argv[2], is_dry_run=False) app.delete_duplicates_in_folder_A() Answer: First of all, make sure you use some tools to check your code (e.g. Pylint or Prospector). And a few comments: Use os.path.join: self._path_A = os.path.join(self._base_directory, "A") vs self._path_A = self._base_directory + r"\A" Consider using object methods to check for the content: if not lines: vs if len(files) == 0: Use the above mentioned tools to find obvious typos: def print_files(self, heading, files): vs def print_files(sel, heading, files) Do not name unused results: for (dirpath, _, filenames) in os.walk(folder_path): vs for (dirpath, dirnames, filenames) in os.walk(folder_path): You do not seem to take into account any subdirectories: for (dirpath, dirnames, filenames) in os.walk(folder_path): only_files.extend(filenames) which you might want to do as you then try to remove files in them: for filepath in [os.path.join(self._path_A, file) for file in files_of_A_that_are_in_B]:
{ "domain": "codereview.stackexchange", "id": 43517, "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, beginner, python-3.x, file-system", "url": null }
python, beginner, python-3.x, file-system Wrap the top-level code into a function: def main() if len(sys.argv) == 4: is_dry_run_argument = sys.argv[3] if not is_dry_run_argument == "--dryrun": print("The 3rd argument must be '--dryrun' or nothing.") else: app = DeleteDuplicateInFolderA(sys.argv[1], sys.argv[2], is_dry_run=True) else: app = DeleteDuplicateInFolderA(sys.argv[1], sys.argv[2], is_dry_run=False) app.delete_duplicates_in_folder_A() if __name__ == '__main__': main() vs if __name__ == '__main__': if len(sys.argv) == 4: is_dry_run_argument = sys.argv[3] if not is_dry_run_argument == "--dryrun": print("The 3rd argument must be '--dryrun' or nothing.") else: app = DeleteDuplicateInFolderA(sys.argv[1], sys.argv[2], is_dry_run=True) else: app = DeleteDuplicateInFolderA(sys.argv[1], sys.argv[2], is_dry_run=False) app.delete_duplicates_in_folder_A()
{ "domain": "codereview.stackexchange", "id": 43517, "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, beginner, python-3.x, file-system", "url": null }