3

We need to implement JavaScript parser in C, and we target very memory-constrained platforms; the most constrained part is the stack.

Currently, we have descent recursive parser, and C stack is easily overflown by reasonably complicated expressions. So, our goal is to make C stack consumption not to grow as the expressions nesting grows.

The only way that I can think of is to maintain our own stack, and our parser will be just a single huge function with lots of labels and gotos. It is rather messy and not very maintainable; we can hide some mess by macros, but anyway, it will be much more messy than usual function calls.

But then:

  • We can implement stack in a more efficient way (embedded compilers are often, ... not very good)
  • We can even use segmented stack (since huge contiguous pieces of memory are very expensive here)

Am I right that there are no other ways to implement that? I mean, other than the single function with lots of labels and gotos, and our own hand-made stack.

If I'm wrong, I'd be happy to listen for your suggestions.

7
  • very memory constrained? what size of memory are we talking about here and what code have you tried? Commented Oct 30, 2015 at 1:00
  • You have to put the data somewhere.... Commented Oct 30, 2015 at 1:23
  • One way to help keep your stack small is to make your data small; e.g. compress the data into bit fields instead of larger data types. For example, in JSON a "value" type can be one of seven values: string, number, object, array, true, false, or null. This can be encoded into 3 bits. Use the other 5 bits in that byte for something else. <Edit> Oh wait, this is Javascript, not JSON :) sorry. The same technique is valid though. Commented Oct 30, 2015 at 3:34
  • You could always use bison. Bison-generated parsers are small, manage their own parser stacks, and execute rapidly. Commented Oct 30, 2015 at 3:39
  • 1
    @dmitry: and they had some evidence for this curious assertion? :-) Commented Oct 30, 2015 at 14:25

1 Answer 1

3

When you write a recursive function, you have to have stack. If the physical stack of you machine is not deep enough, you need to implement the stack another way.

As you said: "maintain our own stack, and our parser will be just a single huge function with lots of labels and gotos. It is rather messy and not very maintainable".

Well, it is maintainable if you stick to rules. Each "function" call is implemented by pushing the next program location onto your implemented psuedo-stack. If you hide all that pushing logic in a subroutine or a macro, it will be just as readable as a real function call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.