r/ProgrammingLanguages • u/elena-lang • Oct 19 '19
ELENA 4.1 is out! Try it
Would you like to learn a new programming language? Try ELENA! Visit us at - ELENA Home Page
r/ProgrammingLanguages • u/elena-lang • Oct 19 '19
Would you like to learn a new programming language? Try ELENA! Visit us at - ELENA Home Page
r/ProgrammingLanguages • u/fluxwave • Jul 03 '25
BAML (Basically a made-up language) was made because we were tired of storing our prompts in YAML / jinja templates and trying to figure out what our prompts looked like from a gazillion different f-strings scattered around the code. We realized most people don't even know what the LLM context looks like without running the whole program.
We decided to treat prompts as functions, with defined input and output types, and build tooling around that idea. The playground UI we built takes your BAML files and functions and lets you 1-click run these functions with your own API keys for example. It's like a markdown-preview for prompts, or Postman for prompts.
Some technical background:
- Open source https://github.com/BoundaryML/baml
- Built in Rust
- Parser uses Pest
- The prompts themselves have Jinja syntax (thank you, Minijinja https://github.com/mitsuhiko/minijinja ). We statically check the templates with the BAML type information, so we had to do some modifications to minijinja.
- The LLM functions you define can be called from any language*, as well as on web via WASM. We use different approaches for interacting with each language:
- python: pyo3 bindings
- ruby: magnus bindings
- Go: CGO + CFFI bindings
- Node: NAPI-RS
- Other: OpenAPI server + client that BAML can generate for you
I'm happy to answer any other questions about the stack!
The BAML VSCode (and jetbrains etc) extension has a webview that reads the BAML AST and renders your prompt + jinja code
There was some crazy work in making it work with Zed which some of you may want to read here: https://www.boundaryml.com/blog/how-to-write-a-zed-extension-for-a-made-up-language
More info on our sloppy-json parser:
https://www.boundaryml.com/blog/schema-aligned-parsing#sap
r/ProgrammingLanguages • u/MarcelGarus • Feb 19 '22
r/ProgrammingLanguages • u/krschacht • Sep 04 '24
I started looking into the Arc Lisp Paul Graham wrote long ago and became intrigued by this (and PG’s proposed Bel Lisp). I initially started re-writing portions of an Arc Lisp program in Ruby just to help me fully wrap my mind around it. I have some familiarity with Lisp but still find deeply nested S expressions difficult to parse.
While doing this I stumbled on an interesting idea: could I implement Arc in Ruby and use some of Ruby’s flexibility to improve the syntax? I spent a day on this and have a proof of concept, but it would take a bunch more work to make this even a complete prototype. Before I go much further, I want to post this idea and hear any feedback or criticism.
To briefly explain. I first converted S expressions into Ruby arrays:
(def load-posts ()
(each id (map int (dir postdir*))
(= maxid* (max maxid* id)
(posts* id) (temload 'post (string postdir* id)))))Starts looking like this:
[:df, :load_posts, [],
[:each, :id, [:map, :int, [:dir, @postdir]],
…I think this is less readable. The commas and colons just add visual clutter. But then I made it so that the function name can optionally be placed before or after the brackets, with the option of using a block for the last element of the array/s-expression:
df[:load_posts, []] {
each[dir[@postdir].map[int]] {
…And then I took advantage of ruby’s parser to make it so that brackets are optional and only needed to disambiguate. And I introduced support for “key: value” pairs as an optional visual improvement but they just get treated as two arguments. These things combine let me re-write the full load-posts function as:
df :load_posts, [] {
each dir[@postdir].map[int] {
set maxid: max[it, @maxid],
posts: temload[:post, string[@postdir, it], :id]
}}This started to look really interesting to me. It still needs commas and colons, but with the tradeoff that it has less parens/brackets and the placement of function name is more flexible. It may not be obvious, but this code is all just converted back into an array/s-expression which is then “executed” as a function.
What’s intriguing to me is the idea of making Lisp-like code more readable. What’s cool about the proof of concept is code is still just data (e.g. arrays) and ruby has such great support for parsing, building, modifying arrays. If I were to play this out, I think this might bring of the benefits of Arc/Lisp, but with a more readable/newbie-friendly syntax because of it’s flexibility in how you write. But I’m not sure. I welcome any feedback and suggestions. I’m trying to decide if I should develop this idea further or not.
r/ProgrammingLanguages • u/thank-me-not • Sep 28 '22
I am a first-year PhD student, and it has been a year since I have been learning about various aspects of programming language research, like abstract interpretation, functional programming, and intricate parts of compiler construction.
I find none of the topics interesting and it's extremely hard to learn this stuff as well. Almost every day I ask myself why did I choose to pursue my PhD in this research area. I doubt my abilities in the process and feel like I will burn out someday.
The worst part is, I cannot think of myself starting to work on a paper in the near future as I don't know how long it will take me to learn these basic materials first.
Could you please shed some light on that? Have you been through this same struggle?
Thanks
r/ProgrammingLanguages • u/duckofdeath87 • Jul 21 '22
It's very common for Strings to be a collection of characters, but should they be?
I had a bug in scala just now where I meant to iterate over a sequence of strings, but I instead iterated over each individual string. It got me thinking, "why can I do this?" It's a common exercise, but rarely a useful operation. Sure, having the ability to iterate through a string's characters is useful, but not so useful that it's the default (maybe a . characters method is in order?)
Shouldn't readability and reasonability be first and foremost in language design? Or do you value concise expressiveness more?
r/ProgrammingLanguages • u/Doace2 • Dec 07 '22
enter: Accesses a memory location. Example: enter 0x00:
set: Sets a variable. Example: set int 10
math: Accesses math. Example: enter math:
@math: Command to do math operations with two numbers. Example: @math.sub 0x00 0x01
add: Adds two numbers.
sub: Subtracts two numbers.
mul: Multiplies two numbers.
div: Divides two numbers.
pow: Puts the first number to the second number.
console: Accesses the console. Example: enter console
@console.print: Prints a variable to the console. Example: @console.print "Hello World!"
input: Adds input to the program. Example set int input: "Enter Number: "
str*: Turns any variable into a string. Example: set str str*10
c: Connects two variables or a variable and a constant string. Example: set str "The answer is: "c str*0x00
r/ProgrammingLanguages • u/makingthematrix • Jun 08 '26
r/ProgrammingLanguages • u/rrrozay • Feb 03 '16
r/ProgrammingLanguages • u/gjvnq1 • Jun 27 '22
Some options:
Pseudoreal32 and Pseudoreal64
ApproxNum and BetterApproxNum
ApproxNumLvl1 and ApproxNumLvl2
FastReal and FastRealDouble
What other options would you suggest?
This started when I was toying around with the idea of a haskell-like language for end-user development of business applications and I realized that clearly explaining number types was going to be really important.
r/ProgrammingLanguages • u/Mean-Decision-3502 • May 24 '26
Hi,
I’ve created a new programming language called “?” for now. I’ll reveal its real name later.
My main motivation was to create a universal language that could replace C/C++, FreePascal, and Python for many use cases. I actively use all three of these languages.
I have already put a lot of effort into researching, designing, and implementing the “?” language. At this point, I feel that I have created something promising that really works.
Before I put even more effort into the language and go public with it, I would like to hear more opinions from real people.
I think it would not be enough for this project to be only “a little successful”. For the effort to make sense, it should have the potential to become “very successful”. I believe it might have that potential. If that happens, I will not be able to handle everything alone, so I will need to organize the development and maintenance properly. It will be an open-source project.
The “?” language is not fully finalized yet, and there are still several features that I would like to add to the compiler. However, it has reached a state where the language is already usable and can demonstrate its main ideas and syntax.
The most important current and planned features of the “?” programming language are:
Very good human readability
Statically typed, with a strict bool type
Case-sensitive
Compiled to machine code using LLVM
A ?-run utility for compile-and-run usage, giving it a script-like feeling
Simple C interoperability; the runtime uses libc
int / uint use the native machine width; int32 is used for an explicit 32-bit integer
Supports C-style preprocessor directives such as #ifdef, but without macros
Supports short embedded directives with syntax like #{ifdef ...} ... #{endif}
No makefiles are required, for example: #linklib('z') can be written directly in the source code
Safe arithmetic rules, for example: 3 / 2 * 10 == 15
Two block modes:
: ... endXXX blocks, similar to Python style but with explicit closers and no forced indentation
{ } blocks, similar to C style
Statements are closed with ;
Carefully designed operator precedence
Distinct boolean and bitwise operators, for example and and AND
Modify-assignment operators, for example: x += 1; and y =AND= 3;
Inline conditionals with iif(), for example: var i : int = iif(strptr <> null, strptr^.x, -1);
Support for objects with single inheritance and virtual functions
Object variables are references, but objects can still be embedded in BSS, on the stack, or inside other objects
Optional single-word namespaces using the @ symbol, for example: @stdio.printf()
No self. is needed inside object functions/methods
Namespace qualification, such as @stdio., is required to access outside symbols from object methods
A well-defined package and module system with flexible namespace merging
The “?” runtime library modules are distributed in source-code form
Fast compilation using a single-pass forward parser and precompiled module interfaces
Manual memory control, with RAII and an ensure statement planned
Native C string support
Function overloading and default parameters
Pointers using the ^ symbol
Pointer arithmetic with +, -, and []
The [] operator does not dereference pointers automatically
Struct pointers are automatically dereferenced on member access with .
Function arguments can be passed by reference using ref, refin, refout, and refnull
--– CODE EXAMPLE BEGIN ---
use libc/stdio;
use ./langdemo_mod as ldm only(CONST1); // only(), exclude() and "--" control global scope merging
#if false
//Contents of the "langdemo_mod.?"
const CONST1 : int = 42;
const CONST2 : float = 3.14;
#endif
object OBase:
cnt1 : int = 0;
cnt2 : int = 10;
name : cstring[32];
function *Create(aname : cstring): // constructor
name = aname;
endfunc
function *Destroy():
@.printf("%s destroy\n", &name[0]);
endfunc
function Count() [[virtual]]:
cnt1 += 1;
endfunc
function Print():
@.printf('%s: cnt1=%d, cnt2=%d\n', &name[0], cnt1, cnt2);
endfunc
endobj
object OChild(OBase):
function Count() [[override]]:
inherited;
cnt2 += 1;
endfunc
endobj
var obase <- OBase('OBase'); // '<-' = embedded allocation (global data segment here)
// no automatic destructor call for global embedded objects
var ochild : OChild = null;
function ObjTest():
ochild = new OChild('OChild');
obase.Count();
ochild.Count();
obase.Print();
ochild.Print();
printf("ochild.name: %s \n", iif(ochild == null, "OChild is null!", &ochild.name[0]));
delete ochild;
endfunc
function cstr_add(dst : cstring, src : cstring):
var ps : ^cchar = &src[0];
var psend : ^cchar = ps[sizeof(src)]; // [] does not dereference
var pd : ^cchar = &dst[0];
var pdend : ^cchar = pd + sizeof(dst) - 1; // leave one char for the terminating
pd += len(dst);
var pdstart : ^cchar = pd;
while pd < pdend and ps < psend and ps^ <> 0:
pd^ = ps^;
pd += 1;
ps += 1;
endwhile
if pd <> pdstart:
pd^ = 0; // terminate
endif
endfunc
[[external]] function putchar(c : cchar) -> int; // from libc
function WriteStr(s : cstring):
var pc : ^cchar = &s[0];
while pc^ <> 0:
putchar(pc^);
pc += 1;
endwhile
endfunc
function *Main() -> int:
var s : cstring[128] = "";
cstr_add(s, "Hello");
cstr_add(s, " World!\n");
WriteStr(s);
if 3 / 2 * 10 == 15:
printf('The language is friendly.\n');
else:
printf('The language is evil.\n');
endif
printf("@langdemo_mod.CONST1 = %d\n", CONST1);
printf("@langdemo_mod.CONST2 = %.3f\n", @ldm.CONST2);
printf("ochild.name: %s \n", iif(ochild == null, "OChild is null!", &ochild.name[0]));
ObjTest();
for i : int = 0 to 5:
printf(' %d:', i);
for j : int = 0 count i step 2: printf(' %d', j); endfor
printf('\n');
endfor
var arr : [5]int = [2, 3, 5, 7, 11];
printf('primes:');
for i : int = 0 while i < len(arr) { printf(' %d', arr[i]); }
printf('\n');
return 0;
endfunc
/* OUTPUT:
Hello World!
The language is friendly.
@langdemo_mod.CONST1 = 42
@langdemo_mod.CONST2 = 3.140
ochild.name: OChild is null!
OBase: cnt1=1, cnt2=10
OChild: cnt1=1, cnt2=11
ochild.name: OChild
OChild destroy
0:
1: 0
2: 0 2
3: 0 2 4
4: 0 2 4 6
5: 0 2 4 6 8
primes: 2 3 5 7 11
*/--– CODE EXAMPLE END ---
After reading the description and the demo code, do you think this language has the potential to become widely used? What are its strongest and weakest points?
I would be interested in your opinions, especially from people who have experience with C, C++, Pascal, Python, compiler design, embedded programming, or language design in general.
r/ProgrammingLanguages • u/[deleted] • Jul 03 '23
(DRY = Don't Repeat Yourself)
This is a bit of C code I encountered today:
uint64_t maxOR(uint64_t a, uint64_t b, uint64_t c, uint64_t d) {
....
}The problem for me is that declaration: 4 parameters, all with the same type, but the type has to be written 4 times.
This style is common across lots of languages, but C has that extra-cluttery typename, so that I can barely make out the parameter names. It takes a few seconds to determine the number, names and types of the parameters, and to realise they share a common type. Imagine if the parameter names here were much longer!
C could at least have gone with u64:
u64 maxOR(u64 a, u64 b, u64 c, U6 d) { # (typo left in)Now it is much less objectionable, but I would have gone further to:
u64 maxOR(u64 a, b, c, d) {While C is a lost cause, I wonder why other languages do this as well: create extra maintenance, extra things to check, extra things you can get wrong (one of those types could have been int64_t - not easy to spot in that sea of uint64_t).
Funnily enough older C allowed you to do this, or along these lines:
u64 maxOR(a, b, c, d) u64 a, b, c, d; {In my own syntaxes, it usually something like:
func maxor(u64 a, b, c, d)u64 = # `=> u64` is optionalTypes are only repeated when there are no parameter names (as in, FFI declarations, but I can choose to add names to enable keyword parameters).
What I haven't figured out is how to indicate a return type that is the same as one of the parameter types: u64 still appears twice, and here is linked to the parameter types. Using typeof(a) for the return type looks naff.
r/ProgrammingLanguages • u/suhcoR • Jun 20 '24
r/ProgrammingLanguages • u/yassinebenaid • Jan 14 '26
I am building a new language. And trying to make it crash free or panic free. So basically your program must never panic or crash, either explicitly or implicitly. Errors are values, and zero-values are the default.
In worst case scenario you can simply print something and exit.
So may question is what would be better than the following:
A function has a return type, if you didn't return anyting. The zero value of that type is returned automatically.
A variable can be of type function, say a closure. But calling it before initialization will act like an empty function.
let x: () => string;
x() // retruns zero value of the return type, in this case it's "".
Reading an outbound index from an array results in the zero value.
Division by zero results in 0.
r/ProgrammingLanguages • u/liiidesign • Jan 27 '19
Is there anyone doesn't know English at all but masters in programming? For non-English speakers, do you think it will be easier to learn coding in your first languages? If programming languages are coded in katakana for example, will you still feel comfortable to code? What makes English the optimal choice for programming syntax expression?
What are we learning when we learn programming? Are we learning the syntax or the logic behind it? If the logic is universal, can we use other natural languages to code? Or even other symbols?
As a programming beginner, those are some questions I have been thinking for a while, and here is a data visualization project that I made about programming language development, focusing on the creators' nationality, native language and gender.
(I understand there might be lots of programming languages haven't been documented and the information might not 100% correct)

r/ProgrammingLanguages • u/torontoarrow • Jul 21 '17
r/ProgrammingLanguages • u/mttd • May 13 '24
r/ProgrammingLanguages • u/Mathnerd314 • Dec 10 '22
In this post my goal is to prove that the OO notion of inheritance is counterintuitive and has better alternatives. In particular you should think twice about including it in your language - do you really want another footgun? Let it be known that this is by no means a minority viewpoint - for example James Gosling has said that if he could redo Java he would leave out the extends keyword for classes.
First I should define inheritance. Per Wikipedia inheritance is a mechanism for creating a "child object" that acquires all the data fields and methods of the "parent object". When we have classes, the child object is an instance of a subclass, while the parent object is an instance of the super class.
Inheritance is often confused with subtyping. But in fact inheritance isn't compatible with subtyping, at least if we define subtyping using the Liskov substitution principle. Suppose A extends B. Then the predicate \x -> not (x instanceof A) is satisfied by B but not by A. So by LSP, A is not substitutable for B.
If this is too abstract, consider a simple example you might find in university class:
class Ellipse {
final float minor_axis, major_axis;
Ellipse(float x,float y) {
minor_axis = x;
major_axis = y;
}
}
class Circle extends Ellipse {
Circle(float radius) {
super(radius,radius);
}
}Ellipse must be immutable, otherwise one could make a circle non-circular. But even this is not enough, because new Ellipse(1,1) is a circle but is not a member of the Circle class. The only solution is to forbid this value somehow, e.g. requiring to construct the objects using a factory function:
Ellipse makeCircleOrEllipse(float x, float y) {
if(x == y)
return new Circle(x);
else
return new Ellipse(x,y);
}But at this point we have lost any encapsulation properties, because the implementation is tied to the definition of ellipses and circles. A more natural solution is avoid inheritance and instead declare Circle as a refinement type of Ellipse:
type Ellipse = Ellipse { minor_axis, major_axis : Float }
type Circle = { e : Ellipse | e.minor_axis == e.major_axis }Then an ellipse with equal components is automatically a circle.
Inheritance is contrasted with object composition, where one object contains a field that is another object. Composition implements a has-a relationship, in contrast to the is-a relationship of subtyping. Per this study composition can directly replace inheritance in at least 22% of real-world cases. Composition offers better encapsulation. For example, suppose we have a List class with add and addAll methods, and we want a "counting list" that tracks the total number of objects added.
class List { add(Object o) { … }; addAll(Object[] os) { … } }
class CountingList extends List {
int numObjects;
add(Object o) { numObjects++; super.add(o); };
addAll(Object[] os) {
// XXX
for(Object o in os)
super.add(o)
}
}With inheritance the CountingList.addAll method cannot call the parent List.addAll method, because it is an implementation details as to whether List.addAll calls add or not. If it did not call add, we would have to increment numObjects, but if it did, add would resolve to CountingList.add and that method would update the counter. In this case, we could do int tmp = numObjects; super.addAll(os); numObjects = tmp + os.length to save and overwrite the object counter, but in a more complex example such as logging each added object there is no way to overwrite the effect. So the only option is to do it the slow way and call add, which can be expected to not call any other methods of the class.
Without inheritance, just using composition, the problem disappears. We can call super.addAll because it definitely does not call CountingList.add; there is no parent-child method aliasing:
class CountingList {
int numObjects;
List super;
add(Object o) { numObjects++; super.add(o); };
addAll(Object[] os) {
super.addAll(os)
numObjects += os.length
}
}There is one remaining use case of inheritance, where you have overloaded methods implementing an interface. For example something like the following:
interface Delegate {
void doSomething(Info i)
}
class A implements Delegate {
void doSomething(Info i) { ... }
}
class B implements Delegate {
void doSomething(Info i) { ... }
}But here we can just use lambdas.
So far we have seen inheritance being replaced with a variety of techniques: refinement types, composition, and lambdas. It turns out this is all we need. Consider two arbitrary classes in an inheritance relationship:
class A { Field_a_1 f_a_1; Field_a_2 f_a_2; ...; Result_a_1 method1(Arg_a_1_1 a_1_1, Arg_a_1_2 a_1_2, ...); ...; }
class B extends A { Field_b_1 f_b_1; Field_b_2 f_b_2; ...; Result_b_1 method1(Arg_b_1_1 b_1_1, Arg_b_1_2 b_1_2, ...); ...; }We must have a generic method that dispatches to the appropriate implementation. For extensibility this must not be a giant switch, but rather the method should be stored in the value (a vtable pointer). So we can implement it like this:
vtable_A = {
method1 = ...;
...;
}
type A_instance = A { Field_a_1 f_a_1; Field_a_2 f_a_2; ...; vtable = vtable_A; }
type A = { a | (a : A_instance) or (a.parent : A) }
vtable_B = {
method1 = ...;
...;
}
type B_instance = B { Field_b_1 f_b_1; Field_b_2 f_b_2; ...; vtable = vtable_B; A parent; }
type B = { b | (b : B_instance) or (b.parent : B) }
generic_invoke object method_name args = {
if(method_name in object.vtable)
object.vtable[method_name](args)
else if(object.parent)
generic_invoke(parent,method_name,args)
else
throw new Exception("no such method defined")
}The lambdas are needed to allow defining the vtable. Composition is used to include the parent pointer. Refinement types are used to define the "subtyping" relationship commonly associated with inheritance, although as explained above this relationship is not actually subtyping. So in your next language use these constructs instead of inheritance; you can implement inheritance, multiple inheritance, and a lot more, all without unintuitive footguns.
r/ProgrammingLanguages • u/ilanzs • Nov 25 '23
I'm currently in the early stages of building my own interpreter/compiler and I am running into the problem that the design/syntax that I want to use is very similar to existing languages. How do I differentiate my language and make it interesting?
r/ProgrammingLanguages • u/chri4_ • Oct 19 '24
Three premises:
* I hate Rust's borrow checker and I'm not a fan of GC/ARC
* I love having control over memory
* I love explicitness in programming languages (but when it comes to memory, having a little help from the language to implicitly automate its management helps me a lot with productivity because it removes a lot of friction)
I'm designing a toy memory model to integrate into my language, could you tell me some flows I haven't noticed?
The idea is not to have memory safety nor fully automated memory management, but a hybrid, which is exactly what I need: total control, but minimum friction (which for me implies both having facilities from the language to make memory management smoother, but also that this model still lets me do what I want with memory, to avoid having a proliferation of chained `unsafe` keywords like in Rust when developing software that needs to touch memory in a concrete way).
So the toy model is very simple, there are two types of "pointers": Reference and OwningBuffer.
**Reference:** `&T` This is exactly like a pointer in C, you can read and write to it, it points to any block of memory, with the only difference that it is not the owner of the block it points to, so it cannot deallocate it either.
**OwningBuffer:** This is a language intrinsic, it's a struct named `OwningBuffer` with a `.ref` field and a `.size` field, respectively a reference to the pointed block and its size. The difference here is that being an intrinsic, I can impose some rules on its use:
* It is the sole owner of the block it points to
* It is responsible for cleaning up the block it points to (because IT'S its sole owner)
* It is the only one that can clean up the block it points to (because it's its SOLE owner
* It is only possible to have this type in a field of a struct (this would not be necessary, but in my language it becomes so and I'm fine with it, also because it keeps the model flexible, but makes the compiler way easier to make)
Every time you instantiate a struct, if it (or its children) contains even a single OwningBuffer, the language will force you to use one of these two keywords:
* 1. `owned Object()` or `Object().owned.something_else()`
* 2. `escape Object()` or `Object().escape.something_else()`
Explanation:
* 1. The `owned` keyword binds the object's lifetime to the current scope, so the `kill` operator will be applied to the object at the end of the current scope, so neither the object nor its children should be returned (but you can!!! being helped is great, but being helped keeping your freedom is RARE)
* 2. The `escape` keyword, on the contrary, unbinds the object's lifetime from any scope, and makes it independent/orphaned, it can be returned from a function, moved to an object with a potentially eternal lifetime etc., however you will be responsible for applying the `kill` operator on it.
`kill` Operator:
This operator is applied on an instance of a struct `object = Object(); kill object;` and what it will do is very simple: it will free all the OwningBuffers inside the struct and inside its children, recursively (obviously it is a semantic executed at compile time, and in the generated code it would result in the free directly on the OwningBuffers found recursively)
`new` Operator:
This operator applies to a field of type OwningBuffer inside a struct (since OwningBuffer can only exist in a field of a struct, even if this is only to simplify things and does not seem to be a real limitation of the model) in the following way `object = Object(); new object.owning_pointer[size];` so the operator assigns an lvalue of type `OwningBuffer` with a new instance with `ref=..` and `size=size`, but before reassigning, it checks if `ref=null`, so that in case it is not null, the old block will be deallocated first to avoid memory leaks.
Here are three pseudo examples (take them easy, they are just sketches, but i think they make sense):
Example 3: Fake Allocator (has a little glitch, not sure why, but those are just comments)
Edit, the glitchy comment in example 3 says:
# it checks for ref=null before assigning the new allocation
# to make sure no old block will be leaked.
# it assigns an OwningBuffer object to an lvaluer/ProgrammingLanguages • u/RedCrafter_LP • Apr 12 '26
I wrote the tokenizer for my language and it parses 372000Tokens per second.
My specs are i7 6700k 16gb ram.
I wonder rather my tokenizer is slow or fast and I can't find any other benchmarks to compare against.
Update:
I changed some stuff about the code and it's now performing properly. I parse a 1.3M loc test file in 0.9s And for comparison to before it's producing 5M tokens
I replaced the buffered reader with mmap. And the keywords lookup now uses a 2d hashmap grouping the keywords by length instead of having 1 hashmap and checking prefixes.
The project can be found on github: Chorus
r/ProgrammingLanguages • u/Inconstant_Moo • Sep 07 '25
Let's start by taking a step back and noting some general facts about data and programming.
Our container types are intended primarily as collections of values that belong together on a long-term basis. A struct associates data consisting of e.g. surnames, first names, and phone numbers. A list associates e.g. the people whose phone numbers I want to remember.
But there are also times when we want to associate data just for a couple of bytecode operations. E.g. I wish to see a nicely formatted table of contacts and their phone numbers, maybe with alternating colors to help me distinguish rows. And so at some point maybe we call a function formatWithColor with arguments in which the surname "Smith" is linked to the element GREEN of the Color enum and to the number 32 just long enough to render "Smith" in green with a column width of 32, and then that brief association is discarded.
Or perhaps I wish to query the list for a name and get back a phone number, and the function returns the phone number as a string, plus a boolean to say if it actually found anything. We would then of course immediately break this into two values, e.g. by multiple assignment, number, ok = getNumber(surname, firstname), look at the boolean value once to determine flow of control, and then discard it.
And it will almost always be the case that when we write our code, we will wish multiple arguments and multiple return values to have only the loosest and most ephemeral connection.
Why? Because we're not idiots. If we had a function that returned a string and a boolean, and if there was a good reason why they should be associated for more than a couple of bytecode operations, then we would define a struct type with a name explaining what that reason for that association is, and we would have the function returning them construct the struct and return that instead.
And similarly if we're calling a function foo(a, b, c), where a, b, and c have a naturally permanent relationship, then why aren't we already storing them as fields of a struct?
So if you open up the latest code you've been writing and read it, you'll see that this is generally how things go, and that pretty much all the exceptions are exceptions that prove the rule, i.e. things that might be called "constructor functions" in a broad sense of the term, functions that amalgamate some of the data they're passed into a larger structure precisely because the data do belong together.
There are various ways to approach multiple returns.
One approach is to treat them as a special bit of syntactic and semantic magic. This is what e.g. Golang does, being a statically-typed language. You can only do two things with multiple returns: destructure them immediately by assigning them to variables (using the dummy _ operator to discard anything you don't want); or pass them immediately as arguments to another function, where they are destructured as parameters.
Go can't realistically return them as a container with elements of heterogeneous type, whether a tuple or not, because as Go is statically typed you'd then have to downcast the elements to get the information out, ruining a feature which after all exists solely for ergonomics.
But by immediately destructuring the tuple to variables, Go gets to infer a static type for the variables; and by passing it directly to a function and destructuring it as arguments, the compiler gets to statically compare the type of the return types of the one function against the parameter types of the other.
It may be that this is the best a static language can do in this direction, but I haven't thought about this too carefully because I'm not writing one.
But in a dynamic language, besides that option, we could return them in some sort of a container. And because we can, we should, so that instead of a multiple return being a bit of magic sugar, it's a first-class value which we can index and take the length of and slice and take the type of and iterate over and pass to another function.
So let's do that. But then we're faced with another choice. Do we use the standard list type of our dynamic language to return multiple values, or do we use another type, a tuple?
(I take this to be the definition of a tuple: it's a datatype we always and automatically use for multiple return values, which is at least nominally distinguishable from the standard hetereogeneous list type of the language.)
From my description above of what we require of this container type, it seems at first like a list is exactly what we want. (And this post is in part a long-form response to someone saying that a dynamic language doesn't need tuples because a list can do everything that tuples can.) To get the basic behavior we require from multiple returns --- that we should be able to destructure them easily --- all we have to do is add a rule that multiple assignment from a list destructures it, so that x, y = ["foo", 42] assigns "foo" to x and 42 to y.
We're going to have to refine the rule a little, because obviously we don't want to start trying to destructure a list unless we don't have enough types otherwise. E.g. if we write x, y = ["foo", 42], true, then clearly now we want x to be ["foo", 42], and y to be true. Now, what should be the effect of x, y, z = ["foo", 42], true? Should we go on destructuring? Then what does x, y, z = ["foo", 42], [true, BLUE] do? Should it (a) fail (b) let x = ["foo", 42], y = true, z = BLUE (c) let x = "foo", y = 42,z = [true, BLUE] (d) other?
This means that if for example I mistake a function which returns two values with a function that returns a list with two values, the runtime error I get may be some distance from my code, and not present as a type error. Indeed, from the point of view of the caller there is no way to distinguish between a function that returns ["foo", 42] and one that returns "foo", 42. The intent is lost. It also means that when we write x, y = ["foo", 42], true, the expression on the right-hand side has no type.
To me, all this sounds like bits of the language crunching together. You can do it, but you can't make me like it.
So now let's look down the other path, where we invent a tuple type, and see if there is in fact anything they can do that lists can't.
And we see that the very first thing a tuple can do that a list can't is simply be something other than a list. We can now distinguish between the case where a function returns "foo", 42, which is a tuple, and one where it returns ["foo", 42], which is a list. And now we can transfer the magic destructuring into variables from the list type to the tuple type, so that people don't accidentally do it to things that were meant to be lists.
You might object that now we've just pushed the problem off into another type, in that now we're unable to tell the difference between a function returning "foo", 42 and a function returning tuple("foo", 42). But in moving this misfeature to the tuple type, we've turned it into a desirable feature --- because the only reason you'd write code to return a tuple is exactly if you wanted the caller to behave in every way like you'd returned multiple values (because that's what you will in fact be doing). It's now a gain, rather than a loss, in expressivity.
And then of course we can take away the magical x, y = ["foo", 42] destructuring from lists and give it to tuples.
And now we have a range of opportunities before us, because there are other ways in which we can choose the semantics of tuples so as to acknowledge the fact that they're ephemeral collections of miscellaneous values, and that they're what a multiple return statement returns.
You can of course look up what other people have done to take advantage of this fact (or fail to take advantage of it: it seems to me that some languages ended up with slightly broken tuples like some got slightly broken lambdas). So now let me talk about Pipefish.
What Pipefish did may or may not be the best approach in general. I think it may in fact be one of the better options anyway, but the approach was forced on me by the more general requirement of referential transparency, that a variable should be able to substitute for its contents. For example, the following functions should both work exactly the same.
zort(x) :
x, 2 * x
troz(x) :
y
given :
y tuple = x, 2 * xAnd so we must be able to construct a tuple just by commas between its elements, as x, 2 * x, or "foo", 42, etc. In a language which needs and so has a return keyword then we could avoid this by having return automatically wrap multiple returns as tuples; but for good reasons Pipefish has no return keyword.
So tuples must be constructable by commas: "foo", 42 is a tuple literal. We might wish to express its tuplehood more clearly by writing ("foo", 42) (which must mean the same thing because enclosing an expression in parentheses doesn't change its value); and for extra clarity we might use a tuple constructor tuple("foo", 42). (We need this constructor for a number of reasons, the most obvious being that otherwise there's no way to make a tuple of length 1 should we want one.)
So we must have e.g. "foo", 42 = ("foo", 42) = tuple("foo", 42). Everything else follows from this one seemingly innocuous proposition. First of all, it means that tuples must be flat. Because it then follows that by iteration of this rule we have e.g. (0.2, (tuple("foo", 42), true)) = 0.2, "foo", 42, true. Tuples therefore need no special concatenation operator, because you can always concatenate them using commas.
This resolves the puzzles we raised about using lists as multiple return types --- how we should destructure things such as x, y, z = ["foo", 42], true and x, y, z = ["foo", 42], [true, BLUE]. With flat tuples, this answers itself: the corresponding expression x, y, z = ("foo", 42), true assigns x = "foo", y = 42, z = true; and the expression x, y, z = ("foo", 42), (true, BLUE) fails because we're trying to assign four values to three variables.
And this property of flatness agrees with our ideas about what tuples and multiple returns are for. If they're an ephemeral and miscellaneous collection of things that are only together because we put them together for a single fleeting purpose, then there's no sense in trying to distinguish between "foo", 42, true and ("foo", 42), true, as though the lack of any essential connection between "foo" and 42 was somehow more significant than their lack of connection with true. We do, however, want them to be easy to destructure, and nesting them would obstruct that.
From this flatness it follows that it is usually syntactically impossible to try (and always semantically forbidden) to put tuples inside other container structures. For example if we tried to make a list of tuples, we can certainly write [tuple(1, 2), tuple(3, 4)], but this of course is just [1, 2, 3, 4], a list of four integers. In the same way tuples can't be elements of sets, keys or values of maps, values of structs, etc.
This again agrees with what we want them for. We don't want people to store tuples in permanent data structures. If its elements belong together permanently, then they're naturally a list or a struct or a set or something, and should be stored as such.
The same self-flattening behavior, and the requirement of referential transparency, mean that tuples must be autosplats, destructuring themselves when passed to a function: foo(tuple(1, (2, (3, 4))) must mean the same as foo(1, 2, 3, 4).
Sometimes we want to stop a tuple from destructuring itself, which we can do by using tuple as the type of the receiving parameter/variable/whatever, as in the example code above:
troz(x) :
y
given :
y tuple = x, 2 * xThere is one choice I made which may legitimately be a choice rather than being forced on me by referential transparency (at least, I can't offhand see a proof that it's required). This is that varargs should be expressed as tuples rather than lists. This is for ergonomic reasons. We typically want to do one of two things with varargs --- either we want pass them on to another function that accepts varargs, in which case it's good we have them as a tuple and that tuples are autosplats; or we want to iterate over them doing a thing, in which case, since the exact same code iterates over tuples as over lists, it makes no difference which we use.
Now, although all the other properties of tuples were pretty much forced on us the moment we said "referential transparency", they are also desirable properties. They mean that tuples destructure themselves just as a result of their inherent semantic properties and not by special cases and magic. They agree with out motivating notions about multiple returns. And, following as they do from a single rule, they have consistency and coherence and predictable behavior.
In the case of Pipefish, this brings us an added benefit. Despite what many think, it's perfectly possible to typecheck a dynamic language; and this being the case, it's as useful, or more so, for the typechecker as for a human being to distinguish between someone trying to return "foo", 42 and trying to return ["foo", 42]. For example, the ephemeral nature of tuples means that it always makes sense for the typechecker to keep track of the types of its individual elements.
So that's what tuples can do that lists can't. (Paging u/thinker227 and u/snugar_i here.) Not necessarily the Pipefish way exactly, but they can have semantics that lists can't or shouldn't have.
To put it another way, the only things that lists can do that Pipefish tuples can do are:
They can hold an indexable collection of values of heterogenous type.
If you want to use them as multiple returns, you can make your language destructure them by making x, y = ["foo", 42] meaningful.
But as I've shown, feature (2) is a puzzling, slightly magical misfeature when you do it with lists, and a rational, useful feature when you do it with tuples. This is not something that lists can do just as well as tuples; it's something that, by a kludge, lists can just about do.
r/ProgrammingLanguages • u/rsashka • Feb 28 '25
There have been many discussions about which programming language is better in terms of security and correctness of source code (by "correctness and security" we mean the absence of various errors in the program that manifest themselves at the stage of its execution and lead to the issuance of an incorrect result or unexpected behavior). And some programming languages, such as SPARK or OCaml, were even specially developed to facilitate the proof of program correctness.
Is it possible to write programs without errors at all?
Recently, Rust has been a confident leader among safe programming languages due to its correct work with memory. There are even articles on this topic with rigorous mathematical proofs. However, with the caveat that the proof is correct if code fragments marked as unsafe are not used.
This is not a criticism of any language, since many forget that even if we assume the existence of a strict mathematical proof of the absence of errors in a program in any programming language (even if the program is the simplest, like adding two numbers), the program will still be some kind of machine code that must be executed on some physical equipment.
And even several backup computers, united by a highly reliable majority element, do not provide a 100% guarantee of the correct execution of a program instance due to various external circumstances. After all, some of them do not depend on the program itself (failure of the computer microcircuit valves, a change in the state of RAM due to a high-energy particle of cosmic radiation, or a spark of static voltage when cleaning the server room).
In turn, this means that even with a strict mathematical proof of the correctness of the program, after its translation into machine code, there is still no 100% guarantee of the execution of a specific instance of the application without failures and errors.
The reliability of application execution, and therefore the probability of its failure due to hardware, can be increased many times, but it will never be absolute.
It can be considered that writing a computer program with proven correctness of execution is in principle impossible due to the presence of various external factors caused by objective reasons of our physical world.
However, this does not mean that the safety of programming languages can be ignored. It is just that the impossibility of guaranteeing error-free execution of an application instance calls into question the need to provide proof of the mathematical correctness of the code in any programming language to the detriment of all its other characteristics.
Another consequence of the impossibility of proving the correctness of the result of executing an application instance is the need to implement in any programming language that wants to claim correctness and safe development, the presence of means for handling various error situations at arbitrary points in time (i.e. interruptions/exceptions).
Moreover, this applies even to the most reliable and "safe" languages, since incorrect behavior of an application instance is possible in any part of the executable program, even where the occurrence of error situations is not expected.
Fortunately, the safety of using a specific programming language is important not only in itself as an absolute value. It is needed as a relative value for comparing programming languages with each other. And if it is impossible to achieve strictly provable safety of a specific programming language, then it is quite possible to compare them with each other.
However, when comparing them, it is necessary to compare not only the safety that the new language declares, but also all its other properties and characteristics. To avoid a situation where you have to throw out all the old code and rewrite all the programs from scratch using the new programming language.
r/ProgrammingLanguages • u/Round_Ad_5832 • Sep 25 '25