🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

89 total messages Page 1 of 2 Started by Dan Cross Wed, 07 Oct 2026 13:28
Page 1 of 2 • 89 total messages
Re: Optimization by programmers
#7
Author: Dan Cross
Date: Wed, 07 Oct 2026 13:28
57 lines
3184 bytes
In article <11a3ofn$2ak3s$1@dont-email.me>,
Terje Mathisen  <terje.mathisen@tmsw.no> wrote:
>Dan Cross wrote:
>> In article <86h5j5pky9.fsf@linuxsc.com>,
>> Tim Rentsch  <tr.17687@z991.linuxsc.com> wrote:
>>> Terje Mathisen <terje.mathisen@tmsw.no> writes:
>>>
>>>> Tim Rentsch wrote:
>>>>
>>>>> Terje Mathisen <terje.mathisen@tmsw.no> writes:
>>>>>
>>>>>> Tim Rentsch wrote:
>>> [...]
>>>>>>> I favor a type equivalent to size_t for use as array index variables.
>>>>>>
>>>>>> In Rust, the only acceptable array index is of type "usize", which is
>>>>>> effectively the same as u64 on most platforms these days, but does not
>>>>>> need to be so:  On a 32-bit target, it would be the same as u32.
>>>>>>
>>>>>> So effectively very similar to size_t.
>>>>>
>>>>> Maybe that limitation works okay in Rust.  In C sometimes it's
>>>>> important to allow a signed value for indexing.  Probably 99% of
>>>>> the time size_t is good, but not always.
>>>>
>>>> The fact that array indices are unsigned is one of the more crucial
>>>> underpinnings of Rust safety.  Even more importantly, all such indices
>>>> are verified against the actual array upper boundary. [...]
>>>
>>> It's nice that array index values are checked against the array
>>> bounds.
>> 
>> Terje was actually incorrect here; bounds checks are added in
>> debug mode, but are (usually) removed in optimized builds.
>
>That's what I assumed, except I check my assumptions by godbolt'ing my 
>code, using -O -C "target_cpu=native" to get a bleeding edge optimized 
>build, and that's where I saw a loop which started with
>
>   while pos+7 < input.len() {
>     ... here a bunch of accesses to input[p], input[p+1]...input[p+6]
>   }
>
>Every one of those secodnary accesses were very obviously tested against 
>the input length (stored in a register for the duration)
>
>I considered reporting this as a very clear performance bug!

I wonder if what you saw was actually loop unrolling.  I just
tried something similar, albeit with a very simple sum in the
loop body, and don't see a bunch of extraneous bounds checks.

I do wonder, though, whether you'd get better object code using
`input.iter().chunks(n)` or `.windows(n)`.

	- Dan C.
Re: Optimization by programmers
#9
Author: Terje Mathisen
Date: Wed, 07 Oct 2026 14:43
77 lines
4336 bytes
Dan Cross wrote:
> In article <11a3ofn$2ak3s$1@dont-email.me>,
> Terje Mathisen  <terje.mathisen@tmsw.no> wrote:
>> Dan Cross wrote:
>>> In article <86h5j5pky9.fsf@linuxsc.com>,
>>> Tim Rentsch  <tr.17687@z991.linuxsc.com> wrote:
>>>> Terje Mathisen <terje.mathisen@tmsw.no> writes:
>>>>
>>>>> Tim Rentsch wrote:
>>>>>
>>>>>> Terje Mathisen <terje.mathisen@tmsw.no> writes:
>>>>>>
>>>>>>> Tim Rentsch wrote:
>>>> [...]
>>>>>>>> I favor a type equivalent to size_t for use as array index variables.
>>>>>>>
>>>>>>> In Rust, the only acceptable array index is of type "usize", which is
>>>>>>> effectively the same as u64 on most platforms these days, but does not
>>>>>>> need to be so:  On a 32-bit target, it would be the same as u32.
>>>>>>>
>>>>>>> So effectively very similar to size_t.
>>>>>>
>>>>>> Maybe that limitation works okay in Rust.  In C sometimes it's
>>>>>> important to allow a signed value for indexing.  Probably 99% of
>>>>>> the time size_t is good, but not always.
>>>>>
>>>>> The fact that array indices are unsigned is one of the more crucial
>>>>> underpinnings of Rust safety.  Even more importantly, all such indices
>>>>> are verified against the actual array upper boundary. [...]
>>>>
>>>> It's nice that array index values are checked against the array
>>>> bounds.
>>>
>>> Terje was actually incorrect here; bounds checks are added in
>>> debug mode, but are (usually) removed in optimized builds.
>>
>> That's what I assumed, except I check my assumptions by godbolt'ing my
>> code, using -O -C "target_cpu=native" to get a bleeding edge optimized
>> build, and that's where I saw a loop which started with
>>
>>    while pos+7 < input.len() {
>>      ... here a bunch of accesses to input[p], input[p+1]...input[p+6]
>>    }
>>
>> Every one of those secodnary accesses were very obviously tested against
>> the input length (stored in a register for the duration)
>>
>> I considered reporting this as a very clear performance bug!
> 
> I wonder if what you saw was actually loop unrolling.  I just
> tried something similar, albeit with a very simple sum in the
> loop body, and don't see a bunch of extraneous bounds checks.

Not unrolling, the code is here:

https://godbolt.org/z/YnY5G1K49

The interesting part starts at line 28/29 .LBB0_02 in the asm window 
where you can see (starting at line 37) a bunch of cmp r8,rsi / jae 
<panic> sequences.


> I do wonder, though, whether you'd get better object code using
> `input.iter().chunks(n)` or `.windows(n)`.

I guess I can try this, I'm guessing chunks(7) will error out if less 
than 7 elements are available?

The code is from Advent of Code 2024 day 3,
https://github.com/TerjeWiigMathisen/aoc/tree/master/2024/day03

Terje


-- 
- <Terje.Mathisen at tmsw.no>
"almost all programming can be viewed as an exercise in caching"
Re: Optimization by programmers
#14
Author: Dan Cross
Date: Wed, 07 Oct 2026 19:57
160 lines
6671 bytes
In article <11a5lqo$2v5bq$1@dont-email.me>,
Terje Mathisen  <terje.mathisen@tmsw.no> wrote:
>Dan Cross wrote:
>> In article <11a3ofn$2ak3s$1@dont-email.me>,
>> Terje Mathisen  <terje.mathisen@tmsw.no> wrote:
>>> Dan Cross wrote:
>>>> In article <86h5j5pky9.fsf@linuxsc.com>,
>>>> Tim Rentsch  <tr.17687@z991.linuxsc.com> wrote:
>>>>> Terje Mathisen <terje.mathisen@tmsw.no> writes:
>>>>>
>>>>>> Tim Rentsch wrote:
>>>>>>
>>>>>>> Terje Mathisen <terje.mathisen@tmsw.no> writes:
>>>>>>>
>>>>>>>> Tim Rentsch wrote:
>>>>> [...]
>>>>>>>>> I favor a type equivalent to size_t for use as array index variables.
>>>>>>>>
>>>>>>>> In Rust, the only acceptable array index is of type "usize", which is
>>>>>>>> effectively the same as u64 on most platforms these days, but does not
>>>>>>>> need to be so:  On a 32-bit target, it would be the same as u32.
>>>>>>>>
>>>>>>>> So effectively very similar to size_t.
>>>>>>>
>>>>>>> Maybe that limitation works okay in Rust.  In C sometimes it's
>>>>>>> important to allow a signed value for indexing.  Probably 99% of
>>>>>>> the time size_t is good, but not always.
>>>>>>
>>>>>> The fact that array indices are unsigned is one of the more crucial
>>>>>> underpinnings of Rust safety.  Even more importantly, all such indices
>>>>>> are verified against the actual array upper boundary. [...]
>>>>>
>>>>> It's nice that array index values are checked against the array
>>>>> bounds.
>>>>
>>>> Terje was actually incorrect here; bounds checks are added in
>>>> debug mode, but are (usually) removed in optimized builds.
>>>
>>> That's what I assumed, except I check my assumptions by godbolt'ing my
>>> code, using -O -C "target_cpu=native" to get a bleeding edge optimized
>>> build, and that's where I saw a loop which started with
>>>
>>>    while pos+7 < input.len() {
>>>      ... here a bunch of accesses to input[p], input[p+1]...input[p+6]
>>>    }
>>>
>>> Every one of those secodnary accesses were very obviously tested against
>>> the input length (stored in a register for the duration)
>>>
>>> I considered reporting this as a very clear performance bug!
>> 
>> I wonder if what you saw was actually loop unrolling.  I just
>> tried something similar, albeit with a very simple sum in the
>> loop body, and don't see a bunch of extraneous bounds checks.
>
>Not unrolling, the code is here:
>
>https://godbolt.org/z/YnY5G1K49
>
>The interesting part starts at line 28/29 .LBB0_02 in the asm window 
>where you can see (starting at line 37) a bunch of cmp r8,rsi / jae 
><panic> sequences.

So you're not actually indexing into an _array_ here, but rather
into a _slice_, which is always bounds-checked in safe Rust
code.

>> I do wonder, though, whether you'd get better object code using
>> `input.iter().chunks(n)` or `.windows(n)`.
>
>I guess I can try this, I'm guessing chunks(7) will error out if less 
>than 7 elements are available?

But really what you want is to find all subsequences matching
the regular expression , `mul([0-9]+,[0-9]+)`, and then extract
the two numeric fields, multiple them, and sum the results.
That's a reduction over a sequence of products, which is itself
a reduction over a sequence of patches that yield pairs of
integers.

I understand you want raw speed; a way to get that is to
implement the DFA corresponding to that regexp by hand, and use
something like Boyer Moore to handle the fixed part.

>The code is from Advent of Code 2024 day 3,
>https://github.com/TerjeWiigMathisen/aoc/tree/master/2024/day03

Oh, I don't do Advent of Code, but looking briefly at the
problem description I don't see why you couldn't use `&str` to
represent the input data.  Nothing says it's not UTF-8, and from
what I understand, the guy who runs it usually isn't a jerk
about that kind of thing.  I haven't tried to benchmark your
code against, e.g., this:

-->BEGIN<---
pub fn next(mut s: &str) -> Option<(i32, &str)> {
    while !s.is_empty() {
        let pos = s.find("mul(")?;
        let (_, rest) = s.split_at(pos + 4);
        s = rest;
        let comma = s.find(|c: char| !c.is_ascii_digit())?;
        let (adigits, rest) = s.split_at(comma);
        let Some(rest) = rest.strip_prefix(",") else {
            s = rest;
            continue;
        };
        let a = adigits.parse::<i32>().ok()?;
        let rparen = rest.find(|c: char| !c.is_ascii_digit())?;
        let (bdigits, rest) = rest.split_at(rparen);
        let Some(rest) = rest.strip_prefix(")") else {
            s = rest;
            continue;
        };
        let b = bdigits.parse::<i32>().ok()?;
        return Some((a * b, rest));
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn invalids() {
        assert_eq!(next("aaa"), None);
        assert_eq!(next(""), None);
        assert_eq!(next("mul(3,5"), None);
        assert_eq!(next("mul(3, 5"), None);
        assert_eq!(next("mul(3,"), None);
        assert_eq!(next("mul(3"), None);
        assert_eq!(next("mul("), None);
    }

    #[test]
    fn aproduct() {
        let s = "abmul[1,2]mul(3,5)a";
        assert_eq!(next(s), Some((15, "a")));
    }

    #[test]
    fn mproducts() {
        let s = "mul(1,2)mul(3,4)";
        let aopt = next(s);
        assert_eq!(aopt, Some((2, "mul(3,4)")));
        let (a, s) = aopt.unwrap();
        let bopt = next(s);
        assert_eq!(bopt, Some((12, "")));
        let (b, s) = bopt.unwrap();
        assert_eq!(next(s), None);
        assert_eq!(a * b, 24);
    }
}
--->END<---

I suspect yours may be somewhat faster, though this likely does
more error checking.  YMMV.

	- Dan C.
Re: Optimization by programmers
#17
Author: Terje Mathisen
Date: Wed, 07 Oct 2026 20:31
162 lines
7442 bytes
Dan Cross wrote:
> In article <11a5lqo$2v5bq$1@dont-email.me>,
> Terje Mathisen  <terje.mathisen@tmsw.no> wrote:
>> Not unrolling, the code is here:
>>
>> https://godbolt.org/z/YnY5G1K49
>>
>> The interesting part starts at line 28/29 .LBB0_02 in the asm window
>> where you can see (starting at line 37) a bunch of cmp r8,rsi / jae
>> <panic> sequences.
> 
> So you're not actually indexing into an _array_ here, but rather
> into a _slice_, which is always bounds-checked in safe Rust
> code.

My old asm/C brain _knows_ that a slice of something with a known 
address and total length is effectively the same thing as an unmutable 
array.

Even if it isn't, the fact that I start by verifying that the slice 
extends at least 7 bytes past the p index means that all of p, 
p+1,p+2...p+6 must be valid, right?

> 
>>> I do wonder, though, whether you'd get better object code using
>>> `input.iter().chunks(n)` or `.windows(n)`.
>>
>> I guess I can try this, I'm guessing chunks(7) will error out if less
>> than 7 elements are available?
> 
> But really what you want is to find all subsequences matching
> the regular expression , `mul([0-9]+,[0-9]+)`, and then extract
> the two numeric fields, multiple them, and sum the results.
> That's a reduction over a sequence of products, which is itself
> a reduction over a sequence of patches that yield pairs of
> integers.

Yes, doing it that way is easy!
> 
> I understand you want raw speed; a way to get that is to
> implement the DFA corresponding to that regexp by hand, and use
> something like Boyer Moore to handle the fixed part.

Collectively we've tried all sorts of stuff in order to come up with the 
absolute fastest solution, without having to use unsafe code.

> 
>> The code is from Advent of Code 2024 day 3,
>> https://github.com/TerjeWiigMathisen/aoc/tree/master/2024/day03
> 
> Oh, I don't do Advent of Code, but looking briefly at the
> problem description I don't see why you couldn't use `&str` to

I typically pass the input to my process(inp:&str) function that way, 
but by turning it into a naked byte array (slice?), indexing is better 
defined with no need to iterate over a potential UTF8 sequence (even 
though we know there won't be any).

> represent the input data.  Nothing says it's not UTF-8, and from
> what I understand, the guy who runs it usually isn't a jerk
> about that kind of thing.  I haven't tried to benchmark your
> code against, e.g., this:

What you implement here is just Part1: After solving that you get to 
read Part2 where you have to also detect "do()" and "don't()" sequences, 
so that the multiplication result only adds to the part2 result if we're 
not following a don't().
> 
> -->BEGIN<---
> pub fn next(mut s: &str) -> Option<(i32, &str)> {
>      while !s.is_empty() {
>          let pos = s.find("mul(")?;
>          let (_, rest) = s.split_at(pos + 4);
>          s = rest;
>          let comma = s.find(|c: char| !c.is_ascii_digit())?;
>          let (adigits, rest) = s.split_at(comma);
>          let Some(rest) = rest.strip_prefix(",") else {
>              s = rest;
>              continue;
>          };
>          let a = adigits.parse::<i32>().ok()?;
>          let rparen = rest.find(|c: char| !c.is_ascii_digit())?;
>          let (bdigits, rest) = rest.split_at(rparen);
>          let Some(rest) = rest.strip_prefix(")") else {
>              s = rest;
>              continue;
>          };
>          let b = bdigits.parse::<i32>().ok()?;
>          return Some((a * b, rest));
>      }
>      None
> }
> 
> #[cfg(test)]
> mod tests {
>      use super::*;
> 
>      #[test]
>      fn invalids() {
>          assert_eq!(next("aaa"), None);
>          assert_eq!(next(""), None);
>          assert_eq!(next("mul(3,5"), None);
>          assert_eq!(next("mul(3, 5"), None);
>          assert_eq!(next("mul(3,"), None);
>          assert_eq!(next("mul(3"), None);
>          assert_eq!(next("mul("), None);
>      }
> 
>      #[test]
>      fn aproduct() {
>          let s = "abmul[1,2]mul(3,5)a";
>          assert_eq!(next(s), Some((15, "a")));
>      }
> 
>      #[test]
>      fn mproducts() {
>          let s = "mul(1,2)mul(3,4)";
>          let aopt = next(s);
>          assert_eq!(aopt, Some((2, "mul(3,4)")));
>          let (a, s) = aopt.unwrap();
>          let bopt = next(s);
>          assert_eq!(bopt, Some((12, "")));
>          let (b, s) = bopt.unwrap();
>          assert_eq!(next(s), None);
>          assert_eq!(a * b, 24);
>      }
> }
> --->END<---
> 
> I suspect yours may be somewhat faster, though this likely does
> more error checking.  YMMV.
> 

My guess is that your code (after adding the simultaneous scans for the 
do/don't markers) will take about twice as long (or more?) as the 7 us 
both my own and u/maneatingape (reddit handle of the guy with the 
fastest Rust solutions to all the 500+ puzzles) needs to deliver the result.

He is famous for solving every one of them in less than half a second:

His current total is 462 milliseconds for 524 stars.

I've managed to improve slightly on his code a few times, but more often 
  he is ahead of the best I've been able to come up with.

Collectively, the group discussing this on reddit have tried many 
different search approaches, including unaligned load of 4 bytes as a 
u32, then compare that directly against "mul(", "do()" and "don'" in a 
match statement. For me, this was slower in Rust, but a C programmer 
gained a us or two this way.

Setting up a combined Boyer-Moore would be doable:

If the fourth byte is '(', ')' or "'", check the preceeding bytes, if 
not a match use a pre-computed skip table (maybe even one for each 
initial match?) to increment the pointer. Hmmm... maybe I'll try this!

Terje

-- 
- <Terje.Mathisen at tmsw.no>
"almost all programming can be viewed as an exercise in caching"
Re: Optimization by programmers
#24
Author: Dan Cross
Date: Thu, 08 Oct 2026 21:28
91 lines
4586 bytes
[Cross-post to comp.programming, Followup-To: comp.programming]

In article <11a6a6h$37i1n$1@dont-email.me>,
Terje Mathisen  <terje.mathisen@tmsw.no> wrote:
>Dan Cross wrote:
>> In article <11a5lqo$2v5bq$1@dont-email.me>,
>> Terje Mathisen  <terje.mathisen@tmsw.no> wrote:
>>> Not unrolling, the code is here:
>>>
>>> https://godbolt.org/z/YnY5G1K49
>>>
>>> The interesting part starts at line 28/29 .LBB0_02 in the asm window
>>> where you can see (starting at line 37) a bunch of cmp r8,rsi / jae
>>> <panic> sequences.
>> 
>> So you're not actually indexing into an _array_ here, but rather
>> into a _slice_, which is always bounds-checked in safe Rust
>> code.
>
>My old asm/C brain _knows_ that a slice of something with a known 
>address and total length is effectively the same thing as an unmutable 
>array.

Sadly, though, it's not. :-/

>Even if it isn't, the fact that I start by verifying that the slice 
>extends at least 7 bytes past the p index means that all of p, 
>p+1,p+2...p+6 must be valid, right?

One would think!

>>>> I do wonder, though, whether you'd get better object code using
>>>> `input.iter().chunks(n)` or `.windows(n)`.
>>>
>>> I guess I can try this, I'm guessing chunks(7) will error out if less
>>> than 7 elements are available?
>> 
>> But really what you want is to find all subsequences matching
>> the regular expression , `mul([0-9]+,[0-9]+)`, and then extract
>> the two numeric fields, multiple them, and sum the results.
>> That's a reduction over a sequence of products, which is itself
>> a reduction over a sequence of patches that yield pairs of
>> integers.
>
>Yes, doing it that way is easy!

Well, I mean as a conceptual thing; not necessary using a regex
library.  That is, mentally write the patterns down as a DFA and
then write that out as code+state tables.

>> [snip]
>> represent the input data.  Nothing says it's not UTF-8, and from
>> what I understand, the guy who runs it usually isn't a jerk
>> about that kind of thing.  I haven't tried to benchmark your
>> code against, e.g., this:
>
>What you implement here is just Part1: After solving that you get to 
>read Part2 where you have to also detect "do()" and "don't()" sequences, 
>so that the multiplication result only adds to the part2 result if we're 
>not following a don't().

Ah. Yeah, I'm going to refrain; it's cool that folks are excited
about that, but it's not my favorite biscuit.

>> [snip]
>> I suspect yours may be somewhat faster, though this likely does
>> more error checking.  YMMV.
>
>My guess is that your code (after adding the simultaneous scans for the 
>do/don't markers) will take about twice as long (or more?) as the 7 us 
>both my own and u/maneatingape (reddit handle of the guy with the 
>fastest Rust solutions to all the 500+ puzzles) needs to deliver the result.

Maybe?  I dunno; the library is probably optimized to use pretty
efficient algorithms, and/or simd and all that jazz.

>[snip]
>Setting up a combined Boyer-Moore would be doable:
>
>If the fourth byte is '(', ')' or "'", check the preceeding bytes, if 
>not a match use a pre-computed skip table (maybe even one for each 
>initial match?) to increment the pointer. Hmmm... maybe I'll try this!

Right. This lets you potentially go sub-linear looking for the
tokens you care about.  I wonder how it would stack up against
using something like `memchr::memmem`, though, since that'll get
you hardware acceleration using SIMD instructions and goofy
stuff like that.

	- Dan C.
Re: Optimization by programmers
#34
Author: Thomas Koenig
Date: Sun, 11 Oct 2026 08:41
18 lines
1915 bytes
Terje Mathisen <terje.mathisen@tmsw.no> schrieb:

> My old asm/C brain _knows_ that a slice of something with a known 
> address and total length is effectively the same thing as an unmutable 
> array.
>
> Even if it isn't, the fact that I start by verifying that the slice 
> extends at least 7 bytes past the p index means that all of p, 
> p+1,p+2...p+6 must be valid, right?

Range checking is very difficult for a compiler, see
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=VRP .


-- 
This USENET posting was made without artificial intelligence,
artificial impertinence, artificial arrogance, artificial stupidity,
artificial flavorings or artificial colorants.
Re: Optimization by programmers
#37
Author: MitchAlsup
Date: Sun, 11 Oct 2026 18:14
21 lines
1552 bytes
Terje Mathisen <terje.mathisen@tmsw.no> posted:

> Dan Cross wrote:
---------
> 
> My old asm/C brain _knows_ that a slice of something with a known 
> address and total length is effectively the same thing as an unmutable 
> array.

Can I get a definition of what mutable in Rust means ??

Intuition would imply the inverse of opposite of const from C.

> Even if it isn't, the fact that I start by verifying that the slice 
> extends at least 7 bytes past the p index means that all of p, 
> p+1,p+2...p+6 must be valid, right?
----------
> 
> Terje
> 
Re: Optimization by programmers
#39
Author: Terje Mathisen
Date: Sun, 11 Oct 2026 18:56
26 lines
2275 bytes
MitchAlsup wrote:
> 
> Terje Mathisen <terje.mathisen@tmsw.no> posted:
> 
>> Dan Cross wrote:
> ---------
>>
>> My old asm/C brain _knows_ that a slice of something with a known
>> address and total length is effectively the same thing as an unmutable
>> array.
> 
> Can I get a definition of what mutable in Rust means ??

It does mean that the function which receives a non-mut parameter, or 
itself declares som non-mut local variables, cannot modify any of them.

So yes, very similar to "not const".

You can discuss if its a good idea to make non-mutability the default 
instead of the opposite. Personally I like that part.

Terje

-- 
- <Terje.Mathisen at tmsw.no>
"almost all programming can be viewed as an exercise in caching"
Re: Optimization by programmers
#47
Author: David Brown
Date: Mon, 12 Oct 2026 05:47
66 lines
3925 bytes
On 11/10/2026 20:56, Terje Mathisen wrote:
> MitchAlsup wrote:
>>
>> Terje Mathisen <terje.mathisen@tmsw.no> posted:
>>
>>> Dan Cross wrote:
>> ---------
>>>
>>> My old asm/C brain _knows_ that a slice of something with a known
>>> address and total length is effectively the same thing as an unmutable
>>> array.
>>
>> Can I get a definition of what mutable in Rust means ??
> 
> It does mean that the function which receives a non-mut parameter, or 
> itself declares som non-mut local variables, cannot modify any of them.
> 
> So yes, very similar to "not const".

It sounds more powerful than "not const" in C.

This is perfectly reasonable C code :

	void change(const int * p, int x) {
		int * q = (int *) p;
		*q = x;
	}

Calling "change" with a pointer to data that was defined with a 
const-qualified type is undefined behaviour.  Other than that, the 
behaviour is fully defined.

So you may not change the value of a variable /defined/ as "const" in C 
- any attempt to do so is UB, and unless you go out of your way (such as 
with pointer casts), accidental attempts will usually be flagged as 
compile-time errors.

But if you receive a "pointer to const" parameter to a function, you can 
still write via a cast version of the pointer if the original object was 
not defined as "const".  (So objects defined as "const" may be placed in 
read-only memory of some kind, and trying to change them might cause a 
crash, signal, bus-error, etc.)

(In C++, members of a class can be marked "mutable" so that they can be 
changed without even needing any pointer cast shenanigans.  This means 
you can have classes where instances are "logically constant" in a 
function call - their user-visible value does not change - but with 
aspects that do change, such as caching the results of a calculation, or 
re-ordering elements in the underlying data structure for a set.)

The weaker promise of "const" in C and C++ blocks some possible compiler 
optimisations of code, but allows some additional user flexibility.

I think (and you will hopefully correct me if I am wrong!) in Rust if a 
function receives a non-mutable reference as a parameter, it is not 
allowed to cast it to a mutable reference.

> 
> You can discuss if its a good idea to make non-mutability the default 
> instead of the opposite. Personally I like that part.
> 

It certainly sounds good to me.


Re: Optimization by programmers
#52
Author: Thomas Koenig
Date: Mon, 12 Oct 2026 11:25
71 lines
3424 bytes
David Brown <david.brown@hesbynett.no> schrieb:

> But if you receive a "pointer to const" parameter to a function, you can 
> still write via a cast version of the pointer if the original object was 
> not defined as "const".  (So objects defined as "const" may be placed in 
> read-only memory of some kind, and trying to change them might cause a 
> crash, signal, bus-error, etc.)

In FORTRAN, it used to be possible on systems such as /360 to write

      CALL FOO(21)
      WRITE (*,*) 21
      END

      SUBROUTINE FOO(N)
      N = 42
      END

and get a printout of 42 (21 is only half the truth,
remember!) because the compiler put the constants in read/write
storage and arguments were passed via address.  (We used to call
this "Variation der Konstanten", which translates to "variation
of parameters", from ODE theory.

On modern systems, you get a bus error:

$ ./a.out

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

Backtrace for this error:
#0  0x72b109a23e59 in ???
#1  0x72b109a22e75 in ???
#2  0x72b10964532f in ???
        at ./signal/../sysdeps/unix/sysv/linux/x86_64/libc_sigaction.c:0
#3  0x401172 in foo_
        at /tmp/crash.f90:6
#4  0x40118f in MAIN__
        at /tmp/crash.f90:1
#5  0x401226 in main
        at /tmp/crash.f90:3


But it would be interesting to be able to put arguments into
storage which can be changed by the caller, but not the callee,
sort of a read-only stack, but I am not sure how one would
efficiently implement that.

(Modern Fortran offers INTENT for that, so

      CALL FOO(21)
      WRITE (*,*) 21
      END

      SUBROUTINE FOO(N)
      INTEGER, INTENT(IN) :: N
      N = 42
      END

gets you

error.f90:7:7:

    7 |       N = 42
      |       1~
Error: Dummy argument 'n' with INTENT(IN) in variable definition context (assignment) at (1)

-- 
This USENET posting was made without artificial intelligence,
artificial impertinence, artificial arrogance, artificial stupidity,
artificial flavorings or artificial colorants.
Re: Optimization by programmers
#54
Author: David Brown
Date: Mon, 12 Oct 2026 14:20
86 lines
3995 bytes
On 12/10/2026 13:25, Thomas Koenig wrote:
> David Brown <david.brown@hesbynett.no> schrieb:
> 
>> But if you receive a "pointer to const" parameter to a function, you can
>> still write via a cast version of the pointer if the original object was
>> not defined as "const".  (So objects defined as "const" may be placed in
>> read-only memory of some kind, and trying to change them might cause a
>> crash, signal, bus-error, etc.)
> 
> In FORTRAN, it used to be possible on systems such as /360 to write
> 
>        CALL FOO(21)
>        WRITE (*,*) 21
>        END
> 
>        SUBROUTINE FOO(N)
>        N = 42
>        END
> 
> and get a printout of 42 (21 is only half the truth,
> remember!) because the compiler put the constants in read/write
> storage and arguments were passed via address.  (We used to call
> this "Variation der Konstanten", which translates to "variation
> of parameters", from ODE theory.
> 

Yes, that "feature" of old FORTRAN is rather famous.

Forth is arguably even better for this :

: 21 42 ;
21 .
42 ok

That is - you can redefine the word "21" to put the value 42 on the 
stack.  Then if you ask for the number "21", you get the value 42.  It 
is not an oddity of the implementation, but the way the language works.





> On modern systems, you get a bus error:
> 
> $ ./a.out
> 
> Program received signal SIGSEGV: Segmentation fault - invalid memory reference.
> 
> Backtrace for this error:
> #0  0x72b109a23e59 in ???
> #1  0x72b109a22e75 in ???
> #2  0x72b10964532f in ???
>          at ./signal/../sysdeps/unix/sysv/linux/x86_64/libc_sigaction.c:0
> #3  0x401172 in foo_
>          at /tmp/crash.f90:6
> #4  0x40118f in MAIN__
>          at /tmp/crash.f90:1
> #5  0x401226 in main
>          at /tmp/crash.f90:3
> 
> 
> But it would be interesting to be able to put arguments into
> storage which can be changed by the caller, but not the callee,
> sort of a read-only stack, but I am not sure how one would
> efficiently implement that.
> 
> (Modern Fortran offers INTENT for that, so
> 
>        CALL FOO(21)
>        WRITE (*,*) 21
>        END
> 
>        SUBROUTINE FOO(N)
>        INTEGER, INTENT(IN) :: N
>        N = 42
>        END
> 
> gets you
> 
> error.f90:7:7:
> 
>      7 |       N = 42
>        |       1~
> Error: Dummy argument 'n' with INTENT(IN) in variable definition context (assignment) at (1)
> 
Re: Optimization by programmers
#55
Author: Dan Cross
Date: Mon, 12 Oct 2026 15:41
238 lines
9845 bytes
In article <1791742457-5857@newsgrouper.org>,
MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
>
>Terje Mathisen <terje.mathisen@tmsw.no> posted:
>
>> Dan Cross wrote:
>---------
>> 
>> My old asm/C brain _knows_ that a slice of something with a known 
>> address and total length is effectively the same thing as an unmutable 
>> array.
>
>Can I get a definition of what mutable in Rust means ??

First, it is important to note that this is a logical concept,
and has no bearing on the physical properties of the computer
that the program is running on.

>Intuition would imply the inverse of opposite of const from C.

Here's a detailed explanation.

By default, variables in Rust are immutable; that is, their
value may not change.  For example, one cannot assign to them,
and to try and do so is a compile-time error:

?	let foo = something();
?	foo = something_else();	// Error: `foo` is immutable.

"Mutable", then, means the opposite: the value _can_ change.
Mutability is intorduced via the `mut` keyword:

	let mut foo = something();
	foo = something_else();	// Ok: `foo` is mutable.

In Rust, this extends to references, which have specific
properties: references are non-nullable, and can only refer to
valid, initialized objects; references are also prohibited from
outliving the object they refer to, and furthermore, they carry
a notion of mutability themselves: a mutable reference can be
used to change its referrent; immutable references cannot.
Immutable references are created using the `&` operator; mutable
references use the `&mut` operator.

Importantly, while immutable references can be created to
mutable objects, the inverse is not true: mutable references
cannot be created to immutable objects.  So, for example this
does not compile:

?	let foo = something();
?	let foomut = &mut foo;	// `foo` is immutable

But this is ok:

	let mut foo = something();
	let foomut = &mut foo;

As is this:

	let mut foo = something();
	let fooref = &foo;	// Immutuable reference
	let barref = &foo;	// Ok; immutable reference

Having multiple immutable references to an object is fine, but
the language requires that _mutable_ references to an object
are mutually exclusive with any other reference to that object.
In Rust, we say that we "borrow" a reference to an object, and
the compiler has a thing called, "the borrow checker" that
checks that all of these properties hold.

So this will fail to compile:

?	let mut foo = something();
?	let foomut = &mut foo;	// Ok: only mutable
?	let barmut = &mut foo	// Fail: a mut ref to foo exists

As will this:

?	let mut foo = something();
?	let foomut = &mut foo;	// Ok; only reference.
?	let fooref = &foo;	// Fail: a mut ref to foo exists

And as will this:

?	let mut foo = something();
?	let fooref = &foo;	// Ok: immutable reference.
?	let barref = &foo;	// Ok: multiple immut. refs ok
?	let foomut = &mut foo;	// Fail: exiting ref already

References also have a property called a "lifetime" that is tied
to the object they are borrowed from; the rule is that a
reference is not allowed to outlive its referrent.  So this,
again, is a compile time error:

?	let foo = {
?	    let bar = something();
?	    &bar		// Error; bar going out of scope
?	};

Here, I created a new scope (indicated by the curly braces) and
bound some object to the name `bar` in that scope, and attempted
to preserve a reference to that object outside of that scope.
However, that object only exists in that scope, so when the
scope ends, so too does the lifetime of the object; trying to
use a reference to it beyond that point violates the life time
rules enforced by the borrow checker.

But this serves to introduce another aspect of this, which is
that scopes and lifetimes matter with respect to how the
compiler treats these rules.

Take the following:

	struct Obj(u32);	// Tuple struct containing a u32
	impl Obj {
	    fn print(&self) {
	        println!("Value in obj is: {}", self.0);
	    }
	}

Here, I have defined a trivial struct (a "tuple struct"
specifically) that contains a simple datum; an unsigned 32-bit
integer.  And I have written an "implementation" of that type
that provides a "print" method that takes `&self`; that is,
takes an immutable reference to an instance of that object and
prints the integer.

Now, consider this code:

	let mut foo = Obj(42);
	foo.print();
	let foomut = &mut foo;
	foomut.print();

What should happen here?  The first three lines are fine; I
create the object, and I invoke its `.print()` method, which
takes an immutable reference to `foo`, and then I borrow a
*mutable* reference to foo, which is fine (the immutable
reference that `.print()` borrowed is gone at that point).

But in the 4th line I try to invoke `.print()` through through
the mutable borrow.  However, as we have seen, `.print()` takes
an immutable reference, and I'm clearly holding a *mutable*
reference, which appears to violate the borrowing rules.
However, this code compiles just fine: what happened?

As it turns out, the compiler allows a mutable reference to be
_coerced_ into an immutable reference, which is what is
happening here.  The compiler is allows this since it can infer
that nothing else can take an mut reference to the original
object while the mut ref exists, and since the mut ref is in
use, nothing can indirect through it and modify the underlying
object.   So things like this are fine:

 0      fn scopes() {
 1	    let mut foo = Obj(42);
 2	    foo.print();
 3	    let foomut = &mut foo;
 4	    foomut.print();
 5	    foo = Obj(32);
 6	    foo.print();
 7	    let barmut = &mut foo;
 8	    barmut.print();
 9	    barmut.0 = 22;
10	    foo.print();
11	}

This also illustrates a couple of other aspects of the type
system: moves and non-lexical lifetimes.

Prior to 2018, the lifetimes of Rust objects followed the
lexical scopes of those objects, and this code would have failed
compilation on line 10, since the `&mut barmut` mutable borrow
from `foo` still existed in the lexical scope where we called
`foo.print()`.  But since 2018, the borrow checker was changed
so that lifetimes reflect the flow graph of the program, not
just the lexical structure; in this case, the compiler can infer
that nothing in the program uses `barmut` after line 9, so
calling `foo.print()` on line 10 is fine; the borrow still
"exists" but is inactive by then.

On the other hand, if I rewrite the last few lines as:

?	foo = Obj(32);
?	let barmut = &mut foo;
?	foo.print();
?	barmut.0 = 22;
?	barmut.print();

Then this fails to compile; the immutable borrow taken for
`foo.print()` conflicts with the mutable borrow taken on the
previous line.

By default, all assignments in Rust have _move_ semantics: after
the assignment, the source is considered destroyed, and any
references to it are no longer valid.  That's why one can assign
to `foo` and on line 5 and then take a mut reference to it on
line 7; the assignment on 5 implicitly dropped the original
`foo` object created on line 1 and replaced it with a new
object, so the mut reference it created on line 3 is invalid;
an attempt to use it subsequently would fail to compile.

One can define a `copy` operator for types that should not have
move semantics; this is usually applied to trivial types (like
integers).

One may ask, "why bother with all of this stuff?" and the answer
is that Rust is designed for a multicore world.  There is one
other wrinkle here that gives Rust a lot of power, and that's
how all of this stuff interacts with data races: safe Rust code
is data race free.

Rust does not mandate a particular shape or type of (software)
thread, but because of the "mut ref ^ immut ref" rule, enforced
by the borrow checker at compile-time, safe Rust programs cannot
race on access to data, even in the face of multithreading.

Rust handles this by exposing two "marker traits", `Sync` and
`Send`. To quote the _Rustinomicon_, "A type is `Send` if it is
safe to send it to another thread" and "A type is `Sync` if it
is safe to share between threads (T is `Sync` if and only if
`&T` is `Send`)."  That is, a type can be _shared_ between
threads if it is safe to send an immutable reference to it from
one thread to another, and the compiler can check borrows
against the lifetimes of objects, hence, can detect data races
_statically, at compile time_.
(https://doc.rust-lang.org/nomicon/send-and-sync.html)

Those of us familiar with writing multithreaded programs will
recognize the power of these constructs: these rules, taken
together, statically eliminate entire categories of common
memory and concurrency problems.

Anyway, that what "mutable" means, in a nutshell, and why it is
important.

	- Dan C.
Re: Optimization by programmers
#56
Author: Dan Cross
Date: Mon, 12 Oct 2026 15:47
26 lines
1892 bytes
In article <11ahs8q$38ir0$4@dont-email.me>,
David Brown  <david.brown@hesbynett.no> wrote:
>[snip]
>I think (and you will hopefully correct me if I am wrong!) in Rust if a 
>function receives a non-mutable reference as a parameter, it is not 
>allowed to cast it to a mutable reference.

That is correct.  There is no way to do that in safe Rust, and
shenanigans that do it using unsafe are UB (UB in safe Rust is a
compile-time error).

As I mentioned in my other response, going the other direction
is ok: it is possible to coerce a mutable reference to an
immutable reference, so that you can e.g. invoke a method that
takes `&self` on an object to which you have an `&mut` borrow.

>> You can discuss if its a good idea to make non-mutability the default 
>> instead of the opposite. Personally I like that part.
>
>It certainly sounds good to me.

It is!  Being explicit about when things are mutable is very
helpful.

	- Dan C.
Re: Optimization by programmers
#57
Author: John Savard
Date: Mon, 12 Oct 2026 16:12
37 lines
2716 bytes
On Mon, 12 Oct 2026 11:25:32 -0000 (UTC), Thomas Koenig
<tkoenig@netcologne.de> wrote:

>David Brown <david.brown@hesbynett.no> schrieb:
>
>> But if you receive a "pointer to const" parameter to a function, you can 
>> still write via a cast version of the pointer if the original object was 
>> not defined as "const".  (So objects defined as "const" may be placed in 
>> read-only memory of some kind, and trying to change them might cause a 
>> crash, signal, bus-error, etc.)
>
>In FORTRAN, it used to be possible on systems such as /360 to write
>
>      CALL FOO(21)
>      WRITE (*,*) 21
>      END
>
>      SUBROUTINE FOO(N)
>      N = 42
>      END
>
>and get a printout of 42 (21 is only half the truth,
>remember!) because the compiler put the constants in read/write
>storage and arguments were passed via address.

And the proper way to correct this error is obvious. Not by putting
constants in a segment marked read-only. But in properly implementing
language semantics.

So the values of constants are stored in memory.

However, when a constant is passed to a function as an argument,
clearly that constant should be treated as an *expression*, not as a
variable. So you copy it to a temporary, and pass the address of the
temporary to the function. Not doing that was the bug.

John Savard
Re: Optimization by programmers
#58
Author: Anton Ertl
Date: Mon, 12 Oct 2026 17:10
47 lines
3025 bytes
David Brown <david.brown@hesbynett.no> writes:
>Forth is arguably even better for this :
>
>: 21 42 ;
>21 .
>42 ok
>
>That is - you can redefine the word "21" to put the value 42 on the 
>stack.  Then if you ask for the number "21", you get the value 42.  It 
>is not an oddity of the implementation, but the way the language works.

Yes, but used like this, it's only a curiosity; nobody does this
except to show that it can be done.

However, there are cases where this is practically relevant:

hex \ change to base #16
add \ is this a dictionary word, or a number?

The classic ways to avoid this has been to

1) prefix hex numbers with 0 if they would otherwise start with a
   letter.  Dictionary words rarely start with digits, and when they
   do, they don't conflict with hex numbers.

2) Use "," at the end of assembly language mnemonics, e.g. "add,":
   Benefits: 1) Avoids conflicts with hex numbers.  2) For postfix
   assemblers (e.g. "r0 r1 r2 add,", the "," nicely separates the
   instruction from the next.  But a significant number of Forth
   assemblers do not follow this convention.

In modern Forth another way is to avoid changing BASE, and just prefix
hex numbers with "$", e.g., "$add".

When you do, e.g.,

hex
: add ;

in Gforth, Gforth tells you: "warning: defined literal add as word".
It does not tell you that when you define "add" when the base is
decimal, however.

- anton
-- 
'Anyone trying for "industrial quality" ISA should avoid undefined behavior.'
  Mitch Alsup, <c17fcd89-f024-40e7-a594-88a85ac10d20o@googlegroups.com>
Re: Optimization by programmers
#61
Author: MitchAlsup
Date: Mon, 12 Oct 2026 18:37
85 lines
4203 bytes
cross@spitfire.i.gajendra.net (Dan Cross) posted:

First off: thank you dan for a well done explanation.

> In article <1791742457-5857@newsgrouper.org>,
> MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
> >
> >Terje Mathisen <terje.mathisen@tmsw.no> posted:
> >
> >> Dan Cross wrote:
> >---------
> >> 
> >> My old asm/C brain _knows_ that a slice of something with a known 
> >> address and total length is effectively the same thing as an unmutable 
> >> array.
> >
> >Can I get a definition of what mutable in Rust means ??
> 
--------snip of what I understand clearly------------
> 
> So this will fail to compile:
> 
> ?	let mut foo = something();
> ?	let foomut = &mut foo;	// Ok: only mutable
> ?	let barmut = &mut foo	// Fail: a mut ref to foo exists

Is this supposed to work across threads ?? so, only 1 thread has write
access at any given point in time. If so, how does one thread hand-off
mutability to another ??
 
--------------snip again--------

> 
> By default, all assignments in Rust have _move_ semantics: after
> the assignment, the source is considered destroyed, and any
> references to it are no longer valid.  That's why one can assign
> to `foo` and on line 5 and then take a mut reference to it on
> line 7; the assignment on 5 implicitly dropped the original
> `foo` object created on line 1 and replaced it with a new
> object, so the mut reference it created on line 3 is invalid;
> an attempt to use it subsequently would fail to compile.

This is clever.
 
> One can define a `copy` operator for types that should not have
> move semantics; this is usually applied to trivial types (like
> integers).
> 
> One may ask, "why bother with all of this stuff?" and the answer
> is that Rust is designed for a multicore world.  There is one
> other wrinkle here that gives Rust a lot of power, and that's
> how all of this stuff interacts with data races: safe Rust code
> is data race free.

See question above.
 
> Rust does not mandate a particular shape or type of (software)
> thread, but because of the "mut ref ^ immut ref" rule, enforced
> by the borrow checker at compile-time, safe Rust programs cannot
> race on access to data, even in the face of multithreading.
> 
> Rust handles this by exposing two "marker traits", `Sync` and
> `Send`. To quote the _Rustinomicon_, "A type is `Send` if it is
> safe to send it to another thread" and "A type is `Sync` if it
> is safe to share between threads (T is `Sync` if and only if
> `&T` is `Send`)."  That is, a type can be _shared_ between
> threads if it is safe to send an immutable reference to it from
> one thread to another, and the compiler can check borrows
> against the lifetimes of objects, hence, can detect data races
> _statically, at compile time_.
> (https://doc.rust-lang.org/nomicon/send-and-sync.html)
> 
> Those of us familiar with writing multithreaded programs will
> recognize the power of these constructs: these rules, taken
> together, statically eliminate entire categories of common
> memory and concurrency problems.
> 
> Anyway, that what "mutable" means, in a nutshell, and why it is
> important.

Thanks again for a complete explanation.
 
> 	- Dan C.
> 
Re: Optimization by programmers
#62
Author: MitchAlsup
Date: Mon, 12 Oct 2026 18:40
46 lines
2749 bytes
quadibloc@invalid.com (John Savard) posted:

> On Mon, 12 Oct 2026 11:25:32 -0000 (UTC), Thomas Koenig
> <tkoenig@netcologne.de> wrote:
> 
> >David Brown <david.brown@hesbynett.no> schrieb:
> >
> >> But if you receive a "pointer to const" parameter to a function, you can 
> >> still write via a cast version of the pointer if the original object was 
> >> not defined as "const".  (So objects defined as "const" may be placed in 
> >> read-only memory of some kind, and trying to change them might cause a 
> >> crash, signal, bus-error, etc.)
> >
> >In FORTRAN, it used to be possible on systems such as /360 to write
> >
> >      CALL FOO(21)
> >      WRITE (*,*) 21
> >      END
> >
> >      SUBROUTINE FOO(N)
> >      N = 42
> >      END
> >
> >and get a printout of 42 (21 is only half the truth,
> >remember!) because the compiler put the constants in read/write
> >storage and arguments were passed via address.
> 
> And the proper way to correct this error is obvious. Not by putting
> constants in a segment marked read-only. But in properly implementing
> language semantics.
> 
> So the values of constants are stored in memory.
> 
> However, when a constant is passed to a function as an argument,
> clearly that constant should be treated as an *expression*, not as a
> variable. So you copy it to a temporary, and pass the address of the
> temporary to the function.

And you think the language designers in 1956 could have figured that out ???

>                           Not doing that was the bug.

Some would disagree.
> 
> John Savard
Re: Optimization by programmers
#63
Author: David Brown
Date: Mon, 12 Oct 2026 19:05
67 lines
3936 bytes
On 12/10/2026 19:10, Anton Ertl wrote:
> David Brown <david.brown@hesbynett.no> writes:
>> Forth is arguably even better for this :
>>
>> : 21 42 ;
>> 21 .
>> 42 ok
>>
>> That is - you can redefine the word "21" to put the value 42 on the
>> stack.  Then if you ask for the number "21", you get the value 42.  It
>> is not an oddity of the implementation, but the way the language works.
> 
> Yes, but used like this, it's only a curiosity; nobody does this
> except to show that it can be done.
> 

Of course :-)

But it /is/ a cool curiosity!

It is a natural consequence of having substantial freedom to define and 
redefine almost anything as a "word".  And I can imagine it having a 
variety of uses, even for things like words that are all digits or 
otherwise mean something.  However, my experience of Forth is quite 
minimal - just playing around a little - and I have no knowledge of 
using it for real code.

> However, there are cases where this is practically relevant:
> 
> hex \ change to base #16
> add \ is this a dictionary word, or a number?
> 

I did not know about the "hex" word, so this is a new detail for me. 
Yes, I can see that having potential for confusion.

> The classic ways to avoid this has been to
> 
> 1) prefix hex numbers with 0 if they would otherwise start with a
>     letter.  Dictionary words rarely start with digits, and when they
>     do, they don't conflict with hex numbers.
> 
> 2) Use "," at the end of assembly language mnemonics, e.g. "add,":
>     Benefits: 1) Avoids conflicts with hex numbers.  2) For postfix
>     assemblers (e.g. "r0 r1 r2 add,", the "," nicely separates the
>     instruction from the next.  But a significant number of Forth
>     assemblers do not follow this convention.
> 
> In modern Forth another way is to avoid changing BASE, and just prefix
> hex numbers with "$", e.g., "$add".
> 

That looks clearer to me.  Using $ for hex numbers is, I think, the 
first convention I learned (it was used in BBC Basic, and by its 6502 
assembler).

> When you do, e.g.,
> 
> hex
> : add ;
> 
> in Gforth, Gforth tells you: "warning: defined literal add as word".
> It does not tell you that when you define "add" when the base is
> decimal, however.
> 
> - anton
Re: Optimization by programmers
#66
Author: Scott Lurndal
Date: Mon, 12 Oct 2026 19:21
25 lines
2282 bytes
MitchAlsup <user5857@newsgrouper.org.invalid> writes:
>
>
>> 
>> However, when a constant is passed to a function as an argument,
>> clearly that constant should be treated as an *expression*, not as a
>> variable. So you copy it to a temporary, and pass the address of the
>> temporary to the function.
>
>And you think the language designers in 1956 could have figured that out ???
>

For the most part, everything was in memory in 1956 (aside from an
accumulator).     The constant would likely have been either in the
instruction stream itself (e.g. burroughs medium systems supported
1 to 6 digit constants in the A operand field for most instructions)
or in memory.  

The electrodata 220 (1958) had:
  "A" register (10 digits plus sign digit) First operand
  "R" register (10 digits plus sign digit)  (extension of A register for product/quotient)
  "D" register (10 digits plus sign digit) Second operand
  "B" regsiter (4 digits)                  Index register
  "C" register (10 digits)                 Current instruction
  "P" register (4 digits)                  Program Counter
Re: Optimization by programmers
#67
Author: John Levine
Date: Mon, 12 Oct 2026 19:54
24 lines
2058 bytes
According to MitchAlsup  <user5857@newsgrouper.org.invalid>:
quadibloc@invalid.com (John Savard) posted:
>> >In FORTRAN, it used to be possible on systems such as /360 to write
>> >
>> >      CALL FOO(21)
>> >      WRITE (*,*) 21
>> >      END
>> >
>> >      SUBROUTINE FOO(N)
>> >      N = 42
>> >      END

>And you think the language designers in 1956 could have figured that out ???

The original FORTRAN compiler didn't have user defined subroutines, only
the infamous ASSIGN statement, so it didn't come up.

By 1958 FORTRAN II had subroutines using call by reference so I suspect someone
smashed a constant argument shortly thereafter.

-- 
Regards,
John Levine, johnl@taugh.com, Primary Perpetrator of "The Internet for Dummies",
Please consider the environment before reading this e-mail. https://jl.ly
Re: Optimization by programmers
#68
Author: Dan Cross
Date: Mon, 12 Oct 2026 21:07
158 lines
7659 bytes
In article <1791830267-5857@newsgrouper.org>,
MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
>
>cross@spitfire.i.gajendra.net (Dan Cross) posted:
>
>First off: thank you dan for a well done explanation.
>
>> In article <1791742457-5857@newsgrouper.org>,
>> MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
>> >
>> >Terje Mathisen <terje.mathisen@tmsw.no> posted:
>> >
>> >> Dan Cross wrote:
>> >---------
>> >> 
>> >> My old asm/C brain _knows_ that a slice of something with a known 
>> >> address and total length is effectively the same thing as an unmutable 
>> >> array.
>> >
>> >Can I get a definition of what mutable in Rust means ??
>> 
>--------snip of what I understand clearly------------
>> 
>> So this will fail to compile:
>> 
>> ?	let mut foo = something();
>> ?	let foomut = &mut foo;	// Ok: only mutable
>> ?	let barmut = &mut foo	// Fail: a mut ref to foo exists
>
>Is this supposed to work across threads ?? so, only 1 thread has write
>access at any given point in time.

Yes, that's right.

>If so, how does one thread hand-off mutability to another ??

Typically, you use a mutual exclusion primitive of one kind or
another to serialize access to mutable state.  For example, the
standard library includes the usual complement of Mutex,
reader/writer locks, condition variables, barriers, reference
counters, thread-safe channels, and so on.  For bare-metal
programs we have to implement these ourselves, but there are
some third-party implementations that can help (for example, the
`spin` crate implements spinlocks, providing, an interface that
looks close to `std::sync::Mutex`).

Something I should have mentioned earlier is that Rust object
has a single, well-defined owner, and that references to that
object are borrowed _from the owner_.

So, using `Mutex` as an example, we make the `Mutex` itself the
owner of the object: the `.lock()` method lets threads borrow
mutable references to the object, and the serialization inherent
in the Mutex type and the locking protocol enforces the
"mut ^ immut" semantics across threads.

Similarly, a `RwLock` can hand out multiple immutable refs to
the object, but keeps track of them, and only lets one borrower
access a `mut ref` at a time, and only when there are no
outstanding immutable refs to it.

In fact, it's slightly more complex in that `mutex.lock()`
actually returns a proxy object that holds onto the reference;
its return type is actually, `LockResult<LockGuard<'_, T>>`,
where `'_` is an anonymous lifetime, and `T` is the type of the
thing protected by the `Mutex`.  `LockResult` lets someone
detect a lock that has been poisoned; the `LockGuard` is the
thing that holds the ref.  When it goes otu of scope, it
automatically unlocks the mutex, and it implements a trait
called `Deref` to forward uses on to the ref to the locked
object.

This all intersects with the `Send`/`Sync` stuff; `Mutex` is
`Sync`, and `Mutex` objects themselves are treated as immutable. 
So to share access to a `Foo` between threads, I use something
like a `Mutex<Foo>`.  This is an example of "Interior
Mutability", where something immutable (the `Mutex` object
itself) can hold onto something that is mutable.

This raises a question: if all this machinery is required for
safe access to shared data across threads anyway, then why all
the language-level rules?  The answer is hinted at by the mutex
object itself is immutable, we can hand out references to it
easily.  Since it owns the (mutable) object the lock protects,
it can decide how to hand out references to the object.

>--------------snip again--------
>> By default, all assignments in Rust have _move_ semantics: after
>> the assignment, the source is considered destroyed, and any
>> references to it are no longer valid.  That's why one can assign
>> to `foo` and on line 5 and then take a mut reference to it on
>> line 7; the assignment on 5 implicitly dropped the original
>> `foo` object created on line 1 and replaced it with a new
>> object, so the mut reference it created on line 3 is invalid;
>> an attempt to use it subsequently would fail to compile.
>
>This is clever.
> 
>> One can define a `copy` operator for types that should not have
>> move semantics; this is usually applied to trivial types (like
>> integers).
>> 
>> One may ask, "why bother with all of this stuff?" and the answer
>> is that Rust is designed for a multicore world.  There is one
>> other wrinkle here that gives Rust a lot of power, and that's
>> how all of this stuff interacts with data races: safe Rust code
>> is data race free.
>
>See question above.

See above; hopefully that helps?

There's one other thing here that may be interesting: how does
one implement any of this stuff _in Rust_?  In particular, how
does one implement interior mutability?

The answer is using something called the `UnsafeCell`:
https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html

`UnsafeCell` allows mutation of an object (the thing owned by
the cell) through a shared (what up to now I've been calling an
"immutable") reference to the cell.  It's the one place that
permits that behavior.

The implementatin of a spinlock in the `spin` crate is an
interesting read to understand the mechanics here:
https://codeberg.org/zesterer/spin/src/branch/master/src/mutex/spin.rs

>> Rust does not mandate a particular shape or type of (software)
>> thread, but because of the "mut ref ^ immut ref" rule, enforced
>> by the borrow checker at compile-time, safe Rust programs cannot
>> race on access to data, even in the face of multithreading.
>> 
>> Rust handles this by exposing two "marker traits", `Sync` and
>> `Send`. To quote the _Rustinomicon_, "A type is `Send` if it is
>> safe to send it to another thread" and "A type is `Sync` if it
>> is safe to share between threads (T is `Sync` if and only if
>> `&T` is `Send`)."  That is, a type can be _shared_ between
>> threads if it is safe to send an immutable reference to it from
>> one thread to another, and the compiler can check borrows
>> against the lifetimes of objects, hence, can detect data races
>> _statically, at compile time_.
>> (https://doc.rust-lang.org/nomicon/send-and-sync.html)
>> 
>> Those of us familiar with writing multithreaded programs will
>> recognize the power of these constructs: these rules, taken
>> together, statically eliminate entire categories of common
>> memory and concurrency problems.
>> 
>> Anyway, that what "mutable" means, in a nutshell, and why it is
>> important.
>
>Thanks again for a complete explanation.

Happy to do it.

	- Dan C.
Re: Optimization by programmers
#69
Author: Dan Cross
Date: Mon, 12 Oct 2026 21:10
50 lines
2805 bytes
In article <1791830400-5857@newsgrouper.org>,
MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
>quadibloc@invalid.com (John Savard) posted:
>> On Mon, 12 Oct 2026 11:25:32 -0000 (UTC), Thomas Koenig
>> <tkoenig@netcologne.de> wrote:
>> >David Brown <david.brown@hesbynett.no> schrieb:
>> >> But if you receive a "pointer to const" parameter to a function, you can 
>> >> still write via a cast version of the pointer if the original object was 
>> >> not defined as "const".  (So objects defined as "const" may be placed in 
>> >> read-only memory of some kind, and trying to change them might cause a 
>> >> crash, signal, bus-error, etc.)
>> >
>> >In FORTRAN, it used to be possible on systems such as /360 to write
>> >
>> >      CALL FOO(21)
>> >      WRITE (*,*) 21
>> >      END
>> >
>> >      SUBROUTINE FOO(N)
>> >      N = 42
>> >      END
>> >
>> >and get a printout of 42 (21 is only half the truth,
>> >remember!) because the compiler put the constants in read/write
>> >storage and arguments were passed via address.
>> 
>> And the proper way to correct this error is obvious. Not by putting
>> constants in a segment marked read-only. But in properly implementing
>> language semantics.
>> 
>> So the values of constants are stored in memory.
>> 
>> However, when a constant is passed to a function as an argument,
>> clearly that constant should be treated as an *expression*, not as a
>> variable. So you copy it to a temporary, and pass the address of the
>> temporary to the function.
>
>And you think the language designers in 1956 could have figured that out ???

I don't think that's the right framing.

>>                           Not doing that was the bug.
>
>Some would disagree.

That it's a bug?  Clearly, changing the value of some constant
is surprising, at best.

	- Dan C.
Re: Optimization by programmers
#71
Author: MitchAlsup
Date: Mon, 12 Oct 2026 22:35
193 lines
9176 bytes
cross@spitfire.i.gajendra.net (Dan Cross) posted:

> In article <1791830267-5857@newsgrouper.org>,
> MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
> >
> >cross@spitfire.i.gajendra.net (Dan Cross) posted:
> >
> >First off: thank you dan for a well done explanation.
> >
> >> In article <1791742457-5857@newsgrouper.org>,
> >> MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
> >> >
> >> >Terje Mathisen <terje.mathisen@tmsw.no> posted:
> >> >
> >> >> Dan Cross wrote:
> >> >---------
> >> >> 
> >> >> My old asm/C brain _knows_ that a slice of something with a known 
> >> >> address and total length is effectively the same thing as an unmutable 
> >> >> array.
> >> >
> >> >Can I get a definition of what mutable in Rust means ??
> >> 
> >--------snip of what I understand clearly------------
> >> 
> >> So this will fail to compile:
> >> 
> >> ?	let mut foo = something();
> >> ?	let foomut = &mut foo;	// Ok: only mutable
> >> ?	let barmut = &mut foo	// Fail: a mut ref to foo exists
> >
> >Is this supposed to work across threads ?? so, only 1 thread has write
> >access at any given point in time.
> 
> Yes, that's right.
> 
> >If so, how does one thread hand-off mutability to another ??
> 
> Typically, you use a mutual exclusion primitive of one kind or
> another to serialize access to mutable state.  For example, the
> standard library includes the usual complement of Mutex,
> reader/writer locks, condition variables, barriers, reference
> counters, thread-safe channels, and so on.  For bare-metal
> programs we have to implement these ourselves, but there are
> some third-party implementations that can help (for example, the
> `spin` crate implements spinlocks, providing, an interface that
> looks close to `std::sync::Mutex`).
> 
> Something I should have mentioned earlier is that Rust object
> has a single, well-defined owner, and that references to that
> object are borrowed _from the owner_.

I was expecting one "thread" to hold (own?) the object in question
and was unsure how mutablility was handed out across other threads.

I had imagined that then current mut owner had its 'pointer' go
out of block and that somehow his no longer having a mutable ref
to the object somehow got propagated automagically by his leaving
of the block {which seems untenable}.

falling back on standard ways of passing this stuff around adds hope.
{{less Ada rendezvous like}}
 
> So, using `Mutex` as an example, we make the `Mutex` itself the
> owner of the object: the `.lock()` method lets threads borrow
> mutable references to the object, and the serialization inherent
> in the Mutex type and the locking protocol enforces the
> "mut ^ immut" semantics across threads.

Since I am a CPU guy, I would like to see the asm from any modern 
architecture perform this handoff ! <please> ?
 
> Similarly, a `RwLock` can hand out multiple immutable refs to
> the object, but keeps track of them, and only lets one borrower
> access a `mut ref` at a time, and only when there are no
> outstanding immutable refs to it.

Sounds like reference counting...
 
> In fact, it's slightly more complex in that `mutex.lock()`
> actually returns a proxy object that holds onto the reference;
> its return type is actually, `LockResult<LockGuard<'_, T>>`,
> where `'_` is an anonymous lifetime, and `T` is the type of the
> thing protected by the `Mutex`.  `LockResult` lets someone
> detect a lock that has been poisoned; the `LockGuard` is the
> thing that holds the ref.  When it goes otu of scope, it
> automatically unlocks the mutex, and it implements a trait
> called `Deref` to forward uses on to the ref to the locked
> object.

Another level of indirection to handle a more complicated issue...
 
> This all intersects with the `Send`/`Sync` stuff; `Mutex` is
> `Sync`, and `Mutex` objects themselves are treated as immutable. 
> So to share access to a `Foo` between threads, I use something
> like a `Mutex<Foo>`.  This is an example of "Interior
> Mutability", where something immutable (the `Mutex` object
> itself) can hold onto something that is mutable.
> 
> This raises a question: if all this machinery is required for
> safe access to shared data across threads anyway, then why all
> the language-level rules?  The answer is hinted at by the mutex
> object itself is immutable, we can hand out references to it
> easily.  Since it owns the (mutable) object the lock protects,
> it can decide how to hand out references to the object.

We have the same problems with coherent caches and there are 3
normal solutions {MESI, MOESI, and Directories}
 
> >--------------snip again--------
> >> By default, all assignments in Rust have _move_ semantics: after
> >> the assignment, the source is considered destroyed, and any
> >> references to it are no longer valid.  That's why one can assign
> >> to `foo` and on line 5 and then take a mut reference to it on
> >> line 7; the assignment on 5 implicitly dropped the original
> >> `foo` object created on line 1 and replaced it with a new
> >> object, so the mut reference it created on line 3 is invalid;
> >> an attempt to use it subsequently would fail to compile.
> >
> >This is clever.
> > 
> >> One can define a `copy` operator for types that should not have
> >> move semantics; this is usually applied to trivial types (like
> >> integers).
> >> 
> >> One may ask, "why bother with all of this stuff?" and the answer
> >> is that Rust is designed for a multicore world.  There is one
> >> other wrinkle here that gives Rust a lot of power, and that's
> >> how all of this stuff interacts with data races: safe Rust code
> >> is data race free.
> >
> >See question above.
> 
> See above; hopefully that helps?

Yes, quite a lot. Thanks for taking the time.

I ask these detailed questions to see if there is some tweak to 
my ISA that could allow a less costly solution with equivalent
semantics.
 
> There's one other thing here that may be interesting: how does
> one implement any of this stuff _in Rust_?  In particular, how
> does one implement interior mutability?

I care about ISA semantics, where some small-moderate tweak might
shrink the code path significantly.
 
> The answer is using something called the `UnsafeCell`:
> https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html
> 
> `UnsafeCell` allows mutation of an object (the thing owned by
> the cell) through a shared (what up to now I've been calling an
> "immutable") reference to the cell.  It's the one place that
> permits that behavior.
> 
> The implementatin of a spinlock in the `spin` crate is an
> interesting read to understand the mechanics here:
> https://codeberg.org/zesterer/spin/src/branch/master/src/mutex/spin.rs

I will read these later.
 
> >> Rust does not mandate a particular shape or type of (software)
> >> thread, but because of the "mut ref ^ immut ref" rule, enforced
> >> by the borrow checker at compile-time, safe Rust programs cannot
> >> race on access to data, even in the face of multithreading.
> >> 
> >> Rust handles this by exposing two "marker traits", `Sync` and
> >> `Send`. To quote the _Rustinomicon_, "A type is `Send` if it is
> >> safe to send it to another thread" and "A type is `Sync` if it
> >> is safe to share between threads (T is `Sync` if and only if
> >> `&T` is `Send`)."  That is, a type can be _shared_ between
> >> threads if it is safe to send an immutable reference to it from
> >> one thread to another, and the compiler can check borrows
> >> against the lifetimes of objects, hence, can detect data races
> >> _statically, at compile time_.
> >> (https://doc.rust-lang.org/nomicon/send-and-sync.html)
> >> 
> >> Those of us familiar with writing multithreaded programs will
> >> recognize the power of these constructs: these rules, taken
> >> together, statically eliminate entire categories of common
> >> memory and concurrency problems.
> >> 
> >> Anyway, that what "mutable" means, in a nutshell, and why it is
> >> important.
> >
> >Thanks again for a complete explanation.
> 
> Happy to do it.
> 
> 	- Dan C.
> 
Re: Optimization by programmers
#72
Author: MitchAlsup
Date: Mon, 12 Oct 2026 22:37
56 lines
3089 bytes
cross@spitfire.i.gajendra.net (Dan Cross) posted:

> In article <1791830400-5857@newsgrouper.org>,
> MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
> >quadibloc@invalid.com (John Savard) posted:
> >> On Mon, 12 Oct 2026 11:25:32 -0000 (UTC), Thomas Koenig
> >> <tkoenig@netcologne.de> wrote:
> >> >David Brown <david.brown@hesbynett.no> schrieb:
> >> >> But if you receive a "pointer to const" parameter to a function, you can 
> >> >> still write via a cast version of the pointer if the original object was 
> >> >> not defined as "const".  (So objects defined as "const" may be placed in 
> >> >> read-only memory of some kind, and trying to change them might cause a 
> >> >> crash, signal, bus-error, etc.)
> >> >
> >> >In FORTRAN, it used to be possible on systems such as /360 to write
> >> >
> >> >      CALL FOO(21)
> >> >      WRITE (*,*) 21
> >> >      END
> >> >
> >> >      SUBROUTINE FOO(N)
> >> >      N = 42
> >> >      END
> >> >
> >> >and get a printout of 42 (21 is only half the truth,
> >> >remember!) because the compiler put the constants in read/write
> >> >storage and arguments were passed via address.
> >> 
> >> And the proper way to correct this error is obvious. Not by putting
> >> constants in a segment marked read-only. But in properly implementing
> >> language semantics.
> >> 
> >> So the values of constants are stored in memory.
> >> 
> >> However, when a constant is passed to a function as an argument,
> >> clearly that constant should be treated as an *expression*, not as a
> >> variable. So you copy it to a temporary, and pass the address of the
> >> temporary to the function.
> >
> >And you think the language designers in 1956 could have figured that out ???
> 
> I don't think that's the right framing.
> 
> >>                           Not doing that was the bug.
> >
> >Some would disagree.
> 
> That it's a bug?  Clearly, changing the value of some constant
> is surprising, at best.

Allows one to have 1 {sin(), cos() ...} subroutine and change the value of pi
so one then has {sinpi(), cospi(), ...}
> 
> 	- Dan C.
> 
Re: smashing constants, sort of like Optimization by programmers
#74
Author: John Levine
Date: Tue, 13 Oct 2026 00:35
31 lines
2605 bytes
According to Dan Cross <cross@spitfire.i.gajendra.net>:
>>> However, when a constant is passed to a function as an argument,
>>> clearly that constant should be treated as an *expression*, not as a
>>> variable. So you copy it to a temporary, and pass the address of the
>>> temporary to the function.
>>
>>And you think the language designers in 1956 could have figured that out ???
>
>I don't think that's the right framing.
>
>>>                           Not doing that was the bug.
>>
>>Some would disagree.
>
>That it's a bug?  Clearly, changing the value of some constant
>is surprising, at best.

I wasn't writing programs in 1958, having had a prior committment in
nursery school, but I was writing programs in the late 1960s.

I think you would find the attitude was yes, you could do that, but it
would be stupid, so don't. Remember that FORTRAN ran on a 70x with 32K
words of memory, S/360 subset FORTRAN E ran on a 360/30 with 32K bytes
and full FORTRAN G ran on a 360/40 with 128K bytes. Every word was
precious, and wasting three or four words creating a temporary to
defend against an obvious programmer error would have been silly.

-- 
Regards,
John Levine, johnl@taugh.com, Primary Perpetrator of "The Internet for Dummies",
Please consider the environment before reading this e-mail. https://jl.ly
Re: Optimization by programmers
#75
Author: Niklas Holsti
Date: Tue, 13 Oct 2026 09:03
26 lines
2391 bytes
On 2026-10-12 20:10, Anton Ertl wrote:
> David Brown <david.brown@hesbynett.no> writes:
>> Forth is arguably even better for this :
>>
>> : 21 42 ;
>> 21 .
>> 42 ok
>>
>> That is - you can redefine the word "21" to put the value 42 on the
>> stack.  Then if you ask for the number "21", you get the value 42.  It
>> is not an oddity of the implementation, but the way the language works.
> 
> Yes, but used like this, it's only a curiosity; nobody does this
> except to show that it can be done.

Forth originated in astronomy, if I remember correctly. I do remember 
that in an astronomy-domain Forth program, where it was often necessary 
to transform the celestial coordinates of stars from the standard 
catalog epoch (the start of the year 1950) to the current time, the word 
1950.0 was defined to perform that transformation.

That Forth system did not have floating-point support, so 1950.0 could 
not be understood as a floating-point literal. But if the program had 
been ported to a Forth system with floating-point support, confusion 
could have resulted.
Re: Optimization by programmers
#77
Author: Anton Ertl
Date: Tue, 13 Oct 2026 10:27
42 lines
3372 bytes
Niklas Holsti <niklas.holsti@tidorum.invalid> writes:
>Forth originated in astronomy, if I remember correctly. I do remember 
>that in an astronomy-domain Forth program, where it was often necessary 
>to transform the celestial coordinates of stars from the standard 
>catalog epoch (the start of the year 1950) to the current time, the word 
>1950.0 was defined to perform that transformation.

That is unlikely, as explained below.

>That Forth system did not have floating-point support, so 1950.0 could 
>not be understood as a floating-point literal. But if the program had 
>been ported to a Forth system with floating-point support, confusion 
>could have resulted.

Most Forth systems recognize strings like 1950.0 as double-cell
numbers.  That's expecially true in early systems, where 16-bit cells
were too small for the arithmetic needs of many applications
(including in astronomy).  In early systems fixed-point was used a
lot, and 1950.0 is interpreted as 19500 with a scale factor of 1/10.

Only in recent times with 32-bit and 64-bit cells roll-your-own system
implementors have chosen to abandon double-cell numbers, but
mainstream systems (even with 64-bit cells) still recognize 1950.0 as
double-cell number.  Just on 2026-10-05 someone complained on
comp.lang.forth <6ac33315@news.ausics.net>:

|Maybe there's a mechanism in Gforth that stops annoying nags when
|printing numbers?
|
|Gforth 0.7.9_20200709
|
|1. d.
|*terminal*:1:1: warning: '1.' is a double-cell integer; type `help' for more info1  ok

The warning is not about printing the double-cell number, but about
the "1.".  But anyway, it shows that double-cell numbers are still
being used.

- anton
-- 
'Anyone trying for "industrial quality" ISA should avoid undefined behavior.'
  Mitch Alsup, <c17fcd89-f024-40e7-a594-88a85ac10d20o@googlegroups.com>
Re: Optimization by programmers
#80
Author: Andy Valencia
Date: Tue, 13 Oct 2026 16:09
22 lines
2080 bytes
anton@mips.complang.tuwien.ac.at (Anton Ertl) writes:
> hex \ change to base #16
> add \ is this a dictionary word, or a number?
> 
> The classic ways to avoid this has been to
> 
> 1) prefix hex numbers with 0 if they would otherwise start with a
>    letter.  Dictionary words rarely start with digits, and when they
>    do, they don't conflict with hex numbers.

Alternately, Forth could adopt practices which have become broad,
de facto standards.  So, referencing above, instead hex numbers
have a 0xadd prefix, and you don't switch the base of the system.

While you're at it, start the transition to "//" as the comment
token.  From memory, who's holding out?  Only Forth, Smalltalk, and
COBOL come to mind.

Andy Valencia
Home page: https://www.vsta.org/andy/
To contact me: https://www.vsta.org/contact/andy.html
No AI was used in the composition of this message
Re: Optimization by programmers
#81
Author: Anton Ertl
Date: Tue, 13 Oct 2026 16:31
48 lines
3239 bytes
Andy Valencia <vandys@vsta.org> writes:
>anton@mips.complang.tuwien.ac.at (Anton Ertl) writes:
>> hex \ change to base #16
>> add \ is this a dictionary word, or a number?
>> 
>> The classic ways to avoid this has been to
>> 
>> 1) prefix hex numbers with 0 if they would otherwise start with a
>>    letter.  Dictionary words rarely start with digits, and when they
>>    do, they don't conflict with hex numbers.
>
>Alternately, Forth could adopt practices which have become broad,
>de facto standards.  So, referencing above, instead hex numbers
>have a 0xadd prefix, and you don't switch the base of the system.

I don't change the base for inputting numbers, and use the
standardized prefix $ instead ($add), as mentioned.  A number of
systems recognize numbers with the prefix 0x as hex numbers, too.
Finally, you can add user-defined recognizers in a number of Forth
systems, and recognize 0x-prefixed numbers on these systems.

>While you're at it, start the transition to "//" as the comment
>token.

You can define that yourself if you want:

: // 0 parse 2drop ; immediate

But unlike for the 0x prefix, few Forth systems have implemented //
comments, so demand for that is low.  And why should there be demand
for it?

For the 0x prefix, the demand comes from interoperating with
C-oriented tools that output hex numbers with a 0x prefix.  But
comments have no such interoperability issues.

>From memory, who's holding out?  Only Forth, Smalltalk, and
>COBOL come to mind.

Most programming languages use something else for comments: Unix
shells, Lisp, Makefiles, assembly language, Postscript and Ada come to
my mind.  Maybe some of them also accept //, but I have yet to see a
program in one of these languages that uses such a comment.

- anton
-- 
'Anyone trying for "industrial quality" ISA should avoid undefined behavior.'
  Mitch Alsup, <c17fcd89-f024-40e7-a594-88a85ac10d20o@googlegroups.com>
Re: Optimization by programmers
#83
Author: Niklas Holsti
Date: Tue, 13 Oct 2026 17:00
39 lines
3118 bytes
On 2026-10-13 13:27, Anton Ertl wrote:
> Niklas Holsti <niklas.holsti@tidorum.invalid> writes:
>> Forth originated in astronomy, if I remember correctly. I do remember
>> that in an astronomy-domain Forth program, where it was often necessary
>> to transform the celestial coordinates of stars from the standard
>> catalog epoch (the start of the year 1950) to the current time, the word
>> 1950.0 was defined to perform that transformation.
> 
> That is unlikely, as explained below.

I am rather sure that my memory is correct.

This was quite a long time ago -- some time in the 1980s, IIRC.

>> That Forth system did not have floating-point support, so 1950.0 could
>> not be understood as a floating-point literal. But if the program had
>> been ported to a Forth system with floating-point support, confusion
>> could have resulted.
> 
> Most Forth systems recognize strings like 1950.0 as double-cell
> numbers.  That's expecially true in early systems, where 16-bit cells
> were too small for the arithmetic needs of many applications
> (including in astronomy).

OK, I did not know about that double-cell interpretation, so my comments 
about floating point are mistaken.

> In early systems fixed-point was used a lot, and 1950.0 is
> interpreted as 19500 with a scale factor of 1/10.
The Forth program in question represented angles as fixed-point 
fractions (0 <= x < 1) of a full circle. I don't remember the number of 
bits used.

Even if that Forth system by default interpreted 1950.0 as a double-cell 
number, apparently it was still possible to override that interpretation 
by defining a word called 1950.0.

But I trust we agree that such word names are not to be recommended.
Re: Optimization by programmers
#82
Author: Niklas Holsti
Date: Tue, 13 Oct 2026 17:02
21 lines
1940 bytes
On 2026-10-13 19:09, Andy Valencia wrote:
> anton@mips.complang.tuwien.ac.at (Anton Ertl) writes:
>> hex \ change to base #16
>> add \ is this a dictionary word, or a number?
>>
>> The classic ways to avoid this has been to
>>
>> 1) prefix hex numbers with 0 if they would otherwise start with a
>>     letter.  Dictionary words rarely start with digits, and when they
>>     do, they don't conflict with hex numbers.
> 
> Alternately, Forth could adopt practices which have become broad,
> de facto standards.  So, referencing above, instead hex numbers
> have a 0xadd prefix, and you don't switch the base of the system.
> 
> While you're at it, start the transition to "//" as the comment
> token.  From memory, who's holding out?  Only Forth, Smalltalk, and
> COBOL come to mind.

Ada uses "--".
Re: Optimization by programmers
#86
Author: David Brown
Date: Tue, 13 Oct 2026 17:50
36 lines
2896 bytes
On 13/10/2026 19:02, Niklas Holsti wrote:
> On 2026-10-13 19:09, Andy Valencia wrote:
>> anton@mips.complang.tuwien.ac.at (Anton Ertl) writes:
>>> hex \ change to base #16
>>> add \ is this a dictionary word, or a number?
>>>
>>> The classic ways to avoid this has been to
>>>
>>> 1) prefix hex numbers with 0 if they would otherwise start with a
>>>     letter.  Dictionary words rarely start with digits, and when they
>>>     do, they don't conflict with hex numbers.
>>
>> Alternately, Forth could adopt practices which have become broad,
>> de facto standards.  So, referencing above, instead hex numbers
>> have a 0xadd prefix, and you don't switch the base of the system.

0x prefixes for hex is certainly common, but $ prefixes for hex have 
been around for a long time too and are used in Pascal.  Some languages 
use a suffix, like 0addH.  Ada has 16#add#, while VHDL has x"add".  Some 
BASICs use &.  So again, there are plenty of options from existing practice.

>>
>> While you're at it, start the transition to "//" as the comment
>> token.  From memory, who's holding out?  Only Forth, Smalltalk, and
>> COBOL come to mind.
> 
> Ada uses "--".
> 

As does Lua, VHDL, Haskell, and SQL.  And lots of languages use #, TeX 
has %, several languages use ; and there are many others.

<https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(syntax)#Comments>


Re: Optimization by programmers
#85
Author: Scott Lurndal
Date: Tue, 13 Oct 2026 18:12
14 lines
1613 bytes
anton@mips.complang.tuwien.ac.at (Anton Ertl) writes:
>Andy Valencia <vandys@vsta.org> writes:

>>From memory, who's holding out?  Only Forth, Smalltalk, and
>>COBOL come to mind.
>
>Most programming languages use something else for comments: Unix
>shells, Lisp, Makefiles, assembly language, Postscript and Ada come to
>my mind.  Maybe some of them also accept //, but I have yet to see a
>program in one of these languages that uses such a comment.

And one can simply pipe them through cpp before sending
the source to the compiler to remove comments starting with '//'.
Re: Optimization by programmers
#84
Author: Thomas Koenig
Date: Tue, 13 Oct 2026 18:40
46 lines
3213 bytes
John Savard <quadibloc@invalid.com> schrieb:
> On Mon, 12 Oct 2026 11:25:32 -0000 (UTC), Thomas Koenig
><tkoenig@netcologne.de> wrote:
>
>>David Brown <david.brown@hesbynett.no> schrieb:
>>
>>> But if you receive a "pointer to const" parameter to a function, you can 
>>> still write via a cast version of the pointer if the original object was 
>>> not defined as "const".  (So objects defined as "const" may be placed in 
>>> read-only memory of some kind, and trying to change them might cause a 
>>> crash, signal, bus-error, etc.)
>>
>>In FORTRAN, it used to be possible on systems such as /360 to write
>>
>>      CALL FOO(21)
>>      WRITE (*,*) 21
>>      END
>>
>>      SUBROUTINE FOO(N)
>>      N = 42
>>      END
>>
>>and get a printout of 42 (21 is only half the truth,
>>remember!) because the compiler put the constants in read/write
>>storage and arguments were passed via address.
>
> And the proper way to correct this error is obvious. Not by putting
> constants in a segment marked read-only. But in properly implementing
> language semantics.

First, those semantics have to be defined... but I thought you were
a great fan of all things /360, so I assumed you would like this :-)

> So the values of constants are stored in memory.
>
> However, when a constant is passed to a function as an argument,
> clearly that constant should be treated as an *expression*, not as a
> variable. So you copy it to a temporary, and pass the address of the
> temporary to the function. Not doing that was the bug.

That would penalize correct code, which is a no-no.

-- 
This USENET posting was made without artificial intelligence,
artificial impertinence, artificial arrogance, artificial stupidity,
artificial flavorings or artificial colorants.
Comment delimiters (was: Optimization by programmers)
#98
Author: Stefan Monnier
Date: Wed, 14 Oct 2026 03:24
10 lines
1883 bytes
> While you're at it, start the transition to "//" as the comment
> token.  From memory, who's holding out?  Only Forth, Smalltalk, and
> COBOL come to mind.

There are many many more, including a little known language named after
something like a snake or some British comedy.  In that language `//` is
the integer division operation.


=== Stefan
Re: Comment delimiters
#102
Author: David Brown
Date: Wed, 14 Oct 2026 07:56
13 lines
2036 bytes
On 14/10/2026 05:24, Stefan Monnier wrote:
>> While you're at it, start the transition to "//" as the comment
>> token.  From memory, who's holding out?  Only Forth, Smalltalk, and
>> COBOL come to mind.
> 
> There are many many more, including a little known language named after
> something like a snake or some British comedy.  In that language `//` is
> the integer division operation.
> 

The language was named for the comedy group.  The group in question does 
not have an explanation for the name, and just like the sound of it.
Re: Optimization by programmers
#104
Author: Anton Ertl
Date: Wed, 14 Oct 2026 08:02
49 lines
3901 bytes
Niklas Holsti <niklas.holsti@tidorum.invalid> writes:
>On 2026-10-13 13:27, Anton Ertl wrote:
>> Niklas Holsti <niklas.holsti@tidorum.invalid> writes:
>>> Forth originated in astronomy, if I remember correctly. I do remember
>>> that in an astronomy-domain Forth program, where it was often necessary
>>> to transform the celestial coordinates of stars from the standard
>>> catalog epoch (the start of the year 1950) to the current time, the word
>>> 1950.0 was defined to perform that transformation.
>> 
>> That is unlikely, as explained below.
>
>I am rather sure that my memory is correct.
>
>> In early systems fixed-point was used a lot, and 1950.0 is
>> interpreted as 19500 with a scale factor of 1/10.
>The Forth program in question represented angles as fixed-point 
>fractions (0 <= x < 1) of a full circle. I don't remember the number of 
>bits used.

Yes, that was customary for angles, as mentioned in the HOPL-II paper
"The Evolution of Forth"
<https://www.forth.com/resources/forth-programming-language/>:

|Moore expressed angles internally as 14-bit, 15-bit or 30-bit
|fixed-point binary fractions.

>Even if that Forth system by default interpreted 1950.0 as a double-cell 
>number, apparently it was still possible to override that interpretation 
>by defining a word called 1950.0.

Sure it's possible, but there is no reason why one would call a
conversion word 1950.0.  What would have been more in line with
practice is to define a word 1950.0 which does what writing 1950.0
without such a word does (if the BASE is right): to push a double-cell
number 19500.  The benefit of defining such a word in an
indirect-threaded code implementation (usual for Forth in those times)
is that invoking the word costs only one cell, whereas a double-cell
constant costs 4 cells.  The word amortizes its memory once more than
three occurences are in play.

The disadvantage of doing that for numbers with more than one digit is
that the BASE no longer influences the number that is pushed by
writing 1950.0.  But it can easily be that, for this application, this
was acceptable.  EPOCH still might have been a better name, though.

- anton
-- 
'Anyone trying for "industrial quality" ISA should avoid undefined behavior.'
  Mitch Alsup, <c17fcd89-f024-40e7-a594-88a85ac10d20o@googlegroups.com>
Re: Optimization by programmers
#105
Author: Anton Ertl
Date: Wed, 14 Oct 2026 08:50
21 lines
2523 bytes
anton@mips.complang.tuwien.ac.at (Anton Ertl) writes:
>What would have been more in line with
>practice is to define a word 1950.0 which does what writing 1950.0
>without such a word does (if the BASE is right): to push a double-cell
>number 19500.
...
>EPOCH still might have been a better name, though.

One possible reason for not calling it EPOCH would be that the
programmer noticed that there were many uses of 1950.0 around the
source code and then decided to save memory by defining a named word
1950.0.  Calling that word EPOCH would have required to search and
replace all occurences of 1950.0, and who knows what editing tools the
programmers had at their disposal (probably the classic Forth block
editor, which I have never used); in any case, calling the word 1950.0
avoided the need for this step.

- anton
-- 
'Anyone trying for "industrial quality" ISA should avoid undefined behavior.'
  Mitch Alsup, <c17fcd89-f024-40e7-a594-88a85ac10d20o@googlegroups.com>
Re: Comment delimiters (was: Optimization by programmers)
#110
Author: George Neuner
Date: Wed, 14 Oct 2026 16:14
26 lines
2299 bytes
On Tue, 13 Oct 2026 23:24:50 -0400, Stefan Monnier
<monnier@iro.umontreal.ca> wrote:


> Andy Valencia wrote:
>> While you're at it, start the transition to "//" as the comment
>> token.  From memory, who's holding out?  Only Forth, Smalltalk, and
>> COBOL come to mind.

@Andy 
Seriously, no thoughts on block comments?  Shouldn't every language be
forced to use  /* */


>There are many many more, ...

Indeed.
https://gist.github.com/dk949/88b2652284234f723decaeb84db2576c

I saw a few examples that were wrong (some addressed by replies), and
a couple I know to be implementation dependent, but this looks to be a
reasonable start on a survey.


MMV but I think too many people in this forum assume that C is the
only language that matters.
Re: Comment delimiters (was: Optimization by programmers)
#111
Author: John Savard
Date: Wed, 14 Oct 2026 18:07
26 lines
2517 bytes
On Wed, 14 Oct 2026 12:14:30 -0400, George Neuner
<gneuner2@comcast.net> wrote:

>Seriously, no thoughts on block comments?  Shouldn't every language be
>forced to use  /* */

Using pairs of special characters for *any* purpose, from ** for
exponentiation in FORTRAN onwards, and including <= and >= as
relational operators, vastly complicates the syntax decoding of
languages.

Of course, even at
http://www.quadibloc.com/comp/lngint.htm
I couldn't _entirely_ avoid compounds of special characters. So what I
did was adopt systematic rules:
Only ?, @, and & can begin multi-character strings which are to be
treated as a single character. @" is used for //, and @< and @> are
used for /* and */. (The @ sign is generally used only for tokens
which are "outside" of actual statements, at the upper level of the
syntax.) &LE and &GE are used for <= and >=.

Incidentally, C didn't invent /* and */; it got them from PL/I,
although no doubt PL/I got them from some representation or other of
ALGOL.

John Savard
Re: Comment delimiters (was: Optimization by programmers)
#113
Author: Thomas Koenig
Date: Wed, 14 Oct 2026 18:50
21 lines
2352 bytes
John Savard <quadibloc@invalid.com> schrieb:
> On Wed, 14 Oct 2026 12:14:30 -0400, George Neuner
><gneuner2@comcast.net> wrote:
>
>>Seriously, no thoughts on block comments?  Shouldn't every language be
>>forced to use  /* */
>
> Using pairs of special characters for *any* purpose, from ** for
> exponentiation in FORTRAN onwards, and including <= and >= as
> relational operators, vastly complicates the syntax decoding of
> languages.

Do learn a bit about regular expressions and how they are
implemented using state machines.  Knowing about state machines
is also fundamental when thinking about computer architectures
and how to iplement them.

-- 
This USENET posting was made without artificial intelligence,
artificial impertinence, artificial arrogance, artificial stupidity,
artificial flavorings or artificial colorants.
Re: Comment delimiters
#116
Author: EricP
Date: Wed, 14 Oct 2026 19:45
57 lines
3555 bytes
On 2026-Oct-14 14:07, John Savard wrote:
> On Wed, 14 Oct 2026 12:14:30 -0400, George Neuner
> <gneuner2@comcast.net> wrote:
> 
>> Seriously, no thoughts on block comments?  Shouldn't every language be
>> forced to use  /* */
> 
> Using pairs of special characters for *any* purpose, from ** for
> exponentiation in FORTRAN onwards, and including <= and >= as
> relational operators, vastly complicates the syntax decoding of
> languages.
> 
> Of course, even at
> http://www.quadibloc.com/comp/lngint.htm
> I couldn't _entirely_ avoid compounds of special characters. So what I
> did was adopt systematic rules:
> Only ?, @, and & can begin multi-character strings which are to be
> treated as a single character. @" is used for //, and @< and @> are
> used for /* and */. (The @ sign is generally used only for tokens
> which are "outside" of actual statements, at the upper level of the
> syntax.) &LE and &GE are used for <= and >=.
> 
> Incidentally, C didn't invent /* and */; it got them from PL/I,
> although no doubt PL/I got them from some representation or other of
> ALGOL.
> 
> John Savard

Most languages are not as bad as pre-FORTRAN-90.
Lexing ** into a single token is a 1 character lookahead.

Old FORTRAN is difficult to parse because
a) it did not separate the language into lexical and syntax levels
b) it was white space oblivious except in quoted strings
c) there were no reserved words - keywords were statement
    position and sometimes semantic context dependent.
d) statements were based on punch cards BUT because
    continuation cards used the absence of a C in column 6
    to indicate the start of a new statement, parsers have to
    always look ahead to see in the next card has a C and
    then "unget" the card if not.

The classic ambiguous parsing example being

   DO I = 1,100
   DOI = 1.100

depends on the presence or absence of a "naked comma" later in the
statement to decide whether there is a keyword DO and a variable I,
or a variable DOI. A "naked comma" is a comma not enclosed inside
a quoted character or string, or inside a possibly nested parenthesis.
There are other examples like keywords in FORMAT statements.

People learned a lot of what not to do in language design
from old FORTRAN.

Re: Optimization by programmers
#118
Author: Terje Mathisen
Date: Wed, 14 Oct 2026 21:39
35 lines
3396 bytes
Anton Ertl wrote:
> Niklas Holsti <niklas.holsti@tidorum.invalid> writes:
>> On 2026-10-13 13:27, Anton Ertl wrote:
>>> Niklas Holsti <niklas.holsti@tidorum.invalid> writes:
>>>> Forth originated in astronomy, if I remember correctly. I do remember
>>>> that in an astronomy-domain Forth program, where it was often necessary
>>>> to transform the celestial coordinates of stars from the standard
>>>> catalog epoch (the start of the year 1950) to the current time, the word
>>>> 1950.0 was defined to perform that transformation.
>>>
>>> That is unlikely, as explained below.
>>
>> I am rather sure that my memory is correct.
>>
>>> In early systems fixed-point was used a lot, and 1950.0 is
>>> interpreted as 19500 with a scale factor of 1/10.
>> The Forth program in question represented angles as fixed-point
>> fractions (0 <= x < 1) of a full circle. I don't remember the number of
>> bits used.
> 
> Yes, that was customary for angles, as mentioned in the HOPL-II paper
> "The Evolution of Forth"
> <https://www.forth.com/resources/forth-programming-language/>:

Garmin uses (used?) fixed-point only in their GPSs, with circles stored 
as a scaled 0:32 value with an implied period in front. Since the Earth 
is 40 000 km around (over the poles, about 1/300 more along equator), 
this corresponds to about 9mm precision which they probably thought was 
more than good enough for a consumer handheld device.

Terje

-- 
- <Terje.Mathisen at tmsw.no>
"almost all programming can be viewed as an exercise in caching"
Re: Comment delimiters (was: Optimization by programmers)
#123
Author: MitchAlsup
Date: Wed, 14 Oct 2026 22:43
32 lines
2520 bytes
quadibloc@invalid.com (John Savard) posted:

> On Wed, 14 Oct 2026 12:14:30 -0400, George Neuner
> <gneuner2@comcast.net> wrote:
> 
> >Seriously, no thoughts on block comments?  Shouldn't every language be
> >forced to use  /* */
> 
> Using pairs of special characters for *any* purpose, from ** for
> exponentiation in FORTRAN onwards, and including <= and >= as
> relational operators, vastly complicates the syntax decoding of
> languages.

On the other hand using « » ÷ ≠ ≤ ≥ ≡ would destroy the 1 char == 1 byte
philosophy of compilers and assemblers.
 
> Of course, even at
> http://www.quadibloc.com/comp/lngint.htm
> I couldn't _entirely_ avoid compounds of special characters. So what I
> did was adopt systematic rules:
> Only ?, @, and & can begin multi-character strings which are to be
> treated as a single character. @" is used for //, and @< and @> are
> used for /* and */. (The @ sign is generally used only for tokens
> which are "outside" of actual statements, at the upper level of the
> syntax.) &LE and &GE are used for <= and >=.
> 
> Incidentally, C didn't invent /* and */; it got them from PL/I,
> although no doubt PL/I got them from some representation or other of
> ALGOL.
> 
> John Savard
Re: Comment delimiters
#130
Author: Anton Ertl
Date: Thu, 15 Oct 2026 06:17
66 lines
4546 bytes
EricP <ThatWouldBeTelling@thevillage.com> writes:
>Old FORTRAN is difficult to parse because
>a) it did not separate the language into lexical and syntax levels
>b) it was white space oblivious except in quoted strings
>c) there were no reserved words - keywords were statement
>    position and sometimes semantic context dependent.
>d) statements were based on punch cards BUT because
>    continuation cards used the absence of a C in column 6
>    to indicate the start of a new statement, parsers have to
>    always look ahead to see in the next card has a C and
>    then "unget" the card if not.

Given that the original FORTRAN worked on an IBM 704, I think that the
designers made it as easy (and with as little memory) to parse as they
could, given the state of the art at the time.  Concerning the points:

a) I guess that the division into lexical and syntax levels had not
   been developed at the time; and even later, e.g., Wirth does not
   make this distinction in his language definitions, using EBNF down
   to the lexical level (although he does define reserved words).

b) Without this distinction, if you ignore white space at all, you
   either ignore it everywhere, or give it a special role in your
   syntax.  Ignoring is probably simpler.

c) The programming language community took quite a while until it
   arrived at reserved words.  E.g., while Algol 60 was specified in
   BNF, being modern in that regard, it does not have reserved words,
   just symbols that are distinct from all identifiers; i.e., you
   could have an identifier like IF in Algol 60, distinct from the
   symbol 'IF', and it's up to the implementation how to distinguish
   them.  Anyway, without a) reserved words make no sense.

d) Does the original FORTRAN support continuation cards?

>The classic ambiguous parsing example being
>
>   DO I = 1,100
>   DOI = 1.100
>
>depends on the presence or absence of a "naked comma" later in the
>statement to decide whether there is a keyword DO and a variable I,
>or a variable DOI. A "naked comma" is a comma not enclosed inside
>a quoted character or string, or inside a possibly nested parenthesis.

My guess as to how this stuff was parsed:

Deal with the first columns as appropriate.  For the rest: Remove any
white space.  Use a backtracking parser that tries to match a rule at
a time; for the DO statement, simply compare the start with "DO".  If
a rule does not match, look at the next rule.

The result is messy, especially when you want to extend the language.

>People learned a lot of what not to do in language design
>from old FORTRAN.

And probably also what to do.  Backus was on the Algol-60 committee,
and the B in BNF stands for his name.  I would not be surprised if the
structure of the parser in the FORTRAN compiler gave him ideas for
BNF.

- anton
-- 
'Anyone trying for "industrial quality" ISA should avoid undefined behavior.'
  Mitch Alsup, <c17fcd89-f024-40e7-a594-88a85ac10d20o@googlegroups.com>
Re: Comment delimiters (was: Optimization by programmers)
#134
Author: John Savard
Date: Thu, 15 Oct 2026 18:15
18 lines
2358 bytes
On Wed, 14 Oct 2026 22:43:32 GMT, MitchAlsup
<user5857@newsgrouper.org.invalid> wrote:

>On the other hand using « » ÷ ≠ ≤ ≥ ≡ would destroy the 1 char == 1 byte
>philosophy of compilers and assemblers.

I'm suspecting that you're posting from the computer that was unable
to have been called a McIntosh due to the pre-existing audio amplifier
brand.

In any case, that's hardly an issue, since a compiler using characters
outside of ISO 8859-1 could always perform a pre-pass which translates
all characters meaningful to the language to a custom character set
which includes them. There's also the option of restricting oneself to
the Basic Multilingual Plane, and just not using UTF-8 but instead
coding for a 1 char == 1 halfword philosophy instead.

John Savard
Re: Comment delimiters
#145
Author: Stefan Monnier
Date: Thu, 15 Oct 2026 19:42
10 lines
2223 bytes
> Given that the original FORTRAN worked on an IBM 704, I think that the
> designers made it as easy (and with as little memory) to parse as they
> could, given the state of the art at the time.  Concerning the points:

Indeed, the issue being that the "state of the art" (in terms of parsing
knowledge) was very primitive.  It's actually in part in response to
the painful experience of Fortran that BNF appeared.


=== Stefan
Re: Comment delimiters
#144
Author: Thomas Koenig
Date: Fri, 16 Oct 2026 06:35
67 lines
4647 bytes
Anton Ertl <anton@mips.complang.tuwien.ac.at> schrieb:
> EricP <ThatWouldBeTelling@thevillage.com> writes:
>>Old FORTRAN is difficult to parse because
>>a) it did not separate the language into lexical and syntax levels
>>b) it was white space oblivious except in quoted strings
>>c) there were no reserved words - keywords were statement
>>    position and sometimes semantic context dependent.
>>d) statements were based on punch cards BUT because
>>    continuation cards used the absence of a C in column 6
>>    to indicate the start of a new statement, parsers have to
>>    always look ahead to see in the next card has a C and
>>    then "unget" the card if not.
>
> Given that the original FORTRAN worked on an IBM 704, I think that the
> designers made it as easy (and with as little memory) to parse as they
> could, given the state of the art at the time.  Concerning the points:
>
> a) I guess that the division into lexical and syntax levels had not
>    been developed at the time;

They did not even have recursive descent parsing, and nobody had
parsed formulas with operator precedence before.  See
https://en.wikipedia.org/wiki/Operator-precedence_parser#Full_parenthesization
.

>    and even later, e.g., Wirth does not
>    make this distinction in his language definitions, using EBNF down
>    to the lexical level (although he does define reserved words).

Also in modern language definition.  Separating lexing and parsing
is a matter of convenience, especially since regular expressions
have been introduced, and speed.

> b) Without this distinction, if you ignore white space at all, you
>    either ignore it everywhere, or give it a special role in your
>    syntax.  Ignoring is probably simpler.

The added complication of separate handling of whitespace is minor.
For the original FORTRAN, they skipped them because card punch operators
often made mistakes with spaces.

> c) The programming language community took quite a while until it
>    arrived at reserved words.

Reserved words make the compiler writer's job easier (somewhat,
but not tremendously), but not having them is a solved problem.
Users are left holding the bag if a new version of the language
introduces new keywords.

Same with intrinsics (or standard functions, or whatever...) if
a new version of the language introduces new ones, users can run
into problems.

>E.g., while Algol 60 was specified in
>    BNF, being modern in that regard, it does not have reserved words,
>    just symbols that are distinct from all identifiers; i.e., you
>    could have an identifier like IF in Algol 60, distinct from the
>    symbol 'IF', and it's up to the implementation how to distinguish
>    them.  Anyway, without a) reserved words make no sense.
>
> d) Does the original FORTRAN support continuation cards?

Yes, it would have extremely restricted otherwise.
-- 
This USENET posting was made without artificial intelligence,
artificial impertinence, artificial arrogance, artificial stupidity,
artificial flavorings or artificial colorants.
Re: Comment delimiters
#151
Author: EricP
Date: Fri, 16 Oct 2026 16:46
101 lines
6020 bytes
On 2026-Oct-15 02:17, Anton Ertl wrote:
> EricP <ThatWouldBeTelling@thevillage.com> writes:
>> Old FORTRAN is difficult to parse because
>> a) it did not separate the language into lexical and syntax levels
>> b) it was white space oblivious except in quoted strings
>> c) there were no reserved words - keywords were statement
>>     position and sometimes semantic context dependent.
>> d) statements were based on punch cards BUT because
>>     continuation cards used the absence of a C in column 6
>>     to indicate the start of a new statement, parsers have to
>>     always look ahead to see in the next card has a C and
>>     then "unget" the card if not.
> 
> Given that the original FORTRAN worked on an IBM 704, I think that the
> designers made it as easy (and with as little memory) to parse as they
> could, given the state of the art at the time.  Concerning the points:
> 
> a) I guess that the division into lexical and syntax levels had not
>     been developed at the time; and even later, e.g., Wirth does not
>     make this distinction in his language definitions, using EBNF down
>     to the lexical level (although he does define reserved words).
> 
> b) Without this distinction, if you ignore white space at all, you
>     either ignore it everywhere, or give it a special role in your
>     syntax.  Ignoring is probably simpler.
> 
> c) The programming language community took quite a while until it
>     arrived at reserved words.  E.g., while Algol 60 was specified in
>     BNF, being modern in that regard, it does not have reserved words,
>     just symbols that are distinct from all identifiers; i.e., you
>     could have an identifier like IF in Algol 60, distinct from the
>     symbol 'IF', and it's up to the implementation how to distinguish
>     them.  Anyway, without a) reserved words make no sense.
> 
> d) Does the original FORTRAN support continuation cards?

Yes. Fortran's continuation card is LL(1) and behaves the same as
an ISA with start bits - you have to look ahead to find out
that you didn't need to look ahead, and unget the card.

Statement terminators like ; act like ISA stop bits and don't need lookahead.

>> The classic ambiguous parsing example being
>>
>>    DO I = 1,100
>>    DOI = 1.100
>>
>> depends on the presence or absence of a "naked comma" later in the
>> statement to decide whether there is a keyword DO and a variable I,
>> or a variable DOI. A "naked comma" is a comma not enclosed inside
>> a quoted character or string, or inside a possibly nested parenthesis.
> 
> My guess as to how this stuff was parsed:
> 
> Deal with the first columns as appropriate.  For the rest: Remove any
> white space.  Use a backtracking parser that tries to match a rule at
> a time; for the DO statement, simply compare the start with "DO".  If
> a rule does not match, look at the next rule.
> 
> The result is messy, especially when you want to extend the language.

A backtracking parser sounds like way overkill.

I am under the impression that many Fortran 77 compilers used
hand written lexer and a recursive decent parser.
The parser passes some local context to the lexer to let it know,
for example, which set of keywords are active at that point.
Anyway, that is how I would do it.

The first thing a Fortran compiler does is scan ahead loading card
statements into a card buffer array from the (possibly nested INCLUDE)
source files until it sees a non-continue card, which it ungets.

Then it checks the format of the cards is ok and extracts things like
a label from columns 2:5.

Compacting out comments and white space is unnecessary -
the hand written lexer knows to skip over them.
There is a method called "Sale's Algorithm" which was published
in CACM in the 1960's which describes how to lex up to Fortran 77.

The parser knows which statement it is working on so can tell the
lexer what options it should handle at the point.
There could be a post pass over the AST to patch up ambiguous
constructs that require semantic context to fix.

After that it is pretty standard AST processing.
The only semantic difference I can think of immediately is
Fortran's parenthesis rule that forces an order of evaluation
and would interact with optimizations like common subexpressions.

>> People learned a lot of what not to do in language design
>>from old FORTRAN.
> 
> And probably also what to do.  Backus was on the Algol-60 committee,
> and the B in BNF stands for his name.  I would not be surprised if the
> structure of the parser in the FORTRAN compiler gave him ideas for
> BNF.
> 
> - anton
Re: Comment delimiters
#152
Author: Anton Ertl
Date: Fri, 16 Oct 2026 17:10
74 lines
5032 bytes
Thomas Koenig <tkoenig@netcologne.de> writes:
>Anton Ertl <anton@mips.complang.tuwien.ac.at> schrieb:
>>    and even later, e.g., Wirth does not
>>    make this distinction in his language definitions, using EBNF down
>>    to the lexical level (although he does define reserved words).
>
>Also in modern language definition.  Separating lexing and parsing
>is a matter of convenience, especially since regular expressions
>have been introduced, and speed.

Speed, yes, but it is also a matter of differences in handling of
ambiguities.  Scanning resolves ambiguities with longest input match,
whereas parsing tends to avoid ambiguities, with only few exceptions
(like the dangling else in some languages, but not, e.g., Algol 60,
which is the first language that used BNF).

As for convenience, for various compilers I read that either the
scanner or the parser (or both) were hand-written (I don't remember
which one was more frequent).  It certainly does not seem much work to
write a scanner for a typical programming language by hand (you
recognize keywords by table lookup of things that will be classified
as identifiers if they are not in the table).  For the parser of a
language that is not LL(1), it's more work, but writing it by hand
allows you to do various things that, e.g., bison does not support
(ANTLR has support for "syntactic predicates" and "semantic
predicates", which probably is good enough for a lot of cases; it was
written with C++ in mind).

>> b) Without this distinction, if you ignore white space at all, you
>>    either ignore it everywhere, or give it a special role in your
>>    syntax.  Ignoring is probably simpler.
>
>The added complication of separate handling of whitespace is minor.
>For the original FORTRAN, they skipped them because card punch operators
>often made mistakes with spaces.

That's a good reason, but it seems to have disappeared with the next
generation of programming languages.  Were programmers later punching
their own cards, or were they writing programs in a way that made
spaces obvious?

>> c) The programming language community took quite a while until it
>>    arrived at reserved words.
>
>Reserved words make the compiler writer's job easier (somewhat,
>but not tremendously), but not having them is a solved problem.
>Users are left holding the bag if a new version of the language
>introduces new keywords.

I don't think they worried about program maintainence across several
Fortran versions when they worked on the original Fortran.  It does
not contain subroutines.

>> d) Does the original FORTRAN support continuation cards?
>
>Yes, it would have extremely restricted otherwise.

The original FORTRAN was extremely restricted.

When I used Microsoft BASIC on the C64, where Commodore's line editor
prevented lines longer than 80 characters, including line numbers, I
did not find that particularly restrictive, especially given all the
other limitations of that version of BASIC, such as no graphics or
sound support apart from POKE and SYS.  BASIC itself supported lines
up to 252 bytes or so, and IIRC the keywords were already tokenized
there, but you could not input such long lines on Commodore computers.

What in FORTRAN makes single 66-char lines (plus line number)
extremely restricted?

- anton
-- 
'Anyone trying for "industrial quality" ISA should avoid undefined behavior.'
  Mitch Alsup, <c17fcd89-f024-40e7-a594-88a85ac10d20o@googlegroups.com>
Re: Comment delimiters
#154
Author: MitchAlsup
Date: Fri, 16 Oct 2026 18:55
17 lines
1893 bytes
anton@mips.complang.tuwien.ac.at (Anton Ertl) posted:

> Thomas Koenig <tkoenig@netcologne.de> writes:
> >Anton Ertl <anton@mips.complang.tuwien.ac.at> schrieb:
------------
> What in FORTRAN makes single 66-char lines (plus line number)
> extremely restricted?

You just setup the key-punch so tab skips the first 6 characters
<to the continuation indicator> and have the key-punch eject the 
card when you get to character 72.

{{There was a machine where it would punch the sequence number
in col[73-80] so you did not have to worry about that until the
program was in good shape.}}
 
> - anton
Page 1 of 2 • 89 total messages
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads