RU2103727C1 - Method for converting input code of translator into object code and device which implements said method - Google Patents
Method for converting input code of translator into object code and device which implements said method Download PDFInfo
- Publication number
- RU2103727C1 RU2103727C1 RU95118821A RU95118821A RU2103727C1 RU 2103727 C1 RU2103727 C1 RU 2103727C1 RU 95118821 A RU95118821 A RU 95118821A RU 95118821 A RU95118821 A RU 95118821A RU 2103727 C1 RU2103727 C1 RU 2103727C1
- Authority
- RU
- Russia
- Prior art keywords
- interface
- data structure
- level
- access
- tcp
- Prior art date
Links
Images
Landscapes
- Stored Programmes (AREA)
Abstract
Description
Изобретение относится к транслятору, в частности к организации и построению транслятора для машинного языка высокого уровня. The invention relates to a translator, in particular to the organization and construction of a translator for a high-level machine language.
Транслятор представляет собой компьютерную программу, которая переводит машинную программу, составленную на входном языке транслятора высокого уровня, легко воспринимаемом людьми, в программу на выходном языке транслятора, исполняемую вычислительной машиной. В типовом случае транслятор включает несколько функциональных блоков. Например, обычный транслятор может включать лексический анализатор, который осуществляет просмотр в исходной программе транслятора и идентифицирует последовательные лексемы (минимальные единицы языка, имеющие значения) в исходной программе. A translator is a computer program that translates a computer program compiled in the input language of a high-level translator, easily perceived by people, into a program in the output language of the translator, executed by a computer. Typically, a translator includes several functional blocks. For example, a conventional translator may include a lexical analyzer that scans the translator in the source program and identifies consecutive tokens (the minimum language units that have meaning) in the source program.
Обычный транслятор также включает синтаксический анализатор, который получает в качестве входных данных грамматику, определяющую язык, подлежащий транслированию, и последовательность операций, связанных с грамматикой. Синтаксический анализатор образует "синтаксическое дерево" (дерево грамматического разбора) для операторов исходной программы в соответствии с грамматическими правилами и операциями. Для каждого оператора исходной программы синтаксический анализатор генерирует синтаксическое дерево исходного ввода данных рекурсивным способом "снизу вверх" в соответствии с подходящими грамматическими правилами и определениями. Таким образом, синтаксическое дерево формируется из узлов, соответствующих одному или более грамматическим правилам. Генерация синтаксического дерева позволяет синтаксическому анализатору определять, подчиняются ли части входной программы правилам грамматики или нет. Если нет, то синтаксический анализатор генерирует сообщение об ошибке. Таким образом, синтаксический анализатор выполняет синтаксическую проверку, но обычно не проверяет содержание ("семантику") исходной программы. Примером известных средств синтаксического анализа может служить синтаксический анализатор LALR (lookahead, left right - "с просмотром вперед, слева направо"), который описан в гл. 4 монографии Aho, Sethi, Ullman, "Compilers: Principles, Techniques and Tools". A conventional translator also includes a parser, which receives as input a grammar that defines the language to be translated and the sequence of operations associated with the grammar. The parser forms a "syntax tree" (parsing tree) for the operators of the source program in accordance with the grammar rules and operations. For each operator of the source program, the parser generates a syntax tree for the initial data input in a recursive way "from bottom to top" in accordance with the appropriate grammar rules and definitions. Thus, a syntax tree is formed from nodes corresponding to one or more grammatical rules. Generating a syntax tree allows the parser to determine whether parts of the input program obey grammar rules or not. If not, the parser generates an error message. Thus, the parser performs parsing, but usually does not check the content ("semantics") of the source program. An example of well-known parsing tools is the LALR parser (lookahead, left right - “looking forward, from left to right”), which is described in chap. 4 monographs by Aho, Sethi, Ullman, "Compilers: Principles, Techniques and Tools".
В обычных трансляторах после того как выполнен синтаксический анализ входной программы она вводится в семантический анализатор, который осуществляет проверку на наличие семантических ошибок, таких как несоответствие типов и т.п. Семантический анализатор оценивает, например, "семантические атрибуты" узлов синтаксического дерева. Атрибуты, которые оцениваются путем просмотра атрибутов их порождаемых узлов, называются "синтезированными атрибутами". После синтаксического и семантического анализа транслятор генерирует промежуточный код, оптимизирует промежуточный код и генерирует выходную программу. In conventional translators, after the input program has been parsed, it is entered into the semantic analyzer, which checks for semantic errors, such as type mismatches, etc. The semantic analyzer evaluates, for example, the "semantic attributes" of the nodes of the syntax tree. Attributes that are evaluated by looking at the attributes of their generated nodes are called "synthesized attributes." After parsing and semantic analysis, the translator generates an intermediate code, optimizes the intermediate code and generates an output program.
Исходная программа транслятора сама является довольно большой и сложной. Многие пользователи продолжают работать над исходным кодом транслятора в течение всего срока пользования транслятора. Тем самым различные пользователи с их разными стилями кодирования как хорошими, так и плохими вносят вклад в формирование исходного кода транслятора. Даже если каждый программист, работающий над исходным кодом транслятора, использует хорошую практику программирования (что является маловероятным), индивидуальные стили программирования различаются, и для большинства трансляторов характерным является большое разнообразие стилей кодирования. В этих условиях для каждого транслятора важно, чтобы исходный код мог легко обновляться и поддерживаться. The original translator program itself is quite large and complex. Many users continue to work on the source code of the translator throughout the life of the translator. Thus, various users with their different coding styles, both good and bad, contribute to the compilation of the translator source code. Even if every programmer working on the translator's source code uses good programming practice (which is unlikely), individual programming styles are different, and most translators are characterized by a wide variety of coding styles. Under these conditions, it is important for each translator that the source code can be easily updated and maintained.
С этой целью важно стандартизировать модули входной программы, а также интерфейсы между модулями. В числе известных решений, направленных на стандартизацию процедур кодирования, можно указать процедуры ADT (Типы Данных Абстрактных Конструкций) и OOP (Объектно-Ориентированное Программирование). To this end, it is important to standardize the input program modules as well as the interfaces between the modules. Among the well-known decisions aimed at standardizing coding procedures, one can specify the ADT (Data Types of Abstract Constructions) and OOP (Object Oriented Programming) procedures.
Задача изобретения - преодоление проблем и устранение недостатков известных из предшествующего уровня техники решений за счет введения иерархической структуры Пакетов Технологических Средств (ПТС) при построении транслятора. Каждый ПТС определяет интерфейс для манипулирования с соответствующей структурой данных, такой как таблица кодировки символов или синтаксическое дерево. Настоящее изобретение позволяет структурировать ПТС во множество уровней абстрактных конструкций, которые включают: "выделенное конкретное представление", "уровень представлений", "уровень определений" и "концептуальный уровень". Интерфейс к ПТС включает, например, концептуальный уровень и частично уровень определений. Конкретное представление и уровень представлений являются скрытыми от программиста компьютерной системы. Кроме того, настоящее изобретение обеспечивает присвоение обозначения интерфейсу на каждом уровне для осуществления операций создания/удаления, обращения, обновления и вывода. The objective of the invention is to overcome the problems and eliminate the shortcomings of the solutions known from the prior art by introducing a hierarchical structure of Technological Tools Packages (TCP) when constructing a translator. Each TCP defines an interface for manipulating a corresponding data structure, such as a character encoding table or a syntax tree. The present invention allows to structure the TCP into many levels of abstract constructions, which include: "highlighted specific presentation", "presentation level", "definition level" and "conceptual level". The interface to the TCP includes, for example, a conceptual layer and a partial definition layer. The specific presentation and level of representations are hidden from the computer system programmer. In addition, the present invention provides an interface designation at each level for performing create / delete, access, update, and output operations.
Цели и преимущества изобретения будут понятны из нижеследующего описания и станут очевидными при использовании изобретения. Цели и преимущества изобретения могут быть достигнуты с использованием признаков изобретения и их комбинаций, охарактеризованных в пунктах формулы изобретения. The objectives and advantages of the invention will be clear from the following description and will become apparent when using the invention. The objectives and advantages of the invention can be achieved using the features of the invention and their combinations described in the claims.
На фиг. 1 дана блок-схема компьютерной системы, соответствующей предпочтительному варианту осуществления изобретения; на фиг. 2 - концептуальная схема структуры ПТС; на фиг. 3 - пример ПТС для синтаксического дерева; на фиг. 4 - блок-схема алгоритма, иллюстрирующая модули транслятора, обеспечивающие создание структур данных в различных ПТС и обращение к ним. In FIG. 1 is a block diagram of a computer system according to a preferred embodiment of the invention; in FIG. 2 is a conceptual diagram of a TCP structure; in FIG. 3 is an example of a TCP for a syntax tree; in FIG. 4 is a flowchart illustrating translator modules providing creation of data structures in various TCPs and access to them.
Рассмотрим предпочтительные варианты осуществления изобретения, иллюстрируемые чертежами, где одни и те же элементы обозначены одинаковыми ссылочными позициями. Consider the preferred embodiments of the invention, illustrated by the drawings, where the same elements are denoted by the same reference position.
Изобретение относится к устройству и способу, обеспечивающим повышение надежности, удобство сопровождения и удобочитаемость программных средств. На фиг. 1 представлена блок-схема компьютерной системы 100, соответствующей изобретению. Компьютерная система 100 содержит центральный процессор 102, память 104 и шины ввода/вывода 106. Специалистам в данной области техники должно быть ясно, что компьютерная система 100 может также включать множество Других элементов, не показанных на чертеже для сохранения его наглядности, например, дисковые запоминающие устройства, клавиатуры, дисплеи, соединения с сетями, дополнительные шины памяти, дополнительные центральные процессоры и т.д. The invention relates to a device and a method that provides increased reliability, ease of maintenance and readability of software. In FIG. 1 is a block diagram of a computer system 100 according to the invention. Computer system 100 includes a central processor 102, memory 104, and I / O bus 106. Those skilled in the art will appreciate that the computer system 100 may also include many other elements not shown in the drawing to maintain its clarity, for example, disk storage devices, keyboards, displays, network connections, additional memory buses, additional central processors, etc.
Память 104 содержит входную программу 110 транслятора, транслятор 111 и выходную программу 124 транслятора. Транслятор 111 включает лексический анализатор 112, синтаксический анализатор 114, семантический анализатор 116, оптимизатор кода 120 (не обязателен) и генератор кода 122. Транслятор 111 вводит входную программу 110 и обрабатывает входную программу для преобразования ее в выходную программу 124. Элементы транслятора 112-116 обрабатывают каждый оператор во входной программе 110 для генерации промежуточного кода. Память 104 также включает множество пакетов технологических средств (ПТС) 133, как описано ниже. Определенные части транслятора (например, интерфейс синтаксического дерева) организованы (или структурированы) как иерархия пакетов технологических средств. Эти ПТС в трансляторе на языке Pascal не содержат информационных данных. ПТС являются структурированными частями программных средств, которые манипулируют некоторыми глобальными данными (и осуществляют отсылки на эти данные). В других вариантах, однако возможно создавать и кодировать ПТС таким образом, чтобы они могли обрабатывать не только эти конкретные данные (например, конкретный перечень имен таблицы перечней имен, одно синтаксическое дерево и т.д.), но любые данные, которые подходят к функциями этих ПТС в качестве параметров. The memory 104 comprises an input program 110 of the translator, a translator 111 and an output program 124 of the translator. Translator 111 includes a lexical analyzer 112, a parser 114, a semantic analyzer 116, a code optimizer 120 (optional), and a code generator 122. The translator 111 inputs the input program 110 and processes the input program to convert it to the output program 124. Elements of the translator 112-116 process each statement in the input program 110 to generate an intermediate code. The memory 104 also includes a plurality of technology tool packages (TCPs) 133, as described below. Certain parts of the translator (for example, the syntax tree interface) are organized (or structured) as a hierarchy of technological tools packages. These TCPs in the Pascal translator do not contain information data. PTAs are structured pieces of software that manipulate some global data (and provide links to that data). In other embodiments, however, it is possible to create and encode the TCP so that they can process not only this specific data (for example, a specific list of names of the table of lists of names, one syntax tree, etc.), but any data that is suitable for functions these TCP as parameters.
Как должно быть ясно специалисту в данной области техники, все части транслятора 111 выполнены в виде команд, хранящихся в памяти 104 и выполняемых центральным процессором 102. Синтаксический анализатор 114 обращается к стековой памяти 135 синтаксического дерева. Синтаксический анализатор 114 использует грамматику, которая включает правила и связанные с ними операции, соответствующие правилам. Операции грамматики осуществляют обращение к ПТС 133, включая ПТС 134 синтаксического дерева, с использованием функций интерфейсов в ПТС. As should be clear to a person skilled in the art, all parts of the translator 111 are executed in the form of instructions stored in the memory 104 and executed by the central processor 102. The parser 114 accesses the stack memory 135 of the syntax tree. The parser 114 uses a grammar that includes rules and associated operations corresponding to the rules. Grammar operations access the TCP 133, including the TCP 134 of the syntax tree, using the interface functions in the TCP.
Семантический анализатор 116 проходит по синтаксическому дереву ПТС 134 синтаксического дерева для всей входной программы (или для большей ее части), создаваемой синтаксическим анализатором 114, и рекурсивно проходит дерево, вызывая соответствующие подпрограммы семантического анализа. The semantic analyzer 116 traverses the
Семантический анализатор 116 распечатывает сообщения об ошибках и/или останавливает выполнение программы, если найдены семантические ошибки. Если семантических ошибок не найдено, то семантический анализатор 116 выводит деревья для программно-совместимых компьютерных систем (ПСК) в представлении для предварительного преобразования способом, известным для специалистов в данной области техники (Aho et al., "Compilers: Principles, Techniques and Tools", p.p. 735-737). Оптимизатор кода 120 (не обязателен) оптимизирует это представление для предварительного преобразования и выводит его в оптимизированной форме (например, неиспользованные фрагменты кода могут быть опущены). Генератор кода 122 предпочтительно преобразует представление для предварительной обработки в выходную программу 124 способом, также хорошо известным специалистам в данной области техники. Semantic analyzer 116 prints error messages and / or stops program execution if semantic errors are found. If no semantic errors are found, then the semantic analyzer 116 displays trees for software-compatible computer systems (UCS) in a pre-conversion view in a manner known to those skilled in the art (Aho et al., "Compilers: Principles, Techniques and Tools" , pp 735-737). Code Optimizer 120 (optional) optimizes this representation for preliminary conversion and displays it in an optimized form (for example, unused code fragments may be omitted). Code generator 122 preferably converts the preprocessing representation into output program 124 in a manner also well known to those skilled in the art.
Предпочтительный вариант осуществления изобретения относится к транслятору SPARCpascal для языка программирования Pascal. Транслятор сам предпочтительно составлен на универсальном языке программирования Си и выполняется под управлением операционной системы Solaris, которая поставляется компанией Sun Microsystems и связана с операционной системой Unix. Solaris - это торговая марка компании Sun Microsystems. Торговые марки SPARC - это торговые марки компании SPARC International, Inc. Unix - это торговая марка, зарегистрированная в США и других странах, эксклюзивно лицензируемая через компанию Х/Ореп Соmpany, LTD. A preferred embodiment of the invention relates to a SPARCpascal translator for the Pascal programming language. The translator itself is preferably written in the universal C programming language and runs on the Solaris operating system, which is supplied by Sun Microsystems and is associated with the Unix operating system. Solaris is a trademark of Sun Microsystems. Trademarks SPARC are trademarks of SPARC International, Inc. Unix is a trademark registered in the United States and other countries, exclusively licensed through X / Orep Company, LTD.
Как показано на фиг. 4, ПТС используются для таблицы идентификаторов, таблицы перечня наименований, интерфейса, например YATTR, который определяет конкретные семантические операции для грамматики YACC языка Pascal и ПСК-деревьев. Таблица идентификаторов и таблица перечня имен (также называемая таблицей кодировки символов) описаны в совместно поданной заявке на "Способ преобразования входной программы транслятора и устройство для его осуществления" того же заявителя. Синтаксическое дерево описано в совместно поданной заявке на "Способ оценки семантических атрибутов при синтаксическом анализе и устройство для его осуществления" того же заявителя. Интерфейс YATTR представляет собой интерфейс семантических операций для обычной грамматики YACC языка Pascal. ПСК-деревья описаны, например, в монографии Aho et al., "Compilers: Principles, Techniques and Tools", p. p. 735-737. Другие варианты осуществления изобретения используют ПТС для других соответствующих структур данных. As shown in FIG. 4, PTSs are used for the identifier table, naming list table, interface, for example YATTR, which defines specific semantic operations for Pascal YACC grammar and UCS trees. The identifier table and the name list table (also called the character encoding table) are described in the jointly filed application for “Translator input program conversion method and device for its implementation” by the same applicant. The syntax tree is described in a jointly filed application for “A method for evaluating semantic attributes in parsing and a device for its implementation” by the same applicant. The YATTR interface is a semantic operations interface for the usual Pascal YACC grammar. UCS trees are described, for example, in the monograph Aho et al., "Compilers: Principles, Techniques and Tools", p. p. 735-737. Other embodiments of the invention use TCP for other relevant data structures.
На фиг. 2 представлена концептуальная диаграмма структуры ПТС 200. После рассмотрения концептуальной модели ниже приведен пример ПТС. Как показано на фиг. 2, каждый ПТС определяет интерфейс общего пользования для манипулирования соответствующей структурой данных, такой как таблица кодировки символов или синтаксическое дерево. Как показано на фиг. 2, ПТС 200 структурирован во множество уровней абстрактных конструкций, которые включают выделенное конкретное представление 202, уровень представлений 204, уровень определений 206 и концептуальный уровень 208. Каждый из этих уровней абстрактных конструкций представлен горизонтальной строкой на фиг. 2. In FIG. 2 is a conceptual diagram of the structure of the
Изобретение обеспечивает назначение группы интерфейсных подпрограмм для каждого уровня для выполнения операций создания/удаления 222, обращения 224, обновления 226 и вывода 228; каждая из упомянутых групп представлена столбцом на фиг .2. Интерфейсы конкретного представления 202 и уровня представлений 204 являются скрытыми для программиста. Интерфейс концептуального уровня 208 содержит множество программно-реализуемых процедур или функций, которые создают интерфейсы, посредством которых к ПТС может быть обеспечен доступ со стороны программных средств, внешних по отношению к ПТС. Предоставляемый интерфейс для доступа к ПТС может также включать часть уровня определений 206. В других случаях уровень определений 206 является скрытым. Упрощенный пример для пояснения сказанного приведен ниже. The invention provides for the assignment of a group of interface routines for each level for performing operations of creation /
Если, например, формируются ПТС для манипулирования с перечнем, его уровень определений может содержать следующие команды (атрибуты абстрактных конструкций) для каждого элемента перечня: INFO(L), представляющая информационную часть; KEY(L)- ключ для ассоциативного поиска; NEXT(L) - указатель для следующего элемента перечня. Атрибуты INFO и KEY могут быть включены в интерфейс ПТС. Но нет необходимости включать в интерфейс атрибут NEXT, так как на концептуальном (более высоком) уровне мы можем создать итератор ELEMENTS (L, P), который сканирует все элементы перечня. Таким образом, атрибут NEXT остается скрытым. If, for example, a TCP is formed to manipulate the list, its definition level may contain the following commands (attributes of abstract constructions) for each element of the list: INFO (L), which represents the information part; KEY (L) - key for associative search; NEXT (L) - pointer to the next list item. The INFO and KEY attributes can be included in the TCP interface. But there is no need to include the NEXT attribute in the interface, since at the conceptual (higher) level we can create an ELEMENTS (L, P) iterator that scans all the elements of the list. Thus, the NEXT attribute remains hidden.
Таким образом, пример ПТС, показанный на фиг. 2, имеет четыре группы интерфейсов, верхний уровень которых доступен для программных средств, выполняющих операции над структурами данных, которым соответствуют ПТС, а нижние уровни используются внутренним для ПТС образом для обеспечения доступа между различными уровнями интерфейсов. Как показано стрелками на фиг. 2, интерфейс уровня N может быть доступен только на уровне N+1. Также возможно (но осуществляется редко) использовать для подпрограмм уровня N другие подпрограммы уровня N. Не все ПТС будут включать каждый из интерфейсов, показанных на фиг. 2, но если такие интерфейсы необходимы, то они должны быть согласованы с форматом, представленным на фиг. 2. Thus, the example TCP shown in FIG. 2, has four groups of interfaces, the upper level of which is available for software that performs operations on data structures to which the TCP corresponds, and the lower levels are used internally for the TCP to provide access between different levels of interfaces. As shown by the arrows in FIG. 2, the N-level interface can only be accessed at N + 1. It is also possible (but rarely performed) to use other N-level routines for level N routines. Not all TCPs will include each of the interfaces shown in FIG. 2, but if such interfaces are necessary, then they must be consistent with the format shown in FIG. 2.
Выделенное конкретное представление 202 является реальной структурой данных, хранящейся в памяти, такой как синтаксическое дерево, таблица кодировки символов (таблица перечня имен - NL-таблица), таблица идентификаторов или структурой данных, представляющей обычную грамматику языка программирования. Действительное представление такой структуры данных не входит в объем настоящего изобретения; могут быть использованы любые соответствующие структуры данных. Уровень представлений 204 включает множество операций, например, создание/удаление 222, обращение 224, обновление 226 и вывод 228, определяющих доступ к атрибутам/элементам конкретного представления 202. Уровень определений 206 включает множество операций, например, создание/удаление 222, обращение 224, обновление 226 и вывод 228, определяющих доступ к атрибутам абстрактных конструкций на уровне представлений 204, которые могут соответствовать (или не соответствовать) конкретным атрибутам/элементам. "Атрибуты абстрактных конструкций" также называются "промежуточными абстрактными понятиями". Концептуальный уровень 208 включает более обобщенные операции (например, итераторы), которые манипулируют структурой данных как единым абстрактным объектом. The highlighted
На фиг. 3 показан пример ПТС 134 для синтаксического дерева. ПТС 134 включает два файла: самодокументированный файл интерфейса (.h) 310 и файл реализации (. с) 320. Самодокументированный файл интерфейса 310 определяет внешние процедуры, функции и переменные и макрокоманды (такие, как для осуществления переходов между различными уровнями ПТС). (В предпочтительном варианте осуществления большинство интерфейсных процедур и функций определены как макрокоманды, потому что их реализация, т.е. конкретное представление абстрактного описания, относительно невелика). Файл реализаций 320 содержит тела (т.е. внутреннюю часть описания) процедур, функций и переменных. In FIG. 3 shows an example of a
Как показано на фиг. 3, синтаксическое дерево 134 включает интерфейс "создание/удаление" 302 для каждого уровня и интерфейс "обращение" 304 для каждого уровня. В описываемом варианте ПТС 134 синтаксического дерева не включает специальных определений для интерфейсов обновления или вывода. Интерфейс обновления для этого ПТС используется в форме назначений (присваиваний имен), левые части которых представляют собой вызовы макрокоманд обращения к интерфейсу, например:
TR_TYPE(t) = p;
Этот фрагмент обновляет атрибут TYPE в узле t синтаксического дерева. Интерфейс вывода для синтаксического дерева используется только для отладки и не вложен в большинство версий транслятора с целью избежать увеличения размера исполняемого кода. Другие ПТС, разумеется, могут включать некоторые или все из интерфейсов создания/удаления, обращения, обновления и вывода, причем каждый из этих интерфейсов включает интерфейсные подпрограммы для каждого из множества уровней ПТС.As shown in FIG. 3,
TR_TYPE (t) = p;
This snippet updates the TYPE attribute in node t of the syntax tree. The output interface for the syntax tree is used only for debugging and is not embedded in most versions of the translator in order to avoid increasing the size of the executable code. Other TCPs, of course, may include some or all of the interfaces for creating / deleting, accessing, updating, and output, each of these interfaces including interface routines for each of the many levels of the TCP.
Как показано на фиг. 3, интерфейс "создание/удаление" существует для каждого из следующих уровней: уровня представлений 310, уровня определений 312 и концептуального уровня 314. В описываемом варианте интерфейсы "создание/удаление" для уровня определений 312 и концептуального уровня 314 существенно идентичны. Аналогично, интерфейс "обращение" существует для каждого из следующих уровней: уровня представлений 320, уровня определений 322 и концептуального уровня 324. Заметим, что в описываемом варианте интерфейсы обращения как для уровня определений 312, так и для концептуального уровня 314 доступны для программных средств, внешних по отношению к ПТС 134. Если необходимо, некоторые отдельные подпрограммы уровня определений могут быть сделаны недоступными извне путем определения их как статические (STATIC). As shown in FIG. 3, a create / delete interface exists for each of the following levels:
Интерфейс "создание/удаление" для концептуального уровня может включать некоторые обобщенные операции, которые создают или удаляют абстрактный объект как целое. Для данного примера такие операции не являются необходимыми, поскольку имеется лишь одно синтаксическое дерево, которое создается неявно, как результат некоторых определений, и которое удаляется также в неявном виде. Если бы имелось несколько таких деревьев, то было бы необходимо определить операции на уровне абстрактных понятий по их созданию/удалению. Такие операции часто определяются понятиями "построение/разрушение". The create / delete interface for a conceptual layer may include some generalized operations that create or delete an abstract object as a whole. For this example, such operations are not necessary, since there is only one syntax tree that is created implicitly, as a result of some definitions, and which is also deleted implicitly. If there were several such trees, it would be necessary to define operations at the level of abstract concepts for their creation / deletion. Such operations are often defined by the concepts of "building / destruction".
Интерфейс "создание/удаление" для уровня определений включает множество определений, используемых для создания и удаления узлов синтаксического дерева. Имеется по существу неограниченное число определений, которые могут быть включены в уровень определений, вследствие чего практически невозможно обсудить их все. Некоторые примеры приведены ниже. The create / delete interface for the definition level includes many definitions used to create and delete nodes in the syntax tree. There is a substantially unlimited number of definitions that can be included in the definition level, making it virtually impossible to discuss all of them. Some examples are given below.
Например, процедура "tree_asgn" в ПТС 134 создает узел синтаксического дерева, который содержит информацию об операторах "присвоения" (например, узел для представления субдерева "V: = E"). Процедура tree_asgn вводит множество параметров, создает новый узел дерева (путем доступа к процедуре "создание" уровня "представление") и запоминает параметры во вновь созданном узле. В предпочтительном варианте различные узлы синтаксического дерева имеют различные структуры. Таким образом, каждый вид узла, который может содержаться в синтаксическом дереве, создается и ему присваивается значение с использованием одной из множества подпрограмм создания узлов в пределах уровня определений интерфейса "создание/удаление" для ПТС 134. For example, the "tree_asgn" procedure in
Интерфейс "создание/удаление" для уровня представлений ПТС 134 включает подпрограмму создания узла необходимой структуры и возврата указателя к вновь созданному узлу. Как обсуждено выше, эта подпрограмма вызывается посредством интерфейса "создание/удаление" уровня определений. В этом примере отсутствует подпрограмма уровня представлений, используемая для удалений. Подпрограмма tr_free() высвобождает память дерева для всего дерева, так что она может рассматриваться как пример специфического интерфейса удаления для концептуального уровня. The create / delete interface for the
Таким образом, интерфейс "создание/удаление" ПТС 134 содержит множество уровней абстрактных конструкций, которые включают выделенное конкретное представление, уровень представлений, уровень определений и концептуальный уровень. Интерфейс "создания/удаления" для ПТС 134 состоит из концептуального уровня и части уровня определений. Конкретное представление и уровень представлений скрыты от программиста компьютерной системы. Thus, the TCP creation /
Интерфейс "обращение" для концептуального уровня для ПТС 134 включает функцию итератора, которая обеспечивает доступ к элементам перечня в узле дерева. Это единственный интерфейс концептуального уровня в данном примере. Обращение к узлам дерева и их атрибутам выполняется посредством операций обращения на уровне определений. The “access” interface for the conceptual level for
Интерфейс "обращение" для уровня определений включает множество определений (например, макроопределений), используемых для обращения к синтаксическому дереву. По существу имеется неограниченное число определений, которые могут быть включены в уровень определений и поэтому практически невозможно обсудить их все. Некоторые примеры приведены ниже. The lookup interface for the definition level includes many definitions (for example, macro definitions) used to access the syntax tree. Essentially there is an unlimited number of definitions that can be included in the level of definitions and therefore it is almost impossible to discuss all of them. Some examples are given below.
Интерфейс обращения для уровня определений может содержать, например, следующие макроопределения на языке программирования СИ:
#определить TR_А5С_ЬН5(1)/*левая часть узла назначения*/\
((t) - > tree_ele.t_asg_node. lhs_var )
#определить TR_VAR_ID( ^^идентификатор переменной*/\
((t)->tree_ele.t_var_node.cptr)
Используя эти определения ПТС 134, средства программного обеспечения могут обратиться к идентификатору (например, "V") левой части узла назначения синтаксического дерева (например, V=E) просто путем использования определенных интерфейсов TR_ASG_LHS и TR_VAR_ID, которые определены на уровне определений ПТС 134 синтаксического дерева следующим образом:
TR_VAR_ID ( TR_ASG_LHS ( Т ) )
Структура синтаксического дерева и обращения указателя являются скрытыми из-за ПТС 134.The access interface for the definition level may contain, for example, the following macro definitions in the SI programming language:
# define TR_А5С_ЬН5 (1) / * left part of the destination node * / \
((t) -> tree_ele.t_asg_node. lhs_var)
# define TR_VAR_ID (^^ variable identifier * / \
((t) -> tree_ele.t_var_node.cptr)
Using these
TR_VAR_ID (TR_ASG_LHS (T))
The structure of the syntax tree and pointer references are hidden due to
В другом примере интерфейс обращения уровня определений для ПТС, соответствующего таблице перечня имен (в ПТС для таблицы перечня имен), может содержать следующие макроопределения на языке программирования СИ:
#определить NL_CLOBAL(пр)/*проверка, если переменная является глобальной*/\
((((np)->extra_flags) & NGLOBAL)!=0)
определить NL_ STATIC(np)/*проверка, если переменная является статической*/\
((((np)->extra_flags) & NSTATIC)!=0)
Используя эти определения ПТС для таблицы перечня имен (таблицы кодировки символов), средства программного обеспечения могут проверить статус переменных в таблице перечня имен для определения их статуса просто с использованием определенных интерфейсов NL_GLOBAL и NL_STATIC следующим образом:
если ( NL_GLOBAL (np) альфа NL_STATIC(np))
Обращения указателя и поразрядные логические операции И скрыты в ПТС для таблицы перечня имен.In another example, the interface for defining the definition level for the TCP corresponding to the table of the list of names (in the TCP for the table of the list of names) may contain the following macro definitions in the SI programming language:
# define NL_CLOBAL (pr) / * check if the variable is global * / \
((((np) -> extra_flags) & NGLOBAL)! = 0)
define NL_ STATIC (np) / * check if the variable is static * / \
(((((np) -> extra_flags) & NSTATIC)! = 0)
Using these TCP definitions for the name list table (character encoding table), the software can check the status of the variables in the name list table to determine their status simply using the defined NL_GLOBAL and NL_STATIC interfaces as follows:
if (NL_GLOBAL (np) alpha NL_STATIC (np))
Pointer references and bitwise logical operations AND are hidden in the TCP for the table of the list of names.
Подпрограммы обращения уровня представлений для ПТС 134 включают, например, подпрограмму (tr_alloc(n)) для выделения узла дерева из n байт. Presentation level access routines for
Таким образом, интерфейс обращения ПТС 134 содержит множество уровней абстрактных конструкций, которые включают выделенное конкретное представление, уровень представлений, уровень определений и концептуальный уровень. Интерфейс доступа общего пользования к ПТС 134 состоит из концептуального уровня и части уровня определений. Конкретное представление и уровень представлений являются скрытыми для программиста компьютерной системы. Thus, the
В заключение можно отметить, что с использованием настоящего изобретения программные средства можно структурировать согласно строгому порядку, что обеспечивает удобочитаемость, надежность и удобство сопровождения программных средств. При использовании настоящего изобретения сопровождающиеся высоким риском фрагменты, использующие указатели, метки, косвенную адресацию и т. п. , записываются только однократно в соответствующем ПТС на уровне определений. Каждый тип интерфейса ПТС (например, интерфейсы создания/удаления, обращения, обновления и вывода) содержит множество уровней абстрактных конструкций, которые включают выделенное конкретное представление, уровень представлений, уровень определений и концептуальный уровень. Каждый интерфейс для ПТС состоит из концептуального уровня и, возможно, части уровня определений. Конкретное представление и уровень представлений являются скрытыми для программиста. In conclusion, it can be noted that using the present invention, software can be structured according to a strict order, which provides readability, reliability and ease of maintenance of software. When using the present invention, fragments accompanied by high risk, using pointers, labels, indirect addressing, etc., are recorded only once in the corresponding TCP at the definition level. Each type of TCP interface (for example, interfaces for creating / deleting, accessing, updating, and output) contains many levels of abstract constructions, which include a highlighted concrete representation, a level of representations, a level of definitions, and a conceptual level. Each interface for a TCP consists of a conceptual layer and possibly a part of a definition layer. The specific presentation and presentation level are hidden to the programmer.
Другие варианты осуществления настоящего изобретения могут быть очевидны для специалиста в данной области техники, исходя из описания изобретения. Например, другие варианты осуществления изобретения могут использовать другие наименования уровней и интерфейсов, описанных здесь. Other embodiments of the present invention may be apparent to a person skilled in the art from the description of the invention. For example, other embodiments of the invention may use other names of the levels and interfaces described herein.
Специалисту в данной области техники должно быть ясно, что технология с использованием ПТС характеризует собой методологию и принципы структурирования при составлении программ для средств программного обеспечения. Таким образом, эта технология с использованием ПТС обеспечивает достижение наилучших результатов, если соответствующие уровни и интерфейсы скрупулезно определены и поддерживаются. Следует иметь в виду, однако, что частичное использование технологии ПТС также обеспечит получение преимуществ в аспекте удобочитаемости и удобства сопровождения, хотя и не в такой степени, как при строгом соблюдении правил использования технологии ПТС. Таким образом, использование ПТС не является фактором, который должен использоваться либо полностью, либо не использоваться совсем. Можно осуществлять составление программ для компьютерных систем, в которых технология ПТС будет использоваться лишь в некоторых частях, а в других будет отсутствовать. It should be clear to a person skilled in the art that the technology using the TCP characterizes the methodology and principles of structuring when compiling programs for software tools. Thus, this technology using PTS ensures the achievement of the best results if the corresponding levels and interfaces are scrupulously defined and supported. It should be borne in mind, however, that the partial use of TCP technology will also provide advantages in terms of readability and ease of maintenance, although not to the same extent as with strict observance of the rules for the use of TCP technology. Thus, the use of TCP is not a factor that should be used either completely or not at all. It is possible to compile programs for computer systems in which the TCP technology will be used only in some parts, and in others it will be absent.
Следует иметь в виду также, что описание и приведенные варианты выполнения не накладывают никаких ограничений и должны рассматриваться как возможные примеры, в то время как действительный объем изобретения должен определяться пунктами формулы изобретения. It should also be borne in mind that the description and the given embodiments do not impose any restrictions and should be considered as possible examples, while the actual scope of the invention should be determined by the claims.
Claims (11)
Priority Applications (1)
Application Number | Priority Date | Filing Date | Title |
---|---|---|---|
RU95118821A RU2103727C1 (en) | 1995-10-24 | 1995-10-24 | Method for converting input code of translator into object code and device which implements said method |
Applications Claiming Priority (1)
Application Number | Priority Date | Filing Date | Title |
---|---|---|---|
RU95118821A RU2103727C1 (en) | 1995-10-24 | 1995-10-24 | Method for converting input code of translator into object code and device which implements said method |
Publications (2)
Publication Number | Publication Date |
---|---|
RU95118821A RU95118821A (en) | 1997-11-10 |
RU2103727C1 true RU2103727C1 (en) | 1998-01-27 |
Family
ID=20173500
Family Applications (1)
Application Number | Title | Priority Date | Filing Date |
---|---|---|---|
RU95118821A RU2103727C1 (en) | 1995-10-24 | 1995-10-24 | Method for converting input code of translator into object code and device which implements said method |
Country Status (1)
Country | Link |
---|---|
RU (1) | RU2103727C1 (en) |
Cited By (2)
Publication number | Priority date | Publication date | Assignee | Title |
---|---|---|---|---|
US8156487B2 (en) | 2004-05-11 | 2012-04-10 | Microsoft Corporation | Efficient patching |
US8539469B2 (en) | 2004-05-11 | 2013-09-17 | Microsoft Corporation | Efficient patching |
-
1995
- 1995-10-24 RU RU95118821A patent/RU2103727C1/en active
Non-Patent Citations (1)
Title |
---|
ЕР, 0372834, патент, кл. G 06 F 9/455, 1989. * |
Cited By (3)
Publication number | Priority date | Publication date | Assignee | Title |
---|---|---|---|---|
US8156487B2 (en) | 2004-05-11 | 2012-04-10 | Microsoft Corporation | Efficient patching |
US8539469B2 (en) | 2004-05-11 | 2013-09-17 | Microsoft Corporation | Efficient patching |
US9092301B2 (en) | 2004-05-11 | 2015-07-28 | Microsoft Technology Licensing, Llc | Efficient patching |
Similar Documents
Publication | Publication Date | Title |
---|---|---|
US6523171B1 (en) | Enhanced source code translator from procedural programming language (PPL) to an object oriented programming language (OOPL) | |
EP0789875B1 (en) | Method of translating source code from one high-level computer language to another | |
Ierusalimschy et al. | Lua—an extensible extension language | |
US5699310A (en) | Method and apparatus for a fully inherited object-oriented computer system for generating source code from user-entered specifications | |
US5680622A (en) | System and methods for quickly detecting shareability of symbol and type information in header files | |
US8327346B2 (en) | Run-time type conversion | |
CA2078247C (en) | Source code analyzer | |
US6083282A (en) | Cross-project namespace compiler and method | |
Doh et al. | Composing programming languages by combining action-semantics modules | |
US5701490A (en) | Method and apparatus for compiler symbol table organization with no lookup in semantic analysis | |
EP0520708B1 (en) | Method and apparatus for converting high level form abstract syntaxes into an intermediate form | |
US6305011B1 (en) | Tip technology and its application to sparcompiler pascal | |
CN113608748A (en) | Data processing method, device and equipment for converting C language into Java language | |
US20030101195A1 (en) | Symbol repository | |
RU2103727C1 (en) | Method for converting input code of translator into object code and device which implements said method | |
Koskimies et al. | The design of a language processor generator | |
Tenma et al. | A system for generating language-oriented editors | |
EP1785848A1 (en) | Method and apparatus for semantic checking of program code | |
van Lamsweerde et al. | The kernel of a generic software development environment | |
Christ-Neumann et al. | ASDL—An object-oriented specification language for syntax-directed environments | |
Boyland et al. | Attributed transformational code generation for dynamic compilers | |
Jarzabek | Systematic design of static program analyzers | |
Tirri et al. | ALCHEMIST/spl minus/an object-oriented tool to build transformations between heterogeneous data representations | |
Ahmad et al. | Unification of Programming Languages. | |
Fritzson | Incremental symbol processing |