0

Say I have a function like this:

function colorize(integer) {
  var hex = '#'

  if (integer > 1) hex += 'ff'
  else hex += '00'
  if (integer < 100) hex += 'aa'
  else hex += 'bb'
  if (integer > 10) hex += '11'
  else hex += '22'

  return hex
}

It returns CSS hex colors, not named colors or rgb(...) values or anything else. For now we can ignore the low-level / platform specific details of JavaScript and hardware and just deal with this abstractly as if it was in a perfect environment.

The goal is to use small step operational semantics to prove that it returns a CSS hex color. If it requires too much initialization to do the proof, then assume the initialization is already handled so all that's focused on is the specific function and its implementation.

From my understanding this means we would have some rule for var, =, if, ===, +=, and return. In addition, there is sort of a trace, since it is modifying the value in memory step by step.

From my understanding this would involve using the operational semantics configuration evaluation〈a, σ〉→〈a', σ'〉like:

〈=, σ〉→〈=, σ'[hex ↦ #]〉
   →
〈if (e) x else y, σ〉→〈...〉
   →
   ...

I am not sure how to:

  1. Actually write the configurations out.
  2. Write out the sequence of the evaluations.
  3. Write a proof that the output will be a hex string such as #00aa22 if given 0 for example.

I was wondering if one could point me in the right direction on how to solve this. Basically:

  1. What some configurations look like using this function as an example.
  2. What a sequence of the evaluations (or trace) looks like.
  3. What a proof would entail (not the actual proof as I imagine there will be lots of steps), maybe just the first few steps of the proof.

Thank you very much for your help.

Lance Pollard
  • 2,323
  • 1
  • 19
  • 34

1 Answers1

2

You are looking for Hoare logic. Writing out the answer to the question would pretty much amount to copying the introduction to Hoare logic from Wikipedia. I suggest that you have a look at proving program correctness using Hoare logic, and try to apply it to your problem. It's actually an easy case because there are no loops. If you get stuck, come back and ask a specific question about Hoare logic.

I would break up the problem into proving several properties about hex:

  1. The length of hex is 7 at the end.
  2. The first character of hex is #.
  3. All characters, except the first one, are hexadecimal digits.

Also not that the proof does not require you to write out any operational semantics. You can just use the Hoare logic to argue about your program, and there is a theorem which guarantees that Hoare logic is correct with respect to the standard operational semantics.

Andrej Bauer
  • 31,657
  • 1
  • 75
  • 121