瀏覽代碼

Comments for Env and Out; partially for In

Arthur Yefimov 2 年之前
父節點
當前提交
86eb05971e
共有 3 個文件被更改,包括 133 次插入47 次删除
  1. 38 12
      src/Env.Mod
  2. 23 9
      src/In.Mod
  3. 72 26
      src/Out.Mod

+ 38 - 12
src/Env.Mod

@@ -1,12 +1,15 @@
 MODULE Env;
-(** OS environment variables *)
+(** OS environment variables
+%RU Переменные окружения ОС *)
 IMPORT CmdArgs, Args, Platform, Utf8, Strings, SYSTEM, Out;
 TYPE SHORTCHAR = Utf8.SHORTCHAR;
 
 VAR count: INTEGER;
 
 (** Return the number of environment variables.
-     If Count() returns N, then you can call Get(x) with 0 <= x < N. *)
+     If Count() returns N, then you can call Get(x) with 0 <= x < N.
+%RU Возвращает количество переменных окружения.                        
+     Если Count() возвращает N, то вы можно вызвать Get(x), где 0 <= x < N. *)
 PROCEDURE Count*(): INTEGER;
 BEGIN
   IF count = -1 THEN count := CmdArgs.EnvCount() END
@@ -14,7 +17,10 @@ RETURN count END Count;
 
 (** Puts in `s` the `n`th environment variable as a string containing a key,
     equal sign and possibly a value (i.e. 'PATH=/usr/bin').
-     `n` must be in range 0 <= x < N, where N is the result of Count() *)
+     `n` must be in range 0 <= x < N, where N is the result of Count()
+%RU Помещает в `s` `n`-ю переменную окружения в виде строки, содержащей ключ,
+    знак равенства и, возможно, значение (например, 'PATH=/usr/bin').
+     `n` должно быть в диапазоне 0 <= x < N, где N -- результат Count() *)
 PROCEDURE Get*(n: INTEGER; VAR s: ARRAY OF CHAR);
 VAR q: ARRAY 10240 OF SHORTCHAR;
 BEGIN
@@ -25,7 +31,9 @@ BEGIN
 END Get;
 
 (** Puts in `val` the value of the environment variable with the given `name`.
-     If there is no such variable, puts an empty string in val. *)
+     If there is no such variable, puts an empty string in val.
+%RU Помещает в `val` значение переменной окружения с заданным `именем`.
+     Если такой переменной нет, помещает в val пустую строку. *)
 PROCEDURE GetByName*(name: ARRAY OF CHAR; VAR val: ARRAY OF CHAR);
 VAR q: ARRAY 10240 OF SHORTCHAR;
   z: ARRAY 1024 OF SHORTCHAR;
@@ -67,7 +75,9 @@ BEGIN
 RETURN found END SearchPath;
 
 (** Removes base name (and a slash) in path s.
-    Example: 'dir/old/new' -> 'dir/old/'. *)
+     Example: 'dir/old/new' -> 'dir/old/'.
+%RU Удаляет базовое имя (и косую черту) в пути s.
+     Пример: 'dir/old/new' -> 'dir/old/'. *)
 PROCEDURE RemoveBaseName(VAR s: ARRAY OF CHAR);
 VAR i: INTEGER;
 BEGIN
@@ -79,12 +89,18 @@ BEGIN
   s[i + 1] := 0X
 END RemoveBaseName;
 
-(** Example: '///' -> '/'. *)
+(** Removes double, tripple etc. slashes from `s`.
+     Example: '///' -> '/'
+     DOES NOT WORK
+%RU Удаляет двойные, тройные и т. д. литеры дроби из `s`.                       
+     Пример: '///' -> '/'
+     НЕ РАБОТАЕТ *)
 PROCEDURE RemoveDoubleSlashes(VAR s: ARRAY OF CHAR);
 BEGIN (*!TODO*)
 END RemoveDoubleSlashes;
 
-(** Leaves '/' in the end. Example: './' -> ''. *)
+(** Leaves '/' in the end. Example: './' -> ''.
+%RU Оставляет '/' в конце. Пример: './' -> ''. *)
 PROCEDURE RemoveDotDirs(VAR s: ARRAY OF CHAR);
 VAR i: INTEGER;
 BEGIN
@@ -101,7 +117,10 @@ BEGIN
   IF (i > 1) & (s[i - 2] = '/') & (s[i - 1] = '.') THEN s[i - 1] := 0X END
 END RemoveDotDirs;
 
-(** Example: 'dir/..' -> ''. *)
+(** Removes (resolves) backtracking in paths (dobule periods).
+     Example: 'dir/..' -> ''.
+%RU Устраняет (разрешает) фрагменты обратного пути в строке (две точки).             
+     Пример: 'dir/..' -> ''. *)
 PROCEDURE RemoveBacktracking(VAR s: ARRAY OF CHAR);
 BEGIN (*!TODO*)
 END RemoveBacktracking;
@@ -144,7 +163,6 @@ BEGIN
     ELSIF ~SearchPath(arg, path, s) THEN s[0] := 0X (* Error *)
     END
   END;
-
   IF s[0] # 0X THEN
     RemoveBaseName(s);
     RemoveDoubleSlashes(s);
@@ -157,7 +175,11 @@ END GetAppDirUnix;
 (** Returns a full path to the application directory. That is the directory
     where the executable file of the currently running program resides.
      It might not be logically possible to determine application directory
-    in some cases on Linux/Unix systems. *)
+    in some cases on Linux/Unix systems
+%RU Возвращает полный путь к директории приложения. Это тот каталог, в котором
+    находится исполняемый файл текущей запущенной программы.
+     В некоторых случаях определить каталог приложения может быть оказаться
+    логически невозможным в ОС Linux/Unix *)
 PROCEDURE GetAppDir*(VAR s: ARRAY OF CHAR);
 VAR z: ARRAY 1024 OF SHORTCHAR;
 BEGIN
@@ -166,8 +188,12 @@ BEGIN
   END
 END GetAppDir;
 
-(** Puts in `s` the language of the user interface (the OS) as lower case
-    2-character strings. For example: 'en', 'ru'. *)
+(** Puts in `s` the language of the user interface (the OS) as a lower case
+    2-character string.
+     Examples: 'en', 'ru'.
+%RU Помещает в `s` язык пользовательского интерфейса (ОС) в виде строки из
+    двух литер в нижнем регистре.
+     Например: 'en', 'ru'. *)
 PROCEDURE GetLang*(VAR s: ARRAY OF CHAR);
 VAR z: ARRAY 256 OF SHORTCHAR;
 BEGIN Platform.GetLang(z); Utf8.Decode(z, s)

+ 23 - 9
src/In.Mod

@@ -6,25 +6,39 @@ MODULE In;
 
     Module In as in Oakwood Guidlines for  Oberon-2 Compiler Developers, 1995.
      With the following changes:
-     LongInt, Int, Int16 also read minus signs first.
+     LongInt, Int, Int16 read and parse minus signs first.
      Char reads a 2-byte character. On Linux it decodes input as UTF-8.
     On Windows it uses ReadConsoleW WinAPI call if console is attached,
-    otherwise uses ReadFile and decodes input as UTF-8.
+    otherwise ReadFile is used and input is decoded from UTF-8.
      Open may not rewind.
-    Extra procedures: Line, HugeInt, Int16. *)
+     Extra procedures: Line, HugeInt, Int16.
 
-(*!FIXME From the Oakwood guidlines:
-  An unsuccessful input operation sets Done to FALSE;
-  it remains FALSE until the next call to Open. *)
+%RU Модуль In предоставляет набор основных процедур для форматированного ввода
+    литер, последовательностей литер, чисел и имён. Он предполагает наличие
+    стандартного потока ввода с текущей позицией, которая может быть сброшена
+    в начало потока (но не всегда это возможно в Linux/Unix или Windows).
+    
+    Модуль In как в Oakwood Guidlines for Oberon-2 Compiler Developers, 1995.
+     Со следующими изменениями:         
+     LongInt, Int, Int16 сначала читают и распознают знаки минус.         
+     Char читает 2-байтовую литеру. В Linux он декодирует вводимые данные как
+    UTF-8. В Windows используется вызов ReadConsoleW из WinAPI если консоль
+    подключена, в противном случае используется ReadFile и ввод автоматически
+    декодируется из UTF-8.
+     Open не может перематывать.
+     Дополнительные процедуры: Line, HugeInt, Int16. *)
 
 IMPORT Platform, SYSTEM, Reals, Out, Utf8;
 
 CONST
-  pending = 0; (* readState when at start of input or end of line. Implies nextch undefined. *)
-  ready   = 1; (* readState when nextch is defined and contains next character on current line. *)
+  pending = 0; (* readState when at start of input or end of line.
+                  Implies nextch undefined. *)
+  ready   = 1; (* readState when nextch is defined and contains
+                  next character on current line. *)
   eof     = 2; (* readState when at end of file. *)
 
-  (** Codepages, values of cp **)
+  (** Codepages, values of cp
+%RU   Кодовые страницы, значения cp **)
   singleByte = 1;
   utf8       = 2; (*!TODO also add UTF16 *)
 

+ 72 - 26
src/Out.Mod

@@ -3,7 +3,12 @@ MODULE Out;
     characters, numbers and strings. It assumes a standard output stream to
     which the symbols are written.
      The output is buffered. The buffer is flushed when and overflow occurres
-    or when Flush or Ln are called. *)
+    or when Flush or Ln are called.
+%RU Модуль Out предоставляет набор базовых процедур для форматированного
+    вывода литер, чисел и строк. Он предполагает наличие стандартного
+    потока вывода, в который записываются литеры.
+     Вывод осуществляется в буфер. Буфер очищается, когда происходит его
+    переполнение, а также при вызове процедур Flush или Ln. *)
 
 IMPORT SYSTEM, Platform, U := Utf8, Reals;
 
@@ -15,7 +20,8 @@ VAR
   buf: ARRAY 128 OF CHAR;
   in: INTEGER;
 
-(** Flushes the output buffer to the output device *)
+(** Flushes the output buffer to the output device
+%RU Сбрасывает буфер вывода на устройство вывода *)
 PROCEDURE Flush*;
 VAR error: Platform.ErrorCode;
 BEGIN
@@ -24,12 +30,15 @@ BEGIN
 END Flush;
 
 (** Initializes the output stream.
-     On Windows, Unix and Linux does nothing. *)
+     On Windows, Unix and Linux does nothing.
+%RU Инициализирует выходной поток. 
+     В Windows, Unix и Linux ничего не делает. *)
 PROCEDURE Open*;
 BEGIN
 END Open;
 
-(** Writes the character `ch` to the end of the output stream *)
+(** Writes the character `ch` to the end of the output stream
+%RU Записывает литеру `ch` в конец выходного потока *)
 PROCEDURE Char*(ch: CHAR);
 BEGIN
   IF in >= LEN(buf) THEN Flush END;
@@ -43,7 +52,9 @@ BEGIN n := 0; WHILE (n < LEN(s)) & (s[n] # 0X) DO INC(n) END; RETURN n
 END Length;
 
 (** Writes the null-terminated character sequence `s` to the end of the
-    output stream (without 0X). *)
+    output stream (without 0X).
+%RU Записывает нуль-терминированную последовательность литер `s` в конец
+    выходного потока (без 0X). *)
 PROCEDURE String*(IN s: ARRAY OF CHAR);
 VAR l: INTEGER; error: Platform.ErrorCode;
 BEGIN
@@ -58,7 +69,9 @@ BEGIN
 END String;
 
 (** Writes the null-terminated 1-byte-character sequence `s` encoded in UTF-8
-    to the end of the output stream (without 0X). *)
+    to the end of the output stream (without 0X).
+%RU Записывает нуль-терминированную последовательность 1-байтовых литер `s`,
+    закодированную в UTF-8 в конец выходного потока (без 0X). *)
 PROCEDURE Utf8*(IN s: ARRAY OF SHORTCHAR);
 VAR q: ARRAY 4096 OF CHAR;
   p: POINTER TO ARRAY OF CHAR;
@@ -74,8 +87,12 @@ END Utf8;
 
 (** Writes the integer number `x` to the end of the output stream.
      `n` is the minimum amount of characters that should be written. If the
-    textual representation of `x` takes less characters, then space characters
-    are written first. If `n` is 0 or 1, `n` does not do anything. *)
+    textual representation of `x` takes less characters, then spaces
+    are written first. If `n` is 0 or 1, `n` means nothing.
+%RU Записывает целое число `x` в конец выходного потока.
+     `n` -- это минимальное количество литер, которое должно быть записано.
+    Если текстовое представление `x` занимает меньше литер, то сначала
+    записываются пробелы. Если `n` равно 0 или 1, то `n` ничего не означает. *)
 PROCEDURE Int*(x, n: HUGEINT);
   CONST zero = ORD('0');
   VAR s: ARRAY 22 OF CHAR; i: INTEGER; negative: BOOLEAN;
@@ -99,8 +116,12 @@ END Int;
 
 (** Writes `x` as hexadecimal integer to the end of the output stream.
      `n` is the minimum amount of characters that should be written. If the
-    textual representation of `x` takes less characters, then space characters
-    are written first. If `n` is 0 or 1, `n` does not do anything. *)
+    textual representation of `x` takes less characters, then zeroes
+    are written first. If `n` is 0 or 1, `n` means nothing.
+%RU Записывает `x` как шестнадцатеричное целое число в конец выходного потока.
+     `n` -- это минимальное количество литер, которое должно быть записано.
+    Если текстовое представление `x` занимает меньше литер, то сначала
+    записываются нули. Если `n` равно 0 или 1, то `n` ничего не означает. *)
 PROCEDURE Hex*(x, n: HUGEINT);
 BEGIN
   IF n < 1 THEN n := 1 ELSIF n > 16 THEN n := 16 END;
@@ -111,53 +132,78 @@ BEGIN
   WHILE n > 0 DO
     x := SYSTEM.ROT(x, 4); DEC(n);
     IF x MOD 16 < 10 THEN Char(SHORT(CHR((x MOD 16) + ORD('0'))))
-    ELSE Char(SHORT(CHR((x MOD 16) - 10 + ORD('A')))) END
+    ELSE Char(SHORT(CHR((x MOD 16) - 10 + ORD('A'))))
+    END
   END
 END Hex;
 
 (** Writes an end-of-line symbol to the end of the output stream.
-     On Linux/Unix it is 0AX. On Windows it is a pair: 0DX, 0AX. *)
+     On Linux/Unix it is 0AX. On Windows it is a pair: 0DX, 0AX.
+%RU Записывает литеру конца строки в конец выходного потока.
+     В Linux/Unix это 0AX. В Windows это пара: 0DX, 0AX. *)
 PROCEDURE Ln*;
 BEGIN String(Platform.NewLine); Flush
 END Ln;
 
-(** Writes the real number `x` to the end of the output stream using an
+(** Writes the real number `x` to the end of the output stream in an
     exponential form.
      `n` is the minimum amount of characters that should be written. If the
-    textual representation of `x` takes less characters, then space characters
-    are written first. *)
+    textual representation of `x` takes less characters, then spaces
+    are written first.
+%RU Записывает вещественное число `x` в конец выходного потока в
+    экспоненциальном виде.
+     `n` -- это минимальное количество литер, которое должно быть записано.
+    Если текстовое представление `x` занимает меньше литер, то сначала
+    записываются пробелы. *)
 PROCEDURE Real*(x: REAL; n: INTEGER);
 VAR s: ARRAY 256 OF CHAR;
 BEGIN Reals.Str(x, n, s); String(s)
 END Real;
 
-(** Writes the long real number `x` to the end of the output stream using an
+(** Writes the long real number `x` to the end of the output stream in an
     exponential form.
      `n` is the minimum amount of characters that should be written. If the
-    textual representation of `x` takes less characters, then space characters
-    are written first. *)
+    textual representation of `x` takes less characters, then spaces
+    are written first.
+%RU Записывает длинное вещественное число `x` в конец выходного потока в
+    экспоненциальном виде.
+     `n` -- это минимальное количество литер, которое должно быть записано.
+    Если текстовое представление `x` занимает меньше литер, то сначала
+    записываются пробелы. *)
 PROCEDURE LongReal*(x: LONGREAL; n: INTEGER);
 VAR s: ARRAY 256 OF CHAR;
 BEGIN Reals.LongStr(x, n, s); String(s)
 END LongReal;
 
-(** Writes the real number `x` to the end of the output stream using an
-    exponential form.
+(** Writes the real number `x` to the end of the output stream in a normal
+    form.
      `n` is the minimum amount of characters that should be written. If the
-    textual representation of `x` takes less characters, then space characters
+    textual representation of `x` takes less characters, then spaces
     are written first.
-     `k` is the number of digits after a decimal point.  *)
+     `k` is the number of digits after a decimal point.
+%RU Записывает вещественное число `x` в конец выходного потока в обычном
+    виде.
+     `n` -- это минимальное количество литер, которое должно быть записано.
+    Если текстовое представление `x` занимает меньше литер, то сначала
+    записываются пробелы.
+     `k` -- количество цифр после запятой (которая выводится как точка). *)
 PROCEDURE RealFix*(x: REAL; n, k: INTEGER);
 VAR s: ARRAY 256 OF CHAR;
 BEGIN Reals.StrFix(x, n, k, s); String(s)
 END RealFix;
 
-(** Writes the long real number `x` to the end of the output stream using an
-    exponential form.
+(** Writes the long real number `x` to the end of the output stream in a
+    normal form.
      `n` is the minimum amount of characters that should be written. If the
-    textual representation of `x` takes less characters, then space characters
+    textual representation of `x` takes less characters, then spaces
     are written first.
-     `k` is the number of digits after a decimal point.  *)
+     `k` is the number of digits after a decimal point.
+%RU Записывает длинное вещественное число `x` в конец выходного потока в
+    обычном виде.
+     `n` -- это минимальное количество литер, которое должно быть записано.
+    Если текстовое представление `x` занимает меньше литер, то сначала
+    записываются пробелы.
+     `k` -- количество цифр после запятой (которая выводится как точка). *)
 PROCEDURE LongRealFix*(x: LONGREAL; n, k: INTEGER);
 VAR s: ARRAY 256 OF CHAR;
 BEGIN Reals.LongStrFix(x, n, k, s); String(s)