831def do_insertions(insertions, tokens):
832 """
833 Helper for lexers which must combine the results of several
834 sublexers.
835
836 ``insertions`` is a list of ``(index, itokens)`` pairs.
837 Each ``itokens`` iterable should be inserted at position
838 ``index`` into the token stream given by the ``tokens``
839 argument.
840
841 The result is a combined token stream.
842
843 TODO: clean up the code here.
844 """
845 insertions = iter(insertions)
846 try:
847 index, itokens = next(insertions)
848 except StopIteration:
849
850 yield from tokens
851 return
852
853 realpos = None
854 insleft = True
855
856
857
858 for i, t, v in tokens:
859
860 if realpos is None:
861 realpos = i
862 oldi = 0
863 while insleft
and i +
len(v) >= index:
864 tmpval = v[oldi:index - i]
865 if tmpval:
866 yield realpos, t, tmpval
867 realpos +=
len(tmpval)
868 for it_index, it_token, it_value in itokens:
869 yield realpos, it_token, it_value
870 realpos +=
len(it_value)
871 oldi = index - i
872 try:
873 index, itokens = next(insertions)
874 except StopIteration:
875 insleft = False
876 break
878 yield realpos, t, v[oldi:]
879 realpos +=
len(v) - oldi
880
881
882 while insleft:
883
884 realpos = realpos or 0
885 for p, t, v in itokens:
886 yield realpos, t, v
888 try:
889 index, itokens = next(insertions)
890 except StopIteration:
891 insleft = False
892 break
893
894